Windows Shell API

This section describes the OLE interfaces and APIs that are used when interacting with the Windows® shell.

Shell Versions

Application Desktop Toolbars

Band Objects

Briefcase Reconcilers

Control Panel Applications

Debugging With the Shell

Dragging and Dropping

File Manager Extensions

File Parsers

File Viewers

Help

Screen Saver Library

Shell Dynamic Data Exchange Interface

Shell Extensions

Shell Library

Shell Links

Shell Namespace

Shell Objects for Scripting and Visual Basic

Shell Utility APIs

Taskbar

Shell Reference


Shell Versions

Microsoft® Internet Explorer 4.0 introduces updates to shell interfaces, functions, and other programming elements. This section describes how to determine which version your application is running on and how to target your application for a specific version.

Shell DLL Versions

Project Versions

Shell DLL Versions

Because of ongoing enhancements, different versions of Shell32.dll implement different features. Throughout this section, programming elements are marked with a version number. This version number indicates that the programming element is implemented in that version and later versions of Shell32.dll. If no version number is specified, the programming element is implemented in all versions. Many programming elements are now contained in Shdocvw.dll, but this file was not included with standard Microsoft® Windows® 95 or Windows NT® 4.0 operating systems. Therefore, Shell32.dll will provide the required version information.

The following table outlines the different versions of Shell32.dll and the platforms on which they are contained.
Version | Platform
4.00 | Windows 95, Windows NT 4.0, Internet Explorer 3.0, and Internet Explorer 4.0 without Web Integrated Desktop.
4.71 | Internet Explorer 4.0 with Web Integrated Desktop.
4.72 | Internet Explorer 4.01 with Web Integrated Desktop.

The following function retrieves the major and minor version numbers of the Shell32.dll that is installed on the local system.

#include <windows.h>
#include <shlwapi.h>

HRESULT GetShell32Version(LPDWORD pdwMajor, LPDWORD pdwMinor)
{
HINSTANCE   hShell32;

if(   IsBadWritePtr(pdwMajor, sizeof(DWORD)) ||
      IsBadWritePtr(pdwMinor, sizeof(DWORD)))
   return E_INVALIDARG;

*pdwMajor = 0;
*pdwMinor = 0;

//Load the DLL.
hShell32 = LoadLibrary(TEXT("shell32.dll"));

if(hShell32)
   {
   HRESULT           hr = S_OK;
   DLLGETVERSIONPROC pDllGetVersion;

   /*
   You must get this function explicitly because earlier versions of the DLL
   don't implement this function. That makes the lack of implementation of the
   function a version marker in itself.
   */
   pDllGetVersion = (DLLGETVERSIONPROC)GetProcAddress(hShell32, TEXT("DllGetVersion"));

   if(pDllGetVersion)
      {
      DLLVERSIONINFO    dvi;

      ZeroMemory(&dvi, sizeof(dvi));
      dvi.cbSize = sizeof(dvi);

      hr = (*pDllGetVersion)(&dvi);

      if(SUCCEEDED(hr))
         {
         *pdwMajor = dvi.dwMajorVersion;

         *pdwMinor = dvi.dwMinorVersion;
         }
      }
   else
      {
      /*
      If GetProcAddress failed, the DLL is a version previous to the one
      shipped with IE 3.x.
      */
      *pdwMajor = 4;
      *pdwMinor = 0;
      }

   FreeLibrary(hShell32);

   return hr;
   }

return E_FAIL;
}

Project Versions

To help you ensure that your application is compatible with different targeted versions of the shell, a version macro has been added to the shell header files. This version macro is used to define, exclude, or redefine certain definitions for different versions of the DLL. The macro name is _WIN32_IE, and you, the developer, are responsible for defining the macro as a hexadecimal number. This version number defines the target version of the application that is using the DLL. The following are the currently available version numbers and the effect each has on your application.
Version | Description
0x0200 | The application will be compatible with Shell32.dll version 4.00 and later. The application will not, however, be able to implement the features that were added after version 4.00 of Shell32.dll.
0x0400 | The application will be compatible with Shell32.dll version 4.71 and later. The application will not, however, be able to implement the features that were added after version 4.71 of Shell32.dll.
0x0401 | The application will be compatible with Shell32.dll version 4.72 and later. The application will not, however, be able to implement the features that were added after version 4.72 of Shell32.dll.

The most effective way to define this macro in your project is to add the following to the compiler directives in your make file (substitute the desired version number for 0x0400).

/D _WIN32_IE=0x0400

Another method that can be used is to add a line similar to the following in your source code before including any header files (substitute the desired version number for 0x0400).

#define _WIN32_IE 0x0400
#include <shlobj.h>

If you do not define this macro in your project, it will automatically be defined as 0x0400.


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

Using Application Desktop Toolbars

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 affect 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, the system always uses the cbSize and hWnd members, so 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 to 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 to 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 Appbar Notification Messages.

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 or prevents other applications from using the screen area occupied by the appbar. An application should always send ABM_REMOVE before destroying an appbar.

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 with which the appbar is associated. 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 to 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.

Appbar Notification Messages

The system sends messages to notify an appbar about events that can affect 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 selects or clears 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 taskbar'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:

  • Registering an application desktop toolbar (appbar)
  • Setting the appbar size and position
  • Processing appbar notification messages

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 to 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 to 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 Appbar 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 the 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 Appbar Notification Messages

An appbar receives a notification message when the state of the taskbar 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 to 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);
    }


Band Objects

Microsoft® Internet Explorer 4.0 allows an application to define and create bands that are displayed within the shell and the browser.

Band Object Types

Implementing a Band Object

Band Object Types

Internet Explorer 4.0 currently supports three different types of band objects: Desk Bands, Explorer Bands, and Communication Bands. Each type of band serves a different purpose. The following sections describe these different band types and their capabilities.

Desk Bands

Desk Bands are band objects that are displayed as a band in the shell taskbar or as a floating tool window on the desktop. Desk Bands are used to display information and to receive input from the user. They are available to the user throughout the entire Microsoft® Windows® session. Desk Bands are supported in shell versions 4.71 and later.

The following illustration shows a Desk Band on the taskbar.

Desk Band on the taskbar

This illustration shows a Desk Band as a floating toolbar.

Desk Band as a floating toolbar

Explorer Bands

Explorer Bands are band objects that are displayed in a browser window. They usually contain information or supply tools that are helpful to the user while using the browser. These bands are displayed to the left of the current view and normally receive user input that results in some action being performed. Explorer Bands are supported in browser versions 4.71 and later.

The following illustration shows an Explorer Band in Internet Explorer 4.0.

Explorer Band in Internet Explorer 4.0

Communication Bands

Communication Bands are band objects that are displayed in a browser window. This can be a Windows Explorer window or an Internet Explorer 4.0 browser window. Communication Bands are normally used to relay information to the user. These bands are displayed below the current view and don't usually accept user input. Communication Bands are supported in browser versions 4.71 and later.

The following illustration shows a Communication Band in Internet Explorer 4.0.

Communication Band in Internet Explorer 4.0

Implementing a Band Object

This section describes the basic steps involved in creating a band object. To receive the most benefit from this information, you should be familiar with OLE COM, C++ programming, component categories, and the registry.

Registering the Band Object

The band object server must be registered as an OLE in-process server that supports the apartment threading model. The default value for the server is a text entry that will be displayed in the band selection menu. The following example shows the required registry entries.

HKEY_CLASSES_ROOT
    CLSID
        <server clsid> = "&Sample Band"
            InProcServer32 = "<server DLL path and file name>"
                             "ThreadingModel"="Apartment"

In addition to these entries, the band object server is registered for one or more component categories. The registered component categories define the type of band object that the server implements. The following list shows the available band object component categories. These component category identifiers are defined in Shlobj.h.
CATID_DeskBand | The band object implements a Desk Band.
CATID_InfoBand | The band object implements an Explorer Band.
CATID_CommBand | The band object implements a Communication Band.

Band Object Interfaces

The following interfaces must be implemented by a band object:

  • IDeskBand
  • IObjectWithSite
  • IPersist
  • IPersistStream

If the band can accept user input, IInputObject is also required. And if you want to add to the context menu that is displayed for the band, you must implement the IContextMenu interface.

Implementing the IDeskBand interface in a band object

A band object must implement the IDeskBand interface. Because IDeskBand is derived from IDockingWindow, the band object must implement all the methods for both of these interfaces.

IDockingWindow is derived from IOleWindow. The IOleWindow interface provides the GetWindow method so that the container can obtain the band object's window handle.

The IDockingWindow methods are used to show, hide, and close the band object window. Unlike a normal docking window implementation, a band object does not have to negotiate its border space within the band container. Instead, the band container resizes the window provided by the band object's IOleWindow::GetWindow method.

The band container calls the IDeskBand::GetBandInfo method to obtain information about the band. In response to this method, the band object must provide all of the display band information that is being requested.

Implementing the IObjectWithSite interface in a band object

A band object must also implement IObjectWithSite. The band container uses this interface to set the band object's site with the SetSite method. The band object should perform the following steps when its SetSite method is called:

  • Release any site pointer that is being maintained.
  • If the site pointer passed to this method is NULL, the band is being removed. The band object can just return S_OK.
  • If the site pointer passed to this method is not NULL, a new site is being set. In this case, the following steps should be performed:
    1. Call QueryInterface on the site interface for IOleWindow, and call the IOleWindow::GetWindow method to obtain the parent window of the band object window. The IOleWindow interface must be released if it is no longer needed.
    2. Create the band object window as a child of the parent window obtained in the previous step. The window should not be created as a visible window.
    3. Call QueryInterface on the site interface for IInputObjectSite, and maintain this as the band object's site pointer. This step is necessary only if the band object implements IInputObject.
    4. If all the previous steps succeeded, the band object should return S_OK. If any of these steps failed, the band object should return an OLE-defined error code indicating what failed.

The following example shows a very simple implementation of a SetSite method.

STDMETHODIMP CBandObject::SetSite(IUnknown* punkSite)
{
//If a site is being held, release it.
if(m_pSite)
   {
   m_pSite->Release();
   m_pSite = NULL;
   }

//If punkSite is not NULL, a new site is being set.
if(punkSite)
   {
   //Get the parent window.
   IOleWindow  *pOleWindow;

   m_hwndParent = NULL;

   if(SUCCEEDED(punkSite->QueryInterface(IID_IOleWindow, (LPVOID*)&pOleWindow)))
      {
      pOleWindow->GetWindow(&m_hwndParent);
      pOleWindow->Release();
      }

   if(!m_hwndParent)
      return E_FAIL;

   if(!CreateBandWindow(m_hwndParent))
      return E_FAIL;

   //Get and keep the IInputObjectSite pointer.
   if(SUCCEEDED(punkSite->QueryInterface(IID_IInputObjectSite, (LPVOID*)&m_pSite)))
      {
      return S_OK;
      }

   return E_FAIL;
   }

return S_OK;
}

Implementing the IPersist and IPersistStream interfaces in a band object

The band container uses the IPersist and IPersistStream interfaces to obtain information from the band object and to allow the band object to load and/or store any persistent information that it needs.

IPersist has only one method—GetClassID—which the container uses to obtain the band object's class identifier.

The band container calls the band object's IPersistStream methods to allow the band object to save or load any persistent data that it requires. If the band object does not have any persistent data, it still must return success codes from the IPersistStream methods, even if no actions are performed in these methods.

Implementing the IInputObject interface in a band object

If a band object accepts user input, it must implement the IInputObject interface. The container uses IInputObject and implements IInputObjectSite to maintain proper user input focus when more than one contained window exists. For implementation and usage information, see the descriptions for the IInputObject and IInputObjectSite interfaces.

Implementing the IContextMenu interface in a band object

If a band object needs to add items to the context menu that is displayed for the band, it must implement the IContextMenu interface. The container will obtain the IContextMenu interface pointer by calling the band object's QueryInterface method, requesting IID_IContextMenu. The container uses the IContextMenu interface to obtain the band-specific context menu items and to execute the selected commands. For implementation information, see the descriptions for the IContextMenu interface.

Band Object Site Commands

The band object container implements an IOleCommandTarget interface that can be used to send commands to the container. This interface is obtained by calling the IInputObjectSite's QueryInterface method, requesting IID_IOleCommandTarget. The IOleCommandTarget::Exec method can then be called to send commands to the container. The command group is identified as CGID_DeskBand, and the following commands are supported:
DBID_BANDINFOCHANGED | The band's information has changed. The container will call the band's IDeskBand::GetBandInfo method, requesting the updated information. The pvaIn argument of the IOleCommandTarget::Exec method is a VARIANT that contains the band identifier that was passed in the most recent call to IDeskBand::GetBandInfo.
DBID_MAXIMIZEBAND | The container will maximize the band. The pvaIn argument of the IOleCommandTarget::Exec method is a VARIANT that contains the band identifier that was passed in the most recent call to IDeskBand::GetBandInfo.


Briefcase Reconcilers

A briefcase reconciler gives the Microsoft® Windows® Briefcase the means to reconcile different versions of a document.

About Briefcase Reconcilers

Briefcase Reconciler Reference

About Briefcase Reconcilers

A briefcase reconciler combines different input versions of a document to produce a single, new output version of the document. You might need to create a briefcase reconciler to support your type of document. This overview 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 has different 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 reconciled 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 acts as 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 might require user interaction to complete reconciliation. Others might 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 might 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 might.

Some briefcase reconcilers work with the Briefcase to allow the user to terminate reconciliation. This is an important feature for a user who might decide that the reconciliation should not proceed. A reconciler typically provides a termination object when the reconciliation requires user interaction and might be lengthy. In some environments, a reconciler might allow partial reconciliation, enabling a user to temporarily suspend a reconciliation and resume it later. The Briefcase does not currently support partial reconciliation, however.

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 method to initiate reconciliation.

Although IReconcilableObject::Reconcile provides 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 method to set the termination object. The Briefcase does not use version identifiers and cannot, therefore, provide previous versions of a document if a reconciler requests them using the corresponding methods in IReconcileInitiator.

The Briefcase passes to IReconcilableObject::Reconcile file monikers 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 method. 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 IMoniker::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 IMoniker::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 might not 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 file name 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\file-clsid\Roles\Reconciler\reconciler-classid

The class must be quick loading, must be designated _MULTIPLEUSE, and, unless marshalers 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 in Reconciliation

A briefcase reconciler should attempt to carry out reconciliation without user interaction. The more automated the reconciliation, the better the user's perception of the process.

In some cases, user intervention can be valuable. For example, a document system might require a user to review changes before accepting the merged version of a document or might 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 might 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.

Reconciling Embedded Objects

When reconciling a document, the briefcase reconciler itself can 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 method 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 might 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 method if an initial version has already been created and uses the IPersistStorage::InitNew method for the initial version. When 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 the IPersistStorage methods. This permits reconciliation of files that are not stored as compound documents.

When 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 method.) 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 method. 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 an 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 so that it contains no elements in the nonreserved part of the IStorage name space. 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, it 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.

Briefcase Reconciler Reference

This section contains information about the reconciliation interfaces. When handling errors, a method can return only those error values that are explicitly defined as possible return values. Furthermore, the method must set all variables whose addresses are passed as parameters to NULL before returning from the error.

Briefcase Reconciler Interfaces

IReconcilableObject
IReconcileInitiator
INotifyReplica


Control Panel Applications

Control Panel applications are special-purpose dynamic-link libraries (DLLs) that let users configure the environment of Microsoft® Windows®.

This section describes Control Panel applications and explains the functions and messages that these applications use and process to complete their work.

About Control Panel Applications

Creating Control Panel Applications

About Control Panel Applications

Though Windows provides a number of standard Control Panel applications, you can create additional applications that 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, such as the mouse Control Panel application. 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 recognize.

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. 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 then carries out the requested work—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 that indicates how many dialog boxes it supports.
CPL_INIT | Sent immediately after the DLL containing the Control Panel application is loaded. The message prompts CPlApplet to perform initialization procedures, including memory allocation.
CPL_INQUIRE | Sent after the CPL_GETCOUNT message to prompt CPlApplet to provide information about a specified dialog box. The lParam2 parameter of CPlApplet points to a CPLINFO structure.
CPL_NEWINQUIRE | Sent after the CPL_GETCOUNT message to prompt CPlApplet to provide information about a specified dialog box. The lParam2 parameter is a pointer to a NEWCPLINFO structure. For better performance on Microsoft® Windows® 95 and Windows NT® version 4.0, your application should process CPL_INQUIRE and not CPL_NEWINQUIRE.
CPL_SELECT | This message is obsolete. Current versions of Windows do not send this message.
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

The CPlApplet callback function processes all messages sent to a Control Panel application by a controlling application. Messages sent to the function should be in a specific order. By the same token, the application requires the messages to be processed in a specific way.

First, the CPlApplet function 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.

Next, if the CPL_INIT message succeeded, the controlling application sends the CPL_GETCOUNT message. The function must then return the number of dialog boxes supported by the Control Panel application.

The CPlApplet function then receives one CPL_INQUIRE message and one CPL_NEWINQUIRE message for each dialog box supported by the Control Panel application. The function fills in a CPLINFO or NEWCPLINFO structure with information about your application, such as its name, icon, and a descriptive string. Most applications should process the CPL_INQUIRE message and ignore the CPL_NEWINQUIRE message. The CPL_INQUIRE message provides information in a form that the controlling application can cache, resulting in much better performance. The CPL_NEWINQUIRE message is useful only if you need to change your application's icon or display strings based on the state of the computer.

The CPlApplet function next 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 value contained in the lData parameter. 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 specified 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 file name 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 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.

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_INQUIRE 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,
};

HANDLE  hinst = NULL;

LONG CALLBACK CPlApplet(hwndCPL, uMsg, lParam1, lParam2)
HWND hwndCPL;      // handle to Control Panel window
UINT uMsg;         // message
LPARAM lParam1;    // first message parameter
LPARAM lParam2;    // second message parameter
{
    int i;
    LPCPLINFO lpCPlInfo;

    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_INQUIRE: // third message, sent once per application
            lpCPlInfo = (LPCPLINFO) lParam2;
            lpCPlInfo->lData = 0;
            lpCPlInfo->idIcon = StereoApplets[i].icon;
            lpCPlInfo->idName = StereoApplets[i].namestring;
            lpCPlInfo->idInfo = StereoApplets[i].descstring;
            break;

        case CPL_DBLCLK:    // application icon double-clicked
            DialogBox(hinst,
                MAKEINTRESOURCE(StereoApplets[i].dlgtemplate),
                hwndCPL, StereoApplets[i].dlgfn);
            break;

        case CPL_STOP:      // sent once per application before CPL_EXIT
            break;

        case CPL_EXIT:    // sent once before FreeLibrary is called
            break;

        default:
            break;
    }
    return 0;
}


Debugging With the Shell

This overview explains how to debug shell and namespace extension DLLs.

Running the Shell Under a Debugger

Running and Testing Shell Extensions on Windows NT

Unloading the DLL

Running the Shell Under a Debugger

To debug your extension, you need to execute the shell from the debugger. Follow these steps:

  1. Load the extension's project into the debugger, but do not run it.
  2. From the Start menu on the Microsoft® Windows® taskbar, choose Shut Down.
  3. Press CTRL+ALT+SHIFT, and click No in the Shut Down Windows dialog box. The shell is now shut down, but all other applications are still running, including the debugger.
  4. Set the debugger to run the extension DLL with Explorer.exe from the Windows directory.
  5. Run the project from the debugger. The shell will start up as usual, but the debugger will be attached to the shell's process.

Running and Testing Shell Extensions on Windows NT

You can run and test your Microsoft® Windows NT® extensions in a separate Windows Explorer process to avoid stopping and restarting the desktop and tray. Your desktop and tray can still be used while you run and test the extensions.

To enable this feature, add the following value to the registry.

HKEY_CURRENT_USER\
   Software\
      Microsoft\
         Windows\
            CurrentVersion\
               Explorer\
                  DesktopProcess(REG_DWORD) = 1

For this value to take effect, you must log off and log on again. This setting causes the desktop and tray windows to be created in one Explorer.exe process and all other Explorer and folder windows to be opened in a different Explorer.exe process.

Besides making running and testing your extensions more convenient, this setting also makes the desktop more robust as it relates to shell extensions. Many such extensions (context menu extensions, for example) will be loaded into the nondesktop Explorer.exe process. If this process terminates, the desktop and tray will be unaffected and the next Explorer or folder window will re-create the terminated process.

Unloading the DLL

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


Dragging and Dropping

This overview explains the general concepts that you need to know to allow your applications to support drag-and-drop capabilities. It also lists the basic steps for implementing drag-and-drop support.

About Dragging and Dropping

About Dragging and Dropping

A Microsoft® Win32®-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 operations. OLE separates what the user does to cause the data transfer from how your application actually transfers the data. This allows you to use the same back-end IDataObject interface for the various ways a user can decide to transfer data.

General OLE Concepts

One of the most useful features 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 adding 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 your application's OLE capabilities. COM is the fundamental, underlying model that OLE is based upon; all OLE objects are also COM objects.

COM stipulates that any COM object must control its own life span and be able to tell other objects about its capabilities when queried. To control its life span, a COM 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. COM objects must use the IUnknown interface to respond to queries and maintain a reference count. Because all OLE interfaces are derived from IUnknown, they are COM objects. This interface 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, the object 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. AddRef is called when another object holds a pointer to the object, and Release 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 delete itself.

COM provides a couple of immediate benefits:

  • An object can determine in advance if another object supports a certain feature. If the feature is not supported, the calling object can react accordingly.
  • Objects do not remain in memory for more time (or less time) than necessary, and they do not rely on the user to launch or close them.

Drag-and-Drop in OLE

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.

You can also use OLE drag-and-drop to add drag-and-drop support within your own application. There is nothing to prevent your application from being both a drop source and a drop target or from accepting dropped objects from itself.

The OLE data transfer mechanism is a crucial element of drag-and-drop support. This mechanism allows objects to be very specific about the data that they transfer. Instead of simply being able to transfer a 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 transfers 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 details about the data that is being transferred—including the target device, aspect, storage medium, and release method.

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 this process. OleInitialize must be called before you call any other OLE functions. Make sure the system's OLE libraries are at least as recent as the ones for which the application was written. 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: IDropSource::QueryContinueDrag and IDropSource::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. 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. OLE will update to its default cursors if the DRAGDROP_S_USEDEFAULTCURSORS value is returned.

  3. 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 IDataObject member functions for drag-and-drop support: IDataObject::GetData, IDataObject::GetDataHere, IDataObject::QueryGetData, and IDataObject::EnumFormatEtc.

  4. Call the DoDragDrop function to begin the drag operation. After you have detected that the user wants to drag something, you should call this function. 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 the pdwEffect parameter 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.

  5. Call OleUninitialize. Before an OLE application exits, it must call this function to release the OLE libraries. You should check your fOleInitialized flag before calling OleUninitialize. It should only be called 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 pointer handy.

  3. Implement the IDropTarget interface. OLE uses the IDropTarget 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 Microsoft 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 DragLeave 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 the 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 this function 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.

Scrap Files

Windows 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 three optional features you may wish to add to your application: round-trip support, caching additional data formats in a scrap file, and delay-rendered formats.

Round-trip support

Round-trip support allows an object to be dragged out of a document and into a new container and then dragged from the new container back into the original document. 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, the cells 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 interface object 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 of object}\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, MSPaint scrap-caches the CF_BITMAP format and WordPad scrap-caches the RTF format as shown in the examples below.

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",,""

Delay-rendered formats

Certain data formats can specify that data will be rendered at a time later than when the data transfer normally occurs. These are called delay-rendered formats. The list of clipboard formats to be delay-rendered is specified under the HKEY_CLASSES_ROOT\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 not an OLE application.

Clipboard Formats for Shell Data Transfers

Windows 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. All transfer methods involve the clipboard.

Windows defines several clipboard formats that you can 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 identifiers. To obtain an identifier for a clipboard format, you simply pass the format's identifier to the RegisterClipboardFormat function. The following list contains the clipboard format names and their corresponding identifiers.
Format name | Identifier
"FileContents" | CFSTR_FILECONTENTS
"FileGroupDescriptor" | CFSTR_FILEDESCRIPTOR
"FileName" | CFSTR_FILENAME
"FileNameMap" | CFSTR_FILENAMEMAP
"InShellDragLoop" | CFSTR_INDRAGLOOP
"Net Resource" | CFSTR_NETRESOURCES
"Paste Succeeded" | CFSTR_PASTESUCCEEDED
"Performed DropEffect" | CFSTR_PERFORMEDDROPEFFECT
"Preferred DropEffect" | CFSTR_PREFERREDDROPEFFECT
"PrinterFriendlyName" | CFSTR_PRINTERGROUP
"Shell IDList Array" | CFSTR_SHELLIDLIST
"Shell Object Offsets" | CFSTR_SHELLIDLISTOFFSET
"UniformResourceLocator" | CFSTR_SHELLURL

The following sections describe the clipboard formats used to transfer data between applications and the shell.

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 file names. An application can retrieve information from the data object by passing the object's handle to the DragQueryFile and DragQueryPoint functions.

"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 file names 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).

"FileName" format

The global memory object contains a single null-terminated and fully qualified file name. 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 file names; each corresponds to the file names 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 file names.

"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 file names (dcxxxx.ext). When the user drags or copies files from the recycle bin, the system uses the file names specified in the "FileNameMap" format to rename the files.

"InShellDragLoop" format

The global memory object contains a DWORD value that indicates if the data object is inside of a drag-and-drop loop. If this value is nonzero, the data object is inside of a drag-and-drop loop. If this value is zero, the data object is not inside of a drag-and-drop loop. This allows a data object implementation to avoid performing time-consuming rendering of data while the user is dragging the object. It also allows the data object to know when the object is actually dropped so that the full data can be rendered.

"Paste Succeeded" format

The global memory object contains a DWORD value that indicates that the drop target's delete-on-paste operation succeeded. This allows the drop target to specify the DROPEFFECT_ flag that was actually performed. The drop target calls IDataObject::SetData to set this value when the operation is complete.

"Performed DropEffect" format

The global memory object contains a DWORD value that represents the drop target's performed drop effect. This allows the drop target to specify the DROPEFFECT_ flag that was actually performed. In the case of an optimized move operation, the target can complete the move, including deletion of the source object, and set this clipboard format to DROPEFFECT_MOVE so that the source does not attempt to delete the source object. The drop target calls IDataObject::SetData to set this value when the operation is complete.

"Preferred DropEffect" format

The global memory object contains a DWORD value that represents the drop source's preferred drop effect. This allows the drop source to specify which of the DROPEFFECT_ flags passed to DoDragDrop is the default drop action.

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

"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. If the ITEMIDLIST for the folder is empty (mkid.cb is 0), the parent folder is the desktop itself.

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

"UniformResourceLocator" format

The global memory object contains a single null-terminated string that contains a Uniform Resource Locator (URL) address.


File Manager Extensions

In Microsoft® Windows®, File Manager extensions are dynamic-link libraries (DLLs) that add menus and buttons to File Manager. File Manager extensions can also display (in the status bar) Help text for the buttons. This document 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 Microsoft® Win32® 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 | The user selected an item from the extension-supplied menu. The value is the identifier of the selected menu item.
FMEVENT_HELPSTRING | The user selected an extension menu or a toolbar command item. File Manager wants the extension to supply a Help string.
FMEVENT_HELPMENUITEM | The user pressed F1 while selecting an extension menu or a toolbar command item. File Manager wants the extension to call WinHelp appropriately for the command item.
FMEVENT_INITMENU | The user 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 | The user selected 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 below:
Task | Action
Initializing the extension (FMEVENT_LOAD) | Provides File Manager with the name and handle to 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 (1–99) | 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 with 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 wMsg 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 wMsg 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

To begin 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 the sum as the idItem parameter to the DeleteMenu function.

If an extension returns FALSE in response to the FMEVENT_LOAD 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. 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 of 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 file name 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

When 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. The extension must initialize all menu items, including those in any submenus, because File Manager will not send the FMEVENT_INITMENU message for submenus within the extension's menu.

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 file name 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 extension's 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 file name.
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 file names.
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 to 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. 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 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 Parser Constants

About File Parsers

File parsers work in conjunction with the file viewing components of the Microsoft® Windows® operating system. These components are the shell, the Quick View program (Quikview.exe), and display engines. When the user wants to generate a quick view for a file, the shell responds 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 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 overview describes the file parser interface and explains how to write file parsers for word processing documents, spreadsheets, databases, bitmapped graphics, and vector graphics. For information about extending the file viewing capabilities in other ways, see File Viewers.

The file viewing technology used in the Quick View feature 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 the "verify data" value under the following key to something other than zero:

\\HKEY_LOCAL_MACHINE\SOFTWARE\SCC\Viewer Technology\MS1

Implementing a File Parser

Every file parser must implement the following functions from the Microsoft Platform SDK:
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 are 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, respectively. 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 VwStreamCloseFunc 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 a 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 font, 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, indentation, 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 a word processing section's text by using the SOBeginTable and SOEndTable functions to mark the start and end of the table definition. It 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. Thus, a filter can 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 can add subdocuments to the document. Subdocuments consist of headers, footers, footnotes, and comments. Subdocuments are added to the document using the SOPutBreak function. To start a subdocument, the file parser calls SOPutBreak with the SO_SUBDOCBEGINBREAK value. To end the subdocument, the file parser calls SOPutBreak with the SO_SUBDOCENDBREAK value.

After ending a subdocument, the file parser must restore character and paragraph attributes to what they were 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.

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 graphics 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 in the document.

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 SOGetInfo. 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 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. Determine if the cell is in the given range of columns. If not, repeat 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. So 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 the dwExtraData parameter in each call to your VwStreamReadFunc function, must eventually be terminated by a call to SOPutBreak with the 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. This ensures that the file position is 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 VwStreamSectionFunc function.

Bitmapped Sections

The file parser starts a bitmapped section by calling the SOPutSectionType function with the SO_BITMAP value while processing the VwStreamSectionFunc function. The file parser must also set the bitmap header information for the section by using the SOPutBitmapHeader function before returning from VwStreamSectionFunc. 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.

Section 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 members set during the stream read can use RGB values, palette index values, or palette-relative RGB values. These values must be set 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 integer 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 lines 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. For example, in 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). So if the first eight pixels of a 4-bit-per-pixel scan line have the hexadecimal 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. In this case, the parser has scan line data stored one tile wide. The scan line data is already in the format that the parser is required to provide it in, 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 VwStreamSectionFunc function. The file parser must also set the vector header by using the SOPutVectorHeader function before returning from VwStreamSectionFunc. 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 graphic device interface (GDI) functions, but they include extensions 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-axes are 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 GDI functions, they are not exactly the same. For example, 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 platforms easier. 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 function pseudonym. 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 a 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.

This example 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"


File Parser Constants

The following vector object values and vector attribute values are used with the vector graphics functions.

Vector object values

SO_ARC | Draws an arc. dwDataSize must be four times the size of the SOPOINT structure, 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 the size of the SOARCINFO structure, 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 the size of the SOARCINFO structure, and pData must be the address of a SOARCINFO structure.
SO_ARCCLOCKWISE | Draws an arc in the clockwise direction. dwDataSize must be four times the size of the SOPOINT structure, and pData must be the address of four SOPOINT structures.
SO_BEGINGROUP | Starts the definition of a group. dwDataSize must be the size of the SOGROUPINFO structure added to GroupInfo.nTransforms times the size of the SOTRANSFORM structure, 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_BEGINPATH Starts the definition of a path. dwDataSize must be the size of the SOPATHINFO structure added to GroupInfo.nTransforms times the size of the SOTRANSFORM structure, 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 later in this section.

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_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 the size of the SORECT structure, and pData must be the address of a SORECT structure that identifies the bounding rectangle of all commands used within the symbol.
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 the size of the SORECT structure, and pData must be the address of a SORECT structure that identifies the bounding rectangle of the text frame.
SO_CHORD | Draws a chord. dwDataSize must be four times the size of the SOPOINT structure, 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 the size of the SOARCINFO structure, and pData must be the address of a SOARCINFO structure that defines the chord in terms of the arc located on the chord.
SO_CLOSESUBPATH | Closes the current subpath. dwDataSize must be zero, and pData must be NULL.
SO_CPARCANGLE | Draws an arc from the current point pivoting around the center point of the specified sweep angle. dwDataSize must be the size of the SOCPARCANGLE structure, and pData must be the address of a SOCPARCANGLE structure that gives the center point of the arc and the sweep angle.
SO_CPARCTRIPLE | Draws a circle arc from the current point through the first point and ending at the second point. dwDataSize must be two times the size of the SOPOINT structure, and pData must be the address of two SOPOINT structures.
SO_CPELLIPSE | Draws an ellipse around the current point with an x- and y-radius described by the SOPOINT data. dwDataSize must be the size of the SOPOINT structure, and pData must be the address of a variable containing the x- and y-radius values.
SO_CPLINE | Draws a line from the current pen position. dwDataSize must be the size of the SOPOINT structure, and pData must be the address of a variable containing the point to draw to.
SO_CPPIEANGLE | Draws a pie with the current position as the center and with the given start and sweep angles. dwDataSize must be the size of the SOCPPIEANGLE structure, and pData must be the address of a SOCPPIEANGLE structure that gives the radius of the circle.
SO_CPRECTANGLE | Draws a rectangle starting at the current pen position. dwDataSize must be the size of SOPOINT structure, and pData must be the address of a variable containing the point to be the opposite corner of the rectangle.
SO_CPSET | Moves the current pen position to this point. dwDataSize must be the size of the SOPOINT structure, and pData must be the address of the variable containing the point.
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 the size of a WORD, and pData must be the address of a variable containing the SODP_STROKE or SODP_FILL value, or both.
SO_ELLIPSE | Draws an ellipse. dwDataSize must be two times the size of the SOPOINT structure, and pData must be the address of two SOPOINT structures.
SO_ENDGROUP | Ends the definition of a group. dwDataSize must be zero, and pData must be NULL.
SO_ENDPATH | Ends the definition of a path. dwDataSize must be zero, and pData must be NULL.
SO_ENDPOLY | Ends drawing of a polygon. dwDataSize must be zero, and pData must be NULL.
SO_ENDSYMBOL | Ends the definition of a symbol. dwDataSize must be zero, and pData must be NULL.
SO_ENDTEXTFRAME | Ends the definition of a text frame. dwDataSize must be zero, and pData must be NULL.
SO_FLOODFILL | Fills the area with the given color. dwDataSize must be the size of the SOPOINT structure plus the size of the SOCOLORREF structure, 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 two times the size of the SOPOINT structure, and pData must be the address of two SOPOINT structures.
SO_PARAEND | Ends a paragraph. dwDataSize must be zero, and pData must be NULL.
SO_PIE | Draws a pie shape. dwDataSize must be four times the size of the SOPOINT structure, 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 the size of the SOARCINFO structure, and pData must be the address of a SOARCINFO structure that defines the pie in terms of the arc located on the pie.
SO_POINTS | Specifies vertices of a polygon. dwDataSize must be N times the size of the SOPOINT structure, 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_RECTANGLE | Draws a rectangle. dwDataSize must be two times the size of the SOPOINT structure, and pData must be the address of two SOPOINT structures.
SO_ROUNDRECT | Draws a rectangle with rounded corners. dwDataSize must be three times the size of the SOPOINT structure, and pData must be address of the three SOPOINT structures.
SO_SETPIXEL | Sets the color of a pixel. dwDataSize must be the size of the SOPOINT structure plus the size of the SOCOLORREF structure, and pData must be the address of a variable containing the pixel point followed by the RGB color value to set.
SO_STARTPOLY | Starts drawing of a polygon. dwDataSize must be the size of the SOPOLYINFO structure, and pData must be the address of a SOPOLYINFO structure.
SO_TEXTATARCANGLE | Draws text at the given location. dwDataSize must be the size of the SOTEXTATARCANGLE structure plus the length of the text string, and pData must be the address of a SOTEXTATARCANGLE structure followed by the text string.
SO_TEXTATPOINT | Draws text at the given point. dwDataSize must be the size of the SOTEXTATPOINT structure plus the length of the text string, and pData must be the address of a SOTEXTATPOINT structure followed by the text string.
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 the size of an INT plus the length of the text string, and pData must be the address of an integer variable containing the size of the text string that follows.
SO_TEXTINRECT | Draws text in a rectangle. dwDataSize must be the size of the SOTEXTINRECT structure plus the length of the text string, and pData must be the address of a SOTEXTINRECT structure followed by the text string.

Vector attribute values

SO_BKCOLOR | Sets the background color used for styled lines, hatched brushes, and text when the background mode is SOBK_OPAQUE. dwDataSize must be the size of the SOCOLORREF structure, 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_BKMODE | Sets the background mode. dwDataSize must be the size of an INT, and pData must be the address of a variable containing either the SOBK_OPAQUE or SOBK_TRANSPARENT value.
SO_CLIPMODE | Sets the clipping mode. dwDataSize must be the size of a WORD, and pData must be the address of a variable containing either the SO_DONOTCLIP or SO_CLIPTOPATH value.
SO_DRAWMODE Sets the drawing mode used when drawing the pen and interiors. dwDataSize must be the size of an 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_OBJECTTRANSFORM | Sets object transformations. dwDataSize must be the size of an INT plus nCount times the size of the SOTRANSFORM structure, and pData must be one INT (nCount) followed by that number of SOTRANSFORM structures. The transformations will occur in the order supplied.
SO_PARAALIGN | Sets the alignment of paragraph text being built into a text frame. dwDataSize must be the size of a WORD, and pData must be the address of a 16-bit variable containing the SO_ALIGNLEFT, SO_ALIGNCENTER, SO_ALIGNRIGHT, or SO_ALIGNJUSTIFY 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 the size of the SOPARAINDENTS structure, and pData must be the address of a SOPARAINDENTS structure.
SO_POINTRELATION | Sets the coordinate orientation. dwDataSize must be the size of an INT, and pData must be the address of a variable containing the SOPR_ABSOLUTE or SOPR_RELATIVE value.
SO_POLYFILLMODE | Sets the polygon-filling mode. dwDataSize must be the size of an INT, and pData must be the address of a variable containing either the SOPF_ALTERNATE or SOPF_WINDING value.
SO_SELECTBRUSH | Selects the given brush. dwDataSize must be the size of the SOLOGBRUSH structure, and pData must be the address of a SOLOGBRUSH structure.
SO_SELECTFONT | Selects the given font. dwDataSize must be the size of the SOLOGFONT structure, and pData must be the address of a SOLOGFONT structure.
SO_SELECTPEN | Selects the given pen. dwDataSize must be the size of the SOLOGPEN structure, and pData must be the address of a SOLOGPEN structure.
SO_TEXTCHAREXTRA | Sets the text character extra value. dwDataSize must be the size of an INT, and pData must be the address of a variable containing a value. This attribute affects text objects.
SO_TEXTCOLOR | Sets the foreground color. dwDataSize must be the size of the SOCOLORREF structure, and pData must be the address of a variable containing an RGB or a palette-relative color value. To set this value, use the SORGB or SOPALETTE macro.


File Viewers

A file viewer is an OLE COM 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

About File Viewers

The shell allows users to browse through the information in the file system and on the network. Using the Quick View feature of the shell, the user can view the contents of a file without running the application that created it; the application doesn't even have to be installed on the user's computer. 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.

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 file name extensions in the system registry.

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. 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 Microsoft® Windows® executable file, it is not a complete 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 COM 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 overview 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. 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, 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 includes display engines for word processor 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 and database display engines, respectively. 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. 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, or paste operations) remain even when a new file parsing DLL is used. For more information about the interface between file parsers and display engines, see File Parsers.

The second method of including file viewing functionality in Windows is to add one or more DLLs that work directly with Quick View. An example of one of these file viewing systems for ASCII files is found in the Samples subdirectory of the Microsoft Platform 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 because its file format is not recognized by one of the default display engines. The main disadvantage of this method is that writing for the Quick View interface requires additional development and testing effort.

The file viewing technology used by the Quick View feature 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 file name extension. If there is no file name extension or if there are no file viewers registered for the file name 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 file name 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.

Structure of registry entries

The following registry structure is required for Quick View to associate a class identifier or file name 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 file name 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 file name extension with the period, as is consistent with the standard 8.3 file name 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 Microsoft 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 file name extension subkeys, each representing a registered file type. Each file name 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 file type class identifier to identify the application as a compound document server.

Each class identifier stored under the file name 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 COM object server is stored. Using this subkey allows the Quick View program to use standard OLE methods 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 file name 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 Microsoft 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) file names 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 will suppress all user interface 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 file name extension from the path given in the -f option. If no file name 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 file name extension.
    A. Quick View attempts to open the HKEY_CLASS_ROOT\QuickView\extension key, where extension is parsed from the path.
    • If the file name 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.
    • 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 (error condition 2). 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. When 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. | When given the IPersistFile interface pointer pIPersistFile, Quick View calls the IPersistFile::Load method, 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 method 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 method of pIPersistFile. Quick View calls the Release method 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.
    D. | (1) If the -v option was present or both the -v and -p options were absent, Quick View calls the ShowInitialize method of pIFileViewer, which instructs the file viewer to load the file and perform any initialization 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 method 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.
    (2) If the -p option was present (and the -v option was absent), Quick View calls the PrintTo method 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 (user interface 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 user interface suppression flag is FALSE.
    E. | When Show or PrintTo returns (whichever was called in steps D1 or D2), Quick View calls the Release method of pIFileViewer, regardless of the return value. If the file viewer successfully executed the IFileViewer::ShowInitialize method, the Release method 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 has and calls OleUninitialize. 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 file name 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 file name 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 file name 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 file name extension key currently in use. 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 file name. 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 that Quick View display a new file in the same window used by the previous file viewer; this is called pinning 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 the user has dropped on the viewer window.

Quick View implements the IFileViewerSite interface, which allows a file viewer to retrieve the handle to the current pinned window, if there is one, or set a new pinned window. When Quick View calls a file viewer's IFileViewer::ShowInitialize method, 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 AddRef method to increment the reference count.

Only one pinned window can exist at a time. A file viewer uses the IFileViewerSite::SetPinnedWindow method to set a new pinned window and the IFileViewerSite::GetPinnedWindow method to retrieve the handle to the current pinned window.

When Quick View calls the file viewer's IFileViewer::Show method, the file viewer receives the address of an FVSHOWINFO structure that includes an 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 method 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 <file name>. 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 <file name>.
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 COM object in an in-process server DLL that 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.

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 COM object DLL will be the fastest and most efficient 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. Once the IPersistFile interface is obtained, 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 methods or asks the object to print the file to a specific printer by using the IFileViewer::PrintTo method. 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 methods of IPersistFile are separate from the IFileViewer file methods, which is why IFileViewer was not just extended with its own Load method. Extending IFileViewer would have been more efficient (because it avoids IPersistFile entry point functions that are not implemented), but the current design is easier to extend.

IFileViewer interface

The shell uses the IFileViewer interface to print the file or to tell a file viewer object when to show its user interface for the file being viewed. In addition to the usual IUnknown members, the interface includes the IFileViewer::ShowInitialize, IFileViewer::Show, and IFileViewer::PrintTo methods.

Before calling IFileViewer::Show, the shell calls IFileViewer::ShowInitialize to instruct the file viewer to perform any necessary initialization. ShowInitialize can fail, whereas Show cannot 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 method should return the FV_ error codes listed in the Structure of registry entries section. Although the sample file viewer included in the Microsoft Platform SDK uses a more generic form of error codes, new file viewer DLLs should use the FV_ codes.

The Show method is similar to the Windows ShowWindow function in that it receives a Show command indicating how the file viewer should initially display its window. 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 can fail is if ShowInitialize has not been called. In that case, it returns the E_UNEXPECTED status code. Otherwise, Show must return the NOERROR error code.

The PrintTo method 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 user interface elements, including error messages, 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 IFileViewer interface identifier is defined in the Windows header files as the IID_IFileViewer.

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 IPersistFile::Load and IPersistFile::GetCurFile methods (as well as the IUnknown methods). The IPersistFile::IsDirty method can simply return ResultFromScode (S_FALSE) because a file viewer does not modify the file, and the IPersistFile::Save and IPersistFile::SaveCompleted methods should simply return ResultFromScode (E_NOTIMPL). IPersistFile::Load stores the file name but delays opening the file until the later call to the IFileViewer::ShowInitialize method. IPersistFile::GetCurFile returns ResultFromScode (E_UNEXPECTED) if Load has not yet been called. Otherwise, it copies the path and returns the NOERROR error code.
  3. Implement the IFileViewer::ShowInitialize and IFileViewer::Show methods (as well as the IUnknown methods). ShowInitialize must perform all operations that are prone to failure. Therefore, if ShowInitialize succeeds, Show will never fail. The implementation of these two member functions is similar to the implementation of an application's WinMain function. ShowInitialize registers window classes, creates any necessary windows, and loads the file as read-only with the path given in the IPersistFile::Load method. ShowInitialize uses the instance handle that the DLL receives in its DllEntryPoint function, not the instance of Quick View, when registering and creating windows. Then Show displays the contents of the file in the viewport window, shows the top-level file viewer window, and enters a message loop. To enhance the appearance of the user interface, the file should be loaded and completely displayed in the viewport window before the windows are made visible.

    IFileViewer::Show does not return until the user has closed the window; Quick View waits for Show to return before it terminates. Quick View delegates the responsibility of the message loop to the Show method, 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 method 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 COM 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 method, as required for any COM object DLL.
  7. Include the Print To feature by using the IFileViewer::PrintTo method. 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-based DLL.

In general, only the implementations of IPersistFile::Load and the IFileViewer methods are specific to a file viewer. The other steps that deal with creating an OLE COM object are standard OLE mechanisms.

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.

File viewer main window

A file viewer's main window should have Minimize, Maximize, and Close buttons and these top-level menu items: File, View, and Help. 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 initial show state of the window (normal, minimized, or maximized) is given in the IFileViewer::Show method.

The following illustration shows an example of a file viewer window.

File viewer window in the typical initial state.

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 command 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 window flags to create a 3-D window appearance and use scroll bars with proportional scroll boxes.

File viewer 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 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 main window, closes the file, destroys all the windows, performs other necessary cleanup, and returns with NOERROR 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.

File viewer 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" | Used to switch between displaying and hiding the toolbar. This item is checked when the toolbar is visible and unchecked when it is hidden.
"&Status Bar" | Used to switch between displaying and hiding the status window. This item is checked when the status bar is visible and unchecked when it is hidden.
"&Page View" | Used to switch between a full-sized view and a single-page view and vice versa.
"Replace &Window" | Used to switch between reusing the current window to view a file and creating a new window to view a file.
Separator | Not applicable.
"&Landscape" | Used to switch between landscape and portrait views 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.

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

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

The following illustration shows an example of an Open File for Editing button implementation.

An Open File for Editing button.

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 switched 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, so you only have to provide the text string. The following illustration shows a tooltip control for a toolbar button.

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

File viewer 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 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 | Moves 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 default file viewers.

  • In the inactive state, when the user is doing nothing else, the status bar 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.

    The following illustration shows a viewer window displaying this message.

    Example status bar text for a mouse move.

    Note that the document type is specific for the file viewer in use.

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

File viewer viewport window contents

The viewport window is where you provide most file-specific user interface 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 right mouse button. 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

You can add more menu items as needed. The Toolbar and Status bar menu item commands on the View menu should not appear in the context menu.

Drag-and-Drop in File Viewers

The default file viewers in Windows 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 overview only describes the minimal file viewer user interface. 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 embedded objects.


Help

Online Help can come in a variety of forms, from detailed conceptual information to quick definitions.

About Help

Using Help

About Help

An important element of a user-friendly application is readily available in 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 the elements of the Microsoft® 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 it 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 a WM_HELP message to the window that had the keyboard focus when the user pressed the F1 key. If the window is a 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 the 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 to the control that received the 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 supplies a consistent user interface, it is recommended that applications use Windows Help rather than other methods. 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 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 them whenever they are requested. Internally, Windows Help uses topic identifiers to locate topics, but applications most often use context identifiers (unique integer values) to specify the 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, it 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 Microsoft® 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 this 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 find other topics in the Help file. It typically displays the main Help window, which includes a title bar, a system menu, minimize and maximize buttons, a main menu, an optional navigation bar, a 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 the 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. The procedure specifies an array of control and context identifier pairs; it also specifies the handle in the wParam parameter 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 a WM_HELP message is generated, the system includes the context identifier in the HELPINFO structure that is passed to the parent window in 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, if there is more than one topic associated with the keyword, displays a list of topics from which the user can choose.

In an application, you can use the HELP_KEY, HELP_PARTIALKEY, or HELP_MULTIKEY command with the WinHelp function 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 to 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 box, and the user can 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).

Your application can search for multiple keywords in a single call to WinHelp by separating the keywords with semicolons. (Searching for multiple keywords is not supported for Help files created for Windows version 3.x.) It can also search for keywords across multiple Help files if the Help file that is specified 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 adding a footnote character other than K, with the keyword definition, in the Help source 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, 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 the main window while searching. In this case, canceling both the Topics Found and Help Topics dialog boxes closes 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 primary 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 the 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. The resulting string is then passed 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.

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 buttons that are associated with TCard macros, which allow the user to tell the application what to do next. Training cards can 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 a 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 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 a 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) 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 WinHelp. 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 DWORD 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 contains the address of a HELPINFO structure. The hItemHandle member of this structure identifies the control for which the user has requested Help. You must pass this 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 then 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.

When calling the WinHelp function, processing WM_CONTEXTMENU is similar to processing WM_HELP with these two exceptions:

  • You pass the wParam parameter from WM_CONTEXTMENU, which is the handle to 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;
}


Screen Saver Library

The Microsoft® Win32® application programming interface (API) supports special applications called screen savers. Screen savers start when the mouse and keyboard have been idle for a specified period of time. They are used for these two reasons:

  • To protect a screen from phosphor burn caused by static images.
  • To conceal sensitive information left on a screen.

About Screen Savers

Using the Screen Saver Functions

About Screen Savers

The Desktop application in the Microsoft® Windows® Control Panel lets users select from a list of screen savers, specify how much time should elapse before the screen saver starts, configure screen savers, and preview screen savers. Screen savers are loaded automatically when Windows starts or when a user activates the screen saver through the Control Panel.

Once a screen saver is chosen, Windows monitors keystrokes and mouse movements and then starts 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 the wParam parameter set to the SC_SCREENSAVE value, but it does not pass the message to the DefWindowProc function.

Screen savers contain specific exported functions, resource definitions, and variable declarations. The screen saver library contains the main function and other startup code required for a screen saver. When a screen saver starts, the startup code in the screen saver library 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 the screen saver library. 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 the screen saver library. Following are some of the typical messages processed by ScreenSaverProc.
Message | Meaning
WM_CREATE | Retrieve any initialization data from the Regedit.ini file. 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 the screen saver library by calling the DefScreenSaverProc function. The following table describes how this function processes various messages.
Message | Action
WM_SETCURSOR | Set the cursor to the null cursor, removing it from the screen.
WM_PAINT | Paint the screen background.
WM_LBUTTONDOWN | Terminate the screen saver.
WM_MBUTTONDOWN | Terminate the screen saver.
WM_RBUTTONDOWN | Terminate the screen saver.
WM_KEYDOWN | Terminate the screen saver.
WM_MOUSEMOVE | Terminate the screen saver.
WM_ACTIVATE | Terminate the screen saver if the wParam parameter is set to FALSE.

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 (an application must provide a corresponding dialog box template). Windows displays the configuration dialog box when the user selects the Setup button in the Control Panel's Screen Saver dialog box.

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 special windows or custom controls 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 the Control Panel, a screen saver must have the .scr file name extension; to be run as a standalone application, it must have the .exe file name extension.) The icon must be identified in the screen saver's resource file by the constant ID_APP, which is defined in the Scrnsave.h header file.

One final requirement is a screen saver description string. The resource file for a screen saver must contain a string that the 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

This section uses example code taken from a screen saver application to illustrate the following tasks:

  • Creating a Screen Saver
  • Installing New Screen Savers
  • Adding Help to the Screen Saver Configuration Dialog

Creating a Screen Saver

At intervals ranging from 1 through 10 seconds, the application in this example 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 selecting the application's configuration dialog box and adjusting a single horizontal scroll bar.

Screen saver library

The static screen saver functions are contained in the screen saver library. There are two versions of the library available, Scrnsave.lib and Scrnsavw.lib. You must link your project with one of these. Scrnsave.lib is used for screen savers that use ANSI characters, and Scrnsavw.lib is used for screen savers that use UNICODE characters. A screen saver that is linked with Scrnsavw.lib will only run on Windows platforms that support UNICODE, while a screen saver linked with Scrnsave.lib will run on any Windows platform.

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 thickness, 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 Shell Dlg"
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 to speed scroll bar */
    static HWND hOK;    /* handle to 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) file name. */

            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 to 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) file name. */

            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, the 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 to the Screen Saver Configuration Dialog

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.


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

Command-String Interface

Requesting Group Information


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 file name of the display driver in use when Program Manager last terminated. When Program Manager starts, it compares this value to the file name 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 this 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 don't need to 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. If no value is specified, the default is 0.
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. If no value is specified, the default setting is 0.
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. If no value is specified, the default setting is 0.

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. The application then 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.

Shell DDE Reference

The following sections describe Program Manager DDE command strings in detail. In the syntax blocks in these sections, brackets enclose optional parameters.

AddItem

CreateGroup

DeleteGroup

DeleteItem

ExitProgman

Reload

ReplaceItem

ShowGroup


AddItem

AddItem(CmdLine[,
Name[,IconPath[,IconIndex[,xPos,yPos[,DefDir[,
HotKey[,fMinimize[fSeparateMemSpace] ] ] ] ] ] ])

Instructs Program Manager to add an icon to an existing group. There is a limit of 50 items per group.

CmdLine
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
Title that is displayed below the icon in the group window.
IconPath
File name 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 this 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. If CmdLine specifies neither an executable file nor an associated executable file, Program Manager uses a default icon.
IconIndex
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
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
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
Name of the default (or working) directory. This parameter is a string.
HotKey
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.


CreateGroup

CreateGroup(GroupName[,CommonGroupFlag])

Instructs Program Manager to create a new group or activate the window of an existing group.

GroupName
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 that is currently logged on must have administrative privileges. If this parameter is 1 but the user does not have administrative privileges, the command fails. If no value is specified and if the user has administrative privileges, the default value of this parameter is 1 (common group). If no value is specified and the user does not have administrative privileges, the default value is 0 (personal group).

If the second parameter of this command specifies the path of the group file (as was required in Windows version 3.1), the parameter is ignored.


DeleteGroup

DeleteGroup(GroupName[,CommonGroupFlag])

Instructs Program Manager to delete an existing group.

GroupName
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. If no value is specified, this parameter defaults to 1 (common group). To delete a common group, the user that is currently logged on must have administrative privileges. If this parameter is 1 but the user does not have administrative privileges, the command fails.

If the second parameter of this command specifies the path of the group file (as was required in Windows version 3.1), the parameter is ignored.


DeleteItem

DeleteItem(ItemName)

Instructs Program Manager to delete an item from the currently active group.

ItemName
Item to delete from the currently active group.


ExitProgman

ExitProgman(bSaveGroups)

Instructs Program Manager to terminate if started by another application and, optionally, save its group information.

bSaveGroups
Boolean value that, if it is nonzero, causes Program Manager to save its group information before closing. If this parameter is zero, Program Manager does not save its group information.


Reload

Reload(GroupName[,CommonGroupFlag])

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.

GroupName
Group to be removed and reloaded. If no value is specified for this 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. If no value is specified, this parameter defaults to 1 (common group). To reload a common group, the user that is currently logged on must have administrative privileges. If this parameter is 1 but the user does not have administrative privileges, the command fails.


ReplaceItem

ReplaceItem(ItemName)

Instructs Program Manager to delete an item and record the position of the deleted item. Program Manager then adds a new item (specified by the next AddItem command) at this recorded position.

ItemName
Item to be deleted. Its position is recorded by Program Manager.


ShowGroup

ShowGroup(GroupName,ShowCommand[,CommonGroupFlag])

Instructs Program Manager to minimize, maximize, or restore the window of an existing group.

GroupName
Group window to be minimized, maximized, or restored.
ShowCommand
Action Program Manager is to perform on the group window. This parameter is an integer. It must have one of the following values:
1 | Activate and display the group window. If the window is minimized or maximized, Windows restores it to its original size and position.
2 | Activate the group window and display it as an icon.
3 | Activate the group window and display it as a maximized window.
4 | Display the group window in its most recent size and position. The window that is currently active remains active.
5 | Activate the group window and display it in its current size and position.
6 | Minimize the group window.
7 | Display the group window as an icon. The currently active window remains active.
8 | Display 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. If no value is specified, this parameter defaults to 1 (common group). To minimize, maximize, or restore a common group, the user that is currently logged on must have administrative privileges. If this parameter is 1 but the user does not have administrative privileges, the command fails.


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 Extensions

Microsoft® Win32®-based applications can extend the shell 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 file systems 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 a file or add commands to the context menu and File menu for a file.

Shell Extension Terms

Shell Extension Types

Registry Entries for Extending the Shell

Installing Handlers on Windows NT

How the Shell Accesses Shell Extension Handlers

Using Shell Extensions

Shell Extension Terms

You should be familiar with the following shell extension terms before proceeding.

  • File Object - 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 a file system; it may only appear that way. For example, printers, Control Panel applications, network shares, servers, and work groups 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 that 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 - The code that implements a particular shell extension.

Shell Extension Types

Microsoft® Windows® supports two groups of shell extensions. The first group is registered for each type of file.

  • Context Menu Handler - Adds items to the context menu for a particular file object. The context menu is displayed when the user clicks a file object with the right mouse button.
  • Icon Handler - Typically used to add instance-specific icons for file objects. They can also be used to add icons for all files belonging to the same class.
  • Data Handler - Provides a type-specific IDataObject interface to be passed to the OLE DoDragDrop function.
  • Drop Handler - Provides type-specific drop behavior to files that can accept drag-and-drop objects.
  • Property Sheet Handler - Adds 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 is associated with file operations such as move, copy, rename, and so on.

  • Copy Hook Handler - Called when a folder object is about to be copied, moved, deleted, or renamed. The handler can either allow or prevent the operation.
  • Drag-and-Drop Handler - A context menu handler 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.

Registry Entries for Extending the Shell

An application that creates and maintains files, such as a spreadsheet, word processor, 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 file name 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 file name extension, and the value (AWordProcessor) denotes the key name that contains the information about the application handling the file name 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 file name extension. (In this case, it is the .doc file name 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 the Default Icon for a Disk Drive

In Microsoft® Internet Explorer 4.0, the icon that is displayed for a disk drive can be modified by adding a key in the registry in the following location:

HKEY_LOCAL_MACHINE
    Software
        Microsoft
            Windows
                CurrentVersion
                    Explorer
                        <drive letter>
                            DefaultIcon

The <drive letter> indicates the letter of the drive that the icon is being specified for, such as "C". The default value of the DefaultIcon key is a string value that contains the path and file name of the module that contains the icon, followed by a comma and by the zero-based index of the icon. An example of this would be "c:\myapp.exe,2".

If the drive icon is changed programmatically, you should use the SHChangeNotify function to notify the shell that the icon has changed. Here's an example of how this is done:

SHChangeNotify(SHCNE_UPDATEITEM, SHCNF_PATH, TEXT("C:\"), NULL);

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 file that contains the icon and the index of the icon within the file. This file can be an executable, a dynamic-link library, or an icon file. The icon displayed for folders can not be modified.

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.

Modifying the Context Menu for a File Class

When the user clicks a file object with the right mouse button, the system displays a context menu for the object. This 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. A context menu handler adds dynamic items to a context menu.

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 first adding a shell key below the application identifier key of the file class and then adding verb value 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 file name 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 file name 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 file name, %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 open, print, explore, find, openas, and properties. The printto verb is also canonical, but it is never actually displayed. 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.

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 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 supports 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 file name 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 file type. 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 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 file name 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 registry database. 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. These special keys are described below. The GUID strings shown in the following examples are given for example purposes only. You must use your own GUIDs when registering your shell extensions. The "<name>" values are also for example purposes only. The name of the extension is not significant as long as it is unique among all of the other keys at the same level.

  • You can use the * key in the following manner to register handlers that the shell calls whenever it creates a context menu or property sheet for a file object.
    HKEY_CLASSES_ROOT
   * = *
      shellex
         ContextMenuHandlers
            <name> = {00000000-1111-2222-3333-00000000000001}
         PropertySheetHandlers
            <name> = {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 the Folder key to register a shell extension for all folders in the 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
         <name> = {00000000-1111-2222-3333-00000000000004}
      CopyHookHandlers
         <name> = {00000000-1111-2222-3333-00000000000005}
  • You can use the Drive key for the same registrations as the Folder key, but the Drive key is called only for root paths (for example, C: \).
  • You can use the Directory key for the same registrations as the Folder key, but the Directory key is only used for file system folders.
    • Version 4.71. Internet Explorer 4.0 adds a Background key to the Directory key. The Background key contains the following entries:
      shellex
    ContextMenuHandlers
        <name> = {00000000-1111-2222-3333-00000000000004}

      These entries affect actions that occur on the background of a file system folder view. For example, if you register a context menu handler under the Background key, the context menu handler will be called when the user right-clicks in a file system folder view in an area that does not contain any items.

  • You can use the AudioCD key for the same registrations as the Folder key. The AudioCD key affects items that represent an audio CD that is in the system's CD drive.
  • Version 4.71. Internet Explorer 4.0 adds an AllFileSystemObjects key. You can use the AllFileSystemObjects key for the same registrations as the Folder key. The AllFileSystemObjects key affects all objects in the file system.
  • 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).

Installing Handlers on Windows NT

Because shell extensions handlers run in a system process, namely the shell process, Microsoft® Windows NT® administrators require control over which shell handlers are allowed to run. Administrators have control over which shell handlers can run in much the same way they control which device drivers can run.

For the Windows NT shell to recognize and run a shell extension handler, you must follow the instructions in Registering Shell Extensions. Then the handler's CLSID must also be listed under another new registry key. 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 (for example: {00000000-1111-2222-3333-00000000000002}). 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; it only checks for 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, 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 for the application to function properly, 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, you do not need to write the CLSID to this key, although doing so is harmless. Note, however, that the key may not exist in a Windows 95 installation, so if your setup application does attempt to write 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 permission 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 new shell.
          //
     }

     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);

     }
}

How the Shell Accesses Shell Extension Handlers

The shell uses one of two interfaces to initialize instances of shell extensions: IShellExtInit or 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. The IPersistFile interface is defined by OLE.

The IShellExtInit interface adds an additional member function, Initialize, to the standard IUnknown interface. A handler should keep a copy of any necessary parameters that the shell passes to Initialize for later use. The values passed to Initialize will vary depending on the type of handler being initialized.

The following example shows how to initialize instances.

 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();

      // Get the file associated with this object, if applicable.
      STGMEDIUM   medium;
      FORMATETC   fe = {CF_HDROP, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL};
      UINT        uCount;

      if(SUCCEEDED(m_pDataObj->GetData(&fe, &medium)))
      {
         // Get the file name from the HDROP.
         uCount = DragQueryFile((HDROP)medium.hGlobal, (UINT)-1, NULL, 0);
         if(uCount)
            DragQueryFile((HDROP)medium.hGlobal, 0, m_szFile, sizeof(m_szFile));

         ReleaseStgMedium(&medium);
      }
   }

   // Duplicate the registry handle.
   if (hRegKey)
      RegOpenKeyEx(  hRegKey,
                     NULL,
                     0L,
                     MAXIMUM_ALLOWED,
                     &m_hRegKey);

   return NOERROR;
}

A shell extension handler must implement three functions: an entry point 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-specific
    // 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 Platform Software Development Kit (SDK). The following example shows how to expose the class factory.

// DllGetClassObject - a DLL entry point 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;
    }
}

Using Shell Extensions

The following sections describe how to program the handlers supported by the shell. These sections assume you are familiar with the registry, C++, and OLE COM.

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. They have different purposes but the same implementation. When a user right-clicks a file object, context menu extensions are used; when a user drags a file object with the right mouse button, drag-and-drop handlers are used. This section describes the types of context menu handlers, how they can be used, how to add them to the registry, and the interfaces that they must implement.

Context menu extensions

When the user right-clicks an item in the shell's namespace (a file, directory, server, or work group, for example), the shell creates the default context menu for the type of item. The shell then loads context menu extensions that are registered for the type (and its base type) so that the extensions can add extra menu items. The context menu extensions are registered at the following location:

HKCR\{ProgID}\shellex\ContextMenuHandlers

The 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 the right mouse button. The menu items can be either class-specific (applicable to all files of a particular type) or instance-specific (applicable to an individual file).

When the user right-clicks a file object, the system passes the handle to the object's context menu to the context menu handler, which can only add items to the menu. You must not delete or modify existing menu items because other handlers may add items either before or after this one does. In addition, the shell adds items to the menu after all context menu handlers have been called.

You enter a context menu handler 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 methods, the context menu handler interface uses the QueryContextMenu, InvokeCommand, and GetCommandString methods.

When the shell 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 method. The menu handle to which any menu items should be added is provided in the hMenu parameter. Menu items are inserted by position starting at the indexMenu position. All menu items must be string items (MF_STRING). To avoid command conflicts, the command identifier for each menu item must be between the idCmdFirst and idCmdLast parameters, inclusive. The uFlags parameter contains a flag that indicates what type of operation is being performed.

If successful, QueryContextMenu returns an HRESULT value that contains SEVERITY_SUCCESS in the severity section and the largest menu item identifier plus one in the code section. The shell will use the return value as the idCmdFirst for the next context menu handler's QueryContextMenu, if necessary. Therefore, all of the command identifiers between idCmdFirst and the return value minus one cannot be used for other context menu handlers. A context menu handler should attempt to use sequential command identifiers so that the largest number of identifiers will remain available. The following example shows a typical QueryContextMenu implementation.

STDMETHODIMP CShellExt::QueryContextMenu(HMENU hMenu, UINT indexMenu,
UINT idCmdFirst, UINT idCmdLast, UINT uFlags)
{
   UINT idCmd = idCmdFirst;
   char szMenuText1[64];
   char szMenuText2[64];
   char szMenuText3[64];
   char szMenuText4[64];
   BOOL bAppendItems=TRUE;

   if ((uFlags & 0x000F) == CMF_NORMAL)
   {
      lstrcpy(szMenuText1, "New menu item 1, Normal File");
      lstrcpy(szMenuText2, "New menu item 2, Normal File");
      lstrcpy(szMenuText3, "New menu item 3, Normal File");
      lstrcpy(szMenuText4, "New menu item 4, Normal File");
   }
   else if (uFlags & CMF_VERBSONLY)
   {
      lstrcpy(szMenuText1, "New menu item 1, Shortcut File");
      lstrcpy(szMenuText2, "New menu item 2, Shortcut File");
      lstrcpy(szMenuText3, "New menu item 3, Shortcut File");
      lstrcpy(szMenuText4, "New menu item 4, Shortcut File");
   }
   else if (uFlags & CMF_EXPLORE)
   {
      lstrcpy(szMenuText1, "New menu item 1, Normal File right click in Explorer");
      lstrcpy(szMenuText2, "New menu item 2, Normal File right click in Explorer");
      lstrcpy(szMenuText3, "New menu item 3, Normal File right click in Explorer");
      lstrcpy(szMenuText4, "New menu item 4, Normal File right click in Explorer");
   }
   else
   {
      bAppendItems = FALSE;
   }

   if (bAppendItems)
   {
      // Insert a separator
      InsertMenu(hMenu, indexMenu++, MF_SEPARATOR | MF_BYPOSITION, 0, NULL);

      // Insert the menu items
      InsertMenu(hMenu, indexMenu++, MF_STRING | MF_BYPOSITION, idCmd++, szMenuText1);
      InsertMenu(hMenu, indexMenu++, MF_STRING | MF_BYPOSITION, idCmd++, szMenuText2);
      InsertMenu(hMenu, indexMenu++, MF_STRING | MF_BYPOSITION, idCmd++, szMenuText3);
      InsertMenu(hMenu, indexMenu++, MF_STRING | MF_BYPOSITION, idCmd++, szMenuText4);

      // Must return the greatest menu item identifier plus one.
      return MAKE_HRESULT(SEVERITY_SUCCESS, 0, idCmd);
   }

   return NOERROR;
}

When the user selects one of the menu items added by a context menu handler, the shell calls the handler's InvokeCommand method 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. 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))
   {
      switch (LOWORD(lpcmi->lpVerb))
      {
         case 0:
            hr = DoMenu1(lpcmi->hwnd, lpcmi->lpDirectory,
                  lpcmi->lpVerb, lpcmi->lpParameters, lpcmi->nShow);
            break;

         case 1:
            hr = DoMenu2(lpcmi->hwnd, lpcmi->lpDirectory,
                  lpcmi->lpVerb, lpcmi->lpParameters, lpcmi->nShow);
            break;

         case 2:
            hr = DoMenu3(lpcmi->hwnd, lpcmi->lpDirectory,
                  lpcmi->lpVerb, lpcmi->lpParameters, lpcmi->nShow);
            break;

         case 3:
            hr = DoMenu4(lpcmi->hwnd, lpcmi->lpDirectory,
                  lpcmi->lpVerb, lpcmi->lpParameters, lpcmi->nShow);
            break;
      }
   }
   return hr;
}

Windows calls the GetCommandString method to retrieve a language-independent command string or the Help text for a context menu item.

Modifying the Find submenu

The Start menu and Windows Explorer's Tools menu contain a Find submenu that includes all of the registered search applications. If your application includes a search utility, you can add an item under this menu to allow the user to access your search utility without launching or switching to your application. These types of extensions are called Find extensions. There are two types of Find extensions—static and dynamic.

Static Find extensions

A static Find extension will only be loaded when the user selects one of the Find commands. This will slow the Find submenu creation and the execution of the command. The static method is best if your extension DLL is small and can load quickly. You add a static Find extension by making a registry entry under:

HKEY_LOCAL_MACHINE
   Software
      Microsoft
         Windows
            CurrentVersion
               Explorer
                  FindExtensions
                     Static

You create a unique key under this key. The key name is not significant as long as it is unique among the other key names at the same level. The value for this key is a string that contains the class identifier of the context menu handler. Under this key, you create one or more command keys. The command key name corresponds to the command identifier for the menu item. For example, a name of "0" (zero) corresponds to a command identifier of 0. More than one command key can be created, but the commands must start at 0 and be sequential. The value for each command key is a string that contains the text that will be displayed in the menu. This text can also contain an "&" character in front of the desired accelerator character.

The Start menu's Find submenu can display small icons next to the command string for the Find command. The icon that is displayed is entered in the registry under your static Find extension's command key (the numeric entry described in the previous paragraph) by inserting a key under the command key named "DefaultIcon". The default string value for this key is the path and file name of the module containing the icon, followed by a comma and then a number the represents the zero-based index of the icon in the module. The following example shows a static Find extension that registers one command and an associated icon.

HKEY_LOCAL_MACHINE
   Software
      Microsoft
         Windows
            CurrentVersion
               Explorer
                  FindExtensions
                     Static
                        MyFind (default value = "<clsid>")
                           0 (default value = "&My Find Utility")
                              DefaultIcon (default value = "c:\MyFind.dll,0")

When the user selects Find from the Tools menu, the browser enumerates the keys under the FindExtensions\Static key and adds the registered menu items. When the user selects one of the Find commands, the browser loads the context menu handler specified by the class identifier and calls IContextMenu::InvokeCommand. The low-order word of the lpVerb member of the CMINVOKECOMMANDINFO structure passed to InvokeCommand contains the numeric representation of the command key name. In response to the command, the context menu handler launches the find utility.

Dynamic Find extensions

A dynamic Find extension is loaded when the shell loads at startup, and it is kept loaded until the shell exits. This can slow the load time of the shell, but the responsiveness of the Find submenu creation and the execution of the command will be increased. The dynamic method is best if your extension DLL may take a long time to load or if it is likely to be loaded and unloaded often. You add a dynamic Find extension by creating a registry entry under:

HKEY_LOCAL_MACHINE
   Software
      Microsoft
         Windows
            CurrentVersion
               Explorer
                  FindExtensions

You create a unique key under this key. The key name is not significant as long as it is unique among the other key names at the same level. The default value for this key is a string that contains the class identifier of the context menu handler. The following example shows a properly registered dynamic Find extension.

HKEY_LOCAL_MACHINE
   Software
      Microsoft
         Windows
            CurrentVersion
               Explorer
                  FindExtensions
                     MyFind (default value = "<clsid>")

The loading of a dynamic Find extension occurs in the same manner as a file-based context menu extension except that the pidlFolder and lpdobj arguments in the extension's IShellExtInit::Initialize will be NULL. When the menu is built, the extension is loaded and initialized and the extension's IContextMenu::QueryContextMenu is called to add the item(s) to the Find menu. When the user selects an item, the proper extension's IContextMenu::InvokeCommand is called with the proper menu identifier. In response to the command, the context menu handler launches the Find utility.

Menu icons are not supported for dynamic Find extensions.

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 that affects the menu the shell displays when a user drags a file object with the right mouse button. 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 folder type key (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 displayed for folders cannot be modified.

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.

An application can also 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 IExtractIcon interface has the IExtractIcon::GetIconLocation and IExtractIcon::Extract methods in addition to the usual IUnknown methods.

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 method.
  4. Uses the QueryInterface method to retrieve the IExtractIcon interface.
  5. Calls the GetIconLocation and Extract methods.

The system calls the GetIconLocation method to get the location and index of an icon to display. Typically, the icon location is an executable or DLL file name, but it can be any file.

The system calls the Extract method 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 method as a return-only function that returns the E_FAIL error value. You only need to implement the Extract method 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 method.

Property Sheet Handlers

Another way the shell can be extended is with 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 contains 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 implements the AddPages method in addition to the usual IUnknown methods. The system calls the AddPages method when a property sheet is about to be displayed. 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 a typical implementation of the AddPages method:

STDMETHODIMP CSamplePageExt::AddPages(LPFNADDPROPSHEETPAGE lpfnAddPage, LPARAM lParam)
{
   PROPSHEETPAGE  psp;
   HPROPSHEETPAGE hpage;

   // Size of the structure.
   psp.dwSize = sizeof(psp);

   // Flags.
   psp.dwFlags = PSP_USEREFPARENT;

   // Instance handle to the DLL that contains the property page dialog resource.
   psp.hInstance = (HINSTANCE)g_hinstDll;

   // Identifier of the property page dialog resource.
   psp.pszTemplate = MAKEINTRESOURCE(IDD_PAGE);

   // Address of the dialog procedure.
   psp.pfnDlgProc = DlgProc;

   /*
   Allow the shell access to the reference count. This prevents the
   DLL from being unloaded while the property page still exists.
   */
   psp.pcRefParent = &g_cRefThisDll;

   // Application-defined data.
   psp.lParam = (LPARAM)this;

   hpage = CreatePropertySheetPage(&psp);
   if (hpage)
   {
      if (!lpfnAddPage(hpage, lParam))
         DestroyPropertySheetPage(hpage);
   }
   return NOERROR;
}

Replacing Control Panel pages

The ReplacePage method 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 Buttons page in the Control Panel's Mouse Properties property sheet. The ReplacePage method is not called by the shell because the shell does not have any property pages that can be replaced by a shell extension. Currently, only Control Panel applications call this method, but other property sheet suppliers could use it to allow their property pages to be replaced.

Each property sheet handler that allows a property 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 page replacement handlers must register. For example, a property sheet handler that needs to replace a property page in the Mouse Properties 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 replaceable property page: Mouse for a Mouse Properties Control Panel application and Keyboard for a Keyboard Properties Control Panel application.

Standard Control Panel applications define replaceable page identifiers in Cplext.h. For example, CPLPAGE_MOUSE_BUTTONS is the identifier for the Buttons page in the Mouse Properties property sheet, and CPLPAGE_KEYBOARD_SPEED is the identifier for the Speed page in the Keyboard Properties property sheet.

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; it only approves the task. When the shell receives approval from the copy hook handler, the shell performs the actual file system operation (copies, moves, deletes, or renames). Copy hook handlers are not informed about the success of an operation, so they cannot monitor actions that occur on folder objects.

The shell initializes the copy hook handler interface directly, without using an IShellExtInit or IPersistFile interface first. A folder object can have multiple copy hook handlers. The copy hook handler interface has one method—CopyCallback—in addition to the standard IUnknown methods.

The shell calls the CopyCallback method before it copies, moves, deletes, or renames a folder object. The method 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 method. When a data handler is provided, the default IDataObject interface delegates some method 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. However, 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 method. 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 methods 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 following example:

shellex
    DropHandler = {00000000-1111-2222-3333-00000000000003}


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

Shell Library Reference

About the Shell Library

The following features are supported by the dynamic-link library Shell.dll:

  • The drag-and-drop feature.
  • Associations used to find and start applications.
  • Extraction of icons from executable files.

Using the Drag-and-Drop Feature

When an application implements the drag-and-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 file names 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 to a structure that 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-and-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 file name 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 file name extension that is associated with an application, that application starts automatically whenever the 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 to the executable file that is associated with a specified file name. 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 file name extension.

You can use ShellExecute to open or explore a 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", the function will open the file in a new window. If lpOperation is "explore", the function will browse to the folder using an existing Explorer window, if one is open. If an Explorer window is not open, a new one will be created.

Extracting Icons from Executable Files

An application can use the ExtractIcon function to retrieve the handle to 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 file name of a dropped file, and the ExtractIcon function to retrieve the handle to 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 programming elements are associated with shell features.

Shell Library Functions

The following functions are used to implement shell features.
DragAcceptFiles
DragFinish
DragQueryFile
DragQueryPoint
ExtractAssociatedIcon
ExtractIcon
ExtractIconEx
FindExecutable
ShellAbout
ShellExecute
ShellExecuteEx

Shell Library Messages

The following message is used to implement shell features.
Message | Description
WM_DROPFILES | Sent to the window that the mouse is over when the user drops an item or items on the window. See the WM_DROPFILES description for more information.

Shell Library Structures

The following structure is used to implement shell features.
SHELLEXECUTEINFO


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 types of objects that can be accessed through shell links include files, folders, disk drives, and printers. A shell link allows a 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

Using Shell Links

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 that is located in a subfolder and place the shortcut icon on the desktop. The user can then open the document by double-clicking the shortcut icon. If the document is moved or renamed after the shortcut is created, the system will attempt 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. The application uses the IPersistFile or IPersistStream interface to store the object in a file or stream.

This overview describes the IShellLink interface and explains how to use it to create and resolve shell links from within a Microsoft® Win32®-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 overview.

Link Resolution

If a user creates a shortcut to an object and the name or location of the object is later 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 method.

When a shell link is created, the system saves information about the link. When resolving a link (either automatically or with an IShellLink::Resolve call), 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.) 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 an object with either the same name or creation time. If the system still does not find a match, 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 file name for the object. If the object is stored remotely, the system provides a 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—a binary file that has the .lnk file name extension. A link file contains the following information:

  • The location (path) of the object referenced by the shortcut (called the corresponding object).
  • The working directory of the corresponding object.
  • The list of arguments that the system passes to the corresponding object when the IContextMenu::InvokeCommand method is activated for the shortcut.
  • The show command used to set the initial show state of the corresponding object. This is one of the SW_ values described in ShowWindow.
  • 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. In this case, the shortcuts will not be independent of each other.

An application can register a file name extension as a shortcut file type. If a file has a file name 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 file name extension as a shortcut file type, you must add the IsShortcut value to the registry description of the file name extension, as shown in the example below. Note that the shell must be restarted for the overlay icon to take effect.

HKEY_CLASSES_ROOT
  .xyz    (Default) = "XYZApp"
  .
  .
  .
  XYZApp  IsShortcut = ""

Shortcut names

The shortcut's name, which is a string that appears below the shell link icon, is actually the file name of the shortcut itself. The user can edit the description string by selecting it and entering a new string.

Location of shortcuts 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 method to set the path and file name for the associated object, and the IShellLink::GetPath method to retrieve the current path and file name for the object.

Shortcut 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 method and can retrieve the name of the current working directory for the corresponding object by using the IShellLink::GetWorkingDirectory method.

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

Shortcut show commands

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 method and can retrieve the current show command by using the IShellLink::GetShowCmd method.

Shortcut icons

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 method. An application can retrieve this location by using the IShellLink::GetIconLocation method.

Shortcut descriptions

Shortcuts have descriptions, but the user never sees them. An application can use a description to store any text information. Descriptions are set using the IShellLink::SetDescription method and retrieved using the IShellLink::GetDescription method.

Shortcut hot keys

A shortcut object can have a hot key associated with it. Hot keys allow a user to press a combination of keys to activate a shortcut. An application can set the hot key for a shortcut by using the IShellLink::SetHotkey method and can retrieve the current hot key by using the IShellLink::GetHotkey method.

Item Identifiers and Identifier Lists

The shell uses object identifiers within the shell's namespace. All objects visible in the shell (files, directories, servers, workgroups, and so on) have unique identifiers among the objects within their 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 that identifies 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 it contains. 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 its parent folder.

An application can set a shortcut's item identifier list by using the IShellLink::SetIDList method. This method 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 method.

Using Shell Links

This section contains examples that demonstrate how to create and resolve shortcuts from within a Win32-based application. This section assumes you are familiar with Win32, C++, and OLE COM programming.

Creating a Shortcut to a File

The CreateLink sample 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 file name," where file name 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 file name 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 previously created. 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 is shown 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 Shortcut to a Nonfile Object

Creating a shortcut to a nonfile object, such as a printer, is similar to creating a shortcut to a file except that rather than setting the path to the file, you must set the identifier list to the printer. To set the identifier list, call the IShellLink::SetIDList method, specifying the address of an identifier list.

Each object within the shell's namespace has an item identifier. The shell often concatenates item identifiers into null-terminated lists consisting of any number of item identifiers. For more information about item identifiers, see Item Identifiers and Identifier Lists.

In general, if you need to set a shortcut to an item that does not have a file name, such as a printer, you will already have a pointer to the object's IShellFolder interface. IShellFolder is used to create namespace extensions.

Once you have the class identifier for IShellFolder, 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.


Shell Namespace

A namespace is a collection of symbols, such as database keys or file and directory names. The shell uses a single hierarchical namespace to organize all objects of interest to the user, including files, storage devices, printers, network resources, and anything else that can be viewed using Microsoft® Windows® Explorer. The root of this unified namespace is the desktop.

In many ways, the shell namespace is analogous to a file system's directory structure. However, the namespace contains more types of objects than just files and directories. This overview discusses some of these associations, outlines the organization of the shell namespace, and describes the functions and interfaces associated with the namespace.

Folders and File Objects

Item Identifiers and Pointers to Item Identifier Lists

Folder Locations

Item Enumeration

Display Names

Object Attributes and Interfaces

Using the Shell Namespace

Extending the Shell Namespace

Shell Namespace Reference

Folders and File Objects

A folder is a collection of items in the shell 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 can contain other folders as well as items called file objects. Examples of file objects are Control Panel applications, printers, and actual files. Each type of folder can only contain certain kinds of file objects; for example, a Control Panel application can only exist in the Control Panel folder. It cannot exist in a file system directory.

Because there are many kinds of folders and file objects, each folder is an OLE component object model (COM) object that can 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. When an object's IShellFolder interface is obtained, the interface must eventually be freed by calling its Release method.

You can bind to the desktop folder (retrieve the folder's IShellFolder interface) by using the SHGetDesktopFolder function. You can enumerate subfolders by using the IShellFolder::EnumObjects method. You can bind to a subfolder of any given folder by using the IShellFolder::BindToObject method. Using these three functions, an application can navigate throughout the entire shell namespace.

Item Identifiers and Pointers to Item Identifier Lists

Objects in the shell 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 namespace by tracing a path to the item from a known point—usually the desktop. A pointer to an item identifier list (PIDL) is used throughout the shell to identify an item.

Item identifiers and PIDLs are much like the file names and paths, respectively, 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 that can be shown to the user (called display names) are described in Display Names.

An item identifier is defined by the variable-length SHITEMID structure. The first two bytes specify the identifier's size, and the format of the remaining bytes depends on the software that implements the parent folder's IShellFolder interface. Except for the first two bytes, item identifiers are not strictly defined, and you should make no assumptions about their format when designing applications. To determine whether two item identifiers are equal, your application can use the IShellFolder::CompareIDs method.

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 byte-aligned ITEMIDLIST structures, followed by a 16-bit zero value. An application can traverse 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 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 your responsibility to make sure the application frees the PIDL that is using the shell's allocator. Note that the SHGetMalloc function retrieves the task allocator for OLE applications.

Folder Locations

Many folders have special meanings to 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 the Control Panel and Printers, that are not part of the file system.

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 (see SHGetMalloc). If the folder is part of the file system, you can convert the PIDL to a file system path 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. Your application can use this function to prompt the user for a directory or remote computer. This function can also be used to browse for network printers, though printers are not considered folders. The application can specify the root folder in which to browse. For example, to prompt the user for a program group, you could call SHBrowseForFolder, specifying the PIDL for the Programs folder as the root.

Item Enumeration

A folder's IShellFolder interface can be used to determine the folder's contents by using the IShellFolder::EnumObjects method. This method 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 method. Calling this function repeatedly allows an application to retrieve all of the item identifiers, one or more at a time. Using other methods, you can skip items in the sequence, return to the beginning of the sequence, or make a copy of the enumeration object to save its state.

When you are finished using the enumeration object, you must free it by calling the Release method.

Display Names

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 methods in the IShellFolder interface to retrieve an item's display name, to find an item with a specified display name, or to change an item's display name.

The IShellFolder::GetDisplayNameOf method 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 enumeration.

There is a special type of display name that can be converted back to an item identifier by using the IShellFolder::ParseDisplayName method. You might use this type of display name as a parameter to the ShellExecute function or as a command-line argument for an application.

The IShellFolder::SetNameOf method 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.

The SHGNO enumeration consists of two sets of values. The first set is contained in bits 0 through 7 and specifies if the name is relative to this folder or if the name is a full name. The second set is contained in bits 8 through 15 and is a modifier to the first set that specifies what the name will be used for. Here is an example of how an IShellFolder::GetDisplayNameOf implementation might handle this enumeration:

#define GET_SHGDN_FOR(dwFlags)         ((DWORD)dwFlags & (DWORD)0x0000FF00)
#define GET_SHGDN_RELATION(dwFlags)    ((DWORD)dwFlags & (DWORD)0x000000FF)

STDMETHODIMP CShellFolder::GetDisplayNameOf( LPCITEMIDLIST pidl,
                                             DWORD dwFlags,
                                             LPSTRRET lpName)
{
switch(GET_SHGDN_FOR(dwFlags))
   {
   case SHGDN_FORPARSING:
      switch(GET_SHGDN_RELATION(dwFlags))
         {
         case SHGDN_NORMAL:
            //get the full name
            GetParsingFullName(pidl, lpName->cStr, sizeof(lpName->cStr));
            break;

         case SHGDN_INFOLDER:
            //get the relative name
            GetParsingRelativeName(pidl, szText, sizeof(szText));
            break;

         default:
            return E_INVALIDARG;
         }
      break;

   case SHGDN_FORADDRESSBAR:
      switch(GET_SHGDN_RELATION(dwFlags))
         {
         case SHGDN_NORMAL:
            //get the full name
            GetAddressBarFullName(pidl, lpName->cStr, sizeof(lpName->cStr));
            break;

         case SHGDN_INFOLDER:
            //get the relative name
            GetAddressBarRelativeName(pidl, lpName->cStr, sizeof(lpName->cStr));
            break;

         default:
            return E_INVALIDARG;
         }
      break;

   case SHGDN_NORMAL:
      switch(GET_SHGDN_RELATION(dwFlags))
         {
         case SHGDN_NORMAL:
            //get the full name
            GetNormalFullName(pidl, lpName->cStr, sizeof(lpName->cStr));
            break;

         case SHGDN_INFOLDER:
            //get the relative name
            GetNormalRelativeName(pidl, lpName->cStr, sizeof(lpName->cStr));
            break;

         default:
            return E_INVALIDARG;
         }
      break;
   }

lpName->uType = STRRET_CSTR;

return S_OK;
}

Object Attributes and Interfaces

Every file object and folder has attributes that determine, among other things, what actions can be carried out on it. Your application can obtain the attributes of any file object or folder and can retrieve interfaces for items in a shell folder.

To obtain the attributes of a file object or folder, your application can use the IShellFolder::GetAttributesOf method. Information obtained by this method includes 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), and 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 method.

Your application can retrieve interfaces that carry out actions on a file object or folder by using the IShellFolder::GetUIObjectOf method. This method can be used to retrieve the IContextMenu, IExtractIcon, IDataObject, or IDropTarget interface for the object.

Using the Shell Namespace

This section contains examples that demonstrate the functions and interfaces associated with the shell namespace. The code samples given here are for demonstration purposes only. If you wish to use them in your application, you must enhance them to perform proper error and parameter checking.

Using PIDLs and Display Names

This section presents an example illustrating how to retrieve the location of a special folder, traverse an item identifier list, and use the IShellFolder interface to retrieve display names. The example is a 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 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. Traverse 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, your application should retrieve a pointer to the shell's IMalloc interface (which is saved in the g_pMalloc global variable) by using the SHGetMalloc function.

The following example shows the application's main function. This function carries out all of the steps described previously using the application-defined GetNextItemID and CopyItemID functions to traverse the item identifier list and the application-defined PrintStrRet function to print the display names. Code for these application-defined functions is shown following the code for the main function.

#include <conio.h>
#include <stdio.h>
#include <shlobj.h>

// Global pointer to the shell's IMalloc interface.
LPMALLOC g_pMalloc;

// main - the application's entry-point 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, this function returns a pointer to the next element (or NULL if there are no more elements). The main function calls this function to traverse 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.
// pidl - 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, this 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 interface methods.

// 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 method 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 lpStr->uType is 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_ACP,
                                    0,
                                    lpStr->pOleStr,
                                    -1,
                                    NULL,
                                    0,
                                    NULL,
                                    NULL);
         lpsz = (LPSTR) g_pMalloc->lpVtbl->Alloc(g_pMalloc, cch);
         if (lpsz != NULL)
            {
            WideCharToMultiByte( CP_ACP,
                                 0,
                                 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 to 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);
}

Extending the Shell Namespace

A namespace extension provides a way for you to define a new object that a browser, such as Windows Explorer, can view. The code you provide and the registry entries you make define the icon images and text that the user sees while viewing your data. It also defines the menus, toolbars, and status information that apply to your data objects.

One of the reasons it is relatively easy to extend the shell namespace is that Windows Explorer can be viewed as two independent parts: the browser code and the system namespace provider code. Because these parts were written polymorphically and communicate by using COM-based interfaces, they do not depend on each other's implementation. Thus, anyone can provide either browser code that browses the system namespace or a system namespace extension that can be browsed using Windows Explorer.

Your extension has to provide Windows Explorer with the icons, names, and details that you want to represent the items in your namespace. It can provide Explorer with a custom context menu for your data as well as drag-and-drop capabilities. It is important to remember that only you know the contents of the items in your namespace. Therefore, Explorer cannot make any assumptions about these objects and can only display the information that you provide.

Structuring a Namespace Extension

As is the case with shell extensions, a namespace extension is implemented as a COM in-process server DLL. To implement even the simplest extensions, you should have experience with COM and OLE, and you should be knowledgeable about the behavior of Windows Explorer. You must also properly register your extension, or it will not work.

Remember that the construction of an in-process server DLL requires the implementation of a DLL that exports the following functions:

  • DllGetClassObject
  • DllCanUnloadNow

The DLL also implements an object that exposes the IClassFactory interface for the creation of the other objects contained in the DLL. Those objects will expose the IUnknown interface and any other interfaces necessary to implement a namespace extension, including IPersistFolder, IShellFolder, IEnumIDList, and IShellView. These interfaces allow Windows Explorer and your extension to interact.

It is important to remember that Windows Explorer communicates with your extension by using the IShellFolder and IShellView interfaces you have implemented in your extension. The IShellBrowser interface (implemented by Explorer), allows your extension to communicate with Explorer. This is very similar to site-type interfaces commonly found in OLE hosting situations.

Beyond these required interfaces, your extension will need to implement other interfaces that will be created by the IShellFolder object. These include IExtractIcon to provide icons, IContextMenu to provide context menus for your items, drag-and-drop interfaces ( IDropSource and IDropTarget), and IDataObject for data transfer.

Studying examples of in-process server DLLs, especially any that contain namespace or shell extensions, is helpful in learning to build namespace extension DLLs. The RegView sample included with the Internet Client SDK is a good example of a namespace extension.

Identifying Items in the Namespace

One of the operations that must be handled when you are extending the shell namespace is the enumeration of items. A call to the IShellFolder::EnumObjects method returns an IEnumIDList interface that will return a set of identifiers for the items within a specific folder. Called a shell item IDLIST, it is an array of bytes that contains enough data to identify items by the parent folder. Only the first two bytes are defined, and they contain the size of the identifier list. The rest of the identifier list contains data that is specific to the folder implementation. This data has no meaning to the caller.

A shell item IDLIST must contain sufficient information to identify an object within a folder, but it may also contain additional information for efficient manipulation (such as sorting or retrieving display names). You have the option to store additional information in the shell IDLIST because Windows Explorer does not compare two item identifiers directly for either sorting or identification. Instead it uses IShellFolder::CompareIDs to perform this task.

Nonrooted and Rooted Explorers

Your namespace extension can be implemented in one of two ways: you can implement your extension so the user can view it using the standard Windows Explorer, or you can create a completely separate namespace. There are no set criteria for determining which to use; you should evaluate which is more logical and better suited for your particular application.

If you choose to implement your extension so the user can browse into it using the standard Explorer, your new namespace is presented as a subnamespace to the system namespace already present. Since the Desktop is the root folder of the system's namespace, it also serves this purpose for your extension. Accordingly, your extension resides within the existing hierarchy of objects on the desktop and appears to the user as just another item in the system namespace.

If you analyze your application and determine that implementing a completely separate namespace makes more sense, the user will not be able to view it without running a special instance of Windows Explorer rooted in an item of your choosing. The rooted Explorer's top level is referred to as a junction point. The junction point can be a file or a folder, but if the extension uses any junction point, it is, by definition, rooted. This is because Explorer does not support browsing directly into files.

As noted earlier, you should decide whether to implement your extension as rooted or nonrooted based on which implementation will work best for your application. There are no set rules. If your extension logically blends into the existing hierarchy of objects, a nonrooted Explorer might be best. If not, it will probably be better to implement a rooted Explorer with a specific file as your entry point to the new namespace.

Creating a junction point

Creating a junction point can be done in several different ways, depending on the item you choose for the junction point, such as a file or directory. For example, to make a junction point in either the Desktop or the My Computer folder, add the following key to the registry:

HKEY_LOCAL_MACHINE
    SOFTWARE
        Microsoft
          Windows
            CurrentVersion
               Explorer
                  [MyComputer or Desktop]
                       {CLSID}

You can also use a directory as your junction point. If your operating system supports long file names, you can use the CLSID of your namespace extension as the file extension of a folder (MyFolder.{20D....}. Otherwise, you can create a directory, change its file attributes to read-only, and place a file called Desktop.ini in it. This simple text file is made up of the following:

[.ShellClassInfo]

CLSID={clsid}

Opening a rooted Windows Explorer

To open a rooted Windows Explorer for the namespace you have created, you must provide a way to start the new instance of Explorer.exe using the /root switch on the command line. There are several ways to accomplish this. For example, you can call ShellExecute directly, or you can create a shortcut file that contains one of the following as a command line.

  • If the junction point is an item under the desktop:
    explorer.exe /e,/root,::{CLSID of item}
  • If the junction point is an item under My Computer:
    explorer.exe /e,/root,,::{20D04FE0 - 3AEA - 1069 - A2D8 - 08002B30309D}
           \::{CLSID of item}}
  • If the junction point is a file system folder:
    explorer.exe /e,/root, [path to a junction point]

When Windows Explorer is opened using the /root::{CLSID} option, it sets the junction point object as the root of the hierarchy and calls the IShellFolder interface.

When the user opens a junction point object or one of its subfolders, Windows Explorer causes the extension to create a view object by calling the IShellFolder::CreateViewObject method and requesting an IShellView interface. Explorer then calls the IShellView::CreateViewWindow method to cause the extension to create the view window of the folder. One of the parameters passed is a pointer to the IShellBrowser interface, which allows the extension to communicate with Explorer. The view object is able to do any combination of the following: add menu items to the menu bar, add toolbar buttons, display status information on the status bar, and process shortcut keys.

UI Negotiation (Menu, Toolbar, and Status Bar)

The mechanism to determine which items will appear in the view window while the contents are visible is similar to OLE in-place activation, but notable differences do exist. Three of them are discussed here.

First, the view window always exists, even if it does not have the input focus. Therefore, it should maintain three states:

  • Deactivated
  • Activated with the focus
  • Activated without the focus

The view window may present different sets of menu items depending on the focus state. Windows Explorer notifies the extension of state changes by calling the IShellView::UIActivate method. The view object should call the IShellBrowser::OnViewWindowActive method when the view window is activated by the user.

Second, Windows Explorer does not support layout negotiation. Instead, it allows the view window to add toolbar buttons or set status bar text. The view window can also create modeless pop-up windows, calling either the IShellBrowser::GetControlWindow or IShellBrowser::SendControlMsg method to control them. Explorer forwards appropriate notification messages from those controls by sending a WM_COMMAND message to the window returned by the IShellView::CreateViewWindow method.

Third, Windows Explorer allows the view window to add menu items to Explorer's pull-down menus (in addition to inserting top-level pull-down menus). In other words, the view object is allowed to insert menu items into submenus returned from the IShellBrowser::InsertMenusSB method. To let Explorer dispatch menu messages correctly, a certain range of menu item identifiers (between FCIDM_SHVIEWFIRST and FCIDM_SHVIEWLAST) must be used.

Persistent View State

Windows Explorer defines standard view states that can be used by a view implementation. These include:

  • View mode (such as large icon, small icon, and detail)
  • View attributes (such as snap to grid)

Windows Explorer provides a persistent medium in which to store these states, and although using them is not required, it is recommended. The settings are stored in a FOLDERSETTINGS structure. Explorer supplies the current settings to the view object with the IShellView::CreateViewWindow method. Explorer retrieves the view object's current settings by calling the IShellView::GetCurrentInfo method.

Windows Explorer also provides a persistent medium (a stream) to let the view object store view-specific information (such as scroll positions or icon layout). The view object can access this stream by calling the IShellBrowser::GetViewStateStream method.

When the user is browsing from one folder to another, Explorer passes the pointer to the previously viewed instance of the IShellView interface as a parameter to IShellView::CreateViewWindow (before calling the previous view's IShellView::DestroyViewWindow method). This allows the view object being created to determine if the previous view object is of a known type. It does this by calling the QueryInterface method to obtain an interface that is only known between the two objects. If the previous view object is of a known type, current private settings can be exchanged using an application-dependent method.

Registering Your Namespace Extension

Registering your extension is not difficult, but it must be done precisely or users will not be able to find your namespace extension.

Namespace extensions, like all COM objects, must be registered in the CLSID section. In addition, they must also have the named value ThreadingModel set to Apartment, as shown below.

HKEY_CLASSES_ROOT\CLSID\{CLSID}
HKEY_CLASSES_ROOT_CLSID\{CLSID}\InProcServer32\(default)=path\filename.dll
HKEY_CLASSES_ROOT_CLSID\{CLSID}	\InProcServer32\"ThreadingModel" = "Apartment"

If your namespace extension is going to run under a rooted Windows Explorer, you should add the following entries so the Open and Explore verbs appear on your namespace extension.

HKEY_CLASSES_ROOT_CLSID\{CLSID}\Shell\Open\Command\(default)
                  =c:\windows\explorer.exe/root,%1
HKEY_CLASSES_ROOT_CLSID\{CLSID}\Shell\Explore\Command\(default)
                  =c:\windows\explorer.exe/e,/root/%1

You can also include entries for the default icon under the following key:

HKEY_CLASSES_ROOT_CLSID\{CLSID}\DefaultIcon\(default)="path\filename.dll",IconIndex

The following is an optional key, but it's one that can be very important. If you include the "Attributes" named value under ...{CLSID}\ShellFolder, you specify the attributes of a junction point by using the SFGAO_* flags returned by the IShellFolder::GetAttributesOf method.

HKEY_CLASSES_ROOT_CLSID\{CLSID}\ShellFolder\Attributes = 0000 00 00

For example, if the SFGAO_FOLDER flag is set and its junction point exists in the system namespace, the user sees your extension's icon in Windows Explorer's left pane and is able to browse into it using the standard (nonrooted) Explorer. If this flag is not set, you must provide a rooted Explorer for browsing.

Another example is the SFGAO_HASSUBFOLDER flag. If it is set, Explorer can make the extension's icon expandable to the next level by displaying the "+" icon to its left.

Other registry entries you should know about include those required for putting items into My Computer or on the desktop. The following entries list all the items in those two locations:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer
               \MyComputer\NameSpace
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer
               \Desktop\NameSpace

Finally, the following entry is currently required only for Microsoft® Windows NT&rg, but it should always be added to the registry for future compatibility with all operating systems. This is the list of extensions that the shell will load. Extensions that don't appear on this list will not be loaded by the shell on Windows NT.

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WindowsNT\CurrentVersion\ShellExtensions
               \Approved\{CLSID}="Extension Name"

Shell Namespace Reference

The following programming elements are used with the shell namespace.

Interfaces
ICommDlgBrowser
IDockingWindow
IDockingWindowFrame
IDockingWindowSite
IEnumIDList
IPersistFolder
IShellBrowser
IShellExecuteHook
IShellFolder
IShellIcon
IShellView

Functions
BrowseCallbackProc
SHAddToRecentDocs
SHBrowseForFolder
SHChangeNotify
SHFileOperation
SHFreeNameMappings
SHGetDataFromIDList
SHGetDesktopFolder
SHGetFileInfo
SHGetInstanceExplorer
SHGetMalloc
SHGetPathFromIDList
SHGetSpecialFolderLocation
SHLoadInProc

Structures
BROWSEINFO
CIDA
FOLDERSETTINGS
SHFILEINFO
SHFILEOPSTRUCT
SHNAMEMAPPING
STRRET

Enumerations
SHCONTF
SHGNO


Shell Objects

The following objects are implemented by the shell for use in scripting and Visual Basic.

Objects
Folder
FolderItem
FolderItems
FolderItemVerb
FolderItemVerbs
Shell
ShellFolderView
ShellUIHelper
ShellWindows


Folder Object

The Folder object represents a shell folder. It contains properties and methods that allow you to get information about the folder.
Properties
Methods


Folder object properties Folder object properties *
  * Previous Topic: Folder Object
  * Next Topic: Application Property

Folder object properties

The Folder object has the following properties:
Application
Parent
ParentFolder
Title


Application Property

Description

Contains the Application object of the folder. This is a read-only property.

Syntax

object.Application

Parameter | Description
object | Required. An object expression that evaluates to a Folder object.


Parent Property

Description

Contains the object's parent object. This is a read-only property.

Syntax

object.Parent

Parameter | Description
object | Required. An object expression that evaluates to a Folder object.


ParentFolder Property

Description

Contains the parent Folder object. This is a read-only property.

Syntax

object.ParentFolder

Parameter | Description
object | Required. An object expression that evaluates to a Folder object.


Title Property

Description

Contains the title of the folder. This is a read-only property.

Syntax

object.Title

Parameter | Description
object | Required. An object expression that evaluates to a Folder object.


Folder object methods

The Folder object has the following methods:
CopyHere
GetDetailsOf
Items
MoveHere
NewFolder
ParseName


CopyHere Method

Description

Copies an item or items to a folder.

Syntax

object.CopyHere vItem, [vOptions]

Parameter | Description
object | Required. An object expression that evaluates to a Folder object. This is the folder to which the item or items will be copied.
vItem | Required. Specifies the item or items to copy. This can be a string that represents a file name, a FolderItem object, or a FolderItems object.
vOptions | Optional. Specifies options for the copy operation. This can be zero or a combination of the FOF_ flags described under the fFlags member of the SHFILEOPSTRUCT structure.


GetDetailsOf Method

Description

Retrieves information about an item in a folder.

Syntax

object.GetDetailsOf vItem, iColumn

Parameter | Description
object | Required. An object expression that evaluates to a Folder object.
vItem | Required. Specifies the item for which to get the information. This must be a FolderItem object.
iColumn Required. An integer value that specifies the information to be retrieved. The information available for an item depends on the folder in which it is displayed. This value corresponds to the zero-based column number that is displayed in a shell view. For an item in the file system, this can be one of the following values:
0 | Retrieves the name of the item.
1 | Retrieves the size of the item.
2 | Retrieves the type of the item.
3 | Retrieves the date and time that the item was last modified.
4 | Retrieves the attributes of the item.
-1 | Retrieves the info tip information for the item.


Items Method

Description

Retrieves a FolderItems object that represents the collection of items in the folder.

Syntax

object.Items

Parameter | Description
object | Required. An object expression that evaluates to a Folder object.


MoveHere Method

Description

Moves an item or items to this folder.

Syntax

object.MoveHere vItem, [vOptions]

Parameter | Description
object | Required. An object expression that evaluates to a Folder object. This is the folder to which the item or items will be moved.
vItem | Required. Specifies the item or items to move. This can be a string that represents a file name, a FolderItem object, or a FolderItems object.
vOptions | Optional. Specifies options for the move operation. This can be zero or a combination of the FOF_ flags described under the fFlags member of the SHFILEOPSTRUCT structure.


NewFolder Method

Description

Creates a new folder.

Syntax

object.NewFolder bName, [vOptions]

Parameter | Description
object | Required. An object expression that evaluates to a Folder object. This is the folder in which the new folder will be created.
bName | Required. A string that specifies the name of the new folder.
vOptions | Optional. This value is not currently used.


ParseName Method

Description

Creates and returns a FolderItem object that represents a specified item.

Syntax

object.ParseName bName

Parameter | Description
object | Required. An object expression that evaluates to a Folder object. This is the folder in which the new folder will be created.
bName | Required. A string that specifies the name of the item.


FolderItem Object

The FolderItem object represents an item in a shell folder. It contains properties and methods that allow you to get information about the item.
Properties
Methods


FolderItem object properties

The FolderItem object has the following properties:
Application
GetFolder
GetLink
IsBrowsable
IsFileSystem
IsFolder
IsLink
ModifyDate
Name
Parent
Path
Size
Type


Application Property

Description

Contains the Application object of the folder item. This is a read-only property.

Syntax

object.Application

Parameter | Description
object | Required. An object expression that evaluates to a FolderItem object.


GetFolder Property

Description

Contains the item's Folder object if the item is a folder. This is a read-only property.

Syntax

object.GetFolder

Parameter | Description
object | Required. An object expression that evaluates to a FolderItem object.

See Also

IsFolder Property


GetLink Property

Description

Contains the item's IShellLinkDual object if the item is a shortcut. This is a read-only property.

Syntax

object.GetLink

Parameter | Description
object | Required. An object expression that evaluates to a FolderItem object.

See Also

IsLink Property


IsBrowsable Property

Description

Indicates if the item can be browsed. This property is TRUE if the item can be browsed or FALSE if not. This is a read-only property.

Syntax

object.IsBrowsable

Parameter | Description
object | Required. An object expression that evaluates to a FolderItem object.


IsFileSystem Property

Description

Indicates if the item is part of the file system. This property is TRUE if the item is part of the file system or FALSE if not. This is a read-only property.

Syntax

object.IsFileSystem

Parameter | Description
object | Required. An object expression that evaluates to a FolderItem object.


IsFolder Property

Description

Indicates if the item is a folder. This property is TRUE if the item is a folder or FALSE if not. This is a read-only property.

Syntax

object.IsFolder

Parameter | Description
object | Required. An object expression that evaluates to a FolderItem object.


IsLink Property

Description

Indicates if the item is a shortcut. This property is TRUE if the item is a shortcut or FALSE if not. This is a read-only property.

Syntax

object.IsLink

Parameter | Description
object | Required. An object expression that evaluates to a FolderItem object.


ModifyDate Property

Description

Contains the date and time that the item was last modified.

Syntax

object.ModifyDate

Parameter | Description
object | Required. An object expression that evaluates to a FolderItem object.


Name Property

Description

Contains the name of the item.

Syntax

object.Name

Parameter | Description
object | Required. An object expression that evaluates to a FolderItem object.


Parent Property

Description

Contains the parent object of the item. This is a read-only property.

Syntax

object.Parent

Parameter | Description
object | Required. An object expression that evaluates to a FolderItem object.


Path Property

Description

Contains the full path and name of the item. This is a read-only property.

Syntax

object.Path

Parameter | Description
object | Required. An object expression that evaluates to a FolderItem object.


Size Property

Description

Contains the size of the item, in bytes. This is a read-only property.

Syntax

object.Size

Parameter | Description
object | Required. An object expression that evaluates to a FolderItem object.


Type Property

Description

Contains a string representation of the item's type. This is a read-only property.

Syntax

object.Type

Parameter | Description
object | Required. An object expression that evaluates to a FolderItem object.


FolderItem object methods FolderItem object methods *
  * Previous Topic: Type Property
  * Next Topic: InvokeVerb Method

FolderItem object methods

The FolderItem object has the following methods:
InvokeVerb
Verbs


InvokeVerb Method

Description

Executes a verb on a shell item.

Syntax

object.InvokeVerb [vVerb]

Parameter | Description
object | Required. An object expression that evaluates to a FolderItem object.
vVerb | Optional. A string that specifies the verb to be executed. This must be one of the values returned by the item's FolderItemVerb.Name property.

See Also

FolderItem.Verbs, FolderItemVerb.DoIt


Verbs Method

Description

Retrieves the item's FolderItemVerbs object, which is the collection of verbs that can be executed on the item.

Syntax

object.Verbs

Parameter | Description
object | Required. An object expression that evaluates to a FolderItem object.

See Also

FolderItem.InvokeVerb, FolderItemVerb.DoIt


FolderItems Object

The FolderItems object represents the collection of items in a shell folder. It contains properties and methods that allow you to get information about the collection.
Properties
Methods


FolderItems object properties FolderItems object properties *
  * Previous Topic: FolderItems Object
  * Next Topic: Application Property

FolderItems object properties

The FolderItems object has the following properties:
Application
Count
Parent


Application Property

Description

Contains the Application object of the folder items collection. This is a read-only property.

Syntax

object.Application

Parameter | Description
object | Required. An object expression that evaluates to a FolderItems object.


Count Property

Description

Contains the number of items in the collection. This is a read-only property.

Syntax

object.Count

Parameter | Description
object | Required. An object expression that evaluates to a FolderItems object.


Parent Property

Description

Contains the parent object of the collection. This is a read-only property.

Syntax

object.Parent

Parameter | Description
object | Required. An object expression that evaluates to a FolderItems object.


FolderItems object methods FolderItems object methods *
  * Previous Topic: Parent Property
  * Next Topic: Item Method

FolderItems object methods

The FolderItems object has the following methods:
Item
_NewEnum


Item Method

Description

Retrieves the FolderItem object for a specified item in the collection.

Syntax

object.Item [index]

Parameter | Description
object | Required. An object expression that evaluates to a FolderItems object.
index | Optional. Specifies the zero-based index of the item to retrieve. This value must be less than the value of the Count property.


_NewEnum Method

Description

Creates and returns a new FolderItems object that is a copy of this FolderItems object.

Syntax

object._NewEnum

Parameter | Description
object | Required. An object expression that evaluates to a FolderItems object.


FolderItemVerb Object

The FolderItemVerb object represents the verbs or commands to which an item in a shell folder responds. It contains properties and methods that allow you to get information about the collection.
Properties
Methods


FolderItemVerb object properties FolderItemVerb object properties *
  * Previous Topic: FolderItemVerb Object
  * Next Topic: Application Property

FolderItemVerb object properties

The FolderItemVerb object has the following properties:
Application
Name
Parent


Application Property

Description

Contains the Application object of the object. This is a read-only property.

Syntax

object.Application

Parameter | Description
object | Required. An object expression that evaluates to a FolderItemVerb object.


Name Property

Description

Contains the name of the verb. This is a read-only property.

Syntax

object.Name

Parameter | Description
object | Required. An object expression that evaluates to a FolderItemVerb object.


Parent Property

Description

Contains the parent object of the object. This is a read-only property.

Syntax

object.Parent

Parameter | Description
object | Required. An object expression that evaluates to a FolderItemVerb object.


FolderItemVerb object methods FolderItemVerb object methods *
  * Previous Topic: Parent Property
  * Next Topic: DoIt Method

FolderItemVerb object methods

The FolderItemVerb object has the following method:
DoIt


DoIt Method

Description

Executes the verb on the FolderItem associated with the verb.

Syntax

object.DoIt

Parameter | Description
object | Required. An object expression that evaluates to a FolderItemVerb object.


FolderItemVerbs Object

The FolderItemVerbs object represents the collection of verbs for an item in a shell folder. It contains properties and methods that allow you to get information about the collection.
Properties
Methods


FolderItemVerbs object properties FolderItemVerbs object properties *
  * Previous Topic: FolderItemVerbs Object
  * Next Topic: Application Property

FolderItemVerbs object properties

The FolderItemVerbs object has the following properties:
Application
Count
Parent


Application Property

Description

Contains the Application object of the object. This is a read-only property.

Syntax

object.Application

Parameter | Description
object | Required. An object expression that evaluates to a FolderItemVerbs object.


Count Property

Description

Contains the number of items in the collection. This is a read-only property.

Syntax

object.Count

Parameter | Description
object | Required. An object expression that evaluates to a FolderItemVerbs object.


Parent Property

Description

Contains the parent object of the object. This is a read-only property.

Syntax

object.Parent

Parameter | Description
object | Required. An object expression that evaluates to a FolderItemVerbs object.


FolderItemVerbs object methods FolderItemVerbs object methods *
  * Previous Topic: Parent Property
  * Next Topic: Item Method

FolderItemVerbs object methods

The FolderItemVerbs object has the following methods:
Item
_NewEnum


Item Method

Description

Retrieves the FolderItemVerb object for a specified item in the collection.

Syntax

object.Item [index]

Parameter | Description
object | Required. An object expression that evaluates to a FolderItemVerbs object.
index | Optional. Specifies the zero-based index of the item to retrieve. This value must be less than the value of the Count property.


_NewEnum Method

Description

Creates and returns a new FolderItemVerbs object that is a copy of this FolderItemVerbs object.

Syntax

object._NewEnum

Parameter | Description
object | Required. An object expression that evaluates to a FolderItemVerbs object.


Shell Object

The Shell object represents the objects in the shell. There are methods to control the shell and to execute commands within the shell. There are also methods to obtain other shell-related objects.
Properties
Methods
Constants


Shell object properties Shell object properties *
  * Previous Topic: Shell Object
  * Next Topic: Application Property

Shell object properties

The Shell object has the following properties:
Application
Parent


Application Property

Description

Contains the Application object of the object. This is a read-only property.

Syntax

object.Application

Parameter | Description
object | Required. An object expression that evaluates to a Shell object.


Parent Property

Description

Contains the parent object of the object. This is a read-only property.

Syntax

object.Parent

Parameter | Description
object | Required. An object expression that evaluates to a Shell object.


Shell object methods

The Shell object has the following methods:
BrowseForFolder
CascadeWindows
ControlPanelItem
EjectPC
Explore
FileRun
FindComputer
FindFiles
Help
MinimizeAll
NameSpace
Open
RefreshMenu
SetTime
ShutdownWindows
Suspend
TileHorizontally
TileVertically
TrayProperties
UndoMinimizeALL
Windows


BrowseForFolder Method

Description

Creates a dialog box that allows the user to select a folder and then returns a Folder object that represents the selected folder.

Syntax

object.BrowseForFolder Hwnd, Title, Options, [RootFolder]

Parameter | Description
object | Required. An object expression that evaluates to a Shell object.
Hwnd | Required. The handle to the window that will be the parent of the browse dialog box. This value can be zero.
Title | Required. A string value that represents the title that will be displayed inside the browse dialog box.
Options | Required. A long value that contains the options for the method. This can be zero or a combination of the values listed under the ulFlags member of the BROWSEINFO structure.
RootFolder | Optional. Specifies the root of the browse dialog. The user cannot browse higher in the folder architecture than this folder. If this value is not specified, the root of the browse dialog is the desktop. This value can be a string that specifies the path of the folder or one of the ShellSpecialFolderConstants values.


CascadeWindows Method

Description

Causes all of the windows on the desktop to be cascaded. This is the same as right-clicking on the taskbar and selecting Cascade Windows.

Syntax

object.CascadeWindows

Parameter | Description
object | Required. An object expression that evaluates to a Shell object.


ControlPanelItem Method

Description

Runs the specified Control Panel application. If the application is already open, it will activate the running instance.

Syntax

object.ControlPanelItem szDir

Parameter | Description
object | Required. An object expression that evaluates to a Shell object.
szDir | Required. Specifies the Control Panel application's file name. All Control Panel applications have the .cpl extension.


EjectPC Method

Description

Causes the computer to be ejected from its docking station. This is the same as clicking on the Start menu and selecting Eject PC, if your computer supports this command.

Syntax

object.EjectPC

Parameter | Description
object | Required. An object expression that evaluates to a Shell object.


Explore Method

Description

Explores a folder.

Syntax

object.Explore vDir

Parameter | Description
object | Required. An object expression that evaluates to a Shell object.
vDir | Required. Specifies the folder to be explored. This can be a string that specifies the path of the folder or one of the ShellSpecialFolderConstants values.


FileRun Method

Description

Causes the Run dialog to be displayed to the user. This is the same as clicking on the Start Menu and selecting Run.

Syntax

object.FileRun

Parameter | Description
object | Required. An object expression that evaluates to a Shell object.


FindComputer Method

Description

Causes the Find: Computer dialog to be displayed to the user. This is the same as clicking on the Start Menu, selecting Find, and then selecting Computer.

Syntax

object.FindComputer

Parameter | Description
object | Required. An object expression that evaluates to a Shell object.


FindFiles Method

Description

Causes the Find: All Files dialog to be displayed to the user. This is the same as clicking on the Start Menu, selecting Find, and then selecting Files or Folders.

Syntax

object.FindFiles

Parameter | Description
object | Required. An object expression that evaluates to a Shell object.


Help Method

Description

Causes Microsoft® Windows® Help to be displayed to the user. This is the same as clicking on the Start Menu and selecting Help.

Syntax

object.Help

Parameter | Description
object | Required. An object expression that evaluates to a Shell object.


MinimizeAll Method

Description

Causes all of the windows on the desktop to be minimized. This is the same as right-clicking on the taskbar and selecting Minimize All Windows.

Syntax

object.MinimizeAll

Parameter | Description
object | Required. An object expression that evaluates to a Shell object.

See Also

UndoMinimizeALL


NameSpace Method

Description

Creates and returns a Folder object for the specified folder.

Syntax

object.NameSpace vDir

Parameter | Description
object | Required. An object expression that evaluates to a Shell object.
vDir | Required. Specifies the folder for which to create the Folder object. This can be a string that specifies the path of the folder or one of the ShellSpecialFolderConstants values.


Open Method

Description

Opens a folder.

Syntax

object.Open vDir

Parameter | Description
object | Required. An object expression that evaluates to a Shell object.
vDir | Required. This can be a string that specifies the path of the folder or one of the ShellSpecialFolderConstants values.


RefreshMenu Method

Description

Causes the Start Menu to refresh its contents.

Syntax

object.RefreshMenu

Parameter | Description
object | Required. An object expression that evaluates to a Shell object.


SetTime Method

Description

Causes the Date/Time Properties dialog to be displayed to the user. This is the same as right-clicking on the clock in the tray and selecting Adjust Date/Time.

Syntax

object.SetTime

Parameter | Description
object | Required. An object expression that evaluates to a Shell object.


ShutdownWindows Method

Description

Causes the Shut Down Windows dialog to be displayed to the user. This is the same as clicking on the Start menu and selecting Shut Down.

Syntax

object.ShutdownWindows

Parameter | Description
object | Required. An object expression that evaluates to a Shell object.


Suspend Method

Description

Causes the computer to be suspended. This is the same as clicking on the Start menu and selecting Suspend (for computers that support suspending).

Syntax

object.Suspend

Parameter | Description
object | Required. An object expression that evaluates to a Shell object.


TileHorizontally Method

Description

Causes all of the windows on the desktop to be tiled horizontally. This is the same as right-clicking on the taskbar and selecting Tile Windows Horizontally.

Syntax

object.TileHorizontally

Parameter | Description
object | Required. An object expression that evaluates to a Shell object.


TileVertically Method

Description

Causes all of the windows on the desktop to be tiled vertically. This is the same as right-clicking on the taskbar and selecting Tile Windows Vertically.

Syntax

object.TileVertically

Parameter | Description
object | Required. An object expression that evaluates to a Shell object.


TrayProperties Method

Description

Causes the Taskbar Properties dialog to be displayed to the user. This is the same as right-clicking on the taskbar and selecting Properties.

Syntax

object.TrayProperties

Parameter | Description
object | Required. An object expression that evaluates to a Shell object.


UndoMinimizeALL Method

Description

Causes all of the windows on the desktop to be restored to the same state they were in before the last MinimizeAll command. This is the same as right-clicking on the taskbar and selecting Undo Minimize All Windows.

Syntax

object.UndoMinimizeALL

Parameter | Description
object | Required. An object expression that evaluates to a Shell object.


Windows Method

Description

Creates and returns a ShellWindows object that represents a collection of all of the open windows that belong to the shell.

Syntax

object.Windows

Parameter | Description
object | Required. An object expression that evaluates to a Shell object.


Shell object constants Shell object constants *
  * Previous Topic: Windows Method
  * Next Topic: ShellSpecialFolderConstants Enumeration

Shell object constants

The Shell object uses the following set of constants:
ShellSpecialFolderConstants


ShellSpecialFolderConstants Enumeration

Description

Set of values that specify special folders in the shell.

Syntax

enum ShellSpecialFolderConstants{
    ssfDESKTOP = 0x0000,
    ssfPROGRAMS = 0x0002,
    ssfCONTROLS = 0x0003,
    ssfPRINTERS = 0x0004,
    ssfPERSONAL = 0x0005,
    ssfFAVORITES = 0x0006,
    ssfSTARTUP = 0x0007,
    ssfRECENT = 0x0008,
    ssfSENDTO = 0x0009,
    ssfBITBUCKET = 0x000a,
    ssfSTARTMENU = 0x000b,
    ssfDESKTOPDIRECTORY = 0x0010,
    ssfDRIVES = 0x0011,
    ssfNETWORK = 0x0012,
    ssfNETHOOD = 0x0013,
    ssfFONTS = 0x0014,
    ssfTEMPLATES = 0x0015,
} ShellSpecialFolderConstants;

Parameter | Description
ssfDESKTOP | Desktop folder.
ssfPROGRAMS | File system folder that contains the items in the Programs folder on the Start menu.
ssfCONTROLS | Control Panel folder.
ssfPRINTERS | Printers folder.
ssfPERSONAL | File system folder that contains the user's documents.
ssfFAVORITES | Favorites folder.
ssfSTARTUP | Startup folder on the Start menu.
ssfRECENT | Folder that contains shortcuts to the user's most recently used documents.
ssfSENDTO | Folder that contains the items that are added to the Send To menu.
ssfBITBUCKET | Recycle Bin.
ssfSTARTMENU | Folder that contains the items that are displayed on the Start menu.
ssfDESKTOPDIRECTORY | File system folder that contains the items on the desktop.
ssfDRIVES | My Computer.
ssfNETWORK | Network Neighborhood.
ssfNETHOOD | File system folder that contains items displayed inside the Network Neighborhood.
ssfFONTS | Folder that contains the installed fonts.
ssfTEMPLATES | File system folder that contains document templates.


ShellFolderView Object

The ShellFolderView object represents the objects in a view. There are properties and methods used to obtain information about the contents of the view.
Properties
Methods
Events
Constants


ShellFolderView object properties ShellFolderView object properties *
  * Previous Topic: ShellFolderView Object
  * Next Topic: Application Property

ShellFolderView object properties

The ShellFolderView object has the following properties:
Application
FocusedItem
Folder
Parent
Script
ViewOptions


Application Property

Description

Contains the Application object of the object. This is a read-only property.

Syntax

object.Application

Parameter | Description
object | Required. An object expression that evaluates to a ShellFolderView object.


FocusedItem Property

Description

Contains a FolderItem object that represents the item that has the input focus. This is a read-only property.

Syntax

object.FocusedItem

Parameter | Description
object | Required. An object expression that evaluates to a ShellFolderView object.


Folder Property

Description

Contains a Folder object that represents the view. This is a read-only property.

Syntax

object.Folder

Parameter | Description
object | Required. An object expression that evaluates to a ShellFolderView object.


Parent Property

Description

Contains the parent object of the object. This is a read-only property.

Syntax

object.Parent

Parameter | Description
object | Required. An object expression that evaluates to a ShellFolderView object.


Script Property

Description

Contains the scripting object for the view. This is a read-only property.

Syntax

object.Script

Parameter | Description
object | Required. An object expression that evaluates to a ShellFolderView object.


ViewOptions Property

Description

Contains a set of ShellFolderViewOptions flags that indicate the current options of the view. This is a read-only property.

Syntax

object.ViewOptions

Parameter | Description
object | Required. An object expression that evaluates to a ShellFolderView object.


ShellFolderView object methods ShellFolderView object methods *
  * Previous Topic: ViewOptions Property
  * Next Topic: PopupItemMenu Method

ShellFolderView object methods

The ShellFolderView object has the following methods:
PopupItemMenu
SelectedItems
SelectItem


PopupItemMenu Method

Description

Creates a context menu for the specified item and returns the selected command string.

Syntax

object.PopupItemMenu vItem, [vx], [vy]

Parameter | Description
object | Required. An object expression that evaluates to a ShellFolderView object.
vItem | Required. The FolderItem object for which the context menu will be created.
vx | Optional. The horizontal position of the menu, in screen coordinates.
vy | Optional. The vertical position of the menu, in screen coordinates.


SelectedItems Method

Description

Retrieves a FolderItems object that represents all of the selected items in the view.

Syntax

object.SelectedItems

Parameter | Description
object | Required. An object expression that evaluates to a ShellFolderView object.


SelectItem Method

Description

Sets the selection state of an item in the view.

Syntax

object.SelectItem vItem, dwFlags

Parameter | Description
object | Required. An object expression that evaluates to a ShellFolderView object.
vItem | Required. The FolderItem object for which the selection state will be set.
dwFlags Required. A set of flags that indicate the new selection state. This can be one or more of the following values:
0 | Deselect the item.
1 | Select the item.
3 | Put the item in edit mode.
4 | Deselect all but the specified item.
8 | Ensure the item is displayed in the view.
16 | Give the item the focus.


ShellFolderView object events ShellFolderView object events *
  * Previous Topic: SelectItem Method
  * Next Topic: SelectionChanged Event

ShellFolderView object events

The ShellFolderView object has the following event:
SelectionChanged


SelectionChanged Event

Description

Occurs when the selection state of any item or items in the view has changed.

Syntax

Private Sub object_SelectionChanged

Parameter | Description
object | Required. An object expression that evaluates to a ShellFolderView object.


ShellFolderView object constants ShellFolderView object constants *
  * Previous Topic: SelectionChanged Event
  * Next Topic: ShellFolderViewOptions Enumeration

ShellFolderView object constants

The ShellFolderView object uses the following set of constants:
ShellFolderViewOptions


ShellFolderViewOptions Enumeration

Description

Specifies the view options returned by the ViewOptions property.

Syntax

enum ShellFolderViewOptions {
    SFVVO_SHOWALLOBJECTS = 0x00000001,
    SFVVO_SHOWEXTENSIONS = 0x00000002,
    SFVVO_SHOWCOMPCOLOR = 0x00000008,
    SFVVO_SHOWSYSFILES = 0x00000020,
    SFVVO_WIN95CLASSIC = 0x00000040,
    SFVVO_DOUBLECLICKINWEBVIEW = 0x00000080,
    SFVVO_DESKTOPHTML = 0x00000200,
} ShellFolderViewOptions;

Parameter | Description
SFVVO_SHOWALLOBJECTS | The Show All Files option is enabled.
SFVVO_SHOWEXTENSIONS | The Hide File Extensions for Known File Types option is disabled.
SFVVO_SHOWCOMPCOLOR | The Display Compressed Files and Folders with Alternate Color option is enabled.
SFVVO_SHOWSYSFILES | The Do Not Show Hidden Files option is enabled.
SFVVO_WIN95CLASSIC | The Classic Style option is enabled.
SFVVO_DOUBLECLICKINWEBVIEW | The Double-Click to Open an Item option is enabled.
SFVVO_DESKTOPHTML | The Active Desktop – View as Web Page option is enabled.


ShellUIHelper Object

The ShellUIHelper object is implemented by the shell to help script and Visual Basic developers to use some of the features available in the shell. The ShellUIHelper object does not have any properties or events. There are methods you can use to add items to the shell.
Methods


ShellUIHelper object methods

The ShellUIHelper object has the following methods:
Methods
AddChannel
AddDesktopComponent
AddFavorite
IsSubscribed


AddChannel Method

Description

Adds a new channel to the list of channels.

Syntax

object.AddChannel URL

Parameter | Description
object | Required. An object expression that evaluates to a ShellUIHelper object.
URL | Required. A string value that specifies the URL of the Channel Definition File.


AddDesktopComponent Method

Description

Adds an item to the Active Desktop.

Syntax

object.AddDesktopComponent URL, Type, Left, Top, Width, Height

Parameter | Description
object | Required. An object expression that evaluates to a ShellUIHelper object.
URL | Required. A string value that specifies the URL of the new favorite item.
Type Required. A string value that specifies the type of item being added. This can be one of the following values:
"image" | The component is an image.
"website" | The component is a web site.
Left | Optional. Specifies the position of the left edge of the component, in screen coordinates.
Top | Optional. Specifies the position of the top edge of the component, in screen coordinates.
Width | Optional. Specifies the width of the component, in screen units.
Height | Optional. Specifies the height of the component, in screen units.


AddFavorite Method

Description

Displays the default user interface for creating a favorite item to be displayed. The user interface will be initialized to the specified parameters.

Syntax

object.AddFavorite URL, [Title]

Parameter | Description
object | Required. An object expression that evaluates to a ShellUIHelper object.
URL | Required. A string value that specifies the URL of the item to be added to the Favorites folder.
Title | Optional. A string value that specifies the name of the item.


IsSubscribed Method

Description

Indicates if a URL is subscribed to. Returns TRUE if the URL is subscribed to or FALSE otherwise.

Syntax

object.IsSubscribed URL

Parameter | Description
object | Required. An object expression that evaluates to a ShellUIHelper object.
URL | Required. A string value that specifies the URL that is to be tested.


ShellWindows Object

The ShellWindows object represents a collection of the open windows that belong to the shell. There are methods that can be used to control and execute commands within the shell. There are also methods that can be used to obtain other shell-related objects.
Properties
Methods


ShellWindows object properties ShellWindows object properties *
  * Previous Topic: ShellWindows Object
  * Next Topic: Count Property

ShellWindows object properties

The ShellWindows object has the following property:
Count


Count Property

Description

Contains the number of items in the collection. This is a read-only property.

Syntax

object.Count

Parameter | Description
object | Required. An object expression that evaluates to a ShellWindows object.


ShellWindows object methods ShellWindows object methods *
  * Previous Topic: Count Property
  * Next Topic: Item Method

ShellWindows object methods

The ShellWindows object has the following methods:
Item
_NewEnum


Item Method

Description

Retrieves an InternetExplorer object that represents the shell window.

Syntax

object.Item [index]

Parameter | Description
object | Required. An object expression that evaluates to a ShellWindows object.
index | Optional. Specifies the zero-based index of the item to retrieve. This value must be less than the value of the Count property.


_NewEnum Method

Description

Creates and returns a new ShellWindows object that is a copy of this ShellWindows object.

Syntax

object._NewEnum

Parameter | Description
object | Required. An object expression that evaluates to a ShellWindows object.


Web View Scripting Objects

The following object is implemented by the shell for use inside of a Web View page. A Web View page is the page that Internet Explorer 4.0 displays for a folder when Web View is enabled. This object is not valid outside of a Web View page.
WebViewFolderContents


WebViewFolderContents Object

The WebViewFolderContents object is identical to the ShellFolderView object, except that it is designed to work within a Web View. The WebViewFolderContents object is used to create a shell folder view inside of a Web View page. It will automatically initialize itself to the folder in which it is contained.


Shell Utility APIs

The programming elements explained in this documentation are implemented in Shlwapi.dll and defined in Shlwapi.h and Shlwapi.lib.

String Functions

Path Functions

Registry Functions

DLL Versioning


String Functions

This section provides the definitions for string handling functions.

ChrCmpI
StrCatN
StrChr
StrChrI
StrCmpN
StrCmpNI
StrCpyN
StrCSpn
StrCSpnI
StrDup
StrFormatByteSize
StrFromTimeInterval
StrIntlEqN
StrIntlEqNI
StrIsIntlEqual
StrNCat
StrNCmp
StrNCmpI
StrNCpy
StrPBrk
StrRChr
StrRStrI
StrSpn
StrStr
StrStrI
StrToInt
StrToIntEx
StrToLong
StrTrim


ChrCmpI

BOOL ChrCmpI(
    TCHAR c1,
    TCHAR c2
    );

Performs a comparison between two characters. The comparison is not case sensitive.

  • Returns zero if the two characters are the same, or nonzero otherwise.
c1
First character to be compared.
c2
Second character to be compared.


StrChr

LPTSTR StrChr(
    LPCTSTR lpStart,
    WORD wMatch
    );

Searches a string for the first occurrence of a character that matches the specified character. The comparison is case sensitive.

  • Returns the address of the first occurrence of the character in the string if successful, or NULL otherwise.
lpStart
Address of the string to be searched.
wMatch
Character to be used for comparison.

The comparison assumes lpStart points to the start of a null-terminated string.


StrChrI

LPTSTR StrChrI(
    LPCTSTR lpStart,
    WORD wMatch
    );

Searches a string for the first occurrence of a character that matches the specified character. The comparison is not case sensitive.

  • Returns the address of the first occurrence of the character in the string if successful, or NULL otherwise.
lpStart
Address of the string to be searched.
wMatch
Character to be used for comparison.

The comparison assumes lpStart points to the start of a null-terminated string.


StrCmpN

int StrCmpN(
    LPCTSTR lpStr1,
    LPCTSTR lpStr2,
    int nChar
    );

#define StrNCmp StrCmpN

Compares a specified number of characters of two strings to determine if they are the same. The comparison is case sensitive. The StrNCmp macro differs from this function in name only.

  • Returns zero if the strings are identical, or nonzero if they are not.
lpStr1
Address of the first string to be compared.
lpStr2
Address of the second string to be compared.
nChar
Number of characters to be compared.


StrCmpNI

int StrCmpNI(
    LPCTSTR lpStr1,
    LPCTSTR lpStr2,
    int nChar
    );

#define StrNCmpI StrCmpNI

Compares a specified number of characters of two strings to determine if they are the same. The comparison is not case sensitive. The StrNCmpI macro differs from this function in name only.

  • Returns zero if the strings are identical, or nonzero if they are not.
lpStr1
Address of the first string to be compared.
lpStr2
Address of the second string to be compared.
nChar
Number of characters to be compared.


StrCpyN

LPTSTR StrCpyN(
    LPCTSTR psz1,
    LPCTSTR psz2,
    int cchMax
    );

#define StrNCpy StrCpyN

Copies a specified number of characters from one string to another. The StrNCpy macro differs from this function in name only.

  • Returns the address of the beginning of the first string if successful, or NULL otherwise.
psz1
Address of the destination string.
psz2
Address of the source string.
cchMax
Number of characters to be copied, including the null.

Example:

#include <windows.h>
#include <iostream.h>
#include "Shlwapi.h"

void main( void )
{
  //String one
  char buffer_1[] = "ABCDEFG";
  char *lpStr1;
  lpStr1 = buffer_1;

  //String two
  char buffer_2[] = "HIJKLMN";
  char *lpStr2;
  lpStr2 = buffer_2;

  cout  <<  "The function StrCpyN will allow you to copy (n) numbers"
  <<  "\nof characters from the string 2 to string 1."
  <<  "\nString 1 is : "	<< lpStr1
  <<  "\nString 2 is : "	<< lpStr2
  <<  "\nCopy (n) from 2 onto 1" << endl;
cout  <<  StrCpyN(lpStr1,lpStr2,8)
}

OUTPUT:
- - - - - -
The function StrCpyN will allow you to copy (n) numbers
of characters from the string 2 to string 1.
String 1 is : ABCDEFG
String 2 is : HIJKLMN
Copy (n) from 2 onto 1
HIJKLMN


StrCSpn

int StrCSpn(
    LPCTSTR lpStr,
    LPCTSTR lpSet
    );

Searches for the first occurrence of a substring within a string. The search method is case sensitive, and the NULL terminator is included within the search pattern match.

  • Returns the index of the first character of the substring within the string if successful, or the length of the string if no match is found.
lpStr
Address of the null-terminated string to be searched.
lpSet
Address of the substring to search for.


StrCSpnI

int StrCSpnI(
    LPCTSTR lpStr,
    LPCTSTR lpSet
    );

Searches for the first occurrence of a substring within a string. The search method is not case sensitive, and the NULL terminator is included within the search pattern match.

  • Returns the index of the first character of the substring within the string if successful, or the length of the string if no match is found.
lpStr
Address of the null-terminated source string to be searched.
lpSet
Address of the string to search for.


StrDup

LPTSTR StrDup(
    LPCTSTR lpsz
    );

Duplicates a string.

  • Returns the address of the string that was copied, or NULL if the string cannot be copied.
lpsz
Address of a constant null-terminated character string.

StrDup will allocate storage the size of the original string. If storage allocation is successful, the original string is copied to the duplicate string.

Example:

#include <windows.h>
#include <string.h>
#include <stdio.h>

void main( void )
{
   char buffer[] = "This is the buffer text";
   char *newstring;
   printf( "Original: %s\n", buffer );
   newstring = StrDup( buffer );
   printf( "Copy:     %s\n", newstring );
   free( newstring );
}

   OUTPUT:
   - - - - - -
   Original: This is the buffer text
   Copy:     This is the buffer text

Note This function uses LocalAlloc to allocate storage space for the copy of the string. The calling application must free this memory by calling the LocalFree function on the pointer returned by the call to StrDup.


StrFormatByteSize

LPTSTR StrFormatByteSize(
    DWORD dw,
    LPSTR pszBuf,
    UINT cchBuf
    );

Converts a numeric value into a string that represents the number expressed as a size value in bytes, KB, MB, or GB, depending on the size.

  • Returns the address of the converted string, or NULL otherwise.
dw
Numeric value to be converted.
pszBuf
Address of the converted string.
cchBuf
Size of pszBuf, in characters.

Example:

       532 -> 532 bytes
      1340 -> 1.3KB
     23506 -> 23.5KB
   2400016 -> 2.4MB
2400000000 -> 2.4GB


StrFromTimeInterval

int StrFromTimeInterval(
    LPSTR pszOut,
    UINT cchMax,
    DWORD dwTimeMS,
    int digits
    );

Converts a given time interval, in milliseconds, to a string.

  • Returns the number of characters in the buffer, not including the null terminator.
pszOut
Address of a character buffer that receives the converted string.
cchMax
Size of pszOut, in characters.
dwTimeMS
Time interval in milliseconds.
digits
Minimum number of digits to be converted.

Example:

#include <windows.h>
#include <iostream.h>
#include "Shlwapi.h"

void main( void )
{
    char TimeString[256];
    char *pszOut;
    pszOut = TimeString;

cout << "The return value from the call to"
     << "\nthe function StrFromTimeInterval will"
     << "\nreturn the number of elements in the buffer: " << endl;

cout << "\nThe return from StrFromTimeInterval is "
     << StrFromTimeInterval(pszOut,30, 34000,30);
cout << "\nThe contents of the TimeString Buffer " << pszOut << endl;

cout << "The return from StrFromTimeInterval is "
     << StrFromTimeInterval(pszOut,30, 74000,3);
cout << "\nThe contents of the TimeString Buffer " << pszOut << endl;

cout << "The return from StrFromTimeInterval is "
     << StrFromTimeInterval(pszOut,30, 74000,2);
cout << "\nThe contents of the TimeString Buffer " << pszOut << endl;

cout << "The return from StrFromTimeInterval is "
     << StrFromTimeInterval(pszOut,30, 74000,1)
     << "\nThe contents of the TimeString Buffer " << pszOut << endl;

}

OUTPUT:
- - - - -
The return value from the call to
the function StrFromTimeInterval will
return the number of elements in the buffer:

The return from StrFromTimeInterval is 7
The contents of the TimeString Buffer  34 sec
The return from StrFromTimeInterval is 13
The contents of the TimeString Buffer  1 min 14 sec
The return from StrFromTimeInterval is 13
The contents of the TimeString Buffer  1 min 10 sec
The return from StrFromTimeInterval is 6
The contents of the TimeString Buffer  1 min


StrIsIntlEqual

BOOL StrIsIntlEqual(
    BOOL fCaseSens,
    LPCTSTR lpString1,
    LPCTSTR lpString2,
    int nChar
    );

#define StrIntlEqN(s1, s2, nChar) StrIsIntlEqual(TRUE, s1, s2, nChar)
#define StrIntlEqNI(s1, s2, nChar) StrIsIntlEqual(FALSE, s1, s2, nChar)

Compares a specified number of characters in two strings to determine if they are equal. This function allows you to set the case sensitivity for the search. The StrIntlEqN and StrIntlEqNI macros can be used to call this function. StrIntlEqN performs the comparison with case sensitivity, and StrIntlEqNI performs the comparison without case sensitivity.

  • Returns TRUE if the strings are equal, or FALSE otherwise.
fCaseSens
Determines the case sensitivity of the comparison. If this value is nonzero, the comparison is case sensitive. If this value is zero, the comparison is not case sensitive.
lpString1
Address of the first string to be compared.
lpString2
Address of the second string to be compared.
nChar
Number of characters to compare.


StrNCat

LPTSTR StrNCat(
    LPTSTR front,
    LPCTSTR back,
    int cchMax
    );

#define StrCatN StrNCat

Copies and appends a specified number of characters from one string onto the end of another string. The StrCatN macro differs from this function in name only.

  • Returns the address of the target string.
front
Address of the string to which the characters will be copied.
back
Address of the string to be copied.
cchMax
Number of characters to copy.


StrPBrk

LPTSTR StrPBrk(
    LPCTSTR psz,
    LPCTSTR pszSet
    );

Searches a string for the first occurrence of a character contained in a specified buffer. This search does not include the null terminator.

  • Returns the address in psz of the first occurrence of a character contained in the buffer at pszSet, or NULL if no match is found.
psz
Address of the string to be searched.
pszSet
Address of a null-terminated character buffer that contains the characters for which to search.


StrRChr

LPTSTR StrRChr(
    LPCTSTR lpStart,
    LPCTSTR lpEnd,
    WORD wMatch
    );

Searches a string for the last occurrence of a character that matches the specified character. The comparison is case sensitive.

  • Returns the address of the last occurrence of the character in the string if successful, or NULL otherwise.
lpStart
Address of the string to be searched.
lpEnd
Points to the end of the string to be searched. The character at this location in the buffer is not included in the search.
wMatch
Character to be used for comparison.

The comparison assumes that lpEnd points to the end of the string.


StrRStrI

LPTSTR StrRStrI(
    LPCTSTR lpSource,
    LPCTSTR lpLast,
    LPCTSTR lpSrch
    );

Searches for the last occurrence of a substring within a string. The comparison is not case sensitive.

  • Returns the address of the last occurrence of the string if successful, or NULL otherwise.
lpSource
Address of the null-terminated source string.
lpLast
Address of where to search from in the source string.
lpSrch
Address of the string to search for.


StrSpn

int StrSpn(
    LPCTSTR psz,
    LPCTSTR pszSet
    );

Obtains the length of a substring within a string that consists entirely of characters contained in a specified buffer.

  • Returns the length, in characters, of the matching string or zero if no match is found.
psz
Address of the string that is to be searched.
pszSet
Address of a null-terminated character buffer that contains the set of characters for which to search.


StrStr

LPTSTR StrStr(
    LPCTSTR lpFirst,
    LPCTSTR lpSrch
    );

Finds the first occurrence of a substring within a string. The comparison is case sensitive.

  • Returns the address of the first occurrence of the matching substring if successful, or NULL otherwise.
lpFirst
Address of the string being searched.
lpSrch
Substring to search for.


StrStrI

LPTSTR StrStrI(
    LPCTSTR lpFirst,
    LPCTSTR lpSrch
    );

Finds the first occurrence of a substring within a string. The comparison is not case sensitive.

  • Returns the address of the first occurrence of the matching substring if successful, or NULL otherwise.
lpFirst
Address of the string being searched.
lpSrch
Substring to search for.


StrToInt

int StrToInt(
    LPCTSTR lpSrc
    );

#define StrToLong StrToInt

Converts a decimal string to an integer. The StrToLong macro differs from this function in name only.

  • Returns the INT value of a string.
lpSrc
Address of the null-terminated string to be converted.


StrToIntEx

BOOL StrToIntEx(
    LPCTSTR pszString,
    DWORD dwFlags,
    int FAR * piRet
    );

Converts a decimal or hexadecimal string to an integer.

  • Returns TRUE if the string is converted, or FALSE otherwise.
pszString
Address of a null-terminated string to be converted.
dwFlags
Specifies if pszString contains a decimal or hexadecimal value. This can be one of the following values:
STIF_DEFAULT | pszString contains a decimal value.
STIF_SUPPORT_HEX | pszString contains a hexadecimal value.
piRet
Address of an integer variable that receives the converted string.


StrTrim

BOOL StrTrim(
    LPTSTR psz,
    LPCTSTR pszTrimChars
    );

Removes (trims) any leading and trailing characters from a string.

  • Returns nonzero if any characters were removed, or zero otherwise.
psz
Address of a string buffer that contains the string to be trimmed.
pszTrimChars
Address of an array of characters that will be trimmed from psz. The last element in this array must be zero.

Example:

#include <windows.h>
#include <iostream.h>
#include "Shlwapi.h"

void main( void )
{
  //String one
  TCHAR buffer[] = TEXT("_!ABCDEFG#");
  TCHAR trim[] = TEXT("#A!_\0");

  cout  <<  "The string before calling StrTrim: ";
  cout  <<  buffer;
  cout  <<  "\n";

  StrTrim(buffer, trim);

  cout  <<  "The string after calling StrTrim: ";
  cout  <<  buffer;
  cout  <<  "\n";

}

OUTPUT:
- - - - - -
The string before calling StrTrim: _!ABCDEFG#
The string after calling StrTrim: BCDEFG


Path Functions

This section provides the definitions for path functions.

PathAddBackslash
PathAddExtension
PathAppend
PathBuildRoot
PathCanonicalize
PathCombine
PathCompactPath
PathCompactPathEx
PathCommonPrefix
PathFileExists
PathFindExtension
PathFindFileName
PathFindNextComponent
PathFindOnPath
PathGetArgs
PathGetCharType
PathGetDriveNumber
PathIsContentType
PathIsDirectory
PathIsFileSpec
PathIsHTMLFile
PathIsPrefix
PathIsRelative
PathIsRoot
PathIsSameRoot
PathIsSystemFolder
PathIsUNC
PathIsUNCServer
PathIsUNCServerShare
PathIsURL
PathMakePretty
PathMakeSystemFolder
PathMatchSpec
PathParseIconLocation
PathQuoteSpaces
PathRelativePathTo
PathRemoveArgs
PathRemoveBackslash
PathRemoveBlanks
PathRemoveExtension
PathRemoveFileSpec
PathRenameExtension
PathSearchAndQualify
PathSetDlgItemPath
PathSkipRoot
PathStripPath
PathStripToRoot
PathUnmakeSystemFolder
PathUnquoteSpaces


PathAddBackslash

LPTSTR PathAddBackslash(
    LPCTSTR lpszPath
    );

Adds a backslash to the end of a string to create the correct syntax for a path. If the source path already has a trailing backslash, no backslash will be added.

  • Returns the address of the NULL that terminates the string.
lpszPath
Address of the string that represents a path.

Example:

#include <windows.h>
#include <iostream.h>
#include "Shlwapi.h"

void main( void )
{
    // String for path name without backslash.
    char buffer_1[] = "C:\\dir_name\\dir_name\\file_name";
    char *lpStr1;
    lpStr1 = buffer_1;

    // String for path name with backslash.
    char buffer_2[] = "C:\\dir_name\\dir_name\\file_name\\";
    char *lpStr2;
    lpStr2 = buffer_2;

cout << "The original path string 1 is " << lpStr1 << endl;
cout << "The modified path string 1 is "
     <<  PathAddBackslash(lpStr1)   << lpStr1 << endl;

cout << "\nThe original path string 2 is " << lpStr2 << endl;
cout << "The modified path string 2 is "
     <<  PathAddBackslash(lpStr2)   << lpStr2 << endl;

}
OUTPUT:
---------
The original path string 1 is C:\dir_name\dir_name\file_name
The modified path string 1 is C:\dir_name\dir_name\file_name\

The original path string 2 is C:\dir_name\dir_name\file_name\
The modified path string 2 is C:\dir_name\dir_name\file_name\


PathAddExtension

BOOL PathAddExtension(
    LPTSTR  pszPath,
    LPCTSTR pszExtension
    );

Adds a file extension to a string.

  • Returns TRUE if successful, or FALSE otherwise.
pszPath
Address of the string to which the file extension will be added.
pszExtension
Address of the string that contains the file extension.

If there is already a file extension present, no extension will be added. If the path is a null string, the result will be the file extension only.

Example:

#include <windows.h>
#include <iostream.h>
#include "Shlwapi.h"

void main( void )
{
     // String for path name without file extension.
     char buffer_1[] = "file";
     char *lpStr1;
     lpStr1 = buffer_1;

     // String for path name with file extension.
     char buffer_2[] = "file.doc";
     char *lpStr2;
     lpStr2 = buffer_2;

     // String for extension name.
     char F_Ext[] = ".txt";
     char *lpStr3;
     lpStr3 = F_Ext;

     // Null string as path.
     char N_String[] = "\0";
     char *lpStr4;
     lpStr4 = N_String;

     // Path 1 without the file extension.
     cout << "The original path string 1 is  " << lpStr1 << endl;

     int ret_1 = PathAddExtension(lpStr1,lpStr3);
     cout << "The modified path string 1 is  " << lpStr1 << endl;

    // Path 2 with the file extension already there.
    cout << "The original path string 2 is  " << lpStr2 << endl;
    int ret_2 = PathAddExtension(lpStr2,lpStr3);
    cout << "The modified path string 2 is  " << lpStr2<< endl;

    // Path 3 null string as a path.
    int ret_3 = PathAddExtension(lpStr4,lpStr3);
    cout << "The return value is " << ret_3<< endl;
    cout << "The modified path on a null string is " << lpStr4<< endl;

    int ret_4 = PathAddExtension("sample","");
    cout << "The return value is " << ret_4<< endl;

    if(ret_4 != 1)
    {cout << "The PathAddExtension failed" << endl;}
    else {cout << "The PathAddExtension succeeded" << endl;}
}
OUTPUT:
-----------------------
The original path string 1 is  file
The modified path string 1 is  file.txt
The original path string 2 is  file.doc
The modified path string 2 is  file.doc
The return value is 1
The modified path on a null string is .txt
The return value is 1
The PathAddExtension succeeded


PathAppend

BOOL PathAppend(
    LPTSTR  pPath,
    LPCTSTR pMore
    );

Appends one path to the end of another.

  • Returns TRUE if successful, or FALSE otherwise.
pPath
Address of the string to which the file name will be appended.
pMore
Address of the string that represents the file name.

Example:

#include <windows.h>
#include <iostream.h>
#include "Shlwapi.h"

void main( void )
{
    // String for path name.
    char buffer_1[] = "name_1\\name_2";
    char *lpStr1;
    lpStr1 = buffer_1;

    // String of what is being added.
    char buffer_2[] = "name_3";
    char *lpStr2;
    lpStr2 = buffer_2;

cout << "The original path string is    " << lpStr1 << endl;
cout << "The part to append to end is   " << lpStr2 << endl;
bool ret = PathAppend(lpStr1,lpStr2);
cout << "The appended path string is    " << lpStr1 << endl;
}

OUTPUT:
---------
The original path string is    name_1\name_2
The part to append to end is   name_3
The appended path string is    name_1\name_2\name_3


PathBuildRoot

LPTSTR PathBuildRoot(
    LPTSTR szRoot,
    int iDrive
    );

Creates a root path from a given drive number.

  • Returns the address of the constructed root path, or NULL otherwise.
szRoot
Address of the string that receives the constructed root path. This buffer must be at least four characters in size.
iDrive
Integer value that indicates the desired drive number.

Example:

#include <windows.h>
#include <iostream.h>
#include "Shlwapi.h"

void main( void )
{
    // String for root name
    char buffer_1[4];
    char *lpStr1;
    lpStr1 = buffer_1;

// Generate a root path based on the drive number (0/25)
// "Example: 0=A: to 25=Z:"
cout << "The root path for 0 is     " << PathBuildRoot(lpStr1,0)  << endl;
cout << "The root path for 1 is     " << PathBuildRoot(lpStr1,1)  << endl;
cout << "The root path for 25 is     " << PathBuildRoot(lpStr1,25) << endl;

}
OUTPUT:
---------------
The root path for 0 is     A:\
The root path for 1 is     B:\
The root path for 25 is     Z:\


PathCanonicalize

BOOL PathCanonicalize(
    LPTSTR  lpszDst,
    LPCTSTR lpszSrc
    );

Canonicalizes a path.

  • Returns TRUE if successful, or FALSE otherwise.
lpszDst
Address of a string that receives the canonicalized path. This buffer should be at least as large as the buffer at lpszSrc.
lpszSrc
Address of the path to be canonicalized.

This function allows the user to specify what to remove from a path by inserting special character sequences into the path. The ".." sequence indicates to remove the path part from the current position to the previous path part. The "." sequence indicates to skip over the next path part to the following path part. The root part of the path cannot be removed.

Example:

#include <windows.h>
#include <iostream.h>
#include "Shlwapi.h"

void main( void )
{
    // Path_1 destination buffer.
    char buffer_1[] = "JustABufferToHoldTheCanonicalizedPathForAnExample";
    char *lpStr1;
    lpStr1 = buffer_1;

    // Path_2 to be Canonicalized.
    char buffer_2[] = "A:\\name_1\\.\\name_2\\..\\name_3";
    char *lpStr2;
    lpStr2 = buffer_2;

    // Path_3 to be Canonicalized.
    char buffer_3[] = "A:\\name_1\\..\\name_2\\.\\name_3";
    char *lpStr3;
    lpStr3 = buffer_3;

    // Path_4 to be Canonicalized.
    char buffer_4[] = "A:\\name_1\\name_2\\.\\name_3\\..\\name_4";
    char *lpStr4;
    lpStr4 = buffer_4;

    // Path_5 to be Canonicalized.
    char buffer_5[] = "A:\\name_1\\.\\name_2\\.\\name_3\\..\\name_4\\..";
    char *lpStr5;
    lpStr5 = buffer_5;

    // Path_6 to be Canonicalized.
    char buffer_6[] = "C:\\..";
    char *lpStr6;
    lpStr6 = buffer_6;

    cout << "The un-canonicalized path 2 is : " << lpStr2
         << "\nThe return value is            : "
         << PathCanonicalize(lpStr1,lpStr2)
         << "\nThe canonicalized path 1 is    : " << lpStr1 << endl;

    cout << "\nThe un-canonicalized path 3 is : " << lpStr3
         << "\nThe return value is            : "
         << PathCanonicalize(lpStr1,lpStr3)
         << "\nThe canonicalized path 1 is    : " << lpStr1 << endl;

    cout << "\nThe un-canonicalized path 4 is : " << lpStr4
         << "\nThe return value is            : "
         << PathCanonicalize(lpStr1,lpStr4)
         << "\nThe canonicalized path 1 is    : " << lpStr1 << endl;

    cout << "\nThe un-canonicalized path 5 is : " << lpStr5
         << "\nThe return value is            : "
         << PathCanonicalize(lpStr1,lpStr5)
         << "\nThe canonicalized path 1 is    : " << lpStr1 << endl;

    cout << "\nThe un-canonicalized path 6 is : " << lpStr6
         << "\nThe return value is            : "
         << PathCanonicalize(lpStr1,lpStr6)
         << "\nThe canonicalized path 1 is    : " << lpStr1 << endl;
}
OUTPUT:
---------
The un-canonicalized path 2 is : A:\name_1\.\name_2\..\name_3
The return value is            : 1
The canonicalized path 1 is    : A:\name_1\name_3

The un-canonicalized path 3 is : A:\name_1\..\name_2\.\name_3
The return value is            : 1
The canonicalized path 1 is    : A:\name_2\name_3

The un-canonicalized path 4 is : A:\name_1\name_2\.\name_3\..\name_4
The return value is            : 1
The canonicalized path 1 is    : A:\name_1\name_2\name_4

The un-canonicalized path 5 is : A:\name_1\.\name_2\.\name_3\..\name_4\..
The return value is            : 1
The canonicalized path 1 is    : A:\name_1\name_2

The un-canonicalized path 6 is : C:\..
The return value is            : 1
The canonicalized path 1 is    : C:\


PathCombine

PathCombine(
    LPTSTR  lpszDest,
    LPCTSTR lpszDir,
    LPCTSTR lpszFile
    );

Concatenates two strings that represent properly formed paths into one path, as well as any relative path pieces.

  • Returns the address of the concatenated path string if successful, or NULL otherwise.
lpszDest
Address of the combined path.
lpszDir
Address of the string that represents the directory path.
lpszFile
Address of the string that represents the file path.

The directory path should be in the form of A:,B:, ..., Z:. The file path should be in a correct form that represents the file part of the path. The file path must not be null, and if it ends with a backslash, the backslash will be maintained.

Example:

#include <windows.h>
#include <iostream.h>
#include "Shlwapi.h"

void main( void )
{
    // Buffer to hold combined path.
    char buffer_1[] = "";
    char *lpStr1;
    lpStr1 = buffer_1;

    // String for balance of path name.
    char buffer_2[] = "One\\Two\\Three";
    char *lpStr2;
    lpStr2 = buffer_2;

    // String for directory name.
    char buffer_3[] = "C:";
    char *lpStr3;
    lpStr3 = buffer_3;

cout << "The file path to be combined is  "
     << lpStr2<< endl;
cout << "The directory name path is       "
     << lpStr3<< endl;
cout << "The combined path is             "
     << PathCombine(lpStr1,lpStr3,lpStr2) << endl;

}
------------
INPUT:
------------
Path for directory part: "C:"
Path for file part: "One\Two\Three"
------------
OUTPUT:
------------
The file path to be combined is  One\Two\Three
The directory name path is       C:
The combined path is             C:\One\Two\Three


PathCompactPath

BOOL PathCompactPath(
    HDC 	hDC,
    LPTSTR 	lpszPath,
    UINT   	dx
    );

Truncates a file path to fit within a given pixel width by replacing path components with ellipses.

  • Returns TRUE if successful, or FALSE otherwise.
hDC
Handle to the device context used for font metrics.
lpszPath
Address of the string to be modified.
dx
Width, in pixels, that the string will be forced to fit within.

This function uses the font currently selected in hDC to calculate the width of the text. This function will not compact the path beyond the base file name preceded by ellipses.

Example:

#include <windows.h>
#include <iostream.h>
#include "Shlwapi.h"
HDC hdc;  /* display DC handle for current font metrics */

void main( void )
{

    // String path name 1.
    char buffer_1[] = "C:\\path1\\path2\\sample.txt";
    char *lpStr1;
    lpStr1 = buffer_1;

    // String path name 2.
    char buffer_2[] = "C:\\path1\\path2\\sample.txt";
    char *lpStr2;
    lpStr2 = buffer_2;

    // String path name 3.
    char buffer_3[] = "C:\\path1\\path2\\sample.txt";
    char *lpStr3;
    lpStr3 = buffer_3;

    // String path name 4.
    char buffer_4[] = "C:\\path1\\path2\\sample.txt";
    char *lpStr4;
    lpStr4 = buffer_4;

    // Variable to get the return from "PathCompactPath".
    int retval;

cout << "The un-truncated path is                " << lpStr1 << endl;

retval = PathCompactPath(hdc,lpStr1,125);
cout << "The truncated path at 125 pixels is :   " << lpStr1 << endl;

retval = PathCompactPath(hdc,lpStr2,120);
cout << "The truncated path at 120 pixels is :   " << lpStr2 << endl;

retval = PathCompactPath(hdc,lpStr3,110);
cout << "The truncated path at 110 pixels is :   " << lpStr3 << endl;

retval = PathCompactPath(hdc,lpStr4,25);
cout << "The truncated path at  25 pixels is :   " << lpStr4 << endl;

}
OUTPUT:
===========
The un-truncated path is                C:\path1\path2\sample.txt
The truncated path at 125 pixels is :   C:\path1\...\sample.txt
The truncated path at 120 pixels is :   C:\pat...\sample.txt
The truncated path at 110 pixels is :   C:\p...\sample.txt
The truncated path at  25 pixels is :   ...\sample.txt


PathCompactPathEx

BOOL PathCompactPathEx(
    LPTSTR  pszOut,
    LPCTSTR pszSrc,
    UINT    cchMax,
    DWORD   dwFlags
    );

Truncates a path to fit within a certain number of characters by replacing path components with ellipses.

  • Returns TRUE if successful, or FALSE otherwise.
pszOut
Address of the string that has been altered.
pszSrc
Address of the string to be altered.
cchMax
Maximum number of characters to be contained in the new string.
dwFlags
Type of path separator to be used. (For example, '\' or '/'. The default is '\'.)


PathCommonPrefix

int PathCommonPrefix(
    LPCTSTR pszFile1,
    LPCTSTR pszFile2,
    LPTSTR  pszPath
    );

Compares two paths to determine if they share a common prefix. A prefix is one of these types: "C:\\", ".", "..", "..\\".

  • Returns the number of characters copied to the output buffer (not including the NULL terminator) if successful, or zero otherwise.
pszFile1
Address of the first path name.
pszFile2
Address of the second path name.
pszPath
Address of the common prefix in the path.

Example:

#include <windows.h>
#include <iostream.h>
#include "Shlwapi.h"

void main( void )
{
    // String path name 1.
    char buffer_1[] = "C:\\win\\desktop\\temp.txt";
    char *lpStr1;
    lpStr1 = buffer_1;

    // String path name 2.
    char buffer_2[] = "c:\\win\\tray\\sample.txt";
    char *lpStr2;
    lpStr2 = buffer_2;

    // String path out buffer.
    char buffer_3[] = "abcdef";
    char *lpStr3;
    lpStr3 = buffer_3;

    // Variable to get the return.
    // from "PathCommonPrefix"
    int	retval;
    retval = PathCommonPrefix(lpStr1,lpStr2,lpStr3);
    cout << "The contents of String 1:            " << lpStr1 << endl;
    cout << "The contents of String 2:            " << lpStr2 << endl;
    cout << "The length of the output buffer is : "
         << retval << endl;
    cout << "The contents of Output buffer:       " << lpStr3 << endl;
}
OUTPUT:
-----------
The contents of String 1:            C:\win\desktop\temp.txt
The contents of String 2:            c:\win\tray\sample.txt
The length of the output buffer is : 6
The contents of Output buffer:       C:\win


PathFileExists

BOOL PathFileExists(
    LPCTSTR lpszPath
    );

Determines if a file exists.

  • Returns TRUE if the file exists, or FALSE otherwise.
lpszPath
Address of the file to verify.

This function will test for the validity of the file and path.

Example:

#include <windows.h>
#include <iostream.h>
#include "Shlwapi.h"

void main( void )
{
    // Valid file path name (file is there).
    char buffer_1[] = "C:\\TEST\\file.txt";
    char *lpStr1;
    lpStr1 = buffer_1;

    // Invalid file path name (file is not there).
    char buffer_2[] = "C:\\TEST\\file.doc";
    char *lpStr2;
    lpStr2 = buffer_2;

    // Return value from "PathFileExists".
    int	retval;

    // Search for the presence of a file with a true result.
    retval = PathFileExists(lpStr1);
    if(retval == 1)
    {
    cout << "Search for the file path of : " << lpStr1 << endl;
    cout << "The file requested \"" << lpStr1 << "\" is a valid file" << endl;
    cout << "The return from function is : " << retval << endl;
    }

    else{
        cout << "\nThe file requested " << lpStr1 << " is not a valid file" << endl;
        cout << "The return from function is : " << retval << endl;
        }

    // Search for the presence of a file with a false result.
    retval = PathFileExists(lpStr2);
    if(retval == 1)
    {
    cout << "\nThe file requested " << lpStr2 << "is a valid file" << endl;
    cout << "Search for the file path of : " << lpStr2 << endl;
    cout << "The return from function is : " << retval << endl;
    }

    else{
        cout << "\nThe file requested \"" << lpStr2 << "\" is not a valid file" << endl;
        cout << "The return from function is : " << retval << endl;
        }
}
OUTPUT
==============
Search for the file path of : C:\TEST\file.txt
The file requested "C:\TEST\file.txt" is a valid file
The return from function is : 1

The file requested "C:\TEST\file.doc" is not a valid file
The return from function is : 0


PathFindExtension

LPTSTR PathFindExtension(
    LPCTSTR pPath
    );

Searches a path for an extension.

  • Returns the address of the "." preceding the extension within pPath if an extension is found, or the address of the trailing NULL character otherwise.
pPath
Address of the path that contains the extension for which to search.


PathFindFileName

LPTSTR PathFindFileName(
    LPCTSTR pPath
    );

Searches a path for a file name.

  • Returns a pointer to the address of the string if successful, or a pointer to the beginning of the path otherwise.
pPath
Address of the file name for which to search.

Example:

#include <windows.h>
#include <iostream.h>
#include "Shlwapi.h"

void main( void )
{
    // Path that contains a file part.
    char buffer_1[] = "c:\\path\\file";
    char *lpStr1;
    lpStr1 = buffer_1;

    cout << "Search for the file in path        " << lpStr1
         << "\nReturns the file part of the path \""
         <<  PathFindFileName(lpStr1) << "\"" << endl;

    cout << "\nSearch for the file in path       \"c:\\path\"" << endl;
    cout << "Returns the file part of the path \""
         <<  PathFindFileName("c:\\path") << "\"" << endl;

    cout << "\nSearch for the file in path       \"c:\\path\\\"" << endl;
    cout << "Returns the file part of the path \""
         <<  PathFindFileName("c:\\path\\") << "\"" << endl;

    cout << "\nSearch for the file in path       \"c:\\\"" << endl;
    cout << "Returns the file part of the path \""
         <<  PathFindFileName("c:\\") << "\"" << endl;

    cout << "\nSearch for the file in path       \"c:\"" << endl;
    cout << "Returns the file part of the path \""
         <<  PathFindFileName("c:") << "\"" << endl;

    cout << "\nSearch for the file in path       \"path\"" << endl;
    cout << "Returns the file part of the path \""
         <<  PathFindFileName("path") << "\"" << endl;
}
OUTPUT:
==========
Search for the file in path        c:\path\file
Returns the file part of the path "file"

Search for the file in path       "c:\path"
Returns the file part of the path "path"

Search for the file in path       "c:\path\"
Returns the file part of the path "path\"

Search for the file in path       "c:\"
Returns the file part of the path "c:\"

Search for the file in path       "c:"
Returns the file part of the path "c:"

Search for the file in path       "path"
Returns the file part of the path "path"


PathFindNextComponent

LPTSTR PathFindNextComponent(
    LPCTSTR pszPath
    );

Parses a path for the next path component. Paths are delimited by backslashes or by the NULL at the end of the path.

  • Returns the address of the start of the next path component if successful, or NULL otherwise.
pszPath
Address of the path to search.

Example:

#include <windows.h>
#include <iostream.h>
#include "Shlwapi.h"

void main( void )
{
    // Path to find the next part.
    char buffer_1[] = "c:\\path1\\path2\\test";
    char *lpStr1;
    lpStr1 = buffer_1;

    cout << "Search a path for the next path component "
         << "after the root " << lpStr1 << endl;
    cout << "Return the next path component: \""
         <<  PathFindNextComponent(lpStr1) << "\"" << endl;

    cout << "\nSearch a path for the next path component "
         << "after the root \"c:\\path1\\path2\"" << endl;
    cout << "Return the next path component: \""
         <<  PathFindNextComponent("c:\\path1\\path2") << "\"" << endl;

    cout << "\nSearch a path for the next path component "
         << "after the root \"c:\\path1\"" << endl;
    cout << "Return the next path component: \""
         <<  PathFindNextComponent("c:\\path1") << "\"" << endl;

}
OUTPUT:
===========
Search a path for the next path component after the root c:\path1\path2\test
Return the next path component: "path1\path2\test"

Search a path for the next path component after the root "c:\path1\path2"
Return the next path component: "path1\path2"

Search a path for the next path component after the root "c:\path1"
Return the next path component: "path1"


PathFindOnPath

BOOL PathFindOnPath(
    LPTSTR    pszFile,
    LPCTSTR * ppszOtherDirs
    );

Finds a file within a given path.

  • Returns TRUE if successful, or FALSE otherwise.
pszFile
Address of the file name for which to search.
ppszOtherDirs
Address of the path to be searched.


PathGetArgs

LPTSTR PathGetArgs(
    LPCTSTR pszPath
    );

Finds the command line arguments within a given path.

  • Returns the address of the beginning of the command line arguments if successful, or NULL otherwise.
pszPath
Address of the path to be searched.

Example:

#include <windows.h>
#include <iostream.h>
#include "Shlwapi.h"

void main( void )
{

    // Path_1 to search for file arguments (2-Args):
    char buffer_1[] = "test.exe temp.txt sample.doc";
    char *lpStr1;
    lpStr1 = buffer_1;

    // Path_2 to search for file arguments (3-Args):
    char buffer_2[] = "test.exe 1 2 3";
    char *lpStr2;
    lpStr2 = buffer_2;

    // Path_3 to search for file arguments (3-Args):
    char buffer_3[] = "test.exe sample All 15";
    char *lpStr3;
    lpStr3 = buffer_3;

    // Path_4 to search for file arguments (zero args):
    char buffer_4[] = "test.exe";
    char *lpStr4;
    lpStr4 = buffer_4;

cout << "The path passed to the function was : " << lpStr1 <<
        "\nThe arg(s)found in path 1 were      : " << PathGetArgs(lpStr1) << endl;

cout << "\nThe path passed to the function was : " << lpStr2 <<
        "\nThe arg(s)found in path 2 were      : " << PathGetArgs(lpStr2) << endl;

cout << "\nThe path passed to the function was : " << lpStr3 <<
        "\nThe arg(s)found in path 3 were      : " << PathGetArgs(lpStr3) << endl;

cout << "\nThe path passed to the function was : " << lpStr4 <<
        "\nThe arg(s)found in path 4 were      : " << PathGetArgs(lpStr4) << endl;

}

OUTPUT:
===========
The path passed to the function was : test.exe temp.txt sample.doc
The arg(s)found in path 1 were      : temp.txt sample.doc

The path passed to the function was : test.exe 1 2 3
The arg(s)found in path 2 were      : 1 2 3

The path passed to the function was : test.exe sample All 15
The arg(s)found in path 3 were      : sample All 15

The path passed to the function was : test.exe
The arg(s)found in path 4 were      :
===========


PathGetCharType

UINT PathGetCharType(
    TUCHAR ch
    );

Determines the type of character with respect to a path.

  • Returns one or more of the following values that define the type of character:
    GCT_INVALID | The character is not valid in a path.
    GCT_LFNCHAR | The character is valid in a long file name.
    GCT_SEPARATOR | The character is a path separator.
    GCT_SHORTCHAR | The character is valid in a short (8.3) file name.
    GCT_WILD | The character is a wildcard character.
ch
Character for which to determine the type.


PathGetDriveNumber

int PathGetDriveNumber(
    LPCTSTR lpsz
    );

Searches a path for a drive letter within the range of 'A' to 'Z' and returns the corresponding drive number.

  • Returns 0 through 25 (corresponding to 'A' through 'Z') if the path has a drive letter, or -1 otherwise.
lpsz
Address of a string that contains the path to be searched.

Example:

#include <windows.h>
#include <iostream.h>
#include "Shlwapi.h"

void main( void )
{
    // Paths to search for drive IDs.
    char buffer_1[] = "A:\\TEST\\bar.txt";
    char *lpStr1;
    lpStr1 = buffer_1;

    char buffer_2[] = "B:\\TEST\\bar.txt";
    char *lpStr2;
    lpStr2 = buffer_2;

    char buffer_3[] = "Z:\\TEST\\bar.txt";
    char *lpStr3;
    lpStr3 = buffer_3;

    char buffer_4[] = "%:\\TEST\\bar.txt";
    char *lpStr4;
    lpStr4 = buffer_4;

cout << "The path passed to the function was  : " << lpStr1 <<
        "\nThe path contains a drive identifier : " << PathGetDriveNumber(lpStr1) << endl;

cout << "The path passed to the function was  : " << lpStr2 <<
        "\nThe path contains a drive identifier : " << PathGetDriveNumber(lpStr2) << endl;

cout << "The path passed to the function was  : " << lpStr3 <<
        "\nThe path contains a drive identifier : " << PathGetDriveNumber(lpStr3) << endl;

cout << "The path passed to the function was  : " << lpStr4 <<
        "\nThe path contains a drive identifier : " << PathGetDriveNumber(lpStr4) << endl;
}
OUTPUT:
===========
The path passed to the function was  : A:\TEST\bar.txt
The path contains a drive identifier : 0
The path passed to the function was  : B:\TEST\bar.txt
The path contains a drive identifier : 1
The path passed to the function was  : Z:\TEST\bar.txt
The path contains a drive identifier : 25
The path passed to the function was  : %:\TEST\bar.txt
The path contains a drive identifier : -1


PathIsContentType

BOOL PathIsContentType(
    LPCTSTR pszPath,
    LPCTSTR pszContentType
    );

Determines if a file's registered content type matches the specified content type. This function obtains the content type for the specified file type and compares that string with the pszContentType. The comparison is not case sensitive.

  • Returns nonzero if the file's registered content type matches pszContentType, or zero otherwise.
pszPath
Address of a character buffer that contains the file whose content type will be compared.
pszContentType
Address of a character buffer that contains the content type string to which the file's registered content type will be compared.


PathIsDirectory

BOOL PathIsDirectory(
    LPCTSTR pszPath
    );

Verifies that a path is a valid directory.

  • Returns TRUE if the path is a valid directory, or FALSE otherwise.
pszPath
Address of the path to verify.


PathIsFileSpec

BOOL PathIsFileSpec(
    LPCTSTR lpszPath
    );

Searches a path for any path delimiting characters (for example, ':' or '\' ). If there are no path delimiting characters present, the path is considered to be a File Spec path.

  • Returns TRUE if there are no path delimiting characters within the path, or FALSE if there are path delimiting characters.
lpszPath
Address of the path to be searched.

Example:

#include <windows.h>
#include <iostream.h>
#include "Shlwapi.h"

void main( void )
{

    // Path 1 string.
    char buffer_1[] = "sample";
    char *lpStr1;
    lpStr1 = buffer_1;

    // Path 2 string.
    char buffer_2[] = "C:\\TEST\\sample";
    char *lpStr2;
    lpStr2 = buffer_2;

    //Return value from "PathIsFileSpec".
    int	retval;

    // Test path 1 for file spec.
    retval = PathIsFileSpec(lpStr1);
    cout << "The path to verify file spec is     : " << lpStr1 << endl;
    cout << "PathIsFileSpec returns TRUE and is  : " << retval << endl;

    // Test path 2 for file spec.
    retval = PathIsFileSpec(lpStr2);
    cout << "\nThe path to verify file spec is     : " << lpStr2 << endl;
    cout << "PathIsFileSpec returns FALSE and is : " << retval << endl;

}
OUTPUT:
==============
The path to verify file spec is     : sample
PathIsFileSpec returns TRUE and is  : 1

The path to verify file spec is     : C:\TEST\sample
PathIsFileSpec returns FALSE and is : 0


PathIsHTMLFile

BOOL PathIsHTMLFile(
    LPCTSTR pszFile
    );

Determines if a file is an HTML file. The determination is made based on the content type that is registered for the file's extension.

  • Returns nonzero if the file is an HTML file, or zero otherwise.
pszFile
Address of a character buffer that contains the path and name of the file.


PathIsPrefix

BOOL PathIsPrefix(
    IN LPCTSTR  pszPrefix,
    IN LPCTSTR  pszPath
    );

Searches a path to determine if it contains a valid prefix of the type passed by pszPrefix. A prefix is one of these types: "C:\\", ".", "..", "..\\".

  • Returns TRUE if the compared path is the full prefix for the path, or FALSE otherwise.
pszPrefix
Address of the prefix for which to search.
pszPath
Address of the path to be searched.

Example:

#include <windows.h>
#include <iostream.h>
#include "Shlwapi.h"

void main( void )
{
    // Path prefix 1.
    char buffer_1[] = "C:\\";
    char *lpStr1;
    lpStr1 = buffer_1;

    // Path prefix 2.
    char buffer_2[] = "C:\\test\\Some\\sample";
    char *lpStr2;
    lpStr2 = buffer_2;

    // Path prefix 3.
    char buffer_3[] = "sample";
    char *lpStr3;
    lpStr3 = buffer_3;

    // Search a path prefix with result true.
    cout << "The contents of path 1 is : " << lpStr1
         << "\nThe contents of path 2 is : " << lpStr2
         << "\nThe return from the function is : "
         <<  PathIsPrefix(lpStr1,lpStr2)
         << "\nPathIsPrefix returns TRUE   "
         << "\nand Path lpStr1 and lpStr2"
         << "\nhave the same prefix :" << endl;

    // Search a path prefix with result false.
    cout << "\nThe contents of path 1 is : " << lpStr1
         << "\nThe contents of path 3 is : " << lpStr3
         << "\nThe return from the function is : "
         <<  PathIsPrefix(lpStr1,lpStr3)
         << "\nPathIsPrefix returns FALSE   "
         << "\nand Path lpStr1 and lpStr3"
         << "\nhave different prefixes :" << endl;
}
OUTPUT:
==============
The contents of path 1 is : C:\
The contents of path 2 is : C:\test\Some\sample
The return from the function is : 1
PathIsPrefix returns TRUE
and Path lpStr1 and lpStr2
have the same prefix :

The contents of path 1 is : C:\
The contents of path 3 is : sample
The return from the function is : 0
PathIsPrefix returns FALSE
and Path lpStr1 and lpStr3
have different prefixes :


PathIsRelative

BOOL PathIsRelative(
    LPCTSTR lpszPath
    );

Searches a path and determines if it is relative.

  • Returns TRUE if the path is relative, or FALSE if it is absolute.
lpszPath
Address of the path to search.

Example:

#include <windows.h>
#include <iostream.h>
#include "Shlwapi.h"

void main( void )
{
    // String path name 1.
    char buffer_1[] = "test.exe";
    char *lpStr1;
    lpStr1 = buffer_1;

    // String path name 2.
    char buffer_2[] = "C:\\test.exe";
    char *lpStr2;
    lpStr2 = buffer_2;

    // Variable to get the return from "PathIsRelative".
    int	retval;

    // Test case with path not absolute.
    retval = PathIsRelative(lpStr1);
    cout << "The return from function is :" << retval << endl;
    cout << "The path is not absolute :   " << lpStr1 << endl;

    // Test case with path absolute.
    retval = PathIsRelative(lpStr2);
    cout << "\nThe return from function is :" << retval << endl;
    cout << "The path is absolute :       " << lpStr2 << endl;

}
OUTPUT:
==========
The return from function is :1
The path is not absolute :   test.exe

The return from function is :0
The path is absolute :       C:\test.exe


PathIsRoot

BOOL PathIsRoot(
    LPCTSTR pPath
    );

Parses a path to determine if a root directory path part exists.

  • Returns TRUE for a valid root path, or FALSE otherwise.
pPath
Address of the path to be validated.

Example:

#include <windows.h>
#include <iostream.h>
#include "Shlwapi.h"

void main( void )
{
    // String path name 1.
    char buffer_1[] = "C:\\";
    char *lpStr1;
    lpStr1 = buffer_1;

    // String path name 2.
    char buffer_2[] = "path\\file";
    char *lpStr2;
    lpStr2 = buffer_2;

    // Variable to get the return from "PathIsRoot".
    int	retval;

    // Test case with path not absolute.
    retval = PathIsRoot(lpStr1);
    cout << "The return from function is       :" << retval << endl;
    cout << "The path does contain a root part :" << lpStr1 << endl;

    // Test case with path absolute.
    retval = PathIsRoot(lpStr2);
    cout << "The return from function is       :" << retval << endl;
    cout << "The path does not contain part    :" << lpStr2 << endl;

}
OUTPUT:
============
The return from function is       :1
The path does contain a root part :C:\
The return from function is       :0
The path does not contain part    :path\file
============


PathIsSameRoot

BOOL PathIsSameRoot(
    LPCTSTR pszPath1,
    LPCTSTR pszPath2
    );

Compares two paths to determine if they have a common root component.

  • Returns TRUE if both strings have the same root component, or FALSE otherwise.
pszPath1
Address of the first path to be compared.
pszPath2
Address of the second path to be compared.

Example:

#include <windows.h>
#include <iostream.h>
#include "Shlwapi.h"

void main( void )
{
    // String path name 1.
    char buffer_1[] = "C:\\path1\\one";
    char *lpStr1;
    lpStr1 = buffer_1;

        // String path name 2.
    char buffer_2[] = "C:\\path2\\two";
    char *lpStr2;
    lpStr2 = buffer_2;

    // Variable to get the
    // return from "PathIsSameRoot".
    int	retval;
    // Compare paths with same root.
    retval = PathIsSameRoot(lpStr1,lpStr2);

    cout << "The return from function is : "
         << retval << endl;
    cout << "The contents of String 1:  " << lpStr1
         << "\nThe contents of String 2:  " << lpStr2
         << "\nThese both have the same root part" << endl;

    //compare paths with different roots
    retval = PathIsSameRoot(lpStr1,"E:\\acme\\three");

    cout << "\nThe return from function is : "
         << retval << endl;
    cout << "The contents of String 1:  " << lpStr1
         << "\nThe contents of String 3:  E:\\acme\\three"
         << "\nThese do not have the same root part" << endl;
}
OUTPUT:
==================
The return from function is : 1
The contents of String 1:  C:\path1\one
The contents of String 2:  C:\path2\two
These both have the same root part

The return from function is : 0
The contents of String 1:  C:\path1\one
The contents of String 3:  E:\acme\three
These do not have the same root part


PathIsSystemFolder

BOOL PathIsSystemFolder(
    LPTSTR pszPath,
    DWORD dwAttrb
    );

Determines if an existing folder contains the attributes that make it a system folder. Alternately indicates if certain attributes qualify a folder to be a system folder.

  • Returns nonzero if the pszPath or dwAttrb represent a system folder, or zero otherwise.
pszPath
Address of a character buffer that contains the name of an existing folder. The attributes for this folder will be retrieved and compared with those that define a system folder. If this folder contains the attributes to make it a system folder, the function returns nonzero. If this value is NULL, this function determines if the attributes passed in dwAttrb qualify it to be a system folder.
dwAttrb
Contains the file attributes to be compared. If pszPath is not NULL, this value is ignored. If pszPath is NULL, the attributes passed in this value are compared with those that qualify a folder as a system folder. If the attributes are sufficient to make this a system folder, this function returns nonzero. These attributes are the attributes that are returned from GetFileAttributes.


PathIsUNC

BOOL PathIsUNC(
    LPCTSTR pszPath
    );

Determines if the string is a valid UNC (universal naming convention) for a server and share path.

  • Returns TRUE if the string is a valid UNC path, or FALSE otherwise.
pszPath
Address of the path to validate.

Example:

#include <windows.h>
#include <iostream.h>
#include "Shlwapi.h"

void main( void )
{
    // String path name 1.
    char buffer_1[] = "\\\\path1\\path2";
    char *lpStr1;
    lpStr1 = buffer_1;

    // String path name 2.
    char buffer_2[] = "\\\\path3";
    char *lpStr2;
    lpStr2 = buffer_2;

    // String path name 3.
    char buffer_3[] = "acme\\path4\\path5";
    char *lpStr3;
    lpStr3 = buffer_3;

    // Variable to get the return
    // from "PathIsUNC".
    int	retval;

    // Test path name 1.
    retval = PathIsUNC(lpStr1);
    cout << "The contents of String 1: " << lpStr1
         << "\nThe return value from the function is " << retval << " = TRUE" << endl;
    // Test path name 2.
    retval = PathIsUNC(lpStr2);
    cout << "The contents of String 2: " << lpStr2
         << "\nThe return value from the function is " << retval << " = TRUE" << endl;
    // Test path name 3.
    retval = PathIsUNC(lpStr3);
    cout << "The contents of String 3: " << lpStr3
         << "\nThe return value from the function is " << retval << " = FALSE"<< endl;
}
OUTPUT:
==============
The contents of String 1: \\path1\path2
The return value from the function is 1 = TRUE
The contents of String 2: \\path3
The return value from the function is 1 = TRUE
The contents of String 3: acme\path4\path5
The return value from the function is 0 = FALSE


PathIsUNCServer

BOOL PathIsUNCServer(
    LPCTSTR pszPath
    );

Determines if a string is a valid UNC (universal naming convention) for a server path only.

  • Returns TRUE if the string is a valid UNC path for a server only (no share name), or FALSE otherwise.
pszPath
Address of the path to validate.

Example:

#include <windows.h>
#include <iostream.h>
#include "Shlwapi.h"

void main( void )
{
    // String path name 1.
    char buffer_1[] = "\\\\path1";
    char *lpStr1;
    lpStr1 = buffer_1;

    // String path name 2.
    char buffer_2[] = "\\\\";
    char *lpStr2;
    lpStr2 = buffer_2;

    // String path name 3.
    char buffer_3[] = "acme\\path2\\path3";
    char *lpStr3;
    lpStr3 = buffer_3;

    // Variable to get the return
    // from "PathIsUNCServer".
    int	retval;

    // Test path name 1.
    retval = PathIsUNCServer(lpStr1);
    cout << "The contents of String 1: " << lpStr1
         << "\nThe return value from the function is " << retval << " = TRUE" << endl;
    // Test path name 2.
    retval = PathIsUNCServer(lpStr2);
    cout << "The contents of String 2: " << lpStr2
         << "\nThe return value from the function is " << retval << " = TRUE" << endl;
    // Test path name 3.
    retval = PathIsUNCServer(lpStr3);
    cout << "The contents of String 3: " << lpStr3
         << "\nThe return value from the function is " << retval << " = FALSE"<< endl;
}
OUTPUT:
The contents of String 1: \\path1
The return value from the function is 1 = TRUE
The contents of String 2: \\
The return value from the function is 1 = TRUE
The contents of String 3: acme\path2\path3
The return value from the function is 0 = FALSE


PathIsUNCServerShare

BOOL PathIsUNCServerShare(
    LPCTSTR pszPath
    );

Determines if the string is a valid UNC (universal naming convention) for a share path only.

  • Returns TRUE if the string is a valid UNC path to the share only (no server name), or FALSE otherwise.
pszPath
Address of the path to validate.

Example:

#include <windows.h>
#include <iostream.h>
#include "Shlwapi.h"

void main( void )
{
    // String path name 1.
    char buffer_1[] = "\\\\path1\\path2";
    char *lpStr1;
    lpStr1 = buffer_1;

    // String path name 2.
    char buffer_2[] = "\\\\path3";
    char *lpStr2;
    lpStr2 = buffer_2;

    // String path name 3.
    char buffer_3[] = "acme\\path4\\path5";
    char *lpStr3;
    lpStr3 = buffer_3;

    // Variable to get the return
    // from "PathIsUNCServerShare".
    int	retval;

    // Test path name 1.
    retval = PathIsUNCServerShare(lpStr1);
    cout << "The contents of String 1: " << lpStr1
         << "\nThe return value from the function is " << retval << " = TRUE" << endl;
    // Test path name 2.
    retval = PathIsUNCServerShare(lpStr2);
    cout << "The contents of String 2: " << lpStr2
         << "\nThe return value from the function is " << retval << " = FALSE" << endl;
    // Test path name 3.
    retval = PathIsUNCServerShare(lpStr3);
    cout << "The contents of String 3: " << lpStr3
         << "\nThe return value from the function is " << retval << " = FALSE"<< endl;
}
OUTPUT:
=================
The contents of String 1: \\path1\path2
The return value from the function is 1 = TRUE
The contents of String 2: \\path3
The return value from the function is 0 = FALSE
The contents of String 3: acme\path4\path5
The return value from the function is 0 = FALSE


PathIsURL

BOOL PathIsURL(
    IN LPCTSTR pszPath
    );

Tests a given string to determine if it conforms to the URL format. This function does not verify that the path points to an existing site—only that it is a legal URL format.

  • Returns TRUE if the path is a valid URL, or FALSE otherwise.
pszPath
Address of the URL path to validate.

Example:

#include <windows.h>
#include <iostream.h>
#include "Shlwapi.h"

void main( void )
{
    // String path name 1.
    char buffer_1[] = "http://www.microsoft.com/software/index.html";
    char *lpStr1;
    lpStr1 = buffer_1;

    // String path name 2.
    char buffer_2[] = "http://www.microsoft.com";
    char *lpStr2;
    lpStr2 = buffer_2;

    // String path name 3.
    char buffer_3[] = "microsoft.com";
    char *lpStr3;
    lpStr3 = buffer_3;

    // Variable to get the return
    // from "PathIsURL".
    int	retval;

    // Test path name 1.
    retval = PathIsURL(lpStr1);
    cout << "The contents of String 1: " << lpStr1
         << "\nThe return value from the function is " << retval << " = TRUE" << endl;
    // Test path name 2.
    retval = PathIsURL(lpStr2);
    cout << "The contents of String 2: " << lpStr2
         << "\nThe return value from the function is " << retval << " = TRUE" << endl;
    // Test path name 3.
    retval = PathIsURL(lpStr3);
    cout << "The contents of String 3: " << lpStr3
         << "\nThe return value from the function is " << retval << " = FALSE"<< endl;
}

OUTPUT:
=============
The contents of String 1: http://www.microsoft.com/software/index.html
The return value from the function is 1 = TRUE
The contents of String 2: http://www.microsoft.com
The return value from the function is 1 = TRUE
The contents of String 3: microsoft.com
The return value from the function is 0 = FALSE


PathMakePretty

BOOL PathMakePretty(
    LPTSTR lpPath
    );

Converts a path to all lowercase characters to give the path a consistent appearance.

  • Returns TRUE if the path has been converted, or FALSE otherwise.
lpPath
Address of the path to be converted.

Example:

#include <windows.h>
#include <iostream.h>
#include "Shlwapi.h"

void main( void )
{
    // Path name 1.
    char buffer_1[] = "C:\\TEST\\FILE";
    char *lpStr1;
    lpStr1 = buffer_1;

    // Path name 2.
    char buffer_2[] = "c:\\test\\file";
    char *lpStr2;
    lpStr2 = buffer_2;

    // Test path name 1.
    cout << "The content of the unconverted path is : " << lpStr1 << endl;
    cout << "The \"PathMakePretty\" function returns the value "
         << PathMakePretty(lpStr1) << "  = TRUE & converts"  << endl;
    cout << "The content of the converted path is   : " << lpStr1 << endl;

    // Test path name 2.
    cout << "\nThe content of the unconverted path is : " << lpStr2 << endl;
    cout << "The \"PathMakePretty\" function returns the value "
         << PathMakePretty(lpStr2) << "  = FALSE & no conversion"  << endl;
    cout << "The content of the converted path is   : " << lpStr2 << endl;

}
OUTPUT:
=============
The content of the unconverted path is : C:\TEST\FILE
The "PathMakePretty" function returns the value 1  = TRUE & converts
The content of the converted path is   : C:\test\file

The content of the unconverted path is : c:\test\file
The "PathMakePretty" function returns the value 0  = FALSE & no conversion
The content of the converted path is   : c:\test\file


PathMakeSystemFolder

BOOL PathMakeSystemFolder(
    LPTSTR pszPath
    );

Gives an existing folder the proper attributes to become a system folder.

  • Returns nonzero if successful, or zero otherwise.
pszPath
Address of a character buffer that contains the name of an existing folder that will be made into a system folder.


PathMatchSpec

BOOL PathMatchSpec(
    LPCTSTR pszFileParam,
    LPCTSTR pszSpec
    );

Searches a string using a DOS wild card match type. The string can be searched for a particular file extension, such as *.bmp, *.doc, and so on.

  • Returns TRUE if the string matches, or FALSE otherwise.
pszFileParam
Address of the string to be searched.
pszSpec
Address of the file type for which to search.

Example:

#include <windows.h>
#include <iostream.h>
#include "Shlwapi.h"

void main( void )
{
    // String path name 1.
    char buffer_1[] = "C:\\Test\\File.txt";
    char *lpStr1;
    lpStr1 = buffer_1;

    // String path name 2.
    char buffer_2[] = "C:\\Test\\File.bmp";
    char *lpStr2;
    lpStr2 = buffer_2;

    // String path name 3.
    char buffer_3[] = "*.txt";
    char *lpStr3;
    lpStr3 = buffer_3;

    // String path name 4.
    char buffer_4[] = "C:\\Test\\File";
    char *lpStr4;
    lpStr4 = buffer_4;

    // Variable to get the return.
    // from "PathMatchSpec"
    int	retval;

    // Test path name 1.
    retval = PathMatchSpec(lpStr1,lpStr3);
    cout << "The contents of String 1: " << lpStr1
         << "\nThe return value from the function is " << retval << " = TRUE" << endl;

    // Test path name 2.
    retval = PathMatchSpec(lpStr2,"*.bmp");
    cout << "The contents of String 2: " << lpStr2
         << "\nThe return value from the function is " << retval << " = TRUE" << endl;

    // Test path name 4.
    retval = PathMatchSpec(lpStr4,lpStr2);
    cout << "The contents of String 4: " << lpStr4
         << "\nThe return value from the function is " << retval << " = FALSE"<< endl;
}
OUTPUT:
==========
The contents of String 1: C:\Test\File.txt
The return value from the function is 1 = TRUE
The contents of String 2: C:\Test\File.bmp
The return value from the function is 1 = TRUE
The contents of String 4: C:\Test\File
The return value from the function is 0 = FALSE


PathParseIconLocation

int PathParseIconLocation(
    IN OUT LPTSTR pszIconFile
    );

Parses a file location string for its file component and icon index.

  • Returns the valid icon index value.
pszIconFile
Address of the string that will be parsed.

Example:

#include <windows.h>
#include <iostream.h>
#include "Shlwapi.h"

void main( void )
{

    // Path to parse for file and icon index.
    char buffer_1[] = "C:\\TEST\\sample.txt,3";
    char *lpStr1;
    lpStr1 = buffer_1;

    // Return value from "PathParseIconLocation".
    int	retval;

    // Search a path to parse for file and icon index.
    retval = PathParseIconLocation(lpStr1);
    cout << "The path to parse for file and icon index is   : " << lpStr1 << endl;
    cout << "PathParseIconLocation returns the icon index of: " << retval << endl;

}
OUTPUT:
==========
The path to parse for file and icon index is   : C:\TEST\sample.txt
PathParseIconLocation returns the icon index of: 3


PathQuoteSpaces

void PathQuoteSpaces(
    LPTSTR lpsz
    );

Searches a path for spaces. If spaces are found, the entire path is quoted.

  • No return value.
lpsz
Address of the path to search.

Example:

#include <windows.h>
#include <iostream.h>
#include "Shlwapi.h"

void main( void )
{

    // Path with spaces.
    char buffer_1[] = "C:\\sample_one\\sample two";
    char *lpStr1;
    lpStr1 = buffer_1;

    // Path before quote spaces.
    cout << "The path before PathQuoteSpaces: " << lpStr1 << endl;

    // Call "PathQuoteSpaces".
    PathQuoteSpaces(lpStr1);

    // Path after quote spaces.
    cout << "The path after PathQuoteSpaces: " << lpStr1 << endl;

}
OUTPUT:
==================
The path before PathQuoteSpaces: C:\sample_one\sample two
The path after PathQuoteSpaces: "C:\sample_one\sample two"


PathRelativePathTo

BOOL PathRelativePathTo(
    LPTSTR  pszPath,
    LPCTSTR pszFrom,
    DWORD   dwAttrFrom,
    LPCTSTR pszTo,
    DWORD   dwAttrTo
    );

Creates a relative path from two paths.

  • Returns TRUE if successful, or FALSE otherwise.
pszPath
Address of a string that receives the relative path. This buffer is assumed to be at least MAX_PATH characters in size.
pszFrom
Address of a string that contains the path that pszPath will be relative from. This is the path in which the relative path can be used.
dwAttrFrom
File attributes of pszFrom. If this value contains FILE_ATTRIBUTE_DIRECTORY, pszFrom is assumed to be directory; otherwise, pszFrom is assumed to be a file.
pszTo
Address of a string that contains the path that pszPath will be relative to. The relative path will point to this path.
dwAttrTo
File attributes of pszTo. If this value contains FILE_ATTRIBUTE_DIRECTORY, pszTo is assumed to be directory; otherwise, pszTo is assumed to be a file.

Example:

#include <windows.h>
#include <iostream.h>
#include "Shlwapi.h"

void main( void )
{
    char szOut[MAX_PATH] = "";
    char szFrom[] = "c:\\a\\b\\path";
    char szTo[] = "c:\\a\\x\\y\\file";

    cout  <<  "The relative path is relative from: ";
    cout  <<  szFrom;
    cout  <<  "\n";

    cout  <<  "The relative path is relative to: ";
    cout  <<  szTo;
    cout  <<  "\n";

    PathRelativePathTo(  szOut,
                         szFrom,
                         FILE_ATTRIBUTE_DIRECTORY,
                         szTo,
                         FILE_ATTRIBUTE_NORMAL);

    cout  <<  "The relative path is: ";
    cout  <<  szOut;
    cout  <<  "\n";
}
OUTPUT:
==================
The relative path is relative from: c:\a\b\path
The relative path is relative to: c:\a\x\y\file
The relative path is: ..\x\y\file


PathRemoveArgs

void PathRemoveArgs(
    LPTSTR pszPath
    );

Removes any arguments from a given path.

  • No return value.
pszPath
Address of the path from which to remove arguments.

Example:

#include <windows.h>
#include <iostream.h>
#include "Shlwapi.h"

void main( void )
{

    // Path with arguments.
    char buffer_1[] = "c:\\a\\b\\FileA Arg1 Arg2";
    char *lpStr1;
    lpStr1 = buffer_1;

    // Path before "PathRemoveArgs".
    cout << "Path before calling \"PathRemoveArgs\": " << lpStr1 << endl;

    // Call function "PathRemoveArgs".
    PathRemoveArgs(lpStr1);

    // Path after "PathRemoveArgs".
    cout << "Path before calling \"PathRemoveArgs\": " << lpStr1 << endl;
}
OUTPUT:
==================
Path before calling "PathRemoveArgs": c:\a\b\FileA Arg1 Arg2
Path before calling "PathRemoveArgs": c:\a\b\FileA


PathRemoveBackslash

LPTSTR PathRemoveBackslash(
    LPTSTR lpszPath
    );

Removes the trailing backslash from a given path.

  • Returns the address of the NULL that replaced the backslash, or the address of the last character if it's not a backslash.
lpszPath
Address of the string from which to remove the backslash.

Example:

#include <windows.h>
#include <iostream.h>
#include "Shlwapi.h"

void main( void )
{

    // Path with backslash.
    char buffer_1[] = "c:\\a\\b\\File\\";
    char *lpStr1;
    lpStr1 = buffer_1;

    // Path before "PathRemoveBackslash".
    cout << "Path before calling \"PathRemoveBackslash\": " << lpStr1 << endl;

    // Call function "PathRemoveBackslash".
    PathRemoveBackslash(lpStr1);

    // Path after "PathRemoveBackslash".
    cout << "Path after calling \"PathRemoveBackslash\": " << lpStr1 << endl;

}
OUTPUT:
==================
Path before calling "PathRemoveBackslash": c:\a\b\File\
Path after calling "PathRemoveBackslash": c:\a\b\File


PathRemoveBlanks

void PathRemoveBlanks(
    LPTSTR lpszString
    );

Removes all leading and trailing spaces from a string.

  • No return value.
lpszString
Address of the string from which to strip all leading and trailing spaces.

Example:

#include <windows.h>
#include <iostream.h>
#include "Shlwapi.h"

void main( void )
{

    // Path with leading and trailing spaces.
    char buffer_1[] = "  c:\\TEST\\File1\\File2  ";
    char *lpStr1;   // |--------- leading   &   |-------- trailing spaces
    lpStr1 = buffer_1;

    // Path before "PathRemoveBlanks".
    cout << "Path before calling \"PathRemoveBlanks\": " << lpStr1 << endl;
    cout << "Dashes are only to indicate path width :"
         <<"\n---->|" << lpStr1 << "|<----" << endl;

    // Call function "PathRemoveBlanks".
    PathRemoveBlanks(lpStr1);

    // Path after "PathRemoveBlanks".
    cout << "\nPath after calling \"PathRemoveBlanks\": " << lpStr1 << endl;
    cout << "Dashes are only to indicate path width :"
         << "\n---->|" << lpStr1 << "|<----" << endl;

}
OUTPUT:
==================
Path before calling "PathRemoveBlanks":   c:\TEST\File1\File2
Dashes are only to indicate path width :
---->|  c:\TEST\File1\File2  |<----

Path after calling "PathRemoveBlanks": c:\TEST\File1\File2
Dashes are only to indicate path width :
---->|c:\TEST\File1\File2|<----


PathRemoveExtension

void PathRemoveExtension(
    LPTSTR pszPath
    );

Removes the file extension from a path, if there is one.

  • No return value.
pszPath
Address of the path from which to remove the extension.

Example:

#include <windows.h>
#include <iostream.h>
#include "Shlwapi.h"

void main( void )
{

    // Path to include file spec.
    char buffer_1[] = "C:\\TEST\\sample.txt";
    char *lpStr1;
    lpStr1 = buffer_1;

    // Print the path with the extension.
    cout << "The path with extension is          : " << lpStr1 << endl;

    // Call to "PathRemoveExtension".
    PathRemoveExtension(lpStr1);

    // Print the path without the extension.
    cout << "\nThe path without extension is       : " << lpStr1 << endl;

}
OUTPUT:
==================
The path with extension is          : C:\TEST\sample.txt

The path without extension is       : C:\TEST\sample


PathRemoveFileSpec

BOOL PathRemoveFileSpec(
    LPTSTR pszPath
);

Removes the trailing file name and backslash from a path, if it has them.

  • Returns nonzero if something was removed, or zero otherwise.
pszPath
Address of the path from which to remove the file name.

Example:

#include <windows.h>
#include <iostream.h>
#include "Shlwapi.h"

void main( void )
{

    // Path to include file spec.
    char buffer_1[] = "C:\\TEST\\sample.txt";
    char *lpStr1;
    lpStr1 = buffer_1;

    // Print the path with the file spec.
    cout << "The path with file spec is          : " << lpStr1 << endl;

    // Call to "PathRemoveFileSpec".
    PathRemoveFileSpec(lpStr1);

    // Print the path without the file spec.
    cout << "\nThe path without file spec is       : " << lpStr1 << endl;

}
OUTPUT:
==================
The path with file spec is          : C:\TEST\sample.txt

The path without file spec is       : C:\TEST


PathRenameExtension

BOOL PathRenameExtension(
    LPTSTR pszPath,
    LPCTSTR pszExt
);

Replaces the extension of a file name with a new extension. If the file name does not contain an extension, the extension will be attached to the end of the string.

  • Returns nonzero if successful, or zero if the new path and extension would exceed MAX_PATH characters.
pszPath
Address of the path for which to replace the extension. This buffer must be at least MAX_PATH characters in size.
pszExt
Address of a character buffer that contains a '.' followed by the new extension.


PathSearchAndQualify

BOOL PathSearchAndQualify(
    LPCTSTR pcszPath,
    LPTSTR  pszFullyQualifiedPath,
    UINT    cchFullyQualifiedPath
    );

Determines if a given path is correctly formatted and fully qualified.

  • Returns TRUE if the path is qualified, or FALSE otherwise.
pcszPath
Address of the path to search.
pszFullyQualifiedPath
Address of the path to be referenced.
cchFullyQualifiedPath
Width of the path, in characters, to be qualified.


PathSkipRoot

LPTSTR PathSkipRoot(
    LPCTSTR pszPath
    );

Parses a path, ignoring the drive letter or UNC server/share path parts.

  • Returns the address of the beginning of the subpath that follows the root (drive letter or UNC server/share).
pszPath
Address of the path to parse.

Example:

#include <windows.h>
#include <iostream.h>
#include "Shlwapi.h"

void main( void )
{

    // Path to convert.
    char buffer_1[] = "C:\\path1\\path2";
    char *lpStr1;
    lpStr1 = buffer_1;

    cout << "The path before is : " << lpStr1 << endl;
    cout << "The path after is :  " << PathSkipRoot(lpStr1) << endl;
}
OUTPUT:
==================
The path before is : C:\path1\path2
The path after is : path1\path2


PathSetDlgItemPath

bool PathSetDlgItemPath(
    HWND hDlg,
    int id,
    LPCSTR pszPath,
    );

Sets the text of a child control in a window or dialog box, using PathCompactPath to make sure the path fits in the control.

  • Returns TRUE if successful, or FALSE otherwise.
hDlg
Handle to the dialog box or window.
id
Identifier of the control.
pszPath
Address of a string that contains the path to set in the control.


PathStripPath

void PathStripPath(
    LPTSTR pszPath
    );

Removes the path portion of a fully qualified path and file.

  • No return value.
pszPath
Address of a string that contains the path and file name that will have the path portion removed.


PathStripToRoot

BOOL PathStripToRoot(
    LPTSTR szRoot
    );

Removes all parts of the path except for the root information.

  • Returns TRUE if a valid drive letter was found in the path, or FALSE otherwise.
szRoot
Address of the path to be converted.

Example:

#include <windows.h>
#include <iostream.h>
#include "Shlwapi.h"

void main( void )
{

    // Path to convert.
    char buffer_1[] = "C:\\path1\\path2";
    char *lpStr1;
    lpStr1 = buffer_1;

    // Print the path before the root is stripped.
    cout << "The contents of the path before is :      " << lpStr1 << endl;

    // Print the return value from the function.
    cout << "The return from \"PathStripToRoot\" is :  "
         << PathStripToRoot(lpStr1) << endl;

    // Print the path before the root is stripped.
    cout << "The contents of the path after is :       " << lpStr1 << endl;
}
OUTPUT:
==================
The path before is :      C:\path1\path2
The return from "PathStripToRoot" is :  1
The path after is :       C:\


PathUnmakeSystemFolder

BOOL PathUnmakeSystemFolder(
    LPTSTR pszPath
    );

Removes the attributes from a folder that make it a system folder. This folder must actually exist in the file system.

  • Returns nonzero if successful, or zero otherwise.
pszPath
Address of a character buffer that contains the name of an existing folder that will have the system folder attributes removed.


PathUnquoteSpaces

void PathUnquoteSpaces(
    LPTSTR lpsz
    );

Removes quotes from the beginning and end of a path.

  • No return value.
lpsz
Address of the path from which to remove the quotes.

Example:

#include <windows.h>
#include <iostream.h>
#include "Shlwapi.h"

void main( void )
{

    // Path to convert.
    char buffer_1[] = "\"C:\\path1\\path2\"";
    char *lpStr1;
    lpStr1 = buffer_1;

    // Print the path before quotes are stripped.
      cout << "The contents of the path before is :  " << lpStr1 << endl;

    // Call the "PathUnquoteSpaces".
    PathUnquoteSpaces(lpStr1);

    // Print the path after quotes are stripped.
    cout << "The contents of the path after is :  " << lpStr1 << endl;
}
OUTPUT:
==================
The path before is :  "C:\path1\path2"
The path after is  :   C:\path1\path2


Registry Functions

This section provides the definitions for the registry functions.

HKEY_TYPE
REGSAM
SHDeleteEmptyKey
SHDeleteKey
SHDeleteValue
SHEnumKeyEx
SHEnumValue
SHGetValue
SHOpenRegStream
SHQueryInfoKey
SHQueryValueEx
SHRegCreateUSKey
SHREGDEL_FLAGS
SHRegDeleteEmptyUSKey
SHRegDeleteUSValue
SHREGENUM_FLAGS
SHRegEnumUSKey
SHRegEnumUSValue
SHRegGetUSValue
SHRegOpenUSKey
SHRegQueryInfoUSKey
SHRegQueryUSValue
SHRegSetUSValue
SHRegWriteUSValue
SHSetValue


SHDeleteEmptyKey

DWORD SHDeleteEmptyKey(
    HKEY     hkey,
    LPCTSTR  pszSubKey
    );

Deletes an empty key and all of its descendants. The function will remove the key and all of the key's associated values from the registry.

  • Returns ERROR_SUCCESS if successful, or a nonzero error code defined in Winerror.h otherwise. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic description of the error.
hkey
Handle to the currently open key, or any of the following predefined values:
HKEY_CLASSES_ROOT
HKEY_CURRENT_CONFIG
HKEY_CURRENT_USER
HKEY_DYN_DATA (Microsoft® Windows® 95 only)
HKEY_LOCAL_MACHINE
HKEY_PERFORMANCE_DATA (Microsoft® Windows NT® only)
HKEY_USERS
pszSubKey
Address of a null-terminated string specifying the name of the key to delete.

Note The specified empty key must not contain any subkeys or values.


SHDeleteKey

DWORD SHDeleteKey(
    HKEY     hkey,
    LPCTSTR  pszSubKey
    );

Deletes a subkey and all its descendants. The function will remove the key and all of the key's values from the registry.

  • Returns ERROR_SUCCESS if successful, or a nonzero error code defined in Winerror.h otherwise. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic description of the error.
hkey
Handle to the currently open key, or any of the following predefined values:
HKEY_CLASSES_ROOT
HKEY_CURRENT_CONFIG
HKEY_CURRENT_USER
HKEY_DYN_DATA (Windows 95 only)
HKEY_LOCAL_MACHINE
HKEY_PERFORMANCE_DATA (Windows NT only)
HKEY_USERS
pszSubKey
Address of a null-terminated string specifying the name of the key to delete.

Windows 95: This function deletes a subkey and all its descendants.

Windows NT: The specified key must not contain any subkeys.


SHDeleteValue

DWORD SHDeleteValue(
    HKEY    hkey,
    LPCTSTR pszSubKey,
    LPCTSTR pszValue
    );

Deletes a named value from the specified registry key.

  • Returns ERROR_SUCCESS if successful, or a nonzero error code defined in Winerror.h otherwise. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic description of the error.
hkey
Handle to the currently open key, or any of the following predefined values:
HKEY_CLASSES_ROOT
HKEY_CURRENT_CONFIG
HKEY_CURRENT_USER
HKEY_DYN_DATA (Windows 95 only)
HKEY_LOCAL_MACHINE
HKEY_PERFORMANCE_DATA (Windows NT only)
HKEY_USERS
pszSubKey
Address of a null-terminated string specifying the name of the subkey for which to change the value.
pszValue
Address of the value to be deleted.


SHEnumKeyEx

DWORD SHEnumKeyEx(
    HKEY hkey,
    DWORD dwIndex,
    LPTSTR pszName,
    LPDWORD pcchName
    );

Enumerates the subkeys of the specified open registry key.

  • Returns ERROR_SUCCESS if successful, or a nonzero error code defined in Winerror.h otherwise. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a textual description of the error.
hkey
Handle to the currently open key, or any of the following predefined values:
HKEY_CLASSES_ROOT
HKEY_CURRENT_CONFIG
HKEY_CURRENT_USER
HKEY_DYN_DATA (Windows 95 only)
HKEY_LOCAL_MACHINE
HKEY_PERFORMANCE_DATA (Windows NT only)
HKEY_USERS
dwIndex
Index of the subkey to retrieve. This parameter should be zero for the first call and incremented for subsequent calls.
pszName
Address of a character buffer that receives the enumerated key name.
pcchName
Address of a DWORD that, on entry, contains the size of the buffer at pszName. On exit, this contains the number of characters that were copied to pszName.


SHEnumValue

DWORD SHEnumValue(
    HKEY hkey,
    DWORD dwIndex,
    LPTSTR pszValueName,
    LPDWORD pcchValueName,
    LPDWORD pdwType,
    LPVOID pvData,
    LPDWORD pcbData
    );

Enumerates the values of the specified open registry key.

  • Returns ERROR_SUCCESS if successful, or a nonzero error code defined in Winerror.h otherwise. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a textual description of the error.
hkey
Handle to the currently open key, or any of the following predefined values:
HKEY_CLASSES_ROOT
HKEY_CURRENT_CONFIG
HKEY_CURRENT_USER
HKEY_DYN_DATA (Windows 95 only)
HKEY_LOCAL_MACHINE
HKEY_PERFORMANCE_DATA (Windows NT only)
HKEY_USERS
dwIndex
Index of the value to retrieve. This parameter should be zero for the first call and incremented for subsequent calls.
pszValueName
Address of a character buffer that receives the enumerated value name. The size of this buffer is specified in pcchVlaueName.
pcchValueName
Address of a DWORD that, on entry, contains the size of the buffer at pszValueName. On exit, this contains the number of characters that were copied to pszValueName.
pdwType
Address of a DWORD that receives the data type of the value. These are the same values as those described under the lpType parameter of RegEnumValue.
pvData
Address of a buffer that receives the data for the value entry. The size of this buffer is specified in pcbData. This parameter can be NULL if the data is not required.
pcbData
Address of a DWORD that, on entry, contains the size of the buffer at pvData. On exit, this contains the number of bytes that were copied to pvData.


SHGetValue

DWORD SHGetValue(
    HKEY     hkey,
    LPCTSTR  pszSubKey,
    LPCTSTR  pszValue,
    LPDWORD  pdwType,
    LPVOID   pvData,
    LPDWORD  pcbData
    );

Retrieves a registry value.

  • Returns ERROR_SUCCESS if successful, or a nonzero error code defined in Winerror.h otherwise. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic description of the error.
hkey
Handle to the currently open key, or any of the following predefined values:
HKEY_CLASSES_ROOT
HKEY_CURRENT_CONFIG
HKEY_CURRENT_USER
HKEY_DYN_DATA (Windows 95 only)
HKEY_LOCAL_MACHINE
HKEY_PERFORMANCE_DATA (Windows NT only)
HKEY_USERS
pszSubKey
Address of a null-terminated string that specifies the name of the subkey from which to get the value.
pszValue
Address of the value.
pdwType
Type of value. For more information, see HKEY_TYPE.
pvData
Address of the destination data buffer.
pcbData
Size of the destination data buffer.

Note If your application must set/get a series of values in the same key, it is better to open the key once and set/get the values with the regular Microsoft® Win32® registry functions rather than use this function repeatedly.


SHSetValue

DWORD SHSetValue(
    HKEY     hkey,
    LPCTSTR  pszSubKey,
    LPCTSTR  pszValue,
    DWORD    dwType,
    LPCVOID  pvData,
    DWORD    cbData
    );

Sets the value of a registry key.

  • Returns ERROR_SUCCESS if successful, or a nonzero error code defined in Winerror.h otherwise. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic description of the error.
hkey
Handle to the currently open key, or any of the following predefined values:
HKEY_CLASSES_ROOT
HKEY_CURRENT_CONFIG
HKEY_CURRENT_USER
HKEY_DYN_DATA (Windows 95 only)
HKEY_LOCAL_MACHINE
HKEY_PERFORMANCE_DATA (Windows NT only)
HKEY_USERS
pszSubKey
Address of a null-terminated string that specifies the name of the subkey with which a value is associated. This 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.
pszValue
Address of a null-terminated string that specifies the value.
dwType
Type of data to be stored. This parameter must be the REG_SZ type. For more information, see HKEY_TYPE.
pvData
Address of a null-terminated string that contains the value to set for the specified key.
cbData
Length, in bytes, of the string pointed to by the pvData parameter, not including the terminating null character.


SHOpenRegStream

IStream* SHOpenRegStream(
    HKEY    hkey,
    LPCTSTR pszSubkey,
    LPCTSTR pszValue,
    DWORD   grfMode
    );

Opens a registry value and supplies an IStream interface that can be used to read from or write to the value.

  • Returns the address of an IStream interface if successful, or NULL otherwise. The calling application is responsible for calling this interface's Release method when the IStream object is no longer needed.
hkey
Handle to the key that is currently open.
pszSubkey
Address of a null-terminated string that specifies the name of the subkey.
pszValue
Address of the value to be accessed.
grfMode
Type of access for the stream. This can be one of the following values:
STGM_READ | Open the stream for reading.
STGM_WRITE | Open the stream for writing.
STGM_READWRITE | Open the stream for reading and writing.


SHQueryInfoKey

DWORD SHQueryInfoKey(
    HKEY hkey,
    LPDWORD pcSubKeys,
    LPDWORD pcchMaxSubKeyLen,
    LPDWORD pcValues,
    LPDWORD pcchMaxValueNameLen
);

Retrieves information about a specified registry key.

  • Returns ERROR_SUCCESS if successful, or a nonzero error code defined in Winerror.h otherwise. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a textual description of the error.
hkey
Handle to the currently open key, or any of the following predefined values:
HKEY_CLASSES_ROOT
HKEY_CURRENT_CONFIG
HKEY_CURRENT_USER
HKEY_DYN_DATA (Windows 95 only)
HKEY_LOCAL_MACHINE
HKEY_PERFORMANCE_DATA (Windows NT only)
HKEY_USERS
pcSubKeys
Address of a DWORD that receives the number of subkeys under the specified key.
pcchMaxSubKeyLen
Address of a DWORD that receives the number of characters in the name of the subkey with the largest name.
pcValues
Address of a DWORD that receives the number of values under the specified key.
pcchMaxValueNameLen
Address of a DWORD that receives the number of characters in the name of the value with the largest name.


SHQueryValueEx

DWORD SHQueryValueEx(
    HKEY     hkey,
    LPCTSTR  pszValue,
    LPDWORD  pdwReserved,
    LPDWORD  pdwType,
    LPVOID   pvData,
    LPDWORD  pcbData
    );

Opens a registry key and queries it for a specific value.

  • Returns ERROR_SUCCESS if successful, or a nonzero error code defined in Winerror.h otherwise. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic description of the error.
hkey
Handle to the currently open key, or any of the following predefined values:
HKEY_CLASSES_ROOT
HKEY_CURRENT_CONFIG
HKEY_CURRENT_USER
HKEY_DYN_DATA (Windows 95 only)
HKEY_LOCAL_MACHINE
HKEY_PERFORMANCE_DATA (Windows NT only)
HKEY_USERS
pszValue
Address of the null-terminated string that contains the name of the value to be queried.
pdwReserved
Reserved; must be null.
pdwType
Address of the variable that receives the key's value type. For more information, see HKEY_TYPE.
pvData
Address of the buffer that receives the value's data. This parameter can be NULL if the data is not required.
pcbData
Address of the variable that specifies the size, in bytes, of the buffer pointed to by the pvData parameter. When the function returns, this variable contains the size of the data copied to pvData.


SHRegCreateUSKey

LONG SHRegCreateUSKey(
    LPCTSTR   pszPath,
    REGSAM    samDesired,
    HUSKEY    hRelativeUSKey,
    PHUSKEY   phNewUSKey,
    DWORD     dwFlags
    );

Creates or opens a user-specific registry key.

  • Returns ERROR_SUCCESS if successful, or a nonzero error code defined in Winerror.h otherwise. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic description of the error.
pszPath
Address of a character buffer that contains the registry path of the key to be created or opened.
samDesired
Desired security access. For more information on security access, see REGSAM.
hRelativeUSKey
Data that indicates which type of HUSKEY to create.
phNewUSKey
Address of an HUSKEY that receive the handle to the new key.
dwFlags
Base key under which the key should be opened. This can be one or more of the following values:
SHREGSET_HKCU | Create/open the key under HKEY_CURRENT_USER.
SHREGSET_HKLM | Create/open the key under HKEY_LOCAL_MACHINE.
SHREGSET_DEFAULT | Create/open the key under both HKEY_CURRENT_USER and HKEY_LOCAL_MACHINE.


SHRegDeleteEmptyUSKey

LONG SHRegDeleteEmptyUSKey
    (HUSKEY hUSKey,
    LPCSTR pszValue,
    SHREGDEL_FLAGS delRegFlags
    );

Deletes an empty user-specific registry key.

  • Returns ERROR_SUCCESS if successful, or a nonzero error code defined in Winerror.h otherwise. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic description of the error.
hUSKey
Handle to the currently open user-specific key.
pszValue
Address of the null-terminated string that specifies the empty user-defined registry key to be deleted.
delRegFlags
One of the SHREGDEL_FLAGS that specifies from which base key the key will be deleted.

See also SHRegDeleteUSValue


SHRegDeleteUSValue

LONG SHRegDeleteUSValue(
    HUSKEY          hUSKey,
    LPCTSTR         pszValue,
    SHREGDEL_FLAGS  delRegFlags
    );

Deletes a user-specific registry value.

  • Returns ERROR_SUCCESS if successful, or a nonzero error code defined in Winerror.h otherwise. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic description of the error.
hUSKey
Handle to the currently open user-specific key.
pszValue
Address of the null-terminated string that names the value to remove.
delRegFlags
One of the SHREGDEL_FLAGS that specifies from which base key the value will be deleted.

See also SHRegDeleteEmptyUSKey


SHRegEnumUSKey

DWORD SHRegEnumUSKey(
    HUSKEY hUSKey,
    DWORD dwIndex,
    LPSTR pszName,
    LPDWORD pcchName,
    SHREGENUM_FLAGS enumRegFlags
    );

Enumerates the subkeys of a user-specific key.

  • Returns ERROR_SUCCESS if successful, or a nonzero error code defined in Winerror.h otherwise. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a textual description of the error.
hUSKey
Handle to the currently open user-specific key.
dwIndex
Index of the subkey to retrieve. This parameter should be zero for the first call and incremented for subsequent calls.
pszName
Address of a character buffer that receives the enumerated key name.
pcchName
Address of a DWORD that, on entry, contains the size of the buffer at pszName. On exit, this contains the number of characters that were copied to pszName.
enumRegFlags
One of the SHREGENUM_FLAGS that specifies the base key in which the enumeration should take place.


SHRegEnumUSValue

DWORD SHRegEnumUSValue(
    HUSKEY hUSkey,
    DWORD dwIndex,
    LPTSTR pszValueName,
    LPDWORD pcchValueNameLen,
    LPDWORD pdwType,
    LPVOID pvData,
    LPDWORD pcbData,
    SHREGENUM_FLAGS enumRegFlags
    );

Enumerates the values of the specified user-specific registry key.

  • Returns ERROR_SUCCESS if successful, or a nonzero error code defined in Winerror.h otherwise. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a textual description of the error.
hUSKey
Handle to the currently open user-specific key.
dwIndex
Index of the value to retrieve. This parameter should be zero for the first call and incremented for subsequent calls.
pszValueName
Address of a character buffer that receives the enumerated value name. The size of this buffer is specified in pcchValueName.
pcchValueNameLen
Address of a DWORD that, on entry, contains the size of the buffer at pszValueName. On exit, this contains the number of characters that were copied to pszValueName.
pdwType
Address of a DWORD that receives the data type of the value. These are the same values as those described under the lpType parameter of RegEnumValue.
pvData
Address of a buffer that receives the data for the value entry. The size of this buffer is specified in pcbData. This parameter can be NULL if the data is not required.
pcbData
Address of a DWORD that, on entry, contains the size of the buffer at pvData. On exit, this contains the number of bytes that were copied to pvData.
enumRegFlags
One of the SHREGENUM_FLAGS that specifies the base key in which the enumeration should take place.


SHRegGetUSValue

LONG SHRegGetUSValue(
    LPCTSTR  pszSubKey,
    LPCTSTR  pszValue,
    LPDWORD  pdwType,
    LPVOID   pvData,
    LPDWORD  pcbData,
    BOOL     fIgnoreHKCU,
    LPVOID   pvDefaultData,
    DWORD    dwDefaultDataSize
    );

Retrieves a user-specific registry value.

  • Returns ERROR_SUCCESS if successful, or a nonzero error code defined in Winerror.h otherwise. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic description of the error.
pszSubKey
Handle to the currently open subkey, or any of the following predefined, reserved handle values:
HKEY_CURRENT_USER
HKEY_CURRENT_USER_RELATIVE
HKEY_DYN_DATA (Windows 95 only)
HKEY_LOCAL_MACHINE
HKEY_LOCAL_MACHINE_RELATIVE
HKEY_PERFORMANCE_DATA (Windows NT only)
pszValue
Address of the null-terminated string that specifies the name of the value.
pdwType
Type of data to be stored. This parameter must be the REG_SZ type. For more information, see HKEY_TYPE.
pvData
Address of a null-terminated string that contains the value to set for the specified key.
pcbData
Length, in bytes, of the string pointed to by the pvData parameter, not including the terminating null character.
fIgnoreHKCU
Variable that indicates whether to ignore HKCU and bring HKLM up to date.
pvDefaultData
Address of the default data.
dwDefaultDataSize
Length, in bytes, of the default data.


SHRegOpenUSKey

LONG SHRegOpenUSKey(
    LPCTSTR  pszPath,
    REGSAM   samDesired,
    HUSKEY   hRelativeUSKey,
    PHUSKEY  phNewUSKey,
    BOOL     fIgnoreHKCU
    );

Opens a user-specific registry key.

  • Returns ERROR_SUCCESS if successful, or a nonzero error code defined in Winerror.h otherwise. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic description of the error.
pszPath
Handle to the currently open HKEY, or any of the following predefined handle values:
HKEY_CURRENT_USER
HKEY_CURRENT_USER_RELATIVE
HKEY_DYN_DATA (Windows 95 only)
HKEY_LOCAL_MACHINE
HKEY_LOCAL_MACHINE_RELATIVE
HKEY_PERFORMANCE_DATA (Windows NT only)
samDesired
Desired security access. For more information on security access, see REGSAM.
hRelativeUSKey
Data that indicates which type of HUSKEY to create.
phNewUSKey
Address of a HUSKEY value that receives the new key handle.
fIgnoreHKCU
Variable that indicates whether to ignore HKCU and bring HKLM up to date.


SHRegQueryInfoUSKey

DWORD SHRegQueryInfoUSKey(
    HUSKEY hUSKey,
    LPDWORD pcSubKeys,
    LPDWORD pcchMaxSubKeyLen,
    LPDWORD pcValues,
    LPDWORD pcchMaxValueNameLen
);

Retrieves information about a specified user-specific registry key.

  • Returns ERROR_SUCCESS if successful, or a nonzero error code defined in Winerror.h otherwise. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a textual description of the error.
hUSKey
Handle to the user-specific key that is currently open.
pcSubKeys
Address of a DWORD that receives the number of subkeys under the specified key.
pcchMaxSubKeyLen
Address of a DWORD that receives the number of characters in the largest subkey name.
pcValues
Address of a DWORD that receives the number of values under the specified key.
pcchMaxValueNameLen
Address of a DWORD that receives the number of characters in the largest value name.


SHRegQueryUSValue

LONG SHRegQueryUSValue(
    HUSKEY   hUSKey,
    LPCTSTR  pszValue,
    LPDWORD  pdwType,
    LPVOID   pvData,
    LPDWORD  pcbData,
    BOOL     fIgnoreHKCU,
    LPVOID   pvDefaultData,
    DWORD    dwDefaultDataSize
    );

Retrieves the type and data for a specified name associated with an open USKEY.

  • Returns ERROR_SUCCESS if successful, or a nonzero error code defined in Winerror.h otherwise. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic description of the error.
hUSKey
Handle to the currently open USKEY, or any of the following predefined values:
HKEY_CLASSES_ROOT
HKEY_CURRENT_CONFIG
HKEY_CURRENT_USER
HKEY_DYN_DATA (Windows 95 only)
HKEY_LOCAL_MACHINE
HKEY_PERFORMANCE_DATA (Windows NT only)
HKEY_USERS
pszValue
Address of the null-terminated string that contains the name of the value to be queried.
pdwType
Address of the variable that receives the key's value type. For more information, see HKEY_TYPE.
pvData
Address of the buffer that receives the value's data. This parameter can be NULL if the data is not required.
pcbData
Address of the variable that specifies the size, in bytes, of the buffer pointed to by the pvData parameter. When the function returns, this variable contains the size of the data copied to pvData.
fIgnoreHKCU
Variable to indicate whether to ignore HKCU and bring HKLM up to date.
pvDefaultData
Address of the default data.
dwDefaultDataSize
Length, in bytes, of the default data.


SHRegSetUSValue

LONG SHRegSetUSValue(
    LPCTSTR pszSubKey,
    LPCTSTR pszValue,
    DWORD   dwType,
    LPVOID  pvData,
    DWORD   cbData,
    DWORD   dwFlags
    );

Sets a user-specific registry value.

  • Returns ERROR_SUCCESS if successful, or a nonzero error code defined in Winerror.h otherwise. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic description of the error.
pszSubKey
Handle to the currently open subkey, or any of the following predefined handle values:
HKEY_CURRENT_USER
HKEY_CURRENT_USER_RELATIVE
HKEY_DYN_DATA (Windows 95 only)
HKEY_LOCAL_MACHINE
HKEY_LOCAL_MACHINE_RELATIVE
HKEY_PERFORMANCE_DATA (Windows NT only)
pszValue
Address of the null-terminated string that specifies the name of the value.
dwType
Type of data to be stored. This parameter must be the REG_SZ type. For more information, see HKEY_TYPE.
pvData
Address of a null-terminated string that contains the value to be set for the specified key.
cbData
Length, in bytes, of the string pointed to by the pvData parameter, not including the terminating null character.
dwFlags
Indicates whether to create/open HKCU, HKLM, or both.

Note If your code involves setting a series of values in the same key, rather than use this function repeatedly, it is better to open the key once and then call SHRegWriteUSValue.


SHRegWriteUSValue

LONG SHRegWriteUSValue(
    HUSKEY  hUSKey,
    LPCTSTR pszValue,
    DWORD   dwType,
    LPVOID  pvData,
    DWORD   cbData,
    DWORD   dwFlags
    );

Writes a user-specific registry value.

  • Returns ERROR_SUCCESS if successful, or a nonzero error code defined in Winerror.h otherwise. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic description of the error.
hUSKey
Handle to the currently open USKEY, or any of the following predefined values:
HKEY_CLASSES_ROOT
HKEY_CURRENT_CONFIG
HKEY_CURRENT_USER
HKEY_DYN_DATA (Windows 95 only)
HKEY_LOCAL_MACHINE
HKEY_PERFORMANCE_DATA (Windows NT only)
HKEY_USERS
pszValue
Address of the null-terminated string that specifies the name of the value.
dwType
Type of data to be stored. This parameter must be the REG_SZ type. For more information, see HKEY_TYPE.
pvData
Address of a null-terminated string that contains the value to be set for the specified key.
cbData
Length, in bytes, of the string pointed to by the pvData parameter, not including the terminating null character.
dwFlags
Indicates whether to create/open HKCU, HKLM, or both.


SHREGDEL_FLAGS

typedef enum
{
    SHREGDEL_DEFAULT = 0x00000000,
    SHREGDEL_HKCU    = 0x00000001,
    SHREGDEL_HKLM    = 0x00000010,
    SHREGDEL_BOTH    = 0x00000011,
}  SHREGDEL_FLAGS;

Provides a set of values that indicate from which base key an item will be deleted.

SHREGDEL_DEFAULT
Deletes from HKEY_CURRENT_USER, or, if the specified item is not found under HKEY_CURRENT_USER, deletes from HKEY_LOCAL_MACHINE.
SHREGDEL_HKCU
Enumerates from HKEY_CURRENT_USER only.
SHREGDEL_HKLM
Enumerates under HKEY_LOCAL_MACHINE only.
SHREGDEL_BOTH
Deletes from both HKEY_CURRENT_USER and HKEY_LOCAL_MACHINE.


SHREGENUM_FLAGS

typedef enum{
    SHREGENUM_DEFAULT = 0x00000000,
    SHREGENUM_HKCU    = 0x00000001,
    SHREGENUM_HKLM    = 0x00000010,
    SHREGENUM_BOTH    = 0x00000011,
} SHREGENUM_FLAGS;

Provides a set of values that indicate the base key that will be used for an enumeration.

SHREGENUM_DEFAULT
Enumerates under HKEY_CURRENT_USER, or, if the specified item is not found in HKEY_CURRENT_USER, enumerates under HKEY_LOCAL_MACHINE.
SHREGENUM_HKCU
Enumerates under HKEY_CURRENT_USER only.
SHREGENUM_HKLM
Enumerates under HKEY_LOCAL_MACHINE only.
SHREGENUM_BOTH
Not used.


REGSAM

Data type used for specifying the security access attributes in the registry. A REGSAM value can be one or more of the following values:

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 and KEY_CREATE_SUB_KEY access.


HKEY_TYPE

Data type used for specifying the type of a registry value. An HKEY_TYPE value can be one of the following values:

REG_BINARY
Binary data in any form.

REG_DWORD
32-bit number.

REG_DWORD_LITTLE_ENDIAN
32-bit number in little-endian format. This is equivalent to REG_DWORD.

In little-endian format, a multibyte value is stored in memory from the lowest byte (the "little end") to the highest byte. For example, the value 0x12345678 is stored as (0x78 0x56 0x34 0x12) in little-endian format.

Windows NT and Windows 95 are designed to run on little-endian computer architectures. A user may connect to computers that have big-endian architectures, such as some UNIX systems.

REG_DWORD_BIG_ENDIAN
32-bit number in big-endian format.

In big-endian format, a multibyte value is stored in memory from the highest byte (the "big end") to the lowest byte. For example, the value 0x12345678 is stored as (0x12 0x34 0x56 0x78) in big-endian format.

REG_EXPAND_SZ
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
Unicode symbolic link.

REG_MULTI_SZ
Array of null-terminated strings that are terminated by two null characters.

REG_NONE
No defined value type.

REG_RESOURCE_LIST
Device-driver resource list.

REG_SZ
Null-terminated string. It will be a Unicode or ANSI string, depending on whether you use the Unicode or ANSI functions.


DLL Versioning

This section describes the function used to provide version information in a DLL.

The following programming elements are used to provide or obtain a DLL's version information:
DllGetVersion
DLLGETVERSIONPROC
DLLVERSIONINFO


DllGetVersion

HRESULT CALLBACK DllGetVersion(
    DLLVERSIONINFO *pdvi
);

Implemented by many of the Windows shell DLLs to provide a method for obtaining DLL-specific version information. This function is not an API, but it is exported by name from the DLL.

To call this function, use the LoadLibrary and GetProcAddress functions to obtain the function pointer. The DLLGETVERSIONPROC type is used as the data type for the function pointer. For more information, see the comments at the end of this reference.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
pdvi
Address of a DLLVERSIONINFO structure that receives the version information. The cbSize member must be filled in before calling the function.

Because different DLLs implement this function, it is necessary to call LoadLibrary to obtain the instance handle to the DLL and then call GetProcAddress to obtain the function pointer. The following example shows a function that will attempt to use DllGetVersion for the supplied DLL and display the version information in a message box:

void GetDllVersion(LPCTSTR lpszDllName)
{
HINSTANCE   hinstDll;
TCHAR       szText[MAX_PATH] = TEXT("Could not load DLL");

//Load the DLL.
hinstDll = LoadLibrary(lpszDllName);

if(hinstDll)
   {
   DLLGETVERSIONPROC pDllGetVersion;

   /*
   You must get this function explicitly because the DLL might not implement
   the function. Depending upon the DLL, the lack of implementation of the
   function may be a version marker in itself.
   */
   pDllGetVersion = (DLLGETVERSIONPROC)GetProcAddress(   hinstDll,
                                                         TEXT("DllGetVersion"));

   if(pDllGetVersion)
      {
      DLLVERSIONINFO    dvi;
      HRESULT           hr;

      ZeroMemory(&dvi, sizeof(dvi));
      dvi.cbSize = sizeof(dvi);

      hr = (*pDllGetVersion)(&dvi);

      if(SUCCEEDED(hr))
         {
         wsprintf(   szText,
                     TEXT("DLL Version = %d.%02d\nBuild# = %d\n"),
                     dvi.dwMajorVersion,
                     dvi.dwMinorVersion,
                     dvi.dwBuildNumber);

         switch(dvi.dwPlatformID)
            {
            case DLLVER_PLATFORM_WINDOWS:
               lstrcat(szText, TEXT("Platform is Windows"));
               break;

            case DLLVER_PLATFORM_NT:
               lstrcat(szText, TEXT("Platform is Windows NT"));
               break;

            default:
               lstrcat(szText, TEXT("Platform is not defined"));
               break;
            }
         }
      else
         {
         lstrcpy( szText,
                  TEXT("DllGetVersion Failed - Cannot determine DLL version."));
         }
      }
   else
      {
      //If GetProcAddress failed, the DLL does not implement DllGetVersion.
      lstrcpy( szText,
               TEXT("GetProcAddress Failed - The DLL does not implement DllGetVersion."));
      }

   FreeLibrary(hinstDll);
   }
else
   {
   lstrcpy(szText, TEXT("Could not load the DLL"));
   }

MessageBox(NULL, szText, lpszDllName, MB_OK | MB_ICONINFORMATION);
}

Currently, most of the Windows shell DLLs implement DllGetVersion. These include, but are not limited to, Shell32.dll, Comctl32.dll, Shdocvw.dll, and Shlwapi.dll.


DLLGETVERSIONPROC

typedef HRESULT (CALLBACK* DLLGETVERSIONPROC)(DLLVERSIONINFO *);

This type definition is used to define a pointer to a DllGetVersion function. This pointer is used when calling the function dynamically by loading the library and getting the function's address. For more information, see the example in DllGetVersion.


DLLVERSIONINFO

typedef struct _DllVersionInfo
{
    DWORD cbSize;
    DWORD dwMajorVersion;
    DWORD dwMinorVersion;
    DWORD dwBuildNumber;
    DWORD dwPlatformID;
}DLLVERSIONINFO;

Receives DLL-specific version information. It is used with the DllGetVersion function.

cbSize
Size of the structure, in bytes. This member must be filled in before calling the function.
dwMajorVersion
Major version of the DLL. If the DLL's version is 4.0.950, this value will be 4.
dwMinorVersion
Minor version of the DLL. If the DLL's version is 4.0.950, this value will be 0.
dwBuildNumber
Build number of the DLL. If the DLL's version is 4.0.950, this value will be 950.
dwPlatformID
Identifies the platform for which the DLL was built. This can be one of the following values:
DLLVER_PLATFORM_WINDOWS | The DLL was built for all Windows platforms.
DLLVER_PLATFORM_NT | The DLL was built specifically for Windows NT.


Taskbar

The Microsoft® Windows® interface includes a special application desktop toolbar called the taskbar. The taskbar can be used for such tasks as switching between open windows and starting new applications.

The taskbar is also known as an appbar. For more information on appbars, see Application Desktop Toolbars.

About the Taskbar

Using the Taskbar

About the Taskbar

The taskbar includes the Start menu, taskbar buttons, a shortcut menu, and a status area.

The Start menu contains commands that can be used to access programs, documents, and settings. These commands include Programs, Documents, Settings, Find, Help, Run, and Shut Down.

A button is placed on the taskbar whenever an application creates a window that isn't owned. To switch to a window, the user simply clicks its window button.

To open the shortcut menu, the user clicks the taskbar with the right mouse button. The shortcut menu includes commands to cascade windows, tile windows, minimize all windows, and set taskbar properties.

Applications can put icons in the status area 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 status area to show that a print job is underway. The status area is at the right end of the taskbar (if the taskbar is horizontal) or at the bottom (if the taskbar is vertical). The status area will also contain the current time if the Show Clock check box is selected in the taskbar properties.

Taskbar Display Options

The taskbar supports two display options: Auto Hide and Always on Top. To set these options, open the taskbar shortcut menu, click Properties, and select or clear the Auto Hide check box or the Always on Top check box. To retrieve the state of these display options, use the ABM_GETSTATE message. If you would like to be notified when the state of these display options changes, process the ABN_STATECHANGE notification message in your window procedure.

The work area is the portion of the screen not obscured by the taskbar. To retrieve the size of the work area, call the SystemParametersInfo function with the SPI_GETWORKAREA value set. To retrieve the rectangle coordinates that describe the location of the taskbar, use the ABM_GETTASKBARPOS message.

Adding Shortcuts to the Start Menu

Applications can use the shell dynamic data exchange interface to add items to the Programs submenu of the Start menu, just as they would use it to add items to a group in Program Manager in earlier versions of Windows. However, this is not the recommended method to use with the Microsoft® Windows NT® version 4.0 and Windows 95 operating systems.

To add an item to the Programs submenu, follow these steps:

  • Create a shell link using the IShellLink interface.
  • Obtain the location of the Programs folder using SHGetSpecialFolderLocation, passing CSIDL_PROGRAMS.
  • Add the shell link to the Programs folder. You can also create a folder in the Programs folder and add the link to that folder.

Visibility of Taskbar Buttons

The shell creates a button on the taskbar whenever an application creates a window that isn't owned. To ensure that the window button is placed on the taskbar, create an unowned window with the WS_EX_APPWINDOW extended style. To prevent the window button from being placed on the taskbar, create the unowned window with the WS_EX_TOOLWINDOW extended style. As an alternative, you can create a hidden window and make this hidden window the owner of your visible window.

The window button typically contains the application icon and title. However, if the application does not contain a system menu, the window button is created without the icon.

If you want your application to display a message to the user while its window is not active, use the FlashWindow function to let the user know that a message is waiting. This function flashes the window button. Once the user clicks the window button to activate the window, your application can display the message.

Modifying the Contents of the Taskbar

Microsoft® Internet Explorer 4.0 adds the capability to modify the contents of the taskbar. From an application, you can now add, remove, and activate taskbar items. Activating the item does not activate the window; it simply shows the item as pressed on the taskbar.

The taskbar modification capabilities are implemented in an OLE COM object. This object is created by calling CoCreateInstance with CLSID_TaskbarList. The interface you request for this object is IID_ITaskbarList. This will create the object and return you an ITaskbarList interface pointer. You must then call the object's ITaskbarList::HrInit method to initialize the object. If HrInit succeeds, you can use the methods of the ITaskbarList interface to modify the contents of the taskbar.

Working with the Status Area

Applications use the Shell_NotifyIcon function to put icons in the status area of the taskbar to serve as status indicators. You should allow the user to obtain additional information by moving the mouse over the icon, clicking the icon, clicking the icon with the right mouse button, and double-clicking the icon. The system notifies you of this mouse movement. The information the user can receive can be summarized as follows:

  • When the user moves the mouse over the icon, the system will display the tooltip that you provided when you added the icon.
  • When the user clicks the icon, your application should display a window with additional information.
  • When the user clicks the icon with the right mouse button, your application should display the shortcut menu.
  • When the user double-clicks the icon, your application should execute the default shortcut menu command.

Sending taskbar messages

Use the Shell_NotifyIcon function to send messages to add, modify, or delete icons from the status area. The parameters for Shell_NotifyIcon include the identifier of the message to send and the address of a NOTIFYICONDATA structure. Members of this structure contain information that the system needs to process the specified message.

To add an icon to the taskbar's status area, send the NIM_ADD message. The NOTIFYICONDATA structure that accompanies the message specifies the handle to the icon, the identifier of the icon, and any tooltip text for the icon. If the Show Clock check box (in the taskbar properties) is selected, the system places the icon to the immediate left of the clock. Otherwise, the icon appears on the right side or at the bottom of the taskbar. Any existing icons are shifted to the left to make room for the new icon.

You can delete an icon from the status area by sending the NIM_DELETE message. You 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.

Taskbar Creation Notification

Microsoft® Internet Explorer 4.0 will notify applications that the taskbar has been created. When the taskbar is created, it will register a message with the "TaskbarCreated" string and then broadcast this message to all top-level windows. When your taskbar application receives this message, it should assume that any taskbar icons it added have been removed and add them again. The following example shows a very simplified method for handling this case.

LRESULT CALLBACK WndProc(HWND hWnd, UINT uMessage, WPARAM wParam, LPARAM lParam)
{
static UINT s_uTaskbarRestart;

switch(uMessage)
    {
    case WM_CREATE:
        s_uTaskbarRestart = RegisterWindowMessage(TEXT("TaskbarCreated"));
        break;

    default:
        if(uMessage == s_uTaskbarRestart)
            AddTaskbarIcons();
        break;
    }
return DefWindowProc(hWnd, uMessage, wParam, lParam);
}

Using the Taskbar

This section includes examples that demonstrate how to add icons to the taskbar status area and how to process callback messages for taskbar icons.

Adding and Deleting Taskbar Icons

You add an icon to the taskbar status area by filling in a NOTIFYICONDATA structure and then passing the structure to Shell_NotifyIcon with the NIM_ADD message. The structure members must specify the handle to the window that is adding the icon, as well as the icon identifier and icon handle. You can also specify tooltip text for the icon. If you need to receive mouse messages for the icon, specify the identifier of the callback message that the system should use to send the message to the window procedure.

The function in the following example demonstrates how to add an icon to the taskbar.

// MyTaskBarAddIcon - adds an icon to the taskbar status area.
// Returns TRUE if successful, or FALSE otherwise.
// hwnd - handle to the window to receive callback messages.
// uID - identifier of the icon.
// hicon - handle to 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 status area, fill a NOTIFYICONDATA structure and send it to the system when you send an NIM_DELETE message. When deleting a taskbar icon, specify only the cbSize, hWnd, and uID members, as the following example shows.

// MyTaskBarDeleteIcon - deletes an icon from the taskbar
//     status area.
// Returns TRUE if successful, or FALSE otherwise.
// hwnd - handle to 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 battery and printer icons to the taskbar. The application calls the function when it receives a callback message. The function determines whether 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;
 }


Shell Reference

This reference describes the programming elements that can be used and implemented by the shell, a name space extension, or a shell extension.

Interfaces

Functions

Callback Functions

Macros

Messages

Structures and Enumerations


Interfaces

This section describes the Microsoft® Windows® shell interfaces.

ICommDlgBrowser
IContextMenu
IContextMenu2
IContextMenu3
ICopyHook
IDeskBand
IDockingWindow
IDockingWindowFrame
IDockingWindowSite
IEnumIDList
IExtractIcon
IFileViewer
IFileViewerSite
IInputObject
IInputObjectSite
INewShortcutHook
INotifyReplica
IPersistFolder
IPersistFolder2
IQueryInfo
IReconcilableObject
IReconcileInitiator
IShellBrowser
IShellChangeNotify (No documentation available at this time)
IShellExecuteHook
IShellExtInit
IShellFolder
IShellIcon
IShellIconOverlay (No documentation available at this time)
IShellIconOverlayIdentifier (No documentation available at this time)
IShellLink
IShellPropSheetExt
IShellView
IShellView2 (No documentation available at this time)
ITaskbarList
IURLSearchHook


ICommDlgBrowser

The ICommDlgBrowser interface is used by the common file dialog boxes to extend the behavior of the shell browser. This interface is obtained by calling QueryInterface on the IShellBrowser object.

When to Implement

This interface is implemented only by the common file dialog boxes.

When to Use

Use ICommDlgBrowser when you need to provide special behavior while hosted inside the common dialog boxes.
ICommDlgBrowser Methods | Description
IncludeObject | Allows the common dialog to filter objects that the view displays.
OnDefaultCommand | Called when a user double-clicks in the view or presses the ENTER key.
OnStateChange | Called after a change of state has occurred in a common dialog box.


ICommDlgBrowser::IncludeObject

HRESULT IncludeObject(
    IShellView * ppshv,
    LPCITEMIDLIST pidl
   );

Allows the common dialog to filter objects that the view displays.

  • The browser should return S_OK to include the object in the view, or S_FALSE to hide it.
ppshv
IShellFolder interface address of the view.
pidl
Address of an identifier list (IDLIST) that is relative to the folder.

This method is called by the IEnumIDList implementation when hosted in the file dialogs. The enumerator should call this method to let the common dialog filter out objects that should not be displayed. Typically, the file dialogs will get the display text of the item, and filter by the extension.

Notes to Callers

Call before returning an object in the shell folder's IDLIST enumerator.

See also ICommDlgBrowser


ICommDlgBrowser::OnDefaultCommand

HRESULT OnDefaultCommand(
    IShellView * ppshv
   );

Called when a user double-clicks in the view or presses the ENTER key.

  • Returns NOERROR if successful, or an OLE-defined error code otherwise.
ppshv
IShellFolder interface address of the view.

The browser should return S_OK if it has processed the action or S_FALSE to let the view perform the default action.

Note to Callers

This method allows the default command to be handled by the common dialog box instead of the view.

See also ICommDlgBrowser


ICommDlgBrowser::OnStateChange

HRESULT OnStateChange(
    IShellView * ppshv,
    ULONG uChange
   );

Called after a state, identified by the uChange parameter, has changed in the IShellView interface.

ppshv
IShellFolder interface address of the view.
uChange
Change in the selection state. This parameter can be one of the following values:
CDBOSC_SETFOCUS | The focus has been set to the view.
CDBOSC_KILLFOCUS | The view has lost the focus.
CDBOSC_SELCHANGE | The selection has changed.
CDBOSC_RENAME | An item has been renamed.

This method is used to let the common file dialogs track the state of the view and change its user interface as needed.

Notes to Callers

When items in the view are selected, or when the view loses the focus, it needs to call this method to notify the common dialog that either the view state or selection state is changing.

See also ICommDlgBrowser


IContextMenu

The IContextMenu interface is used to either create or merge a context menu associated with a certain object.

Default context menus are available for most objects that are visible within Windows Explorer's namespace, such as files, folders, and printer objects. System-provided context menus are adaptable to file objects of any type, provided you have made the appropriate registry entries.

When to Implement

Implement IContextMenu in the following situations:

  • To add dynamic menu items to a context menu associated with an object in the shell's namespace. Implementation is accomplished by means of a handler located within a COM in-process server DLL.
  • To allow menu items to be dynamically added to nondefault drag-and-drop menus. Implementation is accomplished by means of a handler.
  • Applications may either create or merge items' context menus in the shell's namespace (or extended namespace). This is accomplished by an application calling IContextMenu using the IShellFolder::GetUIObjectOf method.
  • A namespace extension should implement IContextMenu so that either the shell or another application can access context menus belonging to items in the namespace. This is accomplished by using IShellFolder::GetUIObjectOf.

Shell extensions based on this interface must be initialized by using the IShellExtInit interface.

Also note that shell extensions do not work unless all appropriate registry entries are made.

When to Use

You do not call this interface directly. It is called by the shell when a user chooses a context menu item that has been added by a handler registered under the appropriate registry keys or when an application includes it as the riid parameter in a call to IShellFolder::GetUIObjectOf.
IContextMenu Methods | Description
GetCommandString | Retrieves the language-independent name of a menu command or the Help text for a menu command.
InvokeCommand | Carries out a menu command. For an example, see the IExtractIcon interface.
QueryContextMenu | Adds commands to a context menu.


IContextMenu::GetCommandString

HRESULT GetCommandString(
    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 NOERROR if successful, or an OLE-defined error code otherwise.
idCmd
Menu item identifier offset.
uFlags
Flags specifying the information to retrieve. This can be one of the following 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 method, and handlers must ignore this parameter when called.
pszName
Address of the buffer to receive the null-terminated string being retrieved.
cchMax
Size of the buffer to receive the null-terminated string.

The language-independent command name can be passed to the IContextMenu::InvokeCommand method to activate a command by an application. The Help text is a description that Windows Explorer displays in its status bar; it should be reasonably short (under 40 characters).

See also IContextMenu


IContextMenu::InvokeCommand

HRESULT InvokeCommand(
    LPCMINVOKECOMMANDINFO lpici
   );

Carries out the command associated with a context menu item.

  • Returns NOERROR if successful, or an OLE-defined error code otherwise.
lpici
Address of a CMINVOKECOMMANDINFO structure containing information about the command.

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 IContextMenu


IContextMenu::QueryContextMenu

HRESULT QueryContextMenu(
    HMENU hmenu,
    UINT indexMenu,
    UINT idCmdFirst,
    UINT idCmdLast,
    UINT uFlags
   );

Adds menu items to the specified menu. The menu items should be inserted in the menu at the position specified by indexMenu, and their menu item identifiers must be between the idCmdFirst and idCmdLast parameter values.

  • Returns an HRESULT structure in which, if the method is successful, the code member contains the menu identifier of the last menu item added plus one.
hmenu
Handle to the menu. The handler should specify this handle when adding menu items.
indexMenu
Zero-based position at which to insert the first menu item.
idCmdFirst
Minimum value that the handler can specify for a menu item identifier.
idCmdLast
Maximum value that the handler can specify for a menu item identifier.
uFlags
Optional flags specifying how the context menu can be changed. Can be any combination of the following values:
CMF_CANRENAME | This flag is set if the calling application supports renaming of items. A context menu extension or drag-and-drop handler should ignore this flag. A namespace extension should add a rename item to the menu if applicable.
CMF_DEFAULTONLY | This flag is set when the user is activating the default action, typically by double-clicking. This flag provides a hint for the context menu extension to add nothing if it does not modify the default item in the menu. 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 | This flag is set when Windows Explorer's tree window is present. Context menu handlers should ignore this value.
CMF_INCLUDESTATIC | This flag is set when a static menu is being constructed. Only the browser should use this flag. All other context menu extensions should ignore this flag.
CMF_NODEFAULT | This flag is set if no item in the menu should be the default item. A context menu extension or drag-and-drop handler should ignore this flag. A namespace extension should not set any of the menu items to the default.
CMF_NORMAL | Indicates normal operation. A context menu extension, namespace extension, or drag-and-drop handler can add all menu items.
CMF_NOVERBS | This flag is set for items displayed in the "Send To:" menu. Context menu handlers should ignore this value.
CMF_VERBSONLY | This flag is set if the context menu is for a shortcut object. Context menu handlers should ignore this value.

The remaining bits of the low-order word are reserved by the system. The high-order word may be used for context-specific communications. The CMF_RESERVED value can be used to mask out the low-order word.

The actual identifier of each menu item should be idCmdFirst plus a menu identifier offset in the range zero through (idCmdLast – idCmdFirst).

See also IContextMenu


IContextMenu2

The IContextMenu2 interface is used to either create or merge a context menu associated with a certain object when the menu involves owner-drawn menu items.

When to Implement

Implement IContextMenu2 if your context menu extension needs to process one or more of the following messages:
WM_INITMENUPOPUP
WM_DRAWITEM
WM_MEASUREITEM

These messages are forwarded to IContextMenu2—through the HandleMenuMsg method—only if a QueryInterface call for an IContextMenu2 interface pointer is successful, indicating that the object supports this interface.

When to Use

You do not call this interface directly. IContextMenu2 is used by the operating system only when it has confirmed that your application is aware of this interface.

IContextMenu2 is derived from IUnknown. The following methods are specific to IContextMenu2.
IContextMenu2 Methods | Description
GetCommandString | Retrieves the language-independent name of a menu command or the Help text for a menu command.
HandleMenuMsg | Handles messages related to drawing owner-drawn menu items.
InvokeCommand | Carries out a menu command. For an example, see the IExtractIcon interface.
QueryContextMenu | Adds commands to a context menu.


IContextMenu2::GetCommandString

HRESULT GetCommandString(
    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 NOERROR if successful, or an OLE-defined error code otherwise.
idCmd
Menu item identifier offset.
uFlags
Flag specifying the information to retrieve. This parameter can be one of the following 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 method, and handles must ignore this parameter when called.
pszName
Address of the buffer to receive the null-terminated string being retrieved.
cchMax
Size of the buffer to receive the null-terminated string.

The language-independent command name is a name that can be passed to the IContextMenu::InvokeCommand method to activate a command by an application. The Help text is a description that Windows Explorer displays in its status bar; it should be reasonably short (under 40 characters).

See also IContextMenu2, IContextMenu


IContextMenu2::HandleMenuMsg

HRESULT HandleMenuMsg(
    UINT uMsg,
    WPARAM wParam,
    LPARAM lParam
   );

Allows client objects of the IContextMenu interface to handle messages associated with owner-drawn menu items.

  • Returns NOERROR if successful, or an OLE-defined error code otherwise.
uMsg
Message to be processed. If it is WM_INITPOPUP, WM_DRAWITEM, or WM_MEASUREITEM, the client object being called may provide owner-drawn menu items.
wParam
Additional message information. The value of this parameter depends on the value of the uMsg parameter.
lParam
Additional message information. The value of this parameter depends on the value of the uMsg parameter.

HandleMenuMsg is called when a client of IContextMenu determines that the IContextMenu2 interface is supported and receives one of the messages specified in the description of the uMsg parameter.


IContextMenu2::InvokeCommand

HRESULT InvokeCommand(
    LPCMINVOKECOMMANDINFO lpici
   );

Carries out the command associated with a context menu item.

  • Returns NOERROR if successful, or an OLE-defined error code otherwise.

    The shell calls this method when the user chooses a command added to a context menu by the handler. This method may also be called by an application without any corresponding user action.

lpici
Address of a CMINVOKECOMMANDINFO structure containing information about the command.

See also IContextMenu2, IContextMenu


IContextMenu2::QueryContextMenu

HRESULT QueryContextMenu(
    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 specified position in the menu, and their menu item identifiers must be in a given range.

  • 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 plus one.
hmenu
Handle to the menu. The handler should specify this handle when adding menu items.
indexMenu
Zero-based position at which to insert the first menu item.
idCmdFirst
Minimum value that the handler can specify for a menu item identifier.
idCmdLast
Maximum value that the handler can specify for menu item identifiers.
uFlags
Optional flags specifying how the context menu can be changed. Can be any combination of the following values:
CMF_DEFAULTONLY | The user activates the default action, typically by double-clicking. This value provides a hint for the context menu to add nothing if it does not modify the default item in the menu. 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. It is specified when the context menu is for an object in Windows 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.

The actual identifier of each menu item should be idCmdFirst plus a menu identifier offset in the range zero through (idCmdLast – idCmdFirst).

See also IContextMenu2, IContextMenu


IContextMenu3

The IContextMenu3 interface is used to create or merge a context menu associated with a certain object when the menu implementation needs to process the WM_MENUCHAR message.

When to Implement

Implement IContextMenu3 if your context menu extension needs to process the WM_MENUCHAR message.

These messages are forwarded to IContextMenu3—through the HandleMenuMsg2 method—only if a QueryInterface call for an IContextMenu3 interface pointer is successful, indicating that the object supports this interface.

When to Use

You do not call this interface directly. IContextMenu3 is used by the operating system only when it has confirmed that your application is aware of this interface.

IContextMenu3 is derived from IContextMenu2. The following method is specific to IContextMenu3:
IContextMenu3 Method | Description
HandleMenuMsg2 | Called when the window that owns the menu receives a WM_MENUCHAR message.

Note This interface is only supported in shell versions 4.71 and later.


IContextMenu3::HandleMenuMsg2

HRESULT HandleMenuMsg2(
    UINT uMsg,
    WPARAM wParam,
    LPARAM lParam,
    LRESULT *plResult
);

Allows context menu handlers to process the WM_MENUCHAR message.

  • Returns NOERROR if successful, or an OLE-defined error code otherwise.
uMsg
Message to be processed. At the present time, this method is only called for WM_MENUCHAR.
wParam
Additional message information. The value of this parameter depends on the value of the uMsg parameter.
lParam
Additional message information. The value of this parameter depends on the value of the uMsg parameter.
plResult
Address of an LRESULT value that the owner of the menu will return from the message.

HandleMenuMsg2 is called when a client of IContextMenu determines that the IContextMenu3 interface is supported and receives one of the messages specified in the description of the uMsg parameter.

Version 4.71

See also IContextMenu2


ICopyHook

ICopyHook is a COM-based interface used to create a copy hook handler. A copy hook handler is a shell extension that determines if a shell folder or printer object can be moved, copied, renamed, or deleted. The shell calls the ICopyHook::CopyCallback method prior to performing one of these operations.

The copy hook handler, which is an OLE in-process server (a DLL), does not perform the task itself, but it does approve or disapprove the action. If the shell receives approval from the copy hook handler, it performs the file system operation. Copy hook handlers are not informed about the success of an operation, so they cannot monitor actions taken on folder objects unless FindFirstChangeNotification is used.

A folder object can have multiple copy hook handlers. For example, even if the shell already has a copy hook handler registered for a particular folder object, you can still register one of your own. If two or more copy hook handlers are registered for an object, the shell simply calls each of them before performing one of the specified file system operations.

The shell initializes ICopyHook directly, without using the IShellExtInit interface first.

CopyCallback returns an integer value that indicates whether or not the shell should perform the operation. The shell will call each copy hook handler registered for a folder object until all the handlers have been called or until one of them has returned a value other than IDYES. The handler returns IDYES to specify that the operation should be performed, or IDNO or IDCANCEL to specify that the operation should be discontinued.

When to Implement

Implement a copy hook handler when you want to be able to control when, or if, these file system operations are performed on a given object. You might want to use a copy hook handler on shared folders, for example.

When to Use

You do not call this shell extension directly. ICopyHook::CopyCallback is called by the shell prior to moving, copying, deleting, or renaming a shell folder object.
ICopyHook Method | Description
CopyCallback | Determines whether a move, copy, delete, or rename operation on a folder object should be allowed or disallowed.


ICopyHook::CopyCallback

UINT CopyCallback(
    HWND hwnd,
    UINT wFunc,
    UINT wFlags,
    LPCSTR pszSrcFile,
    DWORD dwSrcAttribs,
    LPCSTR pszDestFile,
    DWORD dwDestAttribs
   );

Determines whether the shell will be allowed to move, copy, delete, or rename a folder or printer object. The shell calls each copy hook handler registered (see comments below) for a folder or printer object until all the handlers have been called or until one of them returns IDNO or IDCANCEL.

  • Returns an integer value that indicates whether or not the shell should perform the operation. It can be one of the following:
    IDYES Allows the operation.

    IDNO

    Prevents the operation on this file but continues with any other operations that have been approved (for example, a batch copy operation).
    IDCANCEL Prevents the current operation and cancels any pending operations.
hwnd
Handle to the window that the copy hook handler should use as the parent 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 values listed under the wFunc member of the SHFILEOPSTRUCT structure.
wFlags
Flags that control the operation. This parameter can be one or more of the values listed under the fFlags member of the SHFILEOPSTRUCT structure.
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 flags (FILE_ATTRIBUTE_*) defined in the Windows header files.
pszDestFile
Address of a string that contains the name of the destination file.
dwDestAttribs
Attributes of the destination file. This parameter can be a combination of any of the file attribute flags (FILE_ATTRIBUTE_*) defined in the Windows header files.

You need to register your copy hook handler. For example, directory copy hook handlers are registered under HKEY_CLASSES_ROOT\directory\shellex\CopyHookHandlers\your_copyhook\{copyhook CLSID value}. Other registry keys associated with shell extensions are: *, Folder, Drives, Printers, Unknown, and AudioCD.

When this method is called, the shell initializes the ICopyHook interface directly without using an IShellExtInit interface first.

See also SHFileOperation


IDeskBand

IDeskBand is used to obtain information about a band object. See Band Objects for more information about band objects.

When to Implement

Implement IDeskBand if you are implementing a band object.

When to Use

You do not call this interface directly. IDeskBand is used by the shell or the browser to obtain display information for a band object.

IDeskBand is derived from IDockingWindow. The following method is specific to IDeskBand.
IDeskBand Method | Description
GetBandInfo | Retrieves the information for a band object.

Note This interface is only supported in shell versions 4.71 and later.


IDeskBand::GetBandInfo

HRESULT GetBandInfo(
    DWORD dwBandID,
    DWORD dwViewMode,
    DESKBANDINFO* pdbi
);

Retrieves the information for a band object.

  • Returns NOERROR if successful, or an OLE-defined error code otherwise.
dwBandID
Identifier of the band. The container assigns this identifier. The band object can keep this value if it is required.
dwViewMode
View mode of the band object. This will be one of the following values:
DBIF_VIEWMODE_NORMAL | The band object is being displayed in a horizontal band.
DBIF_VIEWMODE_VERTICAL | The band object is being displayed in a vertical band.
DBIF_VIEWMODE_FLOATING | The band object is being displayed in a floating band.
DBIF_VIEWMODE_TRANSPARENT | The band object is being displayed in a transparent band.
pdbi
Address of a DESKBANDINFO structure that receives the band information for the object. The dwMask member of this structure indicates what information is being requested.

Version 4.71


IDockingWindow

The IDockingWindow interface is implemented by window objects that can be docked within the border space of a Windows Explorer window.

When to Implement

You implement IDockingWindow when you want to display a window inside a browser frame. This is normally used for user interface windows, such as toolbars.

When to Use

You do not normally use the IDockingWindow interface. The shell browser uses this interface to support docked windows inside the browser frame.

IDockingWindow is derived from IOleWindow. The following are the methods specific to IDockingWindow.
IDockingWindow Method | Description
CloseDW | Notifies the docking window object that it is about to be removed.
ResizeBorderDW | Notifies the docking window object that the frame's border space has changed.
ShowDW | Instructs the docking window object to show or hide itself.

Note This interface is only supported in shell versions 4.71 and later.


IDockingWindow::CloseDW

HRESULT CloseDW(
    DWORD dwReserved
);

Notifies the docking window object that it is about to be removed from the frame. The docking window object should save any persistent information at this time.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
dwReserved
Reserved. This parameter should always be zero.

Version 4.71

See also IDockingWindow, IDockingWindowFrame, IDockingWindowSite


IDockingWindow::ResizeBorderDW

HRESULT ResizeBorderDW(
    LPCRECT prcBorder,
    IUnknown* punkToolbarSite,
    BOOL fReserved
);

Notifies the docking window object that the frame's border space has changed. In response to this method, the IDockingWindow implementation must call IDockingWindowSite::SetBorderSpaceDW, even if no border space is required or a change is not necessary.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
prcBorder
Address of a RECT structure that contains the frame's available border space.
punkToolbarSite
Address of the site's IUnknown interface. The docking window object should call the QueryInterface method for this interface, requesting IID_IShellToolbarSite, and use that interface to negotiate its border space. It is the docking window object's responsibility to release this interface when it is no longer needed.
fReserved
Reserved for future use. This parameter should always be zero.

The prcBorder parameter will contain the frame's entire available border space. The docking window object should negotiate its border space and then use this information to position itself.

For example, if the docking window object requires 25 pixels at the top of the border space, it should negotiate for this by allocating a BORDERWIDTHS structure, setting the top member to 25, calling IDockingWindowSite::RequestBorderSpaceDW, and then calling IDockingWindowSite::SetBorderSpaceDW. The docking window object can then position its window at prcBorder->left and prcBorder->top. The width of the docking window object's window is determined from prcBorder->right - prcBorder->left, and its height is contained in the top member of the BORDERWIDTHS structure.

Version 4.71

See also IDockingWindow, IDockingWindowFrame, IDockingWindowSite


IDockingWindow::ShowDW

HRESULT ShowDW(
    BOOL bShow
);

Instructs the docking window object to show or hide itself.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
bShow
Boolean value indicating whether the docking window object should show or hide itself. If this parameter is nonzero, the docking window object should show its window. If it is zero, the docking window object should hide its window and return its border space by calling IDockingWindowSite::SetBorderSpaceDW with all zeros.

Version 4.71

See also IDockingWindow, IDockingWindowFrame, IDockingWindowSite


IDockingWindowFrame

The IDockingWindowFrame interface is implemented by the browser to support adding IDockingWindow objects to a frame.

When to Implement

You do not normally implement the IDockingWindowFrame interface. The shell browser implements this interface to support docked windows inside the browser frame.

When to Use

You use IDockingWindowFrame to add, find, and remove docking window objects in a browser frame.

IDockingWindowFrame is derived from IOleWindow. The following are the methods specific to IDockingWindowFrame.
IDockingWindowFrame Methods | Description
AddToolbar | Adds an IDockingWindow object to a frame.
FindToolbar | Finds an IDockingWindow object in a frame.
RemoveToolbar | Removes an IDockingWindow object from a frame.

Note This interface is only supported in shell versions 4.71 and later.


IDockingWindowFrame::AddToolbar

HRESULT AddToolbar(
    IUnknown* punkSrc,
    LPCWSTR pwszItem,
    DWORD dwAddFlags
);

Adds the specified IDockingWindow object to the frame.

  • Returns NOERROR if successful, or an OLE-defined error code otherwise.
punkSrc
Address of the IDockingWindow object to be added.
pwszItem
Address of a null-terminated UNICODE string. This is an application-defined string used for identifying the docking window object.
dwAddFlags
Flags for the docking window object being added. This can be one or more of the following values:
0 | The docking window is a regular, visible docking window.
DWFAF_HIDDEN | The docking window is added but is not shown. To show it at a later time, call its IDockingWindow::ShowDW method.

Version 4.71

See also IDockingWindowFrame, IDockingWindowSite


IDockingWindowFrame::FindToolbar

HRESULT FindToolbar(
    LPCWSTR pwszItem,
    REFIID riid,
    LPVOID* ppvObj
);

Finds the specified IDockingWindow object in the toolbar frame and returns an interface pointer to it.

  • Returns NOERROR if successful, or an OLE-defined error code otherwise.
pwszItem
Address of a null-terminated UNICODE string. This is the same string that was passed to the AddToolbar method.
riid
Identifier of the desired COM interface.
ppvObj
Address to receive the interface pointer. If an error occurs, a NULL pointer is placed in this address.

Version 4.71

See also IDockingWindowFrame, IDockingWindowSite


IDockingWindowFrame::RemoveToolbar

HRESULT RemoveToolbar(
    IUnknown* punkSrc,
    DWORD dwRemoveFlags
);

Removes the specified IDockingWindow from the toolbar frame.

  • Returns NOERROR if successful, or an OLE-defined error code otherwise.
punkSrc
Address of the IDockingWindow object to be removed. The IDockingWindowFrame implementation will call the IDockingWindow::CloseDW and Release methods.
dwRemoveFlags
Option flags for removing the docking window object. This parameter can be one or more of the following values:
DWFRF_NORMAL | The default delete processing is performed.
DWFRF_DELETECONFIGDATA | In addition to deleting the toolbar, any configuration data is removed as well.

Version 4.71

See also IDockingWindowSite


IDockingWindowSite

The IDockingWindowSite interface is implemented by the browser to manage the border space for one or more IDockingWindow objects. This interface is similar to the IOleInPlaceUIWindow interface.

When to Implement

You do not normally implement the IDockingWindowSite interface. The shell browser implements this interface to support docked windows inside the browser frame.

When to Use

You use IDockingWindowSite to negotiate the space for a docking window object in a browser frame.

IDockingWindowSite is derived from IOleWindow. The following are the methods specific to IDockingWindowSite.
IDockingWindowSite Methods | Description
GetBorderDW | Retrieves the allocated border space for a particular IDockingWindow object.
RequestBorderSpaceDW | Processes border space requests for an IDockingWindow object.
SetBorderSpaceDW | Allocates border space for an IDockingWindow object.

Note This interface is only supported in shell versions 4.71 and later.


IDockingWindowSite::GetBorderDW

HRESULT GetBorderDW(
    IUnknown* punkSrc,
    LPRECT prcBorder
);

Retrieves the border space allocated for the specified IDockingWindow object.

  • Returns NOERROR if successful, or an OLE-defined error code otherwise.
punkSrc
Address of the IDockingWindow object for which the border space is being requested.
prcBorder
Address of a RECT structure to receive the entire available border space for the browser. The docking window object should use this information to determine where to place itself. See the IDockingWindow::ResizeBorderDW method for more information.

Version 4.71

See also IDockingWindowFrame, IDockingWindowSite


IDockingWindowSite::RequestBorderSpaceDW

HRESULT RequestBorderSpaceDW(
    IUnknown* punkSrc,
    LPCBORDERWIDTHS pbw
);

Approves, modifies, or refuses a request for an IDockingWindow object's border space. The border space is not allocated until the SetBorderSpaceDW method is called.

  • Returns NOERROR if the border space request is approved or modified, or an OLE-defined error code otherwise.
punkSrc
Address of the IDockingWindow object for which the border space is being requested.
pbw
Address of a BORDERWIDTHS structure. Before calling this method, the structure must be filled with the desired border space. After the method's successful completion, the structure will contain the approved border space. The IDockingWindowSite object may change these values. If border space is critical, it is the caller's responsibility to determine if the returned border space is sufficient.

Version 4.71

See also IDockingWindowFrame


IDockingWindowSite::SetBorderSpaceDW

HRESULT SetBorderSpaceDW(
    IUnknown* punkSrc,
    LPCBORDERWIDTHS pbw
);

Allocates and reserves border space for an IDockingWindow object.

  • Returns NOERROR if successful, or an OLE-defined error code otherwise.
punkSrc
Address of the IDockingWindow object for which the border space is being set.
pbw
Address of a BORDERWIDTHS structure that contains the IDockingWindow object's border space. The border space should have been approved by IDockingWindowSite through a successful call to the RequestBorderSpaceDW method.

Version 4.71

See also IDockingWindowFrame


IEnumIDList

The IEnumIDList interface enumerates item identifiers associated with shell folder objects. First, use the IShellFolder::EnumObjects method to create an item enumeration object, and then use IEnumIDList to iterate through the item identifiers in the enumeration object.

When to Implement

You can implement this interface when you want a caller to be able to enumerate the item identifiers contained in a folder object. You get a pointer to IEnumIDList through IShellFolder::EnumObjects.

When to Use

You do not use this interface directly. The IShellFolder::EnumObjects method creates an enumeration object of this kind. In this case, the enumeration is a set of item identifiers. The shell calls the IEnumIDList methods to enumerate the items contained in an enumeration object.
IEnumIDList Methods | Description
Clone | Creates a new item enumeration object identical to the current one.
Next | Retrieves the specified number of item identifiers.
Reset | Returns to the beginning of the enumeration.
Skip | Skips over the specified number of items.


IEnumIDList::Clone

HRESULT Clone(
    IEnumIDList **ppenum
   );

Creates a new item enumeration object with the same contents and state as the current one.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
ppenum
Address of a pointer to the new enumeration object. The calling application must eventually free the new object by calling its Release member function.

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

HRESULT Next(
    ULONG celt,
    LPITEMIDLIST *rgelt,
    ULONG *pceltFetched
   );

Retrieves the specified number of item identifiers in the enumeration sequence and advances the current position by the number of items retrieved.

  • Returns NOERROR if successful, S_FALSE if there are no more items in the enumeration sequence, or an OLE-defined error value otherwise.
celt
Number of elements in the array pointed to by the rgelt parameter.
rgelt
Address of an array of ITEMIDLIST pointers that receives the item identifiers. The implementation must allocate these item identifiers using the shell's allocator (retrieved by the SHGetMalloc function). The calling application is responsible for freeing the item identifiers using the shell's allocator.
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 only if celt is one.

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

HRESULT Reset(void);

Returns to the beginning of the enumeration sequence.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.

See also IEnumIDList


IEnumIDList::Skip

HRESULT Skip(
    ULONG celt
   );

Skips over the specified number of elements in the enumeration sequence.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
celt
Number of item identifiers to skip.

See also IEnumIDList


IExtractIcon

The shell uses the IExtractIcon interface to retrieve icons for objects it displays.

The operating system provides default icons for file objects, but you can specify custom icons by making appropriate registry entries and, in some cases, by using IExtractIcon.

When to Implement

You implement IExtractIcon to provide either instance-specific icons for objects in a particular class or icons for subfolders that extend Windows Explorer's namespace. These implementations are accomplished by writing handler code in an OLE in-process server COM DLL.

Also, if you implement IShellFolder, you will need to provide an implementation of IExtractIcon that callers can obtain by using the IShellFolder::GetUIObjectOf method.

Shell extensions based on IExtractIcon must be initialized by using the IPersistFile::Load method. You should also note that shell extensions do not work unless all appropriate registry entries are made.

When to Use

In most cases, you do not call this interface directly. It is usually called by the shell when an icon has been made available by a properly registered handler. However, you can call IExtractIcon directly if you want to delegate icon extraction to another object.
IExtractIcon Methods | Description
Extract | Extracts an icon from the specified location.
GetIconLocation | Retrieves the icon location for an object.


IExtractIcon::Extract

HRESULT Extract(
    LPCSTR pszFile,
    UINT nIconIndex,
    HICON *phiconLarge,
    HICON *phiconSmall,
    UINT nIconSize
   );

Extracts an icon image from the specified location.

  • Returns NOERROR if the function extracted the icon, or S_FALSE if the calling application should extract the icon.
pszFile
Address of a null-terminated string specifying the icon location.
nIconIndex
Icon index.
phiconLarge
Address of the variable that receives the handle to the large icon.
phiconSmall
Address of the variable that receives the handle to the small icon.
nIconSize
Desired size, in pixels, of the icon. The low word contains the size of the large icon, and the high word contains the size of the small icon. 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 returned by the GetIconLocation method. If this function returns S_FALSE, these values must specify an icon file name and index that form legal parameters for a call to Extract. If Extract does not return S_FALSE, no assumptions should be made about the meanings of the pszFile and nIconIndex parameters.

See also IExtractIcon


IExtractIcon::GetIconLocation

HRESULT GetIconLocation(
    UINT uFlags,
    LPSTR szIconFile,
    INT cchMax,
    LPINT piIndex,
    UINT *pwFlags
   );

Retrieves the location and index of an icon.

  • Returns NOERROR if the function returned a valid location, or S_FALSE if the shell should use a default icon.
uFlags
Flags. This parameter can be zero or one or more of the following values:
GIL_ASYNC | The calling application supports asynchronous retrieval of icons. If the icon is cached by the receiving application, it should supply the icon and return S_OK. If the icon is not cached and must be retrieved, the receiving application should start an asynchronous icon retrieval operation, supply a default icon, and return E_PENDING. This method will be called again at a later time to attempt to retrieve the icon again.
GIL_FORSHELL | The icon is to be displayed in a shell folder.
GIL_OPENICON | The icon should be in the open state if both open- and closed-state images are available. If this flag is not specified, the icon should be in the normal or closed state. This flag is typically used for folder objects.
szIconFile
Address of the buffer that receives the icon location. The icon location is a null-terminated string that identifies the file that contains the icon.
cchMax
Size of the buffer that receives the icon location.
piIndex
Address of an INT that receives the icon index, which further describes the icon location.
pwFlags
Address of a UINT value that receives zero or a combination of the following values:
GIL_DONTCACHE | The physical image bits for this icon should not be cached by the caller. This distinction is important to consider because a GIL_DONTCACHELOCATION flag may be introduced in future versions of the shell.
GIL_NOTFILENAME | The location is not a file name/index pair. Callers that decide to extract the icon from the location must call this object's IExtractIcon::Extract method to obtain the desired icon images.
GIL_PERCLASS | All objects of this class have the same icon. This flag is used internally by the shell. Typical implementations of IExtractIcon do not require this flag because the flag implies that an icon handler is not required to resolve the icon on a per-object basis. The recommended method for implementing per-class icons is to register a DefaultIcon for the class.
GIL_PERINSTANCE | Each object of this class has its own icon. This flag is used internally by the shell to handle cases like Setup.exe, where objects with identical names can have different icons. Typical implementations of IExtractIcon do not require this flag.
GIL_SIMULATEDOC | The caller should create a document icon using the specified icon.

See also IExtractIcon::Extract


IFileViewer

The IFileViewer interface designates an interface that allows a registered file viewer to be notified when it must show or print a file.

When to Implement

You implement this interface to provide a means for your registered file types to be viewed and/or printed.

When to Use

You do not normally use this interface. The shell calls the interface when the user chooses the Quick View command from a file's context menu and the file is a type that the file viewer recognizes.
IFileViewer Methods | Description
PrintTo | Prints a file.
Show | Displays a file.
ShowInitialize | Prepares to display a file.


IFileViewer::PrintTo

HRESULT PrintTo(
    LPSTR pszDriver,
    BOOL fSuppressUI
   );

Prints a file. The shell specifies the name of the file to print by calling the file viewer's IPersistFile::Load method.

  • Returns the NOERROR value if successful, or an OLE-defined error value otherwise.
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 is TRUE, the file viewer should not display any user interface, including error messages, during the print operation. If this parameter is FALSE, the file viewer can show dialog boxes, as needed.

See also IFileViewer


IFileViewer::Show

HRESULT Show(
    LPFVSHOWINFO pvsi
   );

Displays a file. The shell specifies the name of the file to display by calling the file viewer's IPersistFile::Load method.

  • Returns NOERROR if successful, or E_UNEXPECTED if the IFileViewer::ShowInitialize method was not called before IFileViewer::Show.
pvsi
Address of an FVSHOWINFO structure to contain 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.

See also IFileViewer


IFileViewer::ShowInitialize

HRESULT ShowInitialize(
    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 NOERROR if successful, or an OLE-defined error value otherwise.
lpfsi
Address of an IFileViewerSite interface. A file viewer uses this interface to retrieve the handle to the current pinned window or to specify a new pinned window.

The shell calls this method before the IFileViewer::Show method. The shell specifies the name of the file to display by calling the file viewer's IPersistFile::Load method.

ShowInitialize must perform all operations that are prone to failure so that if it succeeds, IFileViewer::Show will not fail.

See also IFileViewer


IFileViewerSite

The IFileViewerSite interface designates an interface that allows a file viewer to retrieve the handle to the current pinned window or to set a new pinned window. The pinned window is the window in which the current file viewer displays 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 create a new window.

When to Implement

You do not normally implement this interface. The shell implements this interface to provide a pinned window for the file viewer.

When to Use

You use this interface to obtain or set the window for a file viewer.
IFileViewerSite Methods | Description
GetPinnedWindow | Retrieves the handle to the current pinned window.
SetPinnedWindow | Sets a new pinned window.


IFileViewerSite::GetPinnedWindow

HRESULT GetPinnedWindow(
    HWND *phwnd
   );

Retrieves the handle to the current pinned window, if one exists.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
phwnd
Address of the handle to the current pinned window or NULL if no pinned window exists.

See also IFileViewerSite


IFileViewerSite::SetPinnedWindow

HRESULT SetPinnedWindow(
    HWND *hwnd
   );

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

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
hwnd
Handle to the new pinned window or NULL if there is to be no pinned window.

See also IFileViewerSite


IInputObject

The IInputObject interface is used to change UI activation and process accelerators for a user input object contained in the shell.

When to Implement

Implement IInputObject if you are implementing a shell object that takes user input.

When to Use

You do not call this interface directly. IInputObject is used by the shell or the browser to notify the object of UI activation changes and to translate keyboard accelerators.

IInputObject is derived from IUnknown. The following methods are specific to IInputObject.
IInputObject Methods | Description
HasFocusIO | Determines if one of the object's windows has the keyboard focus.
TranslateAcceleratorIO | Passes keyboard accelerators to the object.
UIActivateIO | Activates or deactivates the object.

Note This interface is only supported in shell versions 4.71 and later.


IInputObject::HasFocusIO

HRESULT HasFocusIO(void);

Determines if one of the object's windows has the keyboard focus.

  • Returns S_OK if one of the object's windows has the keyboard focus, or S_FALSE otherwise.

Version 4.71


IInputObject::TranslateAcceleratorIO

HRESULT TranslateAcceleratorIO(
    LPMSG lpMsg
);

Allows the object to process keyboard accelerators.

  • Returns S_OK if the accelerator was translated, or S_FALSE otherwise.
lpMsg
Address of an MSG structure that contains the keyboard message that is being translated.

Version 4.71


IInputObject::UIActivateIO

HRESULT UIActivateIO(
    BOOL fActivate,
    LPMSG lpMsg
);

UI-activates or deactivates the object.

  • Returns S_OK if the activation change was successful, or an OLE-defined error code otherwise.
fActivate
Indicates if the object is being activated or deactivated. If this value is nonzero, the object is being activated. If this value is zero, the object is being deactivated.
lpMsg
Address of an MSG structure that contains the message that caused the activation change. This value may be NULL.

Version 4.71


IInputObjectSite

The IInputObjectSite interface is used to communicate focus changes for a user input object contained in the shell.

When to Implement

You do not normally implement this interface. IInputObjectSite is implemented by the shell or the browser to properly maintain the input focus.

When to Use

You use IInputObjectSite if you are implementing a shell object that takes user input.

IInputObjectSite is derived from IUnknown. The following method is specific to IInputObjectSite.
IInputObjectSite Method | Description
OnFocusChangeIS | Informs the browser that the focus has changed.

Note This interface is only supported in shell versions 4.71 and later.


IInputObjectSite::OnFocusChangeIS

HRESULT OnFocusChangeIS(
    IUnknown *punkObj,
    BOOL fSetFocus
);

Informs the browser that the focus has changed.

  • Returns S_OK if the method was successful, or an OLE-defined error code otherwise.
punkObj
Address of the IUnknown interface of the object gaining or losing the focus.
fSetFocus
Indicates if the object has gained or lost the focus. If this value is nonzero, the object has gained the focus. If this value is zero, the object has lost the focus.

The calling object should call this method whenever one of its windows gains or loses the input focus.

Version 4.71


INewShortcutHook

The INewShortcutHook interface is used when creating a new Internet shortcut.

When to Implement

You do not normally implement INewShortcutHook. It is implemented by the shell for Internet shortcuts.

When to Use

You use INewShortcutHook when creating a new Internet shortcut. The methods provided by this interface are supplied as a convenience.

INewShortcutHook is derived from IUnknown. The following methods are specific to INewShortcutHook.
INewShortcutHook Methods | Description
GetExtension | Retrieves the file extension for the shortcut object.
GetFolder | Retrieves the folder name for the shortcut object.
GetName | Retrieves the file name of the shortcut object, without the extension.
GetReferent | Retrieves the referent of the shortcut object.
SetFolder | Sets the folder name for the shortcut object.
SetReferent | Sets the referent of the shortcut object.


INewShortcutHook::GetExtension

HRESULT GetExtension(
    LPTSTR pszExtension,
    int cchExtension
);

Retrieves the file extension for the shortcut object.

  • Returns NOERROR if successful, or an OLE-defined error code otherwise.
pszExtension
Address of a character buffer that receives the extension.
cchExtension
Size of the buffer at pszExtension, in characters.

See also INewShortcutHook


INewShortcutHook::GetFolder

HRESULT GetFolder(
    LPTSTR pszFolder,
    int cchFolder
);

Retrieves the folder name for the shortcut object.

  • Returns S_OK if successful, S_FALSE if no folder has been assigned, or an OLE-defined error code otherwise.
pszFolder
Address of a character buffer that receives the folder name.
cchFolder
Size of the buffer at pszFolder, in characters.

See also INewShortcutHook


INewShortcutHook::GetName

HRESULT GetName(
    LPTSTR pszName,
    int cchName
);

Retrieves the file name of the shortcut object, without the extension.

  • Returns NOERROR if successful, or an OLE-defined error code otherwise.
pszName
Address of a character buffer that receives the name.
cchName
Size of the buffer at pszName, in characters.

See also INewShortcutHook


INewShortcutHook::GetReferent

HRESULT GetReferent(
    LPTSTR pszReferent,
    int cchReferent
);

Retrieves the referent of the shortcut object.

  • Returns NOERROR if successful, or an OLE-defined error code otherwise.
pszReferent
Address of a character buffer that receives the referent.
cchReferent
Size of the buffer at pszReferent, in characters.

For Internet shortcut objects, this method is the same as IUniformResourceLocator::GetURL.

See also INewShortcutHook


INewShortcutHook::SetFolder

HRESULT SetFolder(
    LPTSTR pszFolder
);

Sets the folder name for the shortcut object.

  • Returns NOERROR if successful, or an OLE-defined error code otherwise.
pszFolder
Address of a character buffer that contains the folder name.

See also INewShortcutHook


INewShortcutHook::SetReferent

HRESULT SetReferent(
    LPCTSTR pszReferent,
    HWND hWnd
);

Sets the referent of the shortcut object.

  • Returns NOERROR if successful, or an OLE-defined error code otherwise.
pszReferent
Address of a character buffer that contains the referent.
hWnd
Handle to the window that will be used as the parent if the object needs to display a message box or dialog box.

For Internet shortcut objects, this method is the same as IUniformResourceLocator::SetURL.

See also INewShortcutHook


INotifyReplica

The INotifyReplica interface provides the object's creator with the means to notify an object that it may be subject to subsequent reconciliation. The briefcase reconciler is responsible for implementing this interface.
INotifyReplica Method | Description
YouAreAReplica | Notifies an object that it may be subject to reconciliation.


INotifyReplica::YouAreAReplica

HRESULT INotifyReplica::YouAreAReplica(
   ULONG ulcOtherReplicas,
   IMoniker ** rgpmkOtherReplicas
   );

Notifies an object that it may be subject to subsequent reconciliation through the IReconcilableObject::Reconcile method.

  • Returns S_OK if successful, or E_UNEXPECTED otherwise.
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 fail if that object has not previously been notified through INotifyReplica::YouAreAReplica that it may be subject to reconciliation.

The briefcase calls the INotifyReplica interface when objects are added to it.


IPersistFolder

The IPersistFolder interface is used to initialize shell folder objects.

When to Implement

When implementing a shell namespace extension, specifically the IShellFolder interface, you need to implement this interface so the folder object can be initialized. Implementation of this interface is how the folder is told where it is in the shell namespace.

When to Use

You do not use this interface directly. It is used by the file system implementation of the IShellFolder::BindToObject interface when it is initializing a shell folder object.

IPersistFolder is derived from IPersist. The following method is specific to IPersistFolder.
IPersistFolder Method | Description
Initialize | Instructs a shell folder object to initialize itself based on the information passed.


IPersistFolder::Initialize

HRESULT Initialize(
    LPCITEMIDLIST pidl,
   );

Instructs a shell folder object to initialize itself based on the information passed.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
pidl
Address of the ITEMIDLIST (item identifier list) structure that specifies the absolute location of the folder.

Notes to Implementers

All objects that implement the IShellFolder interface for use in the shell's namespace must implement this method. When a folder's location in the namespace is not a relevant consideration, this method can simply return NOERROR. When the location is relevant to the folder, you should store the fully qualified IDLIST passed in for future reference.

For example, if the folder implementation needs to construct a fully qualified PIDL to elements that it contains, the PIDL passed to this method should be used to construct the fully qualified PIDLs.

See also IPersistFolder


IPersistFolder2

The IPersistFolder2 interface is used to obtain information from shell folder objects.

When implementing a shell namespace extension, specifically the IShellFolder interface, you need to implement this interface so that the shell folder object's ITEMIDLIST can be retrieved.

IPersistFolder2 is derived from IPersistFolder. The following method is specific to IPersistFolder2.

Methods
GetCurFolder Retrieves the ITEMIDLIST for the folder object.

Note This interface is only supported in shell versions 4.71 and later.


IPersistFolder2::GetCurFolder

Retrieves the ITEMIDLIST for the folder object.

Syntax

HRESULT GetCurFolder(
    LPITEMIDLIST *ppidl,
);
Parameters

ppidl
Address of an ITEMIDLIST pointer that receives a copy of the PIDL that represents the absolute location of the folder. This PIDL must be relative to the desktop. This will normally be a copy of the PIDL that was passed to IPersistFolder::Initialize.
Return Values

Returns NOERROR if successful, or an OLE-defined error value otherwise.

Remarks

Version 4.71

See Also

IPersistFolder2


IQueryInfo

The shell uses the IQueryInfo interface to retrieve flags and info tip information for an item that resides in an IShellFolder implementation. Info tips are usually displayed inside of a tooltip control.

When to Implement

You implement IQueryInfo to provide flags and text information that differs from the normal text that is displayed for an item in a folder. For example, if your folder contained file objects, you could use the info tip to provide the entire path and file name for the item rather than just the file name.

This interface is obtained by calling IShellFolder::GetUIObjectOf and passing IID_IQueryInfo for the interface identifier. The item for which info tip information is being requested is contained in the apidl argument of the IShellFolder::GetUIObjectOf call. If IQueryInfo is not supplied by the folder, the shell will use the standard display text in the info tip.

When to Use

In most cases, you do not use this interface directly. The shell will use this interface when it requires additional information to display inside of an info tip. However, you can use IQueryInfo directly if you want to obtain info tip information from another object.
IQueryInfo Methods | Description
GetInfoFlags | Retrieves the information flags for an item.
GetInfoTip | Retrieves the info tip text for an item.

Note This interface is only supported in shell versions 4.71 and later.


IQueryInfo::GetInfoFlags

HRESULT GetInfoFlags(
    DWORD *pdwFlags
);

Retrieves the information flags for an item. This method is not currently used.

  • Returns NOERROR if the function succeeds, or an OLE-defined error value otherwise.
pdwFlags
Address of a DWORD that receives the flags for the item.

Version 4.71

See also IQueryInfo


IQueryInfo::GetInfoTip

HRESULT GetInfoTip(
    DWORD dwFlags,
    LPWSTR *ppwszTip
);

Retrieves the info tip text information for an item.

  • Returns NOERROR if the function succeeds, or an OLE-defined error value otherwise.
dwFlags
Not currently used.
ppwszTip
Address of a wide character string pointer that receives the tip string pointer. The memory for this buffer is allocated by the implementation using the shell's allocator (see SHGetMalloc). The calling application is responsible for freeing this memory when it is no longer needed by using the shell's allocator.

Version 4.71

See also IQueryInfo


IReconcilableObject

The IReconcilableObject interface carries out the reconciliation of a document. The briefcase reconciler is responsible for implementing this interface.
IReconcilableObject Methods | Description
GetProgressFeedbackMaxEstimate | Receives estimate of work required to complete a reconciliation.
Reconcile | Reconciles the state of an object with one or more other objects.


IReconcilableObject::GetProgressFeedbackMaxEstimate

HRESULT IReconcilableObject::GetProgressFeedbackMaxEstimate(
    IMoniker ** pulProgressMax
   );

Retrieves an estimated measurement of the amount of work required to complete a reconciliation. Reconcilers typically use this method to estimate the work needed to reconcile an embedded document. This value corresponds to a similar value that is passed with the IReconcileInitiator::SetProgressFeedback method during reconciliation.

  • Returns S_OK if successful, or one of the following error values otherwise:
    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 to receive the work estimate value.

See also IReconcilableObject


IReconcilableObject::Reconcile

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 values if successful:
    S_OK | Reconciliation 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 method and all the other objects described by rgpmkOtherInput) 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, this method 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 stopped reconciliation in response to a termination request from the initiator (see IReconcileInitiator::SetAbortCallback for more information). 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 RECONCILEF_YOUMAYDOTHEUPDATES flag was not set when the object's Reconcile implementation was called; this implementation requires that this value be set in the dwFlags parameter.
    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 | The hwndProgressFeedback parameter is valid.
RECONCILEF_MAYBOTHERUSER | The briefcase reconciler can prompt for user interaction if it is needed. Without this value, user interaction is not permitted. The hwndOwner parameter 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 method is being called to propagate changes in the changed object to other unchanged objects. This value will only be set if the following key exists in the registry.

HKEY_CLASSES_ROOT\
   CLSID\
      <clsid_of_reconciler>\
         SingleChangeHook

If this 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 the plOutIndex parameter 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 can perform the updates. Without this value, the reconciler cannot perform the updates. If reconciliation is completed successfully, the reconciler should return REC_S_IDIDTHEUPDATES if it performed the updates or S_OK if it did not perform the updates.
hwndOwner
Handle to the window to be used as the parent for any child windows that the briefcase reconciler creates. This parameter is valid only if RECONCILEF_MAYBOTHERUSER is specified in dwFlags.
hwndProgressFeedback
Handle to the progress feedback window to be 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 the new residues. This parameter can be NULL to indicate that residues should not be saved.
pvReserved
Reserved; must be NULL.

See also IReconcilableObject


IReconcileInitiator

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. The initiator is responsible for implementing this interface.
IReconcileInitiator Methods | Description
SetAbortCallback | Sets the object through which the initiator can terminate a reconciliation.
SetProgressFeedback | Indicates the amount of progress in the reconciliation.


IReconcileInitiator::SetAbortCallback

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, or one of the following error values otherwise:
    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 method 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 remove the object by calling this method 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 method must return either the REC_E_ABORTED or REC_E_NOTCOMPLETE value.

See also IReconcileInitiator


IReconcileInitiator::SetProgressFeedback

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 and is computed as the quotient of the ulProgress and ulProgressMax parameters. Reconcilers should call this method periodically during their reconciliation process.

  • Returns the S_OK value if successful, or the E_UNEXPECTED value if an 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 method 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.

See also IReconcileInitiator


IShellBrowser

The IShellBrowser interface provides services for namespace extensions and is the companion to the IShellView interface implemented by namespace extensions. It is similar to the site interfaces that are often found in OLE hosting situations, such as the IOleControl and IOleControlSite interfaces. This allows the extension to communicate with the host of the namespace by providing UI elements like menus, status text, and tool bars. This interface also provides the extension with a way to access storage to save its persistent view state.

IShellBrowser derives from the IOleWindow interface, and it represents the container's top-level window. IShellBrowser allows the contained views to insert their menus into the composite menu, install the composite menu into the appropriate window frame, and remove the container's menu elements from the composite menu. IShellBrowser sets and displays status text relevant to the in-place object. It also enables or disables the frame's modeless dialog boxes and translates accelerator keystrokes intended for the container's frame.

When to Implement

You do not implement this interface directly. IShellBrowser is implemented by Windows Explorer and by the Windows File Open common dialog box.

When to Use

When implementing a namespace extension, notably the IShellView interface, you will use the IShellBrowser implementation that is passed to IShellView::CreateViewWindow to communicate with Windows Explorer.

IShellBrowser is derived from IOleWindow. The following are the methods specific to IShellBrowser.
IShellBrowser Methods | Description
BrowseObject | Tells Windows Explorer to browse in another folder.
EnableModelessSB | Enables or disables modeless windows of Windows Explorer, such as a floating toolbar.
GetControlWindow | Gets the window handle to a Windows Explorer control.
GetViewStateStream | Returns a view-specific stream that can be used to read and write the persistent data for a view.
InsertMenusSB | Inserts Windows Explorer's menu items to an empty menu created by the view.
OnViewWindowActive | Informs Windows Explorer that the view was activated.
QueryActiveShellView | Returns the currently activated (displayed) shell view object.
RemoveMenusSB | Instructs the container to remove its items from a composite menu. The tasks it performs are the opposite of InsertMenusSB tasks.
SendControlMsg | Sends messages to Windows Explorer controls.
SetMenuSB | Installs the composite menu in Windows Explorer.
SetStatusTextSB | Sets and displays status text in the Windows Explorer window.
SetToolbarItems | Adds toolbar items to Windows Explorer's toolbar.
TranslateAcceleratorSB | Reserved for future use.


IShellBrowser::BrowseObject

HRESULT BrowseObject(
    LPCITEMIDLIST pidl,
    UINT *wFlags
   );

Tells Windows Explorer to browse to another folder.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
pidl
Address of an ITEMIDLIST (item identifier list) structure that specifies an object's location. This value is dependent on the flag or flags set in the wFlags parameter.
wFlags
Flags specifying the folder to be browsed. It can be zero or one or more of the following values. These first three flags specify whether another window is to be created.
SBSP_SAMEBROWSER | Browse to another folder with the same Windows Explorer window.
SBSP_NEWBROWSER | Creates another window for the specified folder.
SBSP_DEFBROWSER | The default behavior is to respect the view option (the user setting to create new windows or to browse in place). In most cases, callers should use this flag.

The following flags specify either the open, explore, or default mode. These values are ignored if SBSP_SAMEBROWSER is specified or if SBSP_DEFBROWSER is specified and the user has selected Browse In Place.
SBSP_OPENMODE | Use a normal folder window.
SBSP_EXPLOREMODE | Use a Windows Explorer window.
SBSP_DEFMODE | Use the current window.

The following flags specify the pidl parameter's category:
SBSP_ABSOLUTE | An absolute pidl (relative from the desktop).
SBSP_RELATIVE | A relative pidl (relative from the current folder).
SBSP_PARENT | Browse the parent folder (ignores the pidl).

Views can use this method to force Windows Explorer to browse to a specific place in the namespace. Typically, these are folders contained in the view.

See also IShellBrowser


IShellBrowser::EnableModelessSB

HRESULT EnableModelessSB(
    BOOL fEnable
   );

Tells Windows Explorer to enable or disable its modeless dialog boxes.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
fEnable
Specifies whether the modeless dialog boxes are to be enabled or disabled. If this parameter is nonzero, modeless dialogs are enabled. If this parameter is zero, modeless dialogs are disabled.

This method is similar to the IOleInPlaceFrame::EnableModeless method. Although the current version of Windows Explorer does not have any modeless dialog boxes, the view should call this method when it wants to disable or enable modeless dialog boxes associated with the Windows Explorer window.

See also IShellBrowser


IShellBrowser::GetControlWindow

HRESULT GetControlWindow(
    UINT id,
    HWND *lphwnd
   );

Retrieves the window handle to a browser control.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
id
Control handle that is being requested. This parameter can be one of the following values:
FCW_TOOLBAR | Retrieves the window handle to the browser's toolbar.
FCW_STATUS | Retrieves the window handle to the browser's status bar.
FCW_TREE | Retrieves the window handle to the browser's tree view.
FCW_PROGRESS | Retrieves the window handle to the browser's progress bar.
lphwnd
Address of the window handle to the Windows Explorer control.

GetControlWindow is used so views can directly manipulate the browser's controls. FCW_TREE should be used only to determine if the tree is present.

Notes to Callers

GetControlWindow is used to manipulate and test the state of the control windows. Do not send messages directly to these controls; instead, use IShellBrowser::SendControlMsg. Be prepared for this method to return NULL. Future versions of Windows Explorer may not include a toolbar, status bar, or tree window.

Notes to Implementers

GetControlWindow returns the window handle to these controls if they exist in your implementation.

See also IShellBrowser


IShellBrowser::GetViewStateStream

HRESULT GetViewStateStream(
    DWORD grfMode,
    LPSTREAM *ppStrm
   );

Retrieves an IStream interface that can be used for storage of view-specific state information.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
grfMode
Read/write access of the IStream interface. This may be one of the following values:
STGM_READ | Requests an IStream suitable for reading.
STGM_WRITE | Requests an IStream suitable for writing.
STGM_READWRITE | Requests an IStream suitable for reading and writing.
ppStrm
Address that receives the IStream interface pointer.

This method is used to save and restore the persistent state for a view (the icon positions, the column widths, and the current scroll position, for example).

Notes to Callers

Use GetViewStateStream when the view is being created to read in the saved view state and also when the view is being closed to save any changes to the view state. Typically, the view calls this method with STGM_READ when creating a view window and with STGM_WRITE when the SaveViewState method of its IShellView interface is called.

Notes to Implementers

Each shell view should have its own view stream. Windows Explorer implements a most recently used (MRU) list of view streams that are stored on a per-user basis in the registry.

See also IShellBrowser


IShellBrowser::InsertMenusSB

HRESULT InsertMenusSB(
    HMENU hmenuShared,
    LPOLEMENUGROUPWIDTHS lpMenuWidths
   );

Allows the container to insert its menu groups into the composite menu that is displayed when an extended namespace is being viewed or used.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
hmenuShared
Handle to an empty menu.
lpMenuWidths
Address of an OLEMENUGROUPWIDTHS array of six LONG values. The container fills in elements 0, 2, and 4 to reflect the number of menu elements it provided in the File, View, and Window menu groups.

This method is similar to the IOleInPlaceFrame::InsertMenus method. Windows Explorer puts File and Edit drop-down menus in the File menu group, View and Tools menus in the Container menu group, and a Help menu in the Window menu group. Each drop-down menu will have a unique identifier, FCIDM_MENU_FILE/EDIT/VIEW/TOOLS/HELP. The view is allowed to insert menu items into those submenus by their identifiers, which is different from OLE's in-place activation mechanism. The command identifiers for menus that the view inserts into either Windows Explorer's submenus or its own submenus must be between FCIDM_SHVIEWFIRST and FCIDM_SHVIEWLAST.

Notes to Callers

This method is called by namespace extensions when they are first being activated so they can insert their menus into the frame-level user interface.

The object application asks the container to add its menus to the menu specified in the hmenuShared parameter and to set the group counts in the OLEMENUGROUPWIDTHS array pointed to by the lpMenuWidths parameter. The object application then adds its own menus and counts. Objects can call the IOleInPlaceFrame::InsertMenus method as many times as necessary to build up the composite menus. The container should use the initial menu handle associated with the composite menu for all items in the drop-down menus.

Notes to Implementers

For IShellBrowser implementations, the menu identifiers must be in the range of FCIDM_BROWSERFIRST to FCIDM_BROWSERLAST.


IShellBrowser::OnViewWindowActive

HRESULT OnViewWindowActive(
    IShellView *ppshv
   );

Called by the shell view when the view window or one of its child windows gets the focus or becomes active.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
ppshv
Address of the view object's IShellView pointer.

The view must pass its IShellView implementation to this routine, although the current version of Windows Explorer does not use this parameter.

Notes to Callers

The shell view object must call this method before calling the IShellBrowser::InsertMenusSB method. This method will insert a different set of menu items depending on whether the view has the focus.

Notes to Implementers

This method informs the browser that the view is getting the focus (when the mouse is clicked on the view, for example).

See also IShellBrowser


IShellBrowser::QueryActiveShellView

HRESULT QueryActiveShellView(
    IShellView **ppshv
   );

Returns the currently active (displayed) shell view object.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.

    Notes to Callers

    Because the IShellBrowser interface can host several shell views simultaneously, this method provides an easy way to determine the active shell view object.

ppshv
Address of the pointer to the currently active shell view object.


IShellBrowser::RemoveMenusSB

HRESULT RemoveMenusSB(
    HMENU hmenuShared
   );

Permits the container to remove any of its menu elements from the in-place composite menu and to free all associated resources.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
hmenuShared
Handle to the in-place composite menu that was constructed by calls to IShellBrowser::InsertMenusSB and the Microsoft® Win32® InsertMenu function.

This method is similar to the IOleInPlaceFrame::RemoveMenus method.

The object should always permit the container to remove its menu elements from the composite menu before deactivating the shared user interface.

Notes to Callers

The method is called by the object application while it is being UI-deactivated so the browser can remove its menus.

See also IShellBrowser


IShellBrowser::SendControlMsg

HRESULT SendControlMsg(
    UINT id,
    UINT uMsg,
    WPARAM wParam,
    LPARAM lParam,
    LRESULT *pret
   );

Sends control messages to either the toolbar or the status bar in an Explorer window.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
id
Identifier for either a toolbar (FCW_TOOLBAR) or for a status bar window (FCW_STATUS).
uMsg
Message to be sent to the control.
wParam
Value depends on the message specified in the uMsg parameter.
lParam
Value depends on the message specified in the uMsg parameter.
pret
Address of the return value of the SendMessage function.

Refer to the Common Controls documentation for more information on the messages that can be sent to the toolbar or status bar control.

Notes to Callers

Use of this call requires diligent attention, because leaving either the status bar or toolbar in an inappropriate state will affect the performance of Windows Explorer.

Notes to Implementers

If your Windows Explorer does not have these controls, you can return E_NOTIMPL.

See also IShellBrowser


IShellBrowser::SetMenuSB

RESULT SetMenuSB(
    HMENU hmenuShared,
    HOLEMENU holemenuReserved
   );

Installs the composite menu in the view window.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
hmenuShared
Handle to the composite menu constructed by calls to IShellBrowser::InsertMenusSB and the Win32 InsertMenu function.
holemenuReserved
Reserved for future use.

This method is similar to the IOleInPlaceFrame::SetMenu method. However, Windows Explorer performs menu dispatch based on the menu item identifier.

The availability of specific menu items depends on whether the view has the focus. Accordingly, it is necessary to call the IShellBrowser::OnViewWindowActive method whenever the view window (or one of its child windows) has the focus.

Notes to Callers

The object calls IShellBrowser_SetMenuSB to ask the container to install the composite menu structure set up by calls to IShellBrowser::InsertMenusSB.

Notes to Implementers

A container's implementation of this method should call the Windows SetMenu function.

See also IShellBrowser


IShellBrowser::SetStatusTextSB

HRESULT SetStatusTextSB(
    LPCOLESTR lpszStatusText
   );

Sets and displays status text about the in-place object in the container's frame-window status bar.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
lpszStatusText
Address of a null-terminated character string to contain the message to display.

It is also possible to send messages directly to the status window by using the IShellBrowser::SendControlMsg method.

Notes to Callers

Use this method to set the contents of the status bar.

See also IShellBrowser


IShellBrowser::SetToolbarItems

HRESULT SetToolbarItems(
    LPTBBUTTON lpButtons,
    UINT nButtons,
    UINT uFlags
   );

Adds toolbar items to Windows Explorer's toolbar.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
lpButtons
Address of an array of TBBUTTON structures.
nButtons
Number of TBBUTTON structures in the lpButtons array.
uFlags
Flags specifying where the toolbar buttons should go. This parameter can be one or more of the following values:
FCT_ADDTOEND | Add at the right side of the toolbar.
FCT_CONFIGABLE | Not implemented.
FCT_MERGE | Merge the toolbar items instead of replacing all of the buttons with those provided by the view. This is the recommended choice.

See also IShellBrowser


IShellBrowser::TranslateAcceleratorSB

HRESULT TranslateAcceleratorSB(
    LPMSG lpmsg,
    WORD wID
   );

Translates accelerator keystrokes intended for the browser's frame while the view is active.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
lpmsg
Address of an MSG structure containing the keystroke message.
wID
Command identifier value corresponding to the keystroke in the container-provided accelerator table. Containers should use this value instead of translating again.

This method is similar to the IOleInPlaceFrame::TranslateAccelerator method.

See also IShellBrowser


IShellExecuteHook

The IShellExecuteHook interface extends the behavior of the ShellExecute or ShellExecuteEx function. It is typically implemented by subsystems that expose the names of objects that the user can specify in the Run dialog box after clicking the Windows Start button.

When to Implement

You should implement IShellExecuteHook when you have named objects that the user would expect to be able to run from the Run dialog box after clicking the Windows Start button.

When to Use

You do not use this interface directly. It is generally used by the ShellExecuteEx function's code.
IShellExecuteHook Method | Description
Execute | Called when ShellExecute or ShellExecuteEx is called for an object that is registered.


IShellExecuteHook::Execute

HRESULT Execute(
    LPSHELLEXECUTEINFO pei
   );

Called when ShellExecute or ShellExecuteEx is called for an object that is registered.

  • Returns one of the following values or an OLE-defined error value.
    S_OK | The hook processed the execution. ShellExecute or ShellExecuteEx should not perform any other processing.
    S_FALSE | The hook is installed but did not process the execution. ShellExecute or ShellExecuteEx should perform the default processing.
pei
Address of a SHELLEXECUTEINFO structure that contains information about the object being executed. On successful completion of the hook, the hInstApp member will be filled in by the hook.

This method provides an opportunity for the application to hook the execution of an object and change the default execution or perform some other action before the object is executed.

See also IShellExecuteHook


IShellExtInit

The IShellExtInit interface is used to initialize shell extensions for property sheets, context menus, and drag-and-drop handlers (extensions that add items to context menus during nondefault drag-and-drop operations).

When to Implement

Implement IShellExtInit when you are writing a handler based on the IContextMenu or IShellPropSheetExt interface.

Note that shell extensions based on other interfaces do not use this method of initialization.

When to Use

You do not use this interface directly. The shell calls it to initialize the handler.
IShellExtInit Method | Description
Initialize | Initializes the shell extension.


IShellExtInit::Initialize

HRESULT Initialize(
    LPCITEMIDLIST pidlFolder,
    LPDATAOBJECT lpdobj,
    HKEY hkeyProgID
   );

Initializes a property sheet extension, context menu extension, or drag-and-drop handler.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
pidlFolder
Address of an ITEMIDLIST structure that uniquely identifies a folder. For property sheet extensions, this parameter is NULL. For context menu extensions, it is the item identifier list for the folder that contains the item whose context menu is being displayed. For nondefault drag-and-drop menu extensions, this parameter specifies 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.

The meanings of some parameters depend on the extension type. For drag-and-drop handlers, the pidlFolder parameter specifies the destination folder (the drop target), the lpdobj parameter identifies the items being dropped, and the hkeyProgID parameter specifies the file class of the destination folder.

For context menu extensions, pidlFolder specifies the folder that contains the selected file objects, lpdobj identifies the selected file objects, and hkeyProgID specifies the file class of the file object that has the focus.

For property sheet extensions, pidlFolder is NULL, lpdobj identifies the selected file objects, and hkeyProgID specifies the file class of the file object that has the focus.

Notes to Implementers

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.

See also IShellExtInit


IShellFolder

The IShellFolder interface is used to manage folders.

When to Implement

Implement this interface for objects that extend the shell's namespace. For example, implement this interface to create a separate namespace that requires a rooted Windows Explorer or to install a new namespace directly within the hierarchy of the system namespace. You are most familiar with the contents of your namespace, so you are responsible for implementing everything needed to access your data.

When to Use

Use this interface when you need to display or perform an operation on the contents of the shell's namespace. Objects that support IShellFolder are usually created by other shell folder objects, with the root object (the Desktop shell folder) being returned from the SHGetDesktopFolder function.
IShellFolder Methods | Description
BindToObject | Retrieves the IShellFolder interface for the specified subfolder.
BindToStorage | Returns the storage instance of a subfolder. Not currently implemented.
CompareIDs | Determines the relative order of two file objects or folders, given their item identifier lists.
CreateViewObject | Creates a view object of the folder itself.
EnumObjects | Enumerates the objects in a folder.
GetAttributesOf | Retrieves the attributes of the specified file object or subfolder.
GetDisplayNameOf | Retrieves 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.


IShellFolder::BindToObject

HRESULT BindToObject(
    LPCITEMIDLIST pidl,
    LPBC pbcReserved,
    REFIID riid,
    LPVOID *ppvOut
   );

Retrieves an IShellFolder object for a subfolder.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
pidl
Address of an ITEMIDLIST structure that identifies the subfolder relative to its parent folder.
pbcReserved
Reserved. Callers should specify NULL for this parameter; those called should ignore it.
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.

Use this method to access the COM interface to the subfolder or subobject.

See also SHGetDesktopFolder


IShellFolder::BindToStorage IShellFolder::BindToStorage *
  * Previous Topic: IShellFolder::BindToObject
  * Next Topic: IShellFolder::CompareIDs

IShellFolder::BindToStorage

Reserved for future use. This method should return E_NOTIMPL.


IShellFolder::CompareIDs

HRESULT CompareIDs(
    LPARAM lParam,
    LPCITEMIDLIST pidl1,
    LPCITEMIDLIST pidl2
   );

Determines the relative order of two file objects or folders, given their item identifier lists.

  • If this method is successful, the CODE field of the status code (SCODE) contains one of the following values:
    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).

    If this method is unsuccessful, it returns an OLE-defined error code.

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 ITEMIDLIST structures that uniquely identify the items to compare. Both item identifier lists are relative to this folder. These ITEMIDLIST structures may contain more than one element; therefore, the entire ITEMIDLIST must be compared and not just the first element.

Passing zero for lParam indicates a sort by name. Values ranging from 0x00000001 to 0x7fffffff are for folder-specific sorting rules, while values ranging from 0x80000000 to 0xfffffff are used for system-specific rules.

See also IShellFolder


IShellFolder::CreateViewObject

HRESULT CreateViewObject(
    HWND hwndOwner,
    REFIID riid,
    LPVOID *ppvOut
   );

Creates a view object of a folder.

  • Returns NOERROR if successful, or an OLE defined error value otherwise.
hwndOwner
Handle to the owner window from which to create the view object.
riid
Identifier of the interface to return.
ppvOut
Address of a pointer to the view object.

It is important to remember that the COM object created by CreateViewObject must be a different object than the shell folder object. Windows Explorer may call this method more than once to create multiple view objects, and each of these must behave as independent objects. A new view object must be created for each call.

See also IShellFolder


IShellFolder::EnumObjects

HRESULT EnumObjects(
    HWND hwndOwner,
    DWORD grfFlags,
    LPENUMIDLIST *ppenumIDList
   );

Determines the contents of a folder by creating an item enumeration object (a set of item identifiers) that can be retrieved using the IEnumIDList interface.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
hwndOwner
Handle to the owner window that the client should specify if it displays a dialog box or message box.
grfFlags
Flags indicating which items to include in the enumeration. For a list of possible values, see the SHCONTF enumerated 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.

The calling application must free the returned IEnumIDList object by calling its Release method.

See also IShellFolder, SHGetDesktopFolder


IShellFolder::GetAttributesOf

HRESULT GetAttributesOf(
    UINT cidl,
    LPCITEMIDLIST *apidl,
    ULONG *rgfInOut
   );

Retrieves the attributes of one or more file objects or subfolders.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
cidl
Number of file objects from which to retrieve attributes.
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 a single ULONG value that, on entry, contains the attributes that the caller is requesting. On exit, this value contains the requested attributes that are common to all of the specified objects. Note that this is the address of a single ULONG value, not an array of ULONG values. The lists below describe the possible flags for this parameter.

A file object's capability flags may be zero or a combination 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 be zero or a combination 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 be zero or a combination 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's miscellaneous attributes may be zero or a combination of the following values:
SFGAO_BROWSABLE | The specified items can be browsed in place.
SFGAO_COMPRESSED | The specified items are compressed.
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_NEWCONTENT | The objects contain new content.
SFGAO_NONENUMERATED | The items are nonenumerated items.
SFGAO_REMOVABLE | The specified file objects or folders are on removable media.
SFGAO_VALIDATE | Validate cached information. The shell will validate that the objects specified in apidl still exist and will not used cached information when retrieving the attributes. If one or more of the items specified in apidl no longer exist, this method will return an error code. If cidl is zero, the shell will discard all cached information for the shell folder. This is similar to doing a refresh of the folder.

You can optimize this operation by not returning unspecified flags.

See also IShellFolder


IShellFolder::GetDisplayNameOf

HRESULT GetDisplayNameOf(
    LPCITEMIDLIST pidl,
    DWORD uFlags,
    LPSTRRET lpName
   );

Retrieves the display name for the specified file object or subfolder, returning it in a STRRET structure.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
pidl
Address of an ITEMIDLIST structure that uniquely identifies the file object or subfolder relative to the parent folder.
uFlags
Flags indicating the type of display name to return. For a list of possible values, see 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.

If the identifier contains the display name (in the local character set), it returns the offset to the name. If not, it returns a pointer to the display name string (UNICODE) allocated by the task allocator, or it fills in a buffer. The type of string returned depends on the type of display specified. Values identifying different types of display names are contained in the SHGNO enumerated type.

See also IShellFolder


IShellFolder::GetUIObjectOf

HRESULT GetUIObjectOf(
    HWND hwndOwner,
    UINT cidl,
    LPCITEMIDLIST *apidl,
    REFIID riid,
    UINT *prgfInOut,
    LPVOID *ppvOut
   );

Retrieves an OLE interface that can be used to carry out actions on the specified file objects or folders.

  • Returns NOERROR if successful, E_NOINTERFACE if the interface is not supported, or an OLE-defined error value otherwise.
hwndOwner
Handle to 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 in the apidl parameter.
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 COM interface object to return. This can be any valid interface identifier that can be created for an item. The most common identifiers used by the shell are listed in the comments at the end of this reference.
prgfInOut
Reserved.
ppvOut
Address that receives the interface pointer. If an error occurs, a NULL pointer is returned in this address.

If cidl is greater than one, the GetUIObjectOf implementation should only succeed if it can create one object for all items specified in apidl. If the implementation cannot create one object for all items, this method should fail.

The following are the most common interface identifiers the shell uses when requesting an interface from this method. The list also indicates if cidl can be greater than one for the requested interface.
Interface Identifier | Allowed cidl Value
IContextMenu | The cidl parameter can be greater than or equal to one.
IContextMenu2 | The cidl parameter can be greater than or equal to one.
IDataObject | The cidl parameter can be greater than or equal to one.
IDropTarget | The cidl parameter can only be one.
IExtractIcon | The cidl parameter can only be one.
IQueryInfo | The cidl parameter can only be one.

See also IShellFolder


IShellFolder::ParseDisplayName

HRESULT ParseDisplayName(
    HWND hwndOwner,
    LPBC pbcReserved,
    LPOLESTR lpszDisplayName,
    ULONG *pchEaten,
    LPITEMIDLIST *ppidl,
    ULONG *pdwAttributes
   );

Translates a file object's or folder's display name into an item identifier list.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
hwndOwner
Handle to the owner window that the client should specify if it displays a dialog box or message box.
pbcReserved
Reserved; this parameter is always NULL.
lpszDisplayName
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 a ULONG value that receives the number of characters of the display name that was parsed.
ppidl
Address of an ITEMIDLIST pointer that receives the item identifier list created for the object. The returned item identifier list specifies the item relative to the parsing folder. If the name to be parsed exists within the parsing folder, then the returned item identifier list will contain only one element. If the name to be parsed exists within a sub-folder of the parsing folder, then the returned item identifier list will contain multiple elements. If an error occurs, NULL is returned in this address.
pdwAttributes
Address of the attributes of the file object. Can be NULL if the caller does not need attribute data.

This method is similar to the IParseDisplayName::ParseDisplayName method defined by OLE.

See also IShellFolder, IShellLink


IShellFolder::SetNameOf

HRESULT SetNameOf(
    HWND hwndOwner,
    LPCITEMIDLIST pidl,
    LPCOLESTR lpszName,
    DWORD uFlags,
    LPITEMIDLIST *ppidlOut
   );

Sets the display name of a file object or subfolder, changing the item identifier in the process.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
hwndOwner
Handle to the owner window of any dialog or message boxes that the client displays.
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
Flags indicating the type of name specified by the lpszName parameter. For a list of possible values, see the description of the SHGNO enumerated type.
ppidlOut
Address of 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.

Changing the display name of a file system object, or a folder within it, renames the file or directory.

See also IShellFolder


IShellIcon

The IShellIcon interface is used to obtain an icon index for an IShellFolder object. IShellIcon allows an application to obtain the icon for any object within a folder by using only one instance of the interface. IExtractIcon, on the other hand, requires that a separate instance of the interface be created for each object.

When to Implement

Implement IShellIcon when creating an IShellFolder implementation to provide a quick way to obtain the icon for an object in the folder.

If IShellIcon is not implemented by an IShellFolder object, IShellFolder::GetUIObjectOf is used to get an icon for all objects.

When to Use

Use IShellIcon when retrieving the icon index for an item in a shell folder.
IShellIcon Method | Description
GetIconOf | Retrieves an icon for an object in a folder.


IShellIcon::GetIconOf

HRESULT GetIconOf(
    LPCITEMIDLIST pidl,
    UINT flags,
    LPINT lpIconIndex
   );

Retrieves an icon for an object inside a specific folder.

  • Returns NOERROR if lpIconIndex contains the correct system image list index, or S_FALSE if an icon can't be obtained for this object.
pidl
Address of the ITEMIDLIST structure that specifies the relative location of the folder.
flags
Flags specifying how the icon is to display. This parameter can be zero or one of the following values:
GIL_FORSHELL | The icon is to be displayed in a shell folder.
GIL_OPENICON | The icon should be in the open state if both open- and closed-state images are available. If this flag is not specified, the icon should be in the normal or closed state. This flag is typically used for folder objects.
lpIconIndex
Address of the index of the icon in the system image list. The following standard image list indexes can be returned:
0 | Document (blank page, not associated)
1 | Document (with data on the page)
2 | Application (file extension must be .exe, .com, or .bat)
3 | Folder (plain)
4 | Folder (open)

If you are unable to get an icon for this object using GetIconOf, use the IShellFolder::GetUIObjectOf method to get an object that supports the IExtractIcon::Extract method.

Notes to Callers

The index returned is from the system image list.

Notes to Implementers

If the icon index used is not one of the standard images listed, it is the implementer's responsibility to add the image to the system image list and then place the index into the lpIconIndex parameter. To prevent the system image list from growing too large, each image should only be added once.

See also IShellIcon


IShellLink

The IShellLink interface allows shell links to be created, modified, and resolved.
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 file name 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 file name 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

HRESULT STDMETHODCALLTYPE GetArguments(
    LPSTR pszArgs,
    int cchMaxPath
   );

Retrieves the command-line arguments associated with a shell link object.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
pszArgs
Address of a buffer that receives the command-line arguments.
cchMaxPath
Maximum number of characters to copy to the buffer pointed to by the pszArgs parameter.

See also IShellLink


IShellLink::GetDescription

RESULT STDMETHODCALLTYPE GetDescription(
    LPSTR pszName,
    int cchMaxName
   );

Retrieves the description string for a shell link object.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
pszName
Address of a buffer that receives the description string.
cchMaxName
Maximum number of characters to copy to the buffer pointed to by the pszName parameter.

See also IShellLink


IShellLink::GetHotkey

HRESULT STDMETHODCALLTYPE GetHotkey(
    WORD *pwHotkey
   );

Retrieves the hot key for a shell link object.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
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 the following values:
HOTKEYF_ALT | ALT key
HOTKEYF_CONTROL | CTRL key
HOTKEYF_EXT | Extended key
HOTKEYF_SHIFT | SHIFT key

See also IShellLink


IShellLink::GetIconLocation

HRESULT STDMETHODCALLTYPE GetIconLocation(
    LPSTR pszIconPath,
    int cchIconPath,
    int *piIcon
   );

Retrieves the location (path and index) of the icon for a shell link object.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
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 the pszIconPath parameter.
piIcon
Address of a value that receives the index of the icon.

See also IShellLink


IShellLink::GetIDList

HRESULT STDMETHODCALLTYPE GetIDList(
    LPITEMIDLIST *ppidl
   );

Retrieves the list of item identifiers for a shell link object.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
ppidl
Address of a pointer to a list of item identifiers.

See also IShellLink


IShellLink::GetPath

HRESULT STDMETHODCALLTYPE GetPath(
    LPSTR pszFile,
    int cchMaxPath,
    WIN32_FIND_DATA *pfd,
    DWORD fFlags
   );

Retrieves the path and file name of a shell link object.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
pszFile
Address of a buffer that receives the path and file name of the shell link object.
cchMaxPath
Maximum number of bytes to copy to the buffer pointed to by the pszFile parameter.
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 the following values:
SLGP_SHORTPATH | Retrieves the standard short (8.3 format) file name.
SLGP_UNCPRIORITY | Retrieves the Universal Naming Convention (UNC) path name of the file.

See also IShellLink


IShellLink::GetShowCmd

HRESULT STDMETHODCALLTYPE GetShowCmd(
    int *piShowCmd
   );

Retrieves the show command for a shell link object.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
piShowCmd
Address of the show command. For a list of show commands, see the ShowWindow function.

See also IShellLink


IShellLink::GetWorkingDirectory

HRESULT STDMETHODCALLTYPE GetWorkingDirectory(
    LPSTR pszDir,
    int cchMaxPath
   );

Retrieves the name of the working directory for a shell link object.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
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 the pszDir parameter. The name of the working directory is truncated if it is longer than the maximum specified by this parameter.

See also IShellLink


IShellLink::Resolve

HRESULT STDMETHODCALLTYPE Resolve(
    HWND hwnd,
    DWORD fFlags
   );

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.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
hwnd
Handle to the window that the shell will use as the parent 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 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 method to determine whether the link object has changed.

If the system cannot find the object, it looks in the current directory for an object that has the same attributes and file creation time but has 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 does a recursive search of the subdirectories of the current directory, looking for a match with either the same name or creation time. If it does not find a match, 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

HRESULT STDMETHODCALLTYPE SetArguments(
    LPCSTR pszArgs
   );

Sets the command-line arguments for a shell link object.

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

pszArgs
Address of a buffer that contains the new command-line arguments.

See also IShellLink


IShellLink::SetDescription

HRESULT STDMETHODCALLTYPE SetDescription(
    LPCSTR pszName
   );

Sets the description for a shell link object. The description can be any application-defined string.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
pszName
Address of a buffer containing the new description string.

See also IShellLink


IShellLink::SetHotkey

HRESULT STDMETHODCALLTYPE SetHotkey(
    WORD wHotkey
   );

Sets a hot key for a shell link object.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
wHotkey
New 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.

Setting a hot key allows the user to activate the object by pressing a particular combination of keys.

See also IShellLink


IShellLink::SetIconLocation

HRESULT STDMETHODCALLTYPE SetIconLocation(
    LPCSTR pszIconPath,
    int iIcon
   );

Sets the location (path and index) of the icon for a shell link object.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
pszIconPath
Address of a buffer to contain the path of the file containing the icon.
iIcon
Index of the icon.

See also IShellLink


IShellLink::SetIDList

HRESULT STDMETHODCALLTYPE SetIDList(
    LPCITEMIDLIST pidl
   );

Sets the list of item identifiers for a shell link object.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
pidl
Address of a list of item identifiers.

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

HRESULT STDMETHODCALLTYPE SetPath(
    LPCSTR pszFile
   );

Sets the path and file name of a shell link object.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
pszFile
Address of a buffer that contains the new path.

See also IShellLink


IShellLink::SetRelativePath

HRESULT STDMETHODCALLTYPE SetRelativePath(
    LPCSTR pszPathRel,
    LPCITEMIDLIST pidlRel
   );

Sets the relative path to the shell link object.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
pszPathRel
Address of a buffer that contains the new relative path.
pidlRel
Address of a list of item identifiers that identify the object.

See also IShellLink


IShellLink::SetShowCmd

HRESULT STDMETHODCALLTYPE SetShowCmd(
    int iShowCmd
   );

Sets the show command for a shell link object. The show command sets the initial show state of the window.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
iShowCmd
Show command. For a list of these commands, see the description of the ShowWindow function.

See also IShellLink


IShellLink::SetWorkingDirectory

HRESULT STDMETHODCALLTYPE SetWorkingDirectory(
    LPCSTR pszDir
   );

Sets the name of the working directory for a shell link object.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
pszDir
Address of a buffer that contains the name of the new working directory.

The working directory is optional unless the target requires a working directory. For example, if an application creates a shell link to a Microsoft® Word document that uses a template residing in a different directory, the application would use this method to set the working directory.

See also IShellLink


IShellPropSheetExt

The IShellPropSheetExt interface allows a property sheet handler to add or replace pages in the property sheet displayed for a file object.
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

HRESULT STDMETHODCALLTYPE AddPages(
    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 this method for each property sheet handler registered to the file type.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
lpfnAddPage
Address of 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 the lpfnAddPage method.

For each page the property sheet handler needs to add to a property sheet, the handler fills a PROPSHEETPAGE structure, calls the CreatePropertySheetPage function, and then calls the function specified by the lpfnAddPage parameter.

See also IShellPropSheetExt


IShellPropSheetExt::ReplacePage

HRESULT STDMETHODCALLTYPE ReplacePage(
    UINT uPageID,
    LPFNADDPROPSHEETPAGE lpfnReplacePage,
    LPARAM lParam
   );

Replaces a page in a property sheet for a Control Panel object.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
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
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 method.
lParam
Parameter to pass to the function specified by the lpfnReplacePage parameter.

To replace a page, a property sheet handler fills a PROPSHEETPAGE structure, calls CreatePropertySheetPage, and then calls the function specified by lpfnReplacePage.

See also IShellPropSheetExt


IShellView

The IShellView interface is implemented to present a view in the Windows Explorer or folder windows. The object that exposes IShellView is created by a call to the IShellFolder::CreateViewObject method. This provides the channel of communication between a view object and Windows Explorer's outermost frame window. The communication involves the translation of messages, the state of the frame window (activated or deactivated), the state of the document window (activated or deactivated), and the merging of menus and toolbar items.

When to Implement

This interface is implemented by namespace extensions that display themselves in Windows Explorer's namespace. This object is created by the IShellFolder object that hosts the view.

When to Use

These methods are used by the shell view's Windows Explorer window to manipulate objects while they are active.

IShellView is derived from IOleWindow. The following are the methods specific to IShellView:
IShellView Methods | Description
AddPropertySheetPages | Allows the view to add pages to the Options property sheet.
CreateViewWindow | Creates the view window.
DestroyViewWindow | Destroys the view window.
EnableModeless | Enables or disables modeless dialog boxes. Not in use by Windows Explorer at this time.
EnableModelessSV | Not currently in use.
GetCurrentInfo | Returns the current folder settings.
GetItemObject | Allows callers to get an object that represents something in the view.
Refresh | Refreshes the display in response to user input.
SaveViewState | Saves the shell's view settings so the current state can be restored during a subsequent browsing session.
SelectItem | Changes the state of items within the shell view window.
TranslateAccelerator | Translates accelerator key strokes when a namespace extension's view has the focus.
UIActivate | Called whenever the activation state of the view window is changed by an event not caused by the shell view itself.


IShellView::AddPropertySheetPages

HRESULT AddPropertySheetPages(
    DWORD dwReserved,
    LPFNADDPROPSHEETPAGE lpfn,
    LPARAM lparam
   );

Allows the view to add pages to the Options property sheet from the View menu.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
dwReserved
Reserved for future use.
lpfn
Address of the callback function used to add the pages.
lparam
Value that must be passed to the callback function in the lpfn parameter.

Notes to Implementers

Windows Explorer calls this method when it is opening the Options property sheet from the View menu. Views can add pages by creating them and calling the callback function with the page handles.

See also IShellView


IShellView::CreateViewWindow

RESULT CreateViewWindow(
    ISHELLLINK *lpPrevView,
    LPFOLDERSETTINGS lpfs,
    IShellBrowser *psb,
    RECT *prcView,
    HWND *phWnd
   );

Creates a view window. This can be either the right pane of Windows Explorer or the client window of a folder window.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
lpPrevView
Address of the view window being exited. Views can use this parameter to communicate with a previous view of the same implementation. This can be used to optimize browsing between like views. This pointer may be NULL.
lpfs
Address of a FOLDERSETTINGS structure. The view should use this when creating its view.
psb
Address of the current instance of the IShellBrowser interface. The view should call this interface's AddRef method and keep the interface pointer to allow communication with the Windows Explorer window.
prcView
Dimensions of the new view, in client coordinates.
phWnd
Address of the window handle being created.

Notes to Callers

Call this method when the view needs to be created.

Notes to Implementers

Create your view window and restore any persistent state by calling the IShellBrowser::GetViewStateStream method.

See also IShellView


IShellView::DestroyViewWindow

HRESULT DestroyViewWindow(void)

Destroys the view window.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.

Windows Explorer calls this method when a folder window or Explorer is being closed.

Notes to Implementers

Clean up all states that represent the view, including the window and any other associated resources.

See also IShellView


IShellView::EnableModeless

HRESULT EnableModeless(
    BOOL fEnable
   );

Enables or disables modeless dialog boxes. This method is not currently implemented.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
fEnable
Nonzero to enable modeless dialog box windows or zero to disable them.

See also IShellView


IShellView::EnableModelessSV IShellView::EnableModelessSV *
  * Previous Topic: IShellView::EnableModeless
  * Next Topic: IShellView::GetCurrentInfo

IShellView::EnableModelessSV

Not currently implemented.


IShellView::GetCurrentInfo

HRESULT GetCurrentInfo(
    LPFOLDERSETTINGS lpfs
   );

Retrieves the current folder settings.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
lpfs
Address of a FOLDERSETTINGS structure to receive the settings.

Windows Explorer uses this method to query the view for standard settings.

Notes to Callers

This method is used to get the current view settings of the view.

Notes to Implementers

Return as many of the settings as apply. This is intended to maintain the same basic settings when the user browses from view to view. For example, if the user sets the Details view, that view should be maintained as the user goes from one folder to the other in Windows Explorer mode.

See also IShellView


IShellView::GetItemObject

HRESULT GetItemObject(
    UINT uItem,
    REFIID riid,
    LPVOID *ppv
   );

Retrieves an interface that refers to data presented in the view.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
uItem
Constants that refer to an aspect of the view. This parameter can be any of the following values:
SVGIO_BACKGROUND | Refers to the background of the view. It is used with IID_IContextMenu to get a context menu for the view background.
SVGIO_SELECTION | Refers to the currently selected items. IID_IDataObject uses this constant to get a data object that represents the selected items.
SVGIO_ALLVIEW | Same as SVGIO_SELECTION but refers to all items in the view.
riid
Identifier of the COM interface being requested.
ppv
Address that receives the interface pointer. If an error occurs, the pointer returned must be NULL.

Used by the common dialogs to get the selected items from the view.

See also IShellView


IShellView::Refresh

HRESULT Refresh(void)

Refreshes the view's contents in response to user input.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.

Tells the view to refresh its contents, revalidating any view information it has.

Notes to Callers

Windows Explorer calls this method when the F5 key is pressed on an already open view.

Notes to Implementers

Refill the view by going to any underlying storage for the contents.

See also IShellView


IShellView::SaveViewState

HRESULT SaveViewState(void)

Saves the shell's view settings so the current state can be restored during a subsequent browsing session.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.

The shell view obtains a view stream by calling the IShellBrowser::GetViewStateStream method and stores the current view state in that stream.

Notes to Callers

Windows Explorer calls this method when it wants to save the view state for a view.

Notes to Implementers

Be sure to make the format of the data stored in the stream robust enough that different versions of the implementation can read it without error.

See also IShellView


IShellView::SelectItem

HRESULT SelectItem(
    LPCITEMIDLIST pidlItem,
    UINT uFlags
   );

Changes the selection state of one or more items within the shell view window.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
pidlItem
Address of the ITEMIDLIST structure.
uFlags
Flag specifying what type of selection to apply. This parameter can be one of the following values:
SVSI_DESELECT | Deselect the specified item.
SVSI_DESELECTOTHERS | Deselect all but the specified item. If pidlItem is NULL, deselect all items.
SVSI_EDIT | Put pidlItem in edit mode.
SVSI_ENSUREVISIBLE | Ensure the item is displayed on the screen.
SVSI_FOCUSED | The item should be given the focus.
SVSI_SELECT | The item should be selected.

Notes to Implementers

This method is used to implement the Target command from the File menu of the shell shortcut property sheet.

See also IShellView


IShellView::TranslateAccelerator

HRESULT TranslateAccelerator(
    LPMSG lpmsg
   );

Translates accelerator key strokes when a namespace extension's view has the focus.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.

    If the view returns S_OK, it indicates that the message was translated and should not be translated or dispatched by Windows Explorer.

lpmsg
Address of the message to be translated.

This method is called by Windows Explorer to let the view translate its accelerators.

Notes to Callers

Windows Explorer calls this method before any other translation if the view has the focus. If the view does not have the focus, it is called after Explorer translates its own accelerators.

Notes to Implementers

By default, the view should return S_FALSE so that Windows Explorer can either do its own accelerator translation or normal menu dispatching. The view should return S_OK only if it has processed the message as the accelerator and does not want Explorer to process it further.

See also IShellView


IShellView::UIActivate

HRESULT UIActivate(
    UINT uState
   );

Called when the activation state of the view window is changed by an event that is not caused by the shell view itself. For example, if the TAB key is pressed when the tree has the focus, the view should be given the focus.

  • Returns NOERROR if successful, or an OLE-defined error value otherwise.
uState
Flag specifying the activation state of the window. This parameter can be one of the following values:
SVUIA_ACTIVATE_FOCUS | Windows Explorer has just created the view window with the input focus. This means the shell view should be able to set menu items appropriate for the focused state.
SVUIA_ACTIVATE_NOFOCUS | The shell view is losing the input focus, or it has just been created without the input focus. The shell view should be able to set menu items appropriate for the nonfocused state. This means no selection-specific items should be added.
SVUIA_DEACTIVATE | Windows Explorer is about to destroy the shell view window. The shell view should remove all extended user interfaces. These are typically merged menus and merged modeless pop-up windows.
SVUIA_INPLACEACTIVATE | Not used for this interface.

Before remerging menu items, the shell view typically hooks the WM_SETFOCUS message and calls the IShellView::OnViewWindowActive method. The shell view should not hook the WM_KILLFOCUS message to remerge menu items.

Notes to Callers

Call this method to inform the view of an activation state change.

Notes to Implementers

Use this method to track the activation state and change any behavior, as appropriate.

See also IShellView


ITaskbarList

The ITaskbarList interface is used to control the taskbar. It allows you to dynamically add items to the taskbar, remove items from the taskbar, and activate items on the taskbar. See Modifying the Contents of the Taskbar for more information about using this interface.

When to Implement

You do not implement ITaskbarList; it is implemented by the shell.

When to Use

You use ITaskbarList to add items to the taskbar, remove items from the taskbar, and activate items on the taskbar.

ITaskbarList is derived from IUnknown. The following methods are specific to ITaskbarList:
ITaskbarList Methods | Description
ActivateTab | Activates an item on the taskbar.
AddTab | Adds an item to the taskbar.
DeleteTab | Deletes an item from the taskbar.
HrInit | Initializes the taskbar list object.
SetActiveAlt | Marks a taskbar item as active but does not visually activate it.

Note This interface is only supported in shell versions 4.71 and later.


ITaskbarList::ActivateTab

HRESULT ActivateTab(
    HWND hwnd
);

Activates an item on the taskbar. The window is not actually activated; the window's item on the taskbar is merely displayed as active.

  • Returns NOERROR if successful, or an OLE-defined error code otherwise.
hwnd
Handle to the window on the taskbar to be displayed as active.

Version 4.71


ITaskbarList::AddTab

HRESULT AddTab(
    HWND hwnd
);

Adds an item to the taskbar.

  • Returns NOERROR if successful, or an OLE-defined error code otherwise.
hwnd
Handle to the window to be added to the taskbar.

Any type of window can be added to the taskbar, but it is recommended that the window at least have the WS_CAPTION style.

Any window added with this method must be removed with the DeleteTab method when the added window is destroyed.

Version 4.71


ITaskbarList::DeleteTab

HRESULT DeleteTab(
    HWND hwnd
);

Deletes an item from the taskbar.

  • Returns NOERROR if successful, or an OLE-defined error code otherwise.
hwnd
Handle to the window to be deleted from the taskbar.

Version 4.71


ITaskbarList::HrInit

HRESULT HrInit(void);

Initializes the taskbar list object. This method must be called before any other ITaskbarList methods can be called.

  • Returns NOERROR if successful, or an OLE-defined error code otherwise. If the method fails, no other methods can be called. The calling application should release the interface pointer.

Version 4.71


ITaskbarList::SetActiveAlt

HRESULT SetActiveAlt(
    HWND hwnd
);

Marks a taskbar item as active but does not visually activate it.

  • Returns NOERROR if successful, or an OLE-defined error code otherwise.
hwnd
Handle to the window to be marked as active.

SetActiveAlt marks the item associated with hwnd as the currently active item for the window's process without changing the pressed state of any item. Any user action that would activate a different tab in that process will activate the tab associated with hwnd instead. The active state of the window's item is not guaranteed to be preserved when the process associated with hwnd is not active. To ensure that a given tab is always active, call SetActiveAlt whenever any of your windows are activated. Calling SetActiveAlt with a NULL hwnd clears this state.

Version 4.71


IURLSearchHook

The IURLSearchHook interface is used by the browser to translate the address of an unknown URL protocol. When attempting to browse to a URL address that does not contain a protocol, the browser will first attempt to determine the correct protocol from the address. If this is not successful, the browser will create URL Search Hook objects and call each object's Translate method until the address is translated or all of the hooks have been queried.

URL Search Hooks are registered by adding a key that contains the object's CLSID string under the following key in the registry:

HKEY_LOCAL_MACHINE\
   Software\
   Microsoft\
   Internet Explorer\
   UrlSearchHooks

When to Implement

Implement this interface if your application defines a custom URL protocol and if address translation for this protocol is required.

When to Use

You do not normally use this interface; it is called by the browser.
IURLSearchHook Method | Description
Translate | Called by the browser when the browser cannot determine the protocol of a URL address.

Note This interface is only supported in shell versions 4.71 and later.


IURLSearchHook::Translate

HRESULT Translate(
    LPWSTR lpwszSearchURL,
    DWORD cchBufferSize
   );

Called by the browser when the browser cannot determine the protocol of a URL address.

  • This method must return one of the following values:
    S_OK | The URL address was completely translated. The lpwszSearchURL parameter contains the full URL address. The browser will not call any other URL Search Hooks and will attempt to browse to the modified address.
    S_FALSE | The URL address has been partially processed, but further translation is still required. The lpwszSearchURL parameter contains the result of the processing. The browser will continue executing the rest of the URL Search Hooks.
    E_FAIL | The URL address was not translated. The lpwszSearchURL parameter has not been modified. The browser will continue executing the rest of the URL Search Hooks.
lpwszSearchURL
Address of a wide character buffer that, on entry, contains the URL address for which the browser is trying to determine the protocol. On exit, this buffer contains the modified URL address if the method was successful. See the return value for more information.
cchBufferSize
Size, in characters, of the buffer at lpwszSearchURL.

Version 4.71


Functions

This section describes the Microsoft® Windows® shell functions.

CPlApplet
DefScreenSaverProc
DragAcceptFiles
DragFinish
DragQueryFile
DragQueryPoint
FindExecutable
GetMenuContextHelpId
GetWindowContextHelpId
RegisterDialogClasses
ScreenSaverConfigureDialog
ScreenSaverProc
SetMenuContextHelpId
SetWindowContextHelpId
SHAddToRecentDocs
SHAppBarMessage
SHBrowseForFolder
SHChangeNotify
Shell_NotifyIcon
ShellAbout
ShellExecute
ShellExecuteEx
SHEmptyRecycleBin
SHFileOperation
SHFreeNameMappings
SHGetDataFromIDList
SHGetDesktopFolder
SHGetDiskFreeSpace
SHGetFileInfo
SHGetInstanceExplorer
SHGetMalloc
SHGetNewLinkInfo
SHGetPathFromIDList
SHGetSettings
SHGetSpecialFolderLocation
SHGetSpecialFolderPath
SHInvokePrinterCommand
SHLoadInProc
SHQueryRecycleBin
SOBailOut
SOBeginTable
SOEndColumnInfo
SOEndFieldInfo
SOEndFontTable
SOEndPalette
SOEndTable
SOEndTabStops
SOGetInfo
SOGetScanLineBuffer
SOPutBitmapHeader
SOPutBreak
SOPutChar
SOPutCharAttr
SOPutCharFontById
SOPutCharFontByName
SOPutCharHeight
SOPutCharX
SOPutColumnInfo
SOPutDataCell
SOPutEmbeddedObject
SOPutField
SOPutFieldInfo
SOPutFontTableEntry
SOPutHdrEntry
SOPutMoreText
SOPutMoreVarField
SOPutPaletteEntry
SOPutParaAlign
SOPutParaIndents
SOPutParaMargins
SOPutParaSpacing
SOPutScanLineData
SOPutSectionName
SOPutSectionType
SOPutSpecialCharX
SOPutSubdocInfo
SOPutTableCellInfo
SOPutTableRowFormat
SOPutTabStop
SOPutTextCell
SOPutVarField
SOPutVectorHeader
SOSetDateBase
SOStartColumnInfo
SOStartFieldInfo
SOStartFontTable
SOStartPalette
SOStartTabStops
SOVectorAttr
SOVectorObject
SUUserPopData
SUUserPushData
SUUserRetrieveData
SUUserSaveData
VwStreamCloseFunc
VwStreamOpenFunc
VwStreamReadFunc
VwStreamReadRecordFunc
VwStreamSectionFunc
VwStreamSeekFunc
VwStreamTellFunc
WinHelp


CPlApplet

Library-defined callback function that serves as the entry point for a Control Panel application.

Syntax

LONG APIENTRY CPlApplet(
    HWND hwndCPl,
    UINT uMsg,
    LONG lParam1,
    LONG lParam2
);

Parameters

hwndCPl
Identifies of the main window of the controlling application. Use the hwndCPl parameter for dialog boxes or other windows that require a handle to a parent window.
uMsg
Message being sent to the Control Panel application.
lParam1
Additional message-specific information.
lParam2
Additional message-specific information.

Return Values

The return value depends on the message.

For more information, see the descriptions of the individual Control Panel messages.


DefScreenSaverProc

Provides default processing for any messages that a screen saver application does not process.

Syntax

LONG DefScreenSaverProc(
    HWND hWnd,
    UINT msg,
    WPARAM wParam,
    LPARAM lParam
);

Parameters

hWnd
Identifier of the screen saver window.
msg
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
Additional message-specific information.
lParam
Additional message-specific information.

Return Values

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.

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.


DragAcceptFiles

Registers whether a window accepts dropped files.

Syntax

VOID DragAcceptFiles(
    HWND hWnd,
    BOOL fAccept
);

Parameters

hWnd
Identifies the window that is registering whether it will accept dropped files.
fAccept
Value that indicates if the window identified by the hWnd parameter accepts dropped files. This value is TRUE to accept dropped files or FALSE to discontinue accepting dropped files.

Return Value

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


DragFinish

Releases memory that the system allocated for use in transferring file names to the application.

Syntax

VOID DragFinish(
    HDROP hDrop
);

Parameters

hDrop
Identifier of the structure that describes dropped files. This handle is retrieved from the wParam parameter of the WM_DROPFILES message.

Return Value

No return value.


DragQueryFile

Retrieves the file names of dropped files that have resulted from a successful drag-and-drop operation.

Syntax

UINT DragQueryFile(
    HDROP hDrop,
    UINT iFile,
    LPTSTR lpszFile,
    UINT cch
);

Parameters

hDrop
Identifier of the structure containing the file names of the dropped files.
iFile
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 file name with the corresponding value to the buffer pointed to by the lpszFile parameter.
lpszFile
Address of a buffer to receive the file name of a dropped file when the function returns. This file name is a null-terminated string. If this parameter is NULL, DragQueryFile returns the required size, in characters, of the buffer.
cch
Size, in characters, of the lpszFile buffer.

Return Values

When the function copies a file name 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

Retrieves the position of the mouse pointer at the time a file was dropped from a drag-and-drop operation.

Syntax

BOOL DragQueryPoint(
    HDROP hDrop,
    LPPOINT lppt
);

Parameters

hDrop
Identifier of the structure that describes the dropped file.
lppt
Address of a POINT structure that the function fills with the coordinates of the mouse pointer at the time the file was dropped.

Return Values

Returns nonzero if the drop occurred in the client area of the window, or zero if the drop did not occur in the client area of the window.

Remarks

The window for which coordinates are returned is the window that received the WM_DROPFILES message.

See Also

DragQueryFile


FindExecutable

Retrieves the name of and handle to the executable (.exe) file associated with the specified file name.

Syntax

HINSTANCE FindExecutable(
    LPCTSTR lpFile,
    LPCTSTR lpDirectory,
    LPTSTR lpResult
);

Parameters

lpFile
Address of a null-terminated string specifying a file name. This can be a document or executable file.
lpDirectory
Address of a null-terminated string specifying the default directory.
lpResult
Address of a buffer to receive the file name when the function returns. This file name is a null-terminated string specifying the executable file started when an "open" by association is run on the file specified in the lpFile parameter.

Return Values

Returns a value greater than 32 if successful, or a value less than or equal to 32 otherwise.

The following table lists the possible error values:
0 | The system is out of memory or resources.
31 | There is no association for the specified file type.
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).

Remarks

When FindExecutable returns, the lpResult parameter may contain the path to the DDE (Dynamic Data Exchange) server started if a server does not respond to a request to initiate a DDE conversation with the DDE client application.

See Also

ShellExecute


GetMenuContextHelpId

Retrieves the Help context identifier associated with the specified menu.

Syntax

DWORD GetMenuContextHelpId(
    HMENU hmenu
);

Return Values

Returns the Help context identifier if the menu has one, or zero otherwise.

Parameters

hmenu
Handle to the menu for which the Help context identifier is to be retrieved.

See Also

SetMenuContextHelpId


GetWindowContextHelpId

Retrieves the Help context identifier, if any, associated with the specified window.

Syntax

DWORD GetWindowContextHelpId(
    HWND hwnd
);

Parameter

hwnd
Handle to the window for which the Help context identifier is to be retrieved.

Return Values

Returns the Help context identifier if the window has one, or zero otherwise.

See Also

SetWindowContextHelpId


RegisterDialogClasses

Registers any nonstandard window classes required by a screen saver's configuration dialog box.

Syntax

BOOL RegisterDialogClasses(
    HANDLE hInst
);

Parameters

hInst
Identifier of an instance of the module registering the window classes.

Return Values

Returns nonzero if successful, or zero otherwise.

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


ScreenSaverConfigureDialog

Receives messages sent to a screen saver's configuration dialog box. A screen saver that allows user configuration must define this function.

Syntax

BOOL ScreenSaverConfigureDialog(
    HWND hDlg,
    UINT message,
    WPARAM wParam,
    LPARAM lParam
);

Parameters

hDlg
Identifier of the configuration dialog box.
message
Message that was sent to the screen saver's configuration dialog box.
wParam
Additional message-specific information.
lParam
Additional message-specific information.

Return Values

If the function successfully processes the message, it should return TRUE. If not, it should return 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

RegisterDialogClasses


ScreenSaverProc

Receives messages sent to the specified screen saver window.

Syntax

LONG ScreenSaverProc(
    HWND hWnd,
    UINT message,
    WPARAM wParam,
    LPARAM lParam
);

Parameters

hWnd
Identifier of the window.
message
Message sent to the screen saver window.
wParam
Additional message-specific information.
lParam
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.


SetMenuContextHelpId

Associates a Help context identifier with a menu.

Syntax

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 Values

Returns nonzero if successful, or zero otherwise.

To get extended error information, call GetLastError.

Remarks

All items in the menu share this identifier. Help context identifiers can't be attached to individual menu items.

See Also

GetMenuContextHelpId


SetWindowContextHelpId

Associates a Help context identifier with the specified window.

Syntax

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 Values

Returns nonzero if successful, or zero otherwise.

To get extended error information, call GetLastError.

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.

See Also

GetWindowContextHelpId


SHAddToRecentDocs

WINSHELLAPI void WINAPI 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 gains access to the list through the Start menu of the Windows taskbar.

uFlags
Flag that indicates the meaning of the pv parameter. This flag can be one of the following values:
SHARD_PATH | The pv parameter contains the address of a path string.
SHARD_PIDL | The pv parameter contains the address of an item identifier list (PIDL) that identifies a file object. PIDLs that identify nonfile objects are not allowed.
pv
Address of a character buffer that contains the path and file name of the document, or the address of an ITEMIDLIST structure that contains an item identifier list that uniquely identifies the document. If this parameter is NULL, the function clears all documents from the list.


SHAppBarMessage

WINSHELLAPI UINT APIENTRY SHAppBarMessage(
    DWORD dwMessage,
    PAPPBARDATA pData
);

Sends an appbar message to the system.

  • Returns a message-dependent value. For more information, see the Microsoft Platform SDK documentation for the appbar message sent.
dwMessage
Appbar message value 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 to 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.
pData
Address of an APPBARDATA structure. The content of the structure depends on the value set in the dwMessage parameter.


SHBrowseForFolder

WINSHELLAPI LPITEMIDLIST WINAPI SHBrowseForFolder(
    LPBROWSEINFO lpbi
);

Displays a dialog box that enables the user to select a shell folder.

  • Returns the address of 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 by using the shell's task allocator.


SHChangeNotify

WINSHELLAPI void WINAPI 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.

wEventId
Describes the event that has occurred. Typically, only one event is specified at a time. If more than one event is specified, the values contained in the dwItem1 and dwItem2 parameters must be the same, respectively, for all specified events. This parameter can be one or more of the following values:
SHCNE_ALLEVENTS | All events have occurred.
SHCNE_ASSOCCHANGED | A file type association has changed. SHCNF_IDLIST must be specified in the uFlags parameter. dwItem1 and dwItem2 are not used and must be NULL.
SHCNE_ATTRIBUTES | The attributes of an item or folder have changed. SHCNF_IDLIST or SHCNF_PATH must be specified in uFlags. dwItem1 contains the item or folder that has changed. dwItem2 is not used and should be NULL.
SHCNE_CREATE | A nonfolder item has been created. SHCNF_IDLIST or SHCNF_PATH must be specified in uFlags. dwItem1 contains the item that was created. dwItem2 is not used and should be NULL.
SHCNE_DELETE | A nonfolder item has been deleted. SHCNF_IDLIST or SHCNF_PATH must be specified in uFlags. dwItem1 contains the item that was deleted. dwItem2 is not used and should be NULL.
SHCNE_DRIVEADD | A drive has been added. SHCNF_IDLIST or SHCNF_PATH must be specified in uFlags. dwItem1 contains the root of the drive that was added. dwItem2 is not used and should be NULL.
SHCNE_DRIVEADDGUI | A drive has been added and the shell should create a new window for the drive. SHCNF_IDLIST or SHCNF_PATH must be specified in uFlags. dwItem1 contains the root of the drive that was added. dwItem2 is not used and should be NULL.
SHCNE_DRIVEREMOVED | A drive has been removed. SHCNF_IDLIST or SHCNF_PATH must be specified in uFlags. dwItem1 contains the root of the drive that was removed. dwItem2 is not used and should be NULL.
SHCNE_EXTENDED_EVENT | Not currently used.
SHCNE_FREESPACE | The amount of free space on a drive has changed. SHCNF_IDLIST or SHCNF_PATH must be specified in uFlags. dwItem1 contains the root of the drive on which the free space changed. dwItem2 is not used and should be NULL.
SHCNE_MEDIAINSERTED | Storage media has been inserted into a drive. SHCNF_IDLIST or SHCNF_PATH must be specified in uFlags. dwItem1 contains the root of the drive that contains the new media. dwItem2 is not used and should be NULL.
SHCNE_MEDIAREMOVED | Storage media has been removed from a drive. SHCNF_IDLIST or SHCNF_PATH must be specified in uFlags. dwItem1 contains the root of the drive from which the media was removed. dwItem2 is not used and should be NULL.
SHCNE_MKDIR | A folder has been created. SHCNF_IDLIST or SHCNF_PATH must be specified in uFlags. dwItem1 contains the folder that was created. dwItem2 is not used and should be NULL.
SHCNE_NETSHARE | A folder on the local computer is being shared via the network. SHCNF_IDLIST or SHCNF_PATH must be specified in uFlags. dwItem1 contains the folder that is being shared. dwItem2 is not used and should be NULL.
SHCNE_NETUNSHARE | A folder on the local computer is no longer being shared via the network. SHCNF_IDLIST or SHCNF_PATH must be specified in uFlags. dwItem1 contains the folder that is no longer being shared. dwItem2 is not used and should be NULL.
SHCNE_RENAMEFOLDER | The name of a folder has changed. SHCNF_IDLIST or SHCNF_PATH must be specified in uFlags. dwItem1 contains the previous PIDL or name of the folder. dwItem2 contains the new PIDL or name of the folder.
SHCNE_RENAMEITEM | The name of a nonfolder item has changed. SHCNF_IDLIST or SHCNF_PATH must be specified in uFlags. dwItem1 contains the previous PIDL or name of the item. dwItem2 contains the new PIDL or name of the item.
SHCNE_RMDIR | A folder has been removed. SHCNF_IDLIST or SHCNF_PATH must be specified in uFlags. dwItem1 contains the folder that was removed. dwItem2 is not used and should be NULL.
SHCNE_SERVERDISCONNECT | The computer has disconnected from a server. SHCNF_IDLIST or SHCNF_PATH must be specified in uFlags. dwItem1 contains the server from which the computer was disconnected. dwItem2 is not used and should be NULL.
SHCNE_UPDATEDIR | The contents of an existing folder have changed, but the folder still exists and has not been renamed. SHCNF_IDLIST or SHCNF_PATH must be specified in uFlags. dwItem1 contains the folder that has changed. dwItem2 is not used and should be NULL. If a folder has been created, deleted, or renamed, use SHCNE_MKDIR, SHCNE_RMDIR, or SHCNE_RENAMEFOLDER, respectively, instead.
SHCNE_UPDATEIMAGE | An image in the system image list has changed. SHCNF_DWORD must be specified in uFlags. dwItem1 contains the index in the system image list that has changed. dwItem2 is not used and should be NULL.
SHCNE_UPDATEITEM | An existing nonfolder item has changed, but the item still exists and has not been renamed. SHCNF_IDLIST or SHCNF_PATH must be specified in uFlags. dwItem1 contains the item that has changed. dwItem2 is not used and should be NULL. If a nonfolder item has been created, deleted, or renamed, use SHCNE_CREATE, SHCNE_DELETE, or SHCNE_RENAMEITEM, respectively, instead.

The following values specify combinations of other events:
SHCNE_DISKEVENTS | Specifies a combination of all of the disk event identifiers.
SHCNE_GLOBALEVENT | Specifies a combination of all of the global event identifiers.

The following value modifies other event values and cannot be used alone:
SHCNE_INTERRUPT The specified event occurred as a result of a system interrupt.

uFlags
Flags that indicate the meaning of the dwItem1 and dwItem2 parameters. The uFlags parameter must be one of the following values:
SHCNF_DWORD | The dwItem1 and dwItem2 parameters are DWORD values.
SHCNF_IDLIST | dwItem1 and dwItem2 are the addresses of ITEMIDLIST structures that represent the item(s) affected by the change. Each ITEMIDLIST must be relative to the desktop folder.
SHCNF_PATH | dwItem1 and dwItem2 are the addresses of NULL-terminated strings that contain the full path names of the items affected by the change.
SHCNF_PRINTER | dwItem1 and dwItem2 are the addresses of NULL-terminated strings that represent the friendly names of the printer(s) affected by the change.

The following flags modify other data-type flags and cannot be used by themselves:
SHCNF_FLUSH | The function should not return until the notification has been delivered to all affected components.
SHCNF_FLUSHNOWAIT | The function should begin delivering notifications to all affected components but should return as soon as the notification process has begun.

dwItem1
First event-dependent value.
dwItem2
Second event-dependent value.


Shell_NotifyIcon

WINSHELLAPI BOOL WINAPI Shell_NotifyIcon(
    DWORD dwMessage,
    PNOTIFYICONDATA pnid
);

Sends a message to the system to add, modify, or delete an icon from the taskbar status area.

  • Returns nonzero if successful, or zero otherwise.
dwMessage
Message value to send. This parameter can be one of these values:
NIM_ADD | Adds an icon to the status area.
NIM_DELETE | Deletes an icon from the status area.
NIM_MODIFY | Modifies an icon in the status area.
pnid
Address of a NOTIFYICONDATA structure. The content of the structure depends on the value of dwMessage.


ShellAbout

int ShellAbout (
   HWND hWnd,
   LPCTSTR szApp,
   LPCTSTR szOtherStuff,
   HICON hIcon
);

Displays a ShellAbout dialog box.

  • Returns TRUE if successful, or FALSE otherwise.
hWnd
Window handle to a parent window. This parameter can be NULL.
szApp
Displays text in the title bar of the ShellAbout dialog box and on the first line of the dialog box after the text "Microsoft". 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".
szOtherStuff
Displays text in the dialog box after the version and copyright information.
hIcon
Icon that the function displays in the dialog box. If this parameter is NULL, the function displays the Microsoft® Windows® or Windows NT® icon.

Note that the ShellAbout function dialog box uses text and a default icon that are specific to either Windows or Windows NT.

An example of a ShellAbout dialog box can be seen by selecting the About Program Manager command in Program Manager.


SHEmptyRecycleBin

SHSTDAPI SHEmptyRecycleBin(
    HWND hwnd,
    LPCTSTR pszRootPath,
    DWORD dwFlags
);

Empties the recycle bin on the specified drive.

  • Returns S_OK if successful, or an OLE-defined error value otherwise.
hwnd
Handle to the parent window of any dialog boxes that might be displayed during the operation. This parameter can be NULL.
pszRootPath
Address of a NULL-terminated string that contains the path of the root drive on which the recycle bin is located. This parameter can contain the address of a string formatted with the drive, folder, and subfolder names (c:\windows\system . . .). It can also contain an empty string or NULL. If this value is an empty string or NULL, all recycle bins on all drives will be emptied.
dwFlags
One or more of the following values:
SHERB_NOCONFIRMATION | No dialog confirming the deletion of the objects will be displayed.
SHERB_NOPROGRESSUI | No dialog indicating the progress will be displayed.
SHERB_NOSOUND | No sound will be played when the operation is complete.

See also SHQueryRecycleBin


ShellExecute

HINSTANCE ShellExecute(
    HWND hwnd,
    LPCTSTR lpOperation,
    LPCTSTR lpFile,
    LPCTSTR lpParameters,
    LPCTSTR lpDirectory,
    INT nShowCmd
);

Opens or prints a specified file.

  • Returns a value greater than 32 if successful, or an error value that is less than or equal to 32 otherwise. The following table lists the error values. The return value is cast as an HINSTANCE for backward compatibility with 16-bit Windows applications.
    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 | The operating system denied access to the specified file.
    SE_ERR_ASSOCINCOMPLETE | The file name 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 | The specified dynamic-link library was not found.
    SE_ERR_FNF | The specified file was not found.
    SE_ERR_NOASSOC | There is no application associated with the given file name extension.
    SE_ERR_OOM | There was not enough memory to complete the operation.
    SE_ERR_PNF | The specified path was not found.
    SE_ERR_SHARE | A sharing violation occurred.
hwnd
Window handle to 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
Address of a null-terminated string that specifies the operation to perform. The following operation strings are valid:
"open" | The function opens the file specified by the lpFile parameter. The file can be an executable file or a document file. It can also be a folder.
"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.
"explore" | The function explores the folder specified by lpFile.

This parameter can be NULL. In that case, the function opens the file specified by lpFile.

lpFile
Address of a null-terminated string that specifies the file to open or print or the folder to open or explore. The function can open an executable file or a document file. The function can print a document file.
lpParameters
If the lpFile parameter specifies an executable file, lpParameters is an address to a null-terminated string that specifies the parameters to be passed to the application.
If lpFile specifies a document file, lpParameters should be NULL.
lpDirectory
Address of 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:
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.

You can use this function to open or explore a shell 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 attempt to open or explore the folder.

To obtain information about the application that is launched as a result of calling ShellExecute, use ShellExecuteEx.


ShellExecuteEx

WINSHELLAPI BOOL WINAPI ShellExecuteEx(
    LPSHELLEXECUTEINFO lpExecInfo
);

Performs an action on a file.

  • Returns a nonzero value if successful, or zero otherwise. To get extended error information, call the GetLastError function.
lpExecInfo
Address of a SHELLEXECUTEINFO structure that contains and receives information about the application being executed.

If the function succeeds, it sets the hInstApp member of the SHELLEXECUTEINFO structure to the instance handle to 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.

The error value returned by GetLastError corresponds to the SE_ERR_ values and may be one of the following:
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 file name extension.
ERROR_ACCESS_DENIED | Access to the specified file is denied.
ERROR_DLL_NOT_FOUND | One of the library files necessary to run the application can't be found.
ERROR_CANCELLED | The function prompted the user for the location of the application, but the user canceled the request.
ERROR_NOT_ENOUGH_MEMORY | There is not enough memory to perform the specified action.
ERROR_SHARING_VIOLATION | A sharing violation occurred.


SHFileOperation

WINSHELLAPI int WINAPI SHFileOperation(
    LPSHFILEOPSTRUCT lpFileOp
);

Copies, moves, renames, or deletes a file system object.

  • Returns zero if successful, or nonzero otherwise.
lpFileOp
Address of an SHFILEOPSTRUCT structure that contains information this function needs to carry out the specified operation.


SHFreeNameMappings

WINSHELLAPI void WINAPI SHFreeNameMappings(;
    HANDLE hNameMappings
);

Frees a file name mapping object that was retrieved by the SHFileOperation function.

hNameMappings
Handle to the file name mapping object to be freed.


SHGetDataFromIDList

HRESULT ShGetDataFromIDList(
    LPSHELLFOLDER psf,
    LPCITEMIDLIST pidl,
    int nFormat,
    PVOID pv,
    int cb
);

Retrieves extended property data from a relative identifier list.

  • Returns NOERROR if successful, or E_INVALIDARG otherwise.
psf
Address of the parent IShellFolder interface.
pidl
Address of an ITEMIDLIST structure that identifies the subfolder relative to the folder specified in psf.
nFormat
Specifies the format in which the data is being requested. This must be one of the following formats:
SHGDFIL_FINDDATA | Format used for file system objects. The pv parameter is the address of a WIN32_FIND_DATA structure.
SHGDFIL_NETRESOURCE | Format used for network resources. The pv parameter is the address of a NETRESOURCE structure.
SHGDFIL_DESCRIPTIONID | Format used for network resources. The pv parameter is the address of an SHDESCRIPTIONID structure.
pv
Address of a buffer that receives the requested data. The format of this buffer is determined by nFormat.

If nFormat is SHGDFIL_NETRESOURCE, there are two possible cases. If the buffer is large enough, the net resource's string information (fields for the network name, local name, provider, and comments) will be placed into the buffer. If the buffer is not large enough, only the net resource structure will be placed into the buffer and the string information pointers will be NULL.

cb
Size of the buffer at pv, in bytes.

E_INVALIDARG is returned if the psf, pidl, pv, or cb parameters do not match the nFormat parameter, or if nFormat is not one of the specific SHGDFIL_ values shown above.


SHGetDesktopFolder

WINSHELLAPI HRESULT WINAPI SHGetDesktopFolder(
    LPSHELLFOLDER *ppshf
);

Retrieves the IShellFolder interface for the desktop folder, which is the root of the shell's namespace.

  • Returns NOERROR 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 method.


SHGetDiskFreeSpace

BOOL SHGetDiskFreeSpace(
    LPCTSTR pszVolume,
    ULARGE_INTEGER *pqwFreeCaller,
    ULARGE_INTEGER *pqwTot,
    ULARGE_INTEGER *pqwFree
);

Retrieves disk space information for a disk volume.

  • Returns non-zero if successful or zero otherwise.
pszVolume
A NULL-terminated string that specifies the volume for which size information will be retrieved. This can be a drive letter, UNC name or the path of a folder.
pqwFreeCaller
Address of a ULARGE_INTEGER value that receives the number of bytes available to the caller on the volume. If the operating system implements per-user quotas, this value may be less than the total number of free bytes on the volume.
pqwTot
Address of a ULARGE_INTEGER value that receives the total size of the volume, in bytes.
pqwFree
Address of a ULARGE_INTEGER value that receives the number of bytes of free space on the volume.

SHGetDiskFreeSpace is nearly identical to the GetDiskFreeSpaceEx API. SHGetDiskFreeSpace will load the proper module, obtain the address of GetDiskFreeSpaceEx and then call it. This prevents the caller from having to perform these operations themselves. See the operating system restrictions for GetDiskFreeSpaceEx for more information.

This function is implemented in shell versions 4.71 and later. In order to maintain backward compatibility with previous shell versions, this function should not be used explicitly. Instead, the LoadLibrary and GetProcAddress functions should be used to obtain the function address.

Version 4.71


SHGetFileInfo

WINSHELLAPI DWORD WINAPI SHGetFileInfo(
    LPCTSTR 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 contains the SHGFI_EXETYPE flag, the return value specifies the type of the executable file. It will be one of the following values:
    Value | Executable File Type
    0 | Nonexecutable file or an error condition
    LOWORD = NE or PE and HIWORD = 3.0, 3.5, or 4.0 | Windows application
    LOWORD = MZ and HIWORD = 0 | MS-DOS .exe, .com, or .bat file
    LOWORD = PE and HIWORD = 0 | Win32 console application

    If uFlags contains SHGFI_SYSICONINDEX, the return value is the handle to the system image list that contains the large icon images. If SHGFI_SMALLICON is included with SHGFI_SYSICONINDEX, the return value is the handle to the image list that contains the small icon images.

    If uFlags does not contain SHGFI_EXETYPE or SHGFI_SYSICONINDEX, the return value is nonzero if successful, or zero otherwise.

pszPath
Address of a buffer that contains the path and file name. Both absolute and relative paths are valid.

If the uFlags parameter includes the SHGFI_PIDL flag, this parameter must be the address of an ITEMIDLIST (PIDL) structure that contains the list of item identifiers that uniquely identifies the file within the shell's namespace. The PIDL must be a fully qualified PIDL. Relative PIDLs are not allowed.

If the uFlags parameter includes the SHGFI_USEFILEATTRIBUTES flag, this parameter does not have to be a valid file name. The function will proceed as if the file exists with the specified name and with the file attributes passed in the dwFileAttributes parameter. This allows you to obtain information about a file type by passing just the extension for pszPath and passing FILE_ATTRIBUTE_NORMAL in dwFileAttributes.

This string can use either short (the 8.3 form) or long file names.

dwFileAttributes
Combination of one or more file attribute flags (FILE_ATTRIBUTE_ values). If uFlags does not include the SHGFI_USEFILEATTRIBUTES flag, this parameter is ignored.
psfi
Address of a SHFILEINFO structure to receive the file information.
cbFileInfo
Size, in bytes, of the SHFILEINFO structure pointed to by the psfi parameter.
uFlags
Flags that specify the file information to retrieve. This parameter can be a combination of the following values:
SHGFI_ATTR_SPECIFIED | Modifies SHGFI_ATTRIBUTES. Indicates that the dwAttributes member of the SHFILEINFO structure at psfi contains the specific attributes that are desired. These attributes will be passed to IShellFolder::GetAttributesOf. If this flag is not specified, 0xFFFFFFFF will be passed to GetAttributesOf, requesting all attributes. This flag cannot be specified with the SHGFI_ICON flag.
SHGFI_ATTRIBUTES | Retrieve the item attributes. The attributes are copied to the dwAttributes member of the structure specified in the psfi parameter. These are the same attributes that are obtained from IShellFolder::GetAttributesOf.
SHGFI_DISPLAYNAME | Retrieve the display name for the file. The name is copied to the szDisplayName member of the structure specified in psfi. The returned display name uses the long file name, if there is one, rather than the 8.3 form of the file name.
SHGFI_EXETYPE | Retrieve the type of the executable file if pszPath identifies an executable file. This flag cannot be specified with any other flags.
SHGFI_ICON | Retrieve the handle to 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 to the system image list.
SHGFI_ICONLOCATION | Retrieve the name of the file that contains the icon representing the file. The name is copied to the szDisplayName member of the structure specified in psfi.
SHGFI_LARGEICON | Modify SHGFI_ICON, causing the function to retrieve the file's large icon.
SHGFI_LINKOVERLAY | Modify SHGFI_ICON, causing the function to add the link overlay to the file's icon.
SHGFI_OPENICON | Modify 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 | Indicate that pszPath is the address of an ITEMIDLIST structure rather than a path name.
SHGFI_SELECTED | Modify SHGFI_ICON, causing the function to blend the file's icon with the system highlight color.
SHGFI_SHELLICONSIZE | Modify 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 | Modify SHGFI_ICON, causing the function to retrieve the file's small icon.
SHGFI_SYSICONINDEX | Retrieve 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 to the system image list.
SHGFI_TYPENAME | Retrieve the string that describes the file's type. The string is copied to the szTypeName member of the structure specified in psfi.
SHGFI_USEFILEATTRIBUTES | Indicates that the function should not attempt to access the file specified by pszPath. Rather, it should act as if the file specified by pszPath exists with the file attributes passed in dwFileAttributes. This flag cannot be combined with the SHGFI_ATTRIBUTES, SHGFI_EXETYPE, or SHGFI_PIDL flags.


SHGetInstanceExplorer

WINSHELLAPI HRESULT WINAPI SHGetInstanceExplorer(
    IUnknown *ppunk
);

Retrieves the address of Windows Explorer's IUnknown interface.

  • Returns NOERROR if successful, or E_FAIL otherwise.
ppunk
Address of an IUnknown interface pointer that receives Windows Explorer's IUnknown interface.


SHGetMalloc

HRESULT SHGetMalloc(
    LPMALLOC *ppMalloc
);

Retrieves a pointer to the shell's IMalloc interface. This interface must be used to free memory that was allocated by the shell or to allocate memory that will be freed by the shell. Applications can also use this interface to allocate and free their own memory.

  • Returns NOERROR if successful, or E_FAIL otherwise.
ppMalloc
Address of a pointer that receives the shell's IMalloc interface pointer.


SHGetNewLinkInfo

BOOL SHGetNewLinkInfo(
    LPCTSTR pszLinkTo,
    LPCTSTR pszDir,
    LPTSTR pszName,
    BOOL *pfMustCopy,
    UINT uFlags
);

Creates the proper name for a new shortcut. This function does not actually create a shortcut.

  • Returns non-zero if successful or zero otherwise.
pszLinkTo
Specifies the path and file name of the target of the shortcut. If uFlags does not contain the SHGNLI_PIDL value, this parameter is the address of a NULL-terminated string that contains the target. If uFlags contains the SHGNLI_PIDL value, this parameter is a PIDL that represents the target.
pszDir
Address of a NULL-terminated string that contains the path of the folder that the shortcut would be created in.
pszName
Address of a string that receives the NULL-terminated path and file name for the shortcut. This buffer is assumed to be at least MAX_PATH characters in size.
pfMustCopy
Address of a BOOL value that receives a flag that indicates if the shortcut would be copied. When a shortcut to another shortcut is created, the shell simply copies the target shortcut and modifies that copied shortcut appropriately. This value receives a non-zero value if the target specified in pszLinkTo specifies a shortcut that will cause the target shortcut to be copied. This value receives zero if the target does not specify a shortcut that would be copied.
uFlags
Specifies the options for the function. This can be zero or a combination of the following values:
SHGNLI_PIDL | pszLinkTo is a PIDL that represents the target. If this flag is not included, pszLinkTo is the address of a string that contains the path and file name of the target.
SHGNLI_NOUNIQUE | The function will not create a unique name within the destination folder. If this flag is not included, the function create the shortcut name and then determine if the name is unique in the destination folder. If a file with the same name exists within the destination folder, the shortcut name will be modified. This process is repeated until a unique name is found.
SHGNLI_PREFIXNAME | The created name will be preceded by the string "Shortcut to ".

SHGetNewLinkInfo will determine the executable type of the target. If pszLinkTo specifies a DOS application, the ".PIF" extension will be used, otherwise the ".LNK" extension will be used for the shortcut.

SHGetNewLinkInfo will also determine if the destination file system supports long file names. If the destination file system does support long file names, then a long file name will be used for the shortcut name. If the destination file system does not support long file names, then the shortcut name will be returned in an 8.3 format.

This function is implemented in shell versions 4.71 and later. In order to maintain backward compatibility with previous shell versions, this function should not be used explicitly. Instead, the LoadLibrary and GetProcAddress functions should be used to obtain the function address.

Version 4.71


SHGetPathFromIDList

WINSHELLAPI BOOL WINAPI SHGetPathFromIDList(
    LPCITEMIDLIST pidl,
    LPSTR pszPath
);

Converts an item identifier list to a file system path.

  • Returns TRUE if successful, or FALSE otherwise.
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 to receive the file system path. This buffer must be at least MAX_PATH characters in size.

If the location specified by the pidl parameter is not part of the file system, this function will fail.


SHGetSettings

void WINAPI SHGetSettings(
    LPSHELLFLAGSTATE lpsfs,
    DWORD dwMask
);

Retrieves the current shell option settings.

lpsfs
Address of a SHELLFLAGSTATE structure that receives the shell option settings.
dwMask
Set of flags that determine which members of lpsfs are being requested. This can be one or more of the following values:
SSF_DESKTOPHTML | The fDesktopHTML member is being requested.
SSF_DONTPRETTYPATH | The fDontPrettyPath member is being requested.
SSF_DOUBLECLICKINWEBVIEW | The fDoubleClickInWebView member is being requested.
SSF_HIDEICONS | The fHideIcons member is being requested.
SSF_MAPNETDRVBUTTON | The fMapNetDrvBtn member is being requested.
SSF_NOCONFIRMRECYCLE | The fNoConfirmRecycle member is being requested.
SSF_NOWEBVIEW | The fNoWebView member is being requested.
SSF_SHOWALLOBJECTS | The fShowAllObjects member is being requested.
SSF_SHOWATTRIBCOL | The fShowAttribCol member is being requested.
SSF_SHOWCOMPCOLOR | The fShowCompColor member is being requested.
SSF_SHOWEXTENSIONS | The fShowExtensions member is being requested.
SSF_SHOWINFOTIP | The fShowInfoTip member is being requested.
SSF_SHOWSYSFILES | The fShowSysFiles member is being requested.
SSF_WIN95CLASSIC | The fWin95Classic member is being requested.


SHGetSpecialFolderLocation

WINSHELLAPI HRESULT WINAPI SHGetSpecialFolderLocation(
    HWND hwndOwner,
    int nFolder,
    LPITEMIDLIST *ppidl
);

Retrieves the PIDL of a special folder.

  • Returns NOERROR if successful, or an OLE-defined error result otherwise.
hwndOwner
Handle to the owner window the client should specify if it displays a dialog box or message box.
nFolder
Value specifying the folder for which to retrieve the location. This parameter can be one of the following values:
CSIDL_ALTSTARTUP | File system directory that corresponds to the user's nonlocalized Startup program group.
CSIDL_APPDATA | File system directory that serves as a common repository for application-specific data.
CSIDL_BITBUCKET | 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_COMMON_ALTSTARTUP | File system directory that corresponds to the nonlocalized Startup program group for all users.
CSIDL_COMMON_DESKTOPDIRECTORY | File system directory that contains files and folders that appear on the desktop for all users.
CSIDL_COMMON_FAVORITES | File system directory that serves as a common repository for all users' favorite items.
CSIDL_COMMON_PROGRAMS | File system directory that contains the directories for the common program groups that appear on the Start menu for all users.
CSIDL_COMMON_STARTMENU | File system directory that contains the programs and folders that appear on the Start menu for all users.
CSIDL_COMMON_STARTUP | File system directory that contains the programs that appear in the Startup folder for all users.
CSIDL_CONTROLS | Virtual folder containing icons for the Control Panel applications.
CSIDL_COOKIES | File system directory that serves as a common repository for Internet cookies.
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_FAVORITES | File system directory that serves as a common repository for the user's favorite items.
CSIDL_FONTS | Virtual folder containing fonts.
CSIDL_HISTORY | File system directory that serves as a common repository for Internet history items.
CSIDL_INTERNET | Virtual folder representing the Internet.
CSIDL_INTERNET_CACHE | File system directory that serves as a common repository for temporary Internet files.
CSIDL_NETHOOD | File system directory containing objects that appear in the network neighborhood.
CSIDL_NETWORK | Network Neighborhood Folder—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 | Virtual folder containing installed printers.
CSIDL_PRINTHOOD | File system directory that serves as a common repository for printer links.
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. The system starts these programs whenever any user logs onto Windows NT or starts Windows 95.
CSIDL_TEMPLATES | File system directory that serves as a common repository for document templates.
ppidl
Address of a pointer to an item identifier list specifying the folder's location relative to the root of the namespace (the desktop). The calling application is responsible for freeing this pointer with the shell's IMalloc interface (see SHGetMalloc).

See also SHGetSpecialFolderPath


SHGetSpecialFolderPath

WINSHELLAPI HRESULT WINAPI SHGetSpecialFolderPath(
    HWND hwndOwner,
    LPTSTR lpszPath,
    int nFolder,
    BOOL fCreate
);

Retrieves the path of a special folder.

  • Returns NOERROR if successful, or an OLE-defined error result otherwise.
hwndOwner
Handle to the owner window the client should specify if it displays a dialog box or message box.
lpszPath
Address of a character buffer that receives the drive and path of the specified folder. This buffer must be at least MAX_PATH characters in size.
nFolder
Value specifying the folder for which to retrieve the location. This can be one of the nFolder values described in SHGetSpecialFolderLocation. This argument must specify a real folder and not a virtual folder. If a virtual folder is specified, this function will fail.
fCreate
Indicates if the folder should be created if it does not already exist. If this value is nonzero, the folder will be created. If this value is zero, the folder will not be created.

Version 4.71


SHInvokePrinterCommand

BOOL SHInvokePrinterCommand(
    HWND hwnd,
    UINT uAction,
    LPCTSTR lpBuf1,
    LPCTSTR lpBuf2,
    BOOL fModal
);

Executes a command on a printer object.

  • Returns non-zero if successful or zero otherwise.
hwnd
Handle of the window that will be used as the parent of any windows or dialog boxes that are created during the operation.
uAction
A value that determines the type of printer operation that will be performed. This can be one of the following values:
PRINTACTION_DOCUMENTDEFAULTS | Windows NT® only. The default document properties for the printer specified by the name in lpBuf1 will be displayed. lpBuf2 is ignored.
PRINTACTION_NETINSTALL | The network printer specified by the name in lpBuf1 will be installed. lpBuf2 is ignored.
PRINTACTION_NETINSTALLLINK | A shortcut to the network printer specified by the name in lpBuf1 will be created. lpBuf2 specifies the drive and path of the folder in which the shortcut will be created. The network printer must have already been installed on the local machine.
PRINTACTION_OPEN | The printer specified by the name in lpBuf1 will be opened. lpBuf2 is ignored.
PRINTACTION_OPENNETPRN | The network printer specified by the name in lpBuf1 will be opened. lpBuf2 is ignored.
PRINTACTION_PROPERTIES | The properties for the printer specified by the name in lpBuf1 will be displayed. lpBuf2 can either be NULL or specify.
PRINTACTION_SERVERPROPERTIES | Windows NT® only. The properties for the server of the printer specified by the name in lpBuf1 will be displayed. lpBuf2 is ignored.
PRINTACTION_TESTPAGE | A test page will be printed on the printer specified by the name in lpBuf1. lpBuf2 is ignored.
lpBuf1
Address of a string that contains additional information for the printer command. The information contained in this parameter depends upon the value of uAction.
lpBuf2
Address of a string that contains additional information for the printer command. The information contained in this parameter depends upon the value of uAction.
fModal
A value that determines whether SHInvokePrinterCommand should return after initializing the command or wait until the command is completed. If this value is non-zero, SHInvokePrinterCommand will not return until the command is completed. If this value is zero, SHInvokePrinterCommand will return as soon as the command is initialized.

When a printer name is specified by lpBuf1, the name can either be the name of a local printer or the server and share name of a network printer. When specifying a network printer name, the name must be specified in the format of "\\<server>\<shared printer name>".

This function is implemented in shell versions 4.71 and later. In order to maintain backward compatibility with previous shell versions, this function should not be used explicitly. Instead, the LoadLibrary and GetProcAddress functions should be used to obtain the function address.

Version 4.71


SHLoadInProc

WINSHELLAPI HRESULT WINAPI SHLoadInProc(
    REFCLSID rclsid
);

Creates an instance of the specified object class from within the context of the shell's process.

  • Returns NOERROR if successful, or an OLE-defined error result otherwise.
rclsid
CLSID of the object class to be created.


SHQueryRecycleBin

SHSTDAPI SHQueryRecycleBin(
    LPCTSTR pszRootPath,
    LPSHQUERYRBINFO pSHQueryRBInfo
);

Retrieves the size of the Recycle Bin, and number of items in it, on the specified drive.

  • Returns S_OK if successful, or an OLE-defined error value otherwise.
pszRootPath
Address of a NULL-terminated string to contain the path of the root drive on which the Recycle Bin is located. This parameter can contain the address of a string formatted with the drive, folder, and subfolder names (c:\windows\system . . .). It can also contain an empty string or NULL. If this value is an empty string or NULL, information is retrieved for all Recycle Bins on all drives.
pSHQueryRBInfo
Address of a SHQUERYRBINFO structure that receives the Recycle Bin information. The cbSize member of the structure must be set to the size of the structure before calling this API.

See also SHEmptyRecycleBin


SOBailOut

Allows the file parser to return an error condition.

Syntax

VOID SOBailOut(
    WORD wError,
    HPROC reserved
);

Parameters

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.

Return Value

No return value.

Remarks

The parser should return from the VwStreamReadFunc function as soon as possible after this function is called.


SOBeginTable

Starts a table definition, indicating that the text in subsequent output calls is part of a table. This function must be called between paragraphs and before row and cell formats are specified.

Syntax

VOID SOBeginTable(
    HPROC reserved
);

Parameters

reserved
Reserved; do not use.

Return Value

No return value.


SOEndColumnInfo

Ends the definition of column information. The file parser must call this function immediately after setting the column information.

Syntax

VOID SOEndColumnInfo(
    HPROC reserved
);

Parameters

reserved
Reserved; do not use.

Return Value

No return value.

Remarks

This function can only be called from the VwStreamSectionFunc function.


SOEndFieldInfo

Ends the definition of field information.

Syntax

VOID SOEndFieldInfo(
    HPROC reserved
);

Parameters

reserved
Reserved; do not use.

Return Value

No return value.

Remarks

The file parser must have previously called the SOStartFieldInfo function.

The file parser calls the SOEndFieldInfo function immediately after setting the field information. The SOEndFieldInfo function can only be called from the VwStreamSectionFunc function.


SOEndFontTable

Ends the definition of a font table.

Syntax

VOID SOEndFontTable(
    HPROC reserved
);

Parameters

reserved
Reserved; do not use.

Return

No return value.

Remarks

The file parser must call this function immediately after setting font entries. This function can only be called from the VwStreamSectionFunc function.


SOEndPalette

Ends the definition of a color palette.

Syntax

VOID SOEndPalette(
    HPROC reserved
);

Parameters

reserved
Reserved; do not use.

Return Value

No return value.

Remarks

The file parser calls this function immediately after specifying the last palette entry.


SOEndTable

Ends a table definition, indicating that the text in subsequent output calls is no longer part of a table.

Syntax

VOID SOEndTable(
    HPROC reserved
);

Parameters

reserved
Reserved; do not use.

Return Value

No return value.

Remarks

This function must be called after a row break.


SOEndTabStops

Ends the definition of tabs stops for a paragraph.

Syntax

VOID SOEndTabStops(
    HPROC reserved
);

Parameters

reserved
Reserved; do not use.

Return Value

No return value.

Remarks

To set tab stops, use the SOPutTabStop function.

The file parser calls the SOEndTabStops function immediately after setting the last tab stop for the paragraph.


SOGetInfo

Retrieves information about a spreadsheet.

Syntax

VOID SOGetInfo(
    WORD wInfo,
    void VWPTR *pInfo,
    HPROC reserved
);

Parameters

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.

Return Value

No return value.


SOGetScanLineBuffer

Retrieves the address of the buffer for storing the current scan line.

Syntax

WORD SOGetScanLineBuffer(
    VOID VWPTR *ppScanLineData,
    HPROC reserved

);

Parameters

ppScanLineData
Address of the variable that receives the address of the scan line data buffer.
reserved
Reserved; do not use.

Return Value

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.

Remarks

This function is called from the VwStreamReadFunc function for each scan line produced.

The SOGetScanLineBuffer function sets the variable pointed to by ppScanLineData to the address where the scan line data should be built.


SOPutBitmapHeader

Outputs information about a bitmap.

Syntax

VOID SOPutBitmapHeader(
    PSOBITMAPHEADER pBitmapHeader,
    HPROC reserved
);

Parameters

pBitmapHeader
Address of the SOBITMAPHEADER structure that contains the bitmap header information.
reserved
Reserved; do not use.

Return Value

No return value.


SOPutBreak

Sets a paragraph, cell, record, page, section, or other type of break.

Syntax

WORD SOPutBreak(
    WORD wType,
    DWORD dwInfo,
    HPROC reserved
);

Parameters

wType
Type of break. This parameter can be 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.

dwInfo is saved after every SOPutBreak function and, like the regular save information, should represent the next record, not the one just read.

reserved
Reserved; do not use.

Return Value

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.

Remarks

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

Outputs a character, applying the current font, height, and attributes. The character is assumed to belong to the character set selected by the open function and is countable and within the range of displayable characters.

Syntax

VOID SOPutChar(
    WORD wCh,
    HPROC reserved
);

Parameters

wCh
Character value. This parameter must be within the range specified by the current character set.
reserved
Reserved; do not use.

Return Value

No return value.


SOPutCharAttr

Sets the style attributes for characters in text.

Syntax

VOID SOPutCharAttr(
    WORD wAttr,
    WORD wState,
    HPROC reserved
);

Parameters

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 | Outline rather than solid
SO_SHADOW | Shadow slightly beneath and to the side
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.

Return Value

No return value.


SOPutCharFontById

Sets the font for characters in text.

Syntax

VOID SOPutCharFontById(
    DWORD dwFontId,
    HPROC reserved
);

Parameters

dwFontId
Font identifier, relative to the previously given font table.
reserved
Reserved; do not use.

Return Value

No return value.


SOPutCharFontByName

Sets the font for characters in text by specifying the name of the font.

Syntax

VOID SOPutCharFontByName(
    WORD wFontType,
    WORD pFontName,
    HPROC reserved
);

Parameters

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.

Return Value

No return value.


SOPutCharHeight

Sets the height, in half points, of a character in text.

Syntax

VOID SOPutCharHeight(
    WORD wHeight,
    HPROC reserved
);

Parameters

wHeight
Height, in half points, of the character.
reserved
Reserved; do not use.

Return Value

No return value.


SOPutCharX

Outputs a character, applying the specified character type. The character is assumed to belong to the character set selected by the open function.

Syntax

VOID SOPutCharX(
    WORD wCh,
    WORD wType,
    HPROC reserved
);

Parameters

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.

Return Value

No return value.


SOPutColumnInfo

Sets column information.

Syntax

VOID SOPutColumnInfo(
    PSOCOLUMN pColumn,
    HPROC reserved
);

Parameters

pColumn
Address of the SOCOLUMN structure containing the column information.
reserved
Reserved; do not use.

Return Value

No return value.

Remarks

The file parser must call the SOStartColumnInfo function before calling this function.

The SOPutColumnInfo function can only be called from the VwStreamSectionFunc function.


SOPutDataCell

Outputs data for a cell.

Syntax

VOID SOPutDataCell(
    PSODATACELL pCell,
    HPROC reserved
);

Parameters

pCell
Address of a SODATACELL structure that contains the cell data infomation.
reserved
Reserved; do not use.

Return Value

No return value.


SOPutEmbeddedObject

Sets an embedded graphics object.

Syntax

VOID SOPutEmbeddedObject(
    PSOEMBEDDEDOBJECT pObject,
    HPROC reserved
);

Parameters

pObject
Address of the SOEMBEDDEDOBJECT structure that contains information about the object to be embedded.
reserved
Reserved; do not use.

Return Value

No return value.

Remarks

The file parser must set the SOEMBEDDEDOBJECT structure with the appropriate values.


SOPutField

Outputs data for a field.

Syntax

VOID SOPutField(
    void VWPTR *pData,
    HPROC reserved
);

Parameters

pData
Address of the data for the field.
reserved
Reserved; do not use.

Return Value

No return value.

Remarks

This function is used for all storage types except the SO_FIELDTEXTVAR value.


SOPutFieldInfo

Sets field information.

Syntax

VOID SOPutFieldInfo(
    PSOFIELD pField,
    HPROC reserved
);

Parameters

pField
Address of the SOFIELD structure containing the field information.
reserved
Reserved; do not use.

Return Value

No return value.

Remarks

The file parser must call the SOStartFieldInfo function before calling this function.

The SOPutFieldInfo function can only be called from the VwStreamSectionFunc function.


SOPutFontTableEntry

Sets a font table entry.

Syntax

VOID SOPutFontTableEntry(
    DWORD dwFontId,
    WORD wFontType,
    Char VWPTR *pFontName,
    HPROC reserved
);

Parameters

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.

Return Value

No return value.

Remarks

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


SOPutHdrEntry

Sets strings for the header information.

Syntax

VOID SOPutHdrEntry(
    char VWPTR *pLabel,
    char VWPTR *pData,
    WORD wId,
    HPROC reserved
);

Parameters

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.

Return Values

No return value.

Remarks

This function can only be called from the VwStreamSectionFunc function.


SOPutMoreText

Outputs the text for a cell and indicates whether there is more text to be output for the cell.

Syntax

VOID SOPutMoreText(
    WORD wCount,
    char VWPTR *pText,
    WORD bMore,
    HPROC reserved
);

Parameters

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.

Return Value

No return value.

Remarks

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

Outputs data for a variable field and indicates whether there is more data to be output for the field.

Syntax

VOID SOPutMoreVarField(
    VOID VWPTR *pData,
    WORD wCount,
    WORD bMore,
    HPROC reserved
);

Parameters

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.

Return Value

No return value.

Remarks

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

Sets the colors for a palette entry.

Syntax

VOID SOPutPaletteEntry(
    unsigned char Red,
    unsigned char Green,
    unsigned char Blue,
    HPROC reserved
);

Parameters

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.

Return Value

No return value.

Remarks

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

Sets the alignment for a paragraph.

Syntax

VOID SOPutParAlign(
    WORD wType,
    HPROC reserved
);

Parameters

wType
Type of alignment. This parameter can be the SO_ALIGNLEFT, SO_ALIGNRIGHT, SO_ALIGNCENTER, or SO_ALIGNJUSTIFY value.
reserved
Reserved; do not use.

Return Value

No return value.


SOPutParaIndents

Sets indents for a paragraph.

Syntax

VOID SOPutParaIndents(
    LONG dwLeft,
    LONG dwRight,
    LONG dwFirst,
    HPROC reserved
);

Parameters

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.

Return Value

No return value.


SOPutParaMargins

Sets paragraph margins.

Syntax

VOID SOPutParaMargins(
    LONG dwLeft,
    LONG dwRight,
    HPROC reserved
);

Parameters

dwLeft
Width, in TWIPs, of the left margin.
dwRight
Width, in TWIPs, of the right margin.
reserved
Reserved; do not use.

Return Value

No return value.


SOPutParaSpacing

Sets the spacing for a paragraph.

Syntax

VOID SOPutParaSpacing(
    WORD wLineHeightType,
    DWORD dwLineHeight,
    DWORD dwSpaceBefore,
    DWORD dwSpaceAfter,
    HPROC reserved
);

Parameters

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.

Return Value

No return value.


SOPutScanLineData

Sets the bit values in a single scan line of a bitmap.

Syntax

VOID SOPutScanLineData(
    U_BYTE VWPTR *pScanLineData,
    HPROC reserved
);

Parameters

pScanLineData
Address of the bitmap data for the current scan line.
reserved
Reserved; do not use.

Return Value

No return value.

Remarks

The bitmap format must have been previously defined by using the SOPutBitmapHeader function.


SOPutSectionName

Sets the name of a section.

Syntax

VOID SOPutSectionName(
    char VWPTR *pName,
    HPROC reserved
);

Parameters

pName
Address of a null-terminated string specifying the name of the section.
reserved
Reserved; do not use.

Return Value

No return value.


SOPutSectionType

Outputs a section type.

Syntax

VOID SOPutSectionType(
    WORD wType,
    HPROC reserved
);

Parameters

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.

Return Value

No return value.


SOPutSpecialCharX

Outputs a special character, applying the specified character type.

Syntax

VOID SOPutSpecialCharX(
    WORD wCh,
    WORD wType,
    HPROC reserved
);

Parameters

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.

Return Value

No return value.


SOPutSubdocInfo

Outputs subdocument data.

Syntax

VOID SOPutSubdocInfo(
    WORD wType,
    WORD wSubType,
    HPROC reserved
);

Parameters

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.

Return Value

No return value.


SOPutTableCellInfo

Sets cell information.

Syntax

VOID SOPutTableCellInfo(
    PSOTABLECELLINFO pCellInfo,
    HPROC reserved
);

Parameters

pCellInfo
Address of a SOTABLECELLINFO structure containing information about the cell.
reserved
Reserved; do not use.

Return Value

No return value.


SOPutTableRowFormat

Sets the format of a row in a table.

Syntax

VOID SOPutTableRowFormat(
    WORD wLeftEdge,
    WORD wRowHeight,
    WORD wRowHeightType,
    WORD wCellMargin,
    WORD wRowAlignment,
    WORD wNumCells,
    HPROC reserved
);

Parameters

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.

Return Value

No return value.


SOPutTabStop

Sets a tab stop for the paragraph.

Syntax

VOID SOPutTabStop(
    PSOTAB pTabs,
    HPROC reserved
);

Parameters

pTabs
Address of the SOTAB structure containing the tab stop information.
reserved
Reserved; do not use.

Return Value

No return value.

Remarks

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

Outputs the text for a cell and indicates whether there is more text to be output for the cell.

Syntax

VOID SOPutTextCell(
    PSOTEXTCELL pCell,
    WORD wCount,
    char VWPTR *pText,
    HPROC reserved
);

Parameters

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.

Return Value

No return value.

Remarks

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

Outputs data for a variable field and indicates whether there is more data to be output for the field.

Syntax

VOID SOPutVarField(
    void VWPTR *pData,
    WORD wCount,
    WORD *bMore,
    HPROC reserved
);

Parameters

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.

Return Value

No return value.

Remarks

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

Outputs the vector header, specifying the display resolution, x- and y-axis orientation, background color, and color value type (RGB or palette).

Syntax

VOID SOPutVectorHeader(
    PSOVECTORHEADER pVectorHeader,
    HPROC reserved
);

Parameters

pVectorHeader
Address of a SOVECTORHEADER structure.
reserved
Reserved; do not use.

Return Value

No return value.


SOSetDateBase

Sets the base date. All subsequent dates are calculated as the sum of the base date and the given date value.

Syntax

VOID SOSetDataBase(
    DWORD dwBase,
    WORD wFlags,
    HPROC reserved
);

Parameter

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.

Return Value

No return value.

Remarks

This function can only be called from the VwStreamSectionFunc function.


SOStartColumnInfo

Starts the definition of column information.

Syntax

VOID SOStartColumnInfo(
    HPROC reserved
);

Parameter

reserved
Reserved; do not use.

Return Value

No return value.

Remarks

The file parser must call this function immediately before setting the information. This function can only be called from the VwStreamSectionFunc function.


SOStartFieldInfo

Starts the definition of field information.

Syntax

VOID SOStartFieldInfo(
    HPROC reserved
);

Parameters

reserved
Reserved; do not use.

Return Value

No return value.

Remarks

The file parser calls this function immediately before setting field information. This function can only be called from the VwStreamSectionFunc function.


SOStartFontTable

Starts the definition of a font table.

Syntax

VOID SOStartFontTable(
    HPROC reserved
);

Parameters

reserved
Reserved; do not use.

Return Value

No return value.

Remarks

The file parser must call this function immediately before setting font entries. The function can only be called from the VwStreamSectionFunc function.


SOStartPalette

Starts the definition of a color palette.

Syntax

VOID SOStartPalette(
    HPROC reserved
);

Parameters

reserved
Reserved; do not use.

Return Value

No return value.

Remarks

The file parser calls this function immediately before defining palette entries.


SOStartTabStops

Starts the definition of tab stops for a paragraph.

Syntax

VOID SOStartTabStops(
    HPROC reserved
);

Parameters

reserved
Reserved; do not use.

Return Value

No return value.

Remarks

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

Sets attributes related to drawing vector graphics objects.

Syntax

VOID SOVectorAttr(
    INT nItemId,
    DWORD wDataSize,
    VOID VWPTR *pData,
    HPROC reserved
);

Parameters

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.

Return Value

No return value.


SOVectorObject

Draws or defines the given vector graphics object.

Syntax

VOID SOVectorObject(
    INT nItemId,
    DWORD wDataSize,
    VOID VWPTR *pData,
    HPROC reserved
);

Parameters

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.

Return Value

No return value.


SUUserPopData

Pops user data. The data must have been pushed previously by using the SUUserPushData function.

Syntax

VOID SUUserPopData(
    VOID VWPTR *pData,
    HPROC reserved
);

Parameters

pData
Address of the VwStreamUserSaveType structure receiving the data.
reserved
Reserved; do not use.

Return Value

No return value.


SUUserPushData

Pushes user data. The data can be retrieved by using the SUUserPopData function.

Syntax

VOID SUUserPushData(
    VOID VWPTR *pData,
    HPROC reserved
);

Parameters

pData
Address of a VwStreamUserSaveType structure containing the data to be saved.
reserved
Reserved; do not use.

Return Value

No return value.


SUUserRetrieveData

Retrieves user data. 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.

Syntax

VOID SUUserRetrieveData(
    WORD wIndex,
    VOID VWPTR *pData,
    HPROC reserved
);

Parameters

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.

Return Value

No return value.


SUUserSaveData

Saves user data.

This function should not be used. The SUUserPushData function should be used instead.

Syntax

VOID SUUserSaveData(
    VOID VWPTR *pData,
    HPROC reserved
);

Parameters

pData
Address of a VwStreamUserSaveType structure containing the data to be saved.
reserved
Reserved; do not use.

Return Value

Returns the index used to retrieve the data. Indexes are guaranteed to be zero-based and sequential.


VwStreamCloseFunc

Closes the file. The file parser must carry out any necessary cleanup, such as closing any other open files related to the given file.

Syntax

VOID VwStreamCloseFunc(
    SOFILE hFile,
    HPROC reserved
);

Parameters

hFile
Handle to the file for execute input and output (XIO) routines.
reserved
Reserved; do not use.

Return Value

No return value.


VwStreamOpenFunc

Checks the validity of the specified file and returns information about the file parser.

Syntax

INT VwStreamOpenFunc(
    SOFILE hFile,
    INT wFileId,
    U_BYTE VWPTR *pFileName,
    SOFILTERINFO VWPTR *pFilterInfo,
    HPROC reserved
);

Parameters

hFile
Handle to 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.

Return Values

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


VwStreamReadFunc

Outputs characters, cells, or fields, depending on the current section type and file contents.

Syntax

INT VwStreamReadFunc(
    SOFILE hFile,
    HPROC reserved
);

Parameters

hFile
Handle to the file for execute input and output (XIO) routines.
reserved
Reserved; do not use.

Return Values

Returns zero if successful, or -1 if the end of the file is reached.


VwStreamReadRecordFunc

Outputs a single record by calling various stream output functions.

Syntax

VOID VwStreamReadRecordFunc(
    SOFILE hFile,
    DWORD dwData,
    HPROC reserved
);

Parameters

hFile
Handle to the file for execute input and output (XIO) routines.
dwData
Data to be saved for the record.
reserved
Reserved; do not use.

Return Value

No return value.

Remarks

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

Sets the parameters for a section.

Syntax

INT VwStreamSectionFunc(
    SOFILE hFile,
    HPROC reserved
);

Parameters

hFile
Handle to the file for execute input and output (XIO) routines.
reserved
Reserved; do not use.

Return Value

Always returns zero.

Remarks

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

Same definition as the line filters Seek function.

Syntax

INT VwStreamSeekFunc(
    SOFILE hFile,
    HPROC reserved
);

Parameters

hFile
Handle to the file for execute input and output (XIO) routines.
reserved
Reserved; do not use.

Return Value

Returns zero if successful, or -1 otherwise.


VwStreamTellFunc

Same definition as the line filters Tell function.

Syntax

INT VwStreamTellFunc(
    SOFILE hFile,
    HPROC reserved
);

Parameters

hFile
Handle to the file for execute input and output (XIO) routines.
reserved
Reserved; do not use.

Return Value

Returns zero if successful, or -1 if the function fails.


WinHelp

Starts Microsoft® Windows® Help (Winhelp.exe) and passes additional data indicating the nature of the Help requested by the application.

Syntax

BOOL WinHelp(
    HWND hWndMain,
    LPCTSTR lpszHelp,
    UINT uCommand,
    DWORD dwData
);

Parameters

hWndMain
Identifies the window requesting Help. The WinHelp function uses this handle to keep track of which applications have requested Help. If the uCommand parameter specifies HELP_CONTEXTMENU or HELP_WM_HELP, hWndMain identifies the control requesting Help.
lpszHelp
Address of a null-terminated string containing the path, if necessary, and the name of the Help file that WinHelp is to display.

The file name 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
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
Additional data. The value used depends on the value of the uCommand parameter. For a list of possible values, see the Remarks section.

Return Values

Returns nonzero if successful, or zero otherwise.

To get extended error information, call GetLastError.

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 Windows Help with the HELP_QUIT command is not necessary if you used the HELP_CONTEXTPOPUP command to start Windows Help.

The following table shows the possible values for the uCommand parameter and the corresponding formats of the dwData parameter.
uCommand | ActiondwData
HELP_COMMAND | Executes a Help macro or macro string. Address of a string that specifies the name of the Help macro(s) to run. If the string specifies multiple macro names, the names must be separated by semicolons. You must use the short form of the macro name for some macros because Windows 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 command 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_CONTEXTMENU | Displays the Help menu for the selected window, then displays the topic for the selected control in a pop-up window. Address of an array of double word pairs. The first double word in each pair is a control identifier, and the second is a context number for a topic.
HELP_CONTEXTPOPUP | Displays the topic identified by the specified context identifier defined in the [MAP] section of the .hpj file in a pop-up window. Unsigned long integer containing the context identifier for a topic.
HELP_FINDER | Displays the Help Topics dialog box. Ignored; set to 0.
HELP_FORCEFILE | Ensures that Windows Help is displaying the correct Help file. If the incorrect Help file is being displayed, Windows Help 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 WINHLP32.HLP file is available. Ignored, set to 0.
HELP_INDEX | Displays the topic specified by the Contents option in the [OPTIONS] section of the .hpj file. 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. Multiple keywords must be separated by semicolons.
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 Topics Found dialog box. To display the Index without passing a keyword, you should use a pointer to an empty string. Address of a keyword string. Multiple keywords must be separated by semicolons.
HELP_QUIT | Informs Windows Help that it is no longer needed. If no other applications have asked for Help, Windows closes Windows Help. Ignored, set to 0.
HELP_SETCONTENTS | Specifies the Contents topic. Windows Help displays this topic when the user clicks the Contents button if the Help file does not have an associated .cnt file. Unsigned long integer containing the context identifier for the Contents topic.
HELP_SETPOPUP_POS | Sets the position of the subsequent pop-up window. Address of a POINTS structure. The pop-up window is positioned as if the mouse cursor were at the specified point when the pop-up window is invoked.
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.
HELP_TCARD | Indicates that a command is for a training card instance of Windows Help. Combine this command with other commands using the bitwise OR operator. Depends on the command with which this command is combined.
HELP_WM_HELP | Displays the topic for the control identified by the hWndMain parameter in a pop-up window. | Address of an array of double word pairs. The first double word in each pair is a control identifier, and the second is a context identifier for a topic.

See Also

HELPWININFO, MULTIKEYHELP


Callback Functions

This section describes the Microsoft® Windows® shell callback functions.
BrowseCallbackProc
FMExtensionProc
UndeleteFile


BrowseCallbackProc

int CALLBACK BrowseCallbackProc(
    HWND hwnd,
    UINT uMsg,
    LPARAM lParam,
    LPARAM lpData
    );

Specifies an application-defined callback function used with the SHBrowseForFolder function. The browse dialog box calls this function to notify it about events.

  • Returns zero.
hwnd
Window handle to the browse dialog box. The callback function can send the following messages to this window:
BFFM_ENABLEOK | Enables or disables the dialog's OK button. If the message's lParam is nonzero, the button is enabled. If the message's lParam is zero, the button is disabled.
BFFM_SETSELECTION | Selects the specified folder. The message's lParam is the PIDL of the folder to select if wParam is FALSE, or the path of the folder otherwise.
BFFM_SETSTATUSTEXT | Sets the status text to the null-terminated string specified by the message's lParam parameter.
uMsg
Value identifying the event. This can be one of the following values:
BFFM_INITIALIZED | Indicates the browse dialog box has finished initializing. The lParam parameter is NULL.
BFFM_SELCHANGED | Indicates the selection has changed. The lParam parameter contains the address of the item identifier list for the newly selected folder.
BFFM_VALIDATEFAILED | Version 4.71. Indicates the user typed an invalid name into the edit box of the browse dialog. The lParam parameter is the address of a character buffer that contains the invalid name. An application can use this message to inform the user that the name entered was not valid. Return zero to allow the dialog to be dismissed or nonzero to keep the dialog displayed.
lParam
Value dependent upon the message contained in the uMsg parameter.
lpData
Application-defined value that was specified in the lParam member of the BROWSEINFO structure.


FMExtensionProc

LONG WINAPI FMExtensionProc(
    HWND hwnd,
    WORD wMsg,
    LONG lParam
);

Application-defined callback function called by File Manager to communicate with a File Manager extension.

  • Returns a value dependent upon the wMsg parameter message.
hwnd
Window handle to File Manager. An extension should use this 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.
wMsg
One of the following File Manager messages:
1 through 99 | User selected an item from the extension-supplied menu. The value is the identifier of the selected menu item.
FMEVENT_HELPMENUITEM | User 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_HELPSTRING | User selected an extension menu or toolbar command item. File Manager wants the extension to supply a Help string.
FMEVENT_INITMENU | User 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 selected the Refresh command from the Window menu. The extension should update items in the menu, if necessary.
lParam
Message-specific value.


UndeleteFile

DWORD APIENTRY UndeleteFile(
    HWND hwndOwner,
    LPSTR lpszDir
);

Application-defined callback function called by File Manager when the user chooses the Undelete command from the File menu.

  • Returns one of the following values:
    -1 | An error occurred.
    IDOK | A file was undeleted. File Manager repaints its window.
    IDCANCEL | No file was undeleted.
hwndOwner
Window handle to File Manager. An undelete dynamic-link library (DLL) should use this handle to specify the owner window for any dialog box or message box the DLL might display.
lpszDir
Address of a null-terminated string that contains the name of the initial directory.


Macros

This section describes the Microsoft® Windows® shell utility macros.
SOANGLETENTHS
SOPALETTEINDEX
SOPALETTERGB
SORGB
SOSETRATIO


SOANGLETENTHS

Sets the angle in tenths of a degree.

Syntax

SOANGLETENTHS(AngleInTenthsOfADegree)

Parameters

AngleInTenthsOfADegree
New angle, in tenths of a degree.


SOPALETTEINDEX

Creates a palette-index color value.

Syntax

SOPALETTEINDEX(Index)

Parameters

Index
Valid palette entry index. When this color value is used, the system uses the color from the given palette entry.


SOPALETTERGB

Creates a palette-relative RGB color value. When this color value is specified, the system uses the palette entry that has the color that most closely matches this value.

Syntax

SOPALETTERGB(Red, Green, Blue)

Parameters

Red
Red color intensity in the range 0 to 255.
Green
Green color intensity in the range 0 to 255.
Blue
Blue color intensity in the range 0 to 255.


SORGB

Creates an RGB color value.

Syntax

SORGB(Red, Green, Blue)

Parameters

Red
Red color intensity in the range 0 to 255.
Green
Green color intensity in the range 0 to 255.
Blue
Blue color intensity in the range 0 to 255.


SOSETRATIO

Sets the ratio.

Syntax

SOSETRATIO(Numerator, Denominator)

Parameters

Numerator
Numerator of the ratio factor. This value must be in the range 0 to 65,535.
Denominator
Denominator of the ratio factor. This value must be in the range 0 to 65,535.


Messages

This section describes the Microsoft® Windows® shell messages.

ABM_ACTIVATE
ABM_GETAUTOHIDEBAR
ABM_GETSTATE
ABM_GETTASKBARPOS
ABM_NEW
ABM_QUERYPOS
ABM_REMOVE
ABM_SETAUTOHIDEBAR
ABM_SETPOS
ABM_WINDOWPOSCHANGED
ABN_FULLSCREENAPP
ABN_POSCHANGED
ABN_STATECHANGE
ABN_WINDOWARRANGE
CPL_DBLCLK
CPL_EXIT
CPL_GETCOUNT
CPL_INIT
CPL_INQUIRE
CPL_NEWINQUIRE
CPL_SELECT
CPL_STOP
FM_GETDRIVEINFO
FM_GETFILESEL
FM_GETFILESELLFN
FM_GETFOCUS
FM_GETSELCOUNT
FM_GETSELCOUNTLFN
FM_REFRESH_WINDOWS
FM_RELOAD_EXTENSIONS
FMEVENT_HELPMENUITEM
FMEVENT_HELPSTRING
FMEVENT_INITMENU
FMEVENT_LOAD
FMEVENT_SELCHANGE
FMEVENT_TOOLBARLOAD
FMEVENT_UNLOAD
FMEVENT_USER_REFRESH
NIM_ADD
NIM_DELETE
NIM_MODIFY
WM_CPL_LAUNCH
WM_CPL_LAUNCHED
WM_DROPFILES
WM_HELP
WM_TCARD


ABM_ACTIVATE

Notifies the system that an appbar has been activated. An appbar should call this message in response to the WM_ACTIVATE message.

Syntax

SHAppBarMessage(ABM_ACTIVATE, pabd);

Parameters

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.

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


ABM_GETAUTOHIDEBAR

Retrieves the handle to the autohide appbar associated with an edge of the screen.

Syntax

hwndAutoHide = (HWND) SHAppBarMessage(ABM_GETAUTOHIDEBAR, pabd);

Parameters

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.

Return Values

Returns the handle to the autohide appbar. The return value is NULL if an error occurs or if no autohide appbar is associated with the given edge.


ABM_GETSTATE

Retrieves the autohide and always-on-top states of the Windows taskbar.

Syntax

fuState = (UINT) SHAppBarMessage(ABM_GETSTATE, pabd);

Parameters

pabd
Address of an APPBARDATA structure. You must specify the cbSize and hWnd members when sending this message; all other members are ignored.

Return Values

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:
ABS_ALWAYSONTOP | The taskbar is in the always-on-top state.
ABS_AUTOHIDE | The taskbar is in the autohide state.


ABM_GETTASKBARPOS

Retrieves the bounding rectangle of the Windows taskbar.

Syntax

fResult = (BOOL) SHAppBarMessage(ABM_GETTASKBARPOS, pabd);

Parameters

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 when sending this message; all other members are ignored.

Return Values

Returns TRUE if successful, or FALSE otherwise.


ABM_NEW

Registers a new appbar and specifies the message identifier that the system should use to send it notification messages. An appbar should send this message before sending any other appbar messages.

Syntax

fRegistered = (BOOL) SHAppBarMessage(ABM_NEW, pabd);

Parameters

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.

Return Values

Returns TRUE if successful, or FALSE if an error occurs or if the appbar is already registered.


ABM_QUERYPOS

Requests a size and screen position for an appbar. When the request is made, 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.

Syntax

SHAppBarMessage(ABM_QUERYPOS, pabd);

Parameters

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.

Return Values

Always returns TRUE.

Remarks

An appbar should send this message before sending the ABM_SETPOS message.


ABM_REMOVE

Unregisters an appbar by removing it from the system's internal list. The system no longer sends notification messages to the appbar or prevents other applications from using the screen area occupied by the appbar.

Syntax

SHAppBarMessage(ABM_REMOVE, pabd);

Parameters

pabd
Address of an APPBARDATA structure that contains the handle to the appbar to unregister. You must specify the cbSize and hWnd members when sending this message; all other members are ignored.

Return Values

Always returns TRUE.

Remarks

This message causes the system to send the ABN_POSCHANGED notification message to all appbars.


ABM_SETAUTOHIDEBAR

Registers or unregisters an autohide appbar for an edge of the screen.

Syntax

fSuccess = (BOOL) SHAppBarMessage(ABM_SETAUTOHIDEBAR, pabd);

Parameters

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.

Return Values

Returns TRUE if successful, or FALSE if an error occurs or if an autohide appbar is already registered for the given edge.

Remarks

The system allows only one autohide appbar for each edge of the screen. This is determined when the member uEdge of theAPPBARDATA structure is set.


ABM_SETPOS

Sets the size and screen position of an appbar. The message specifies a screen edge 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.

Syntax

SHAppBarMessage(ABM_SETPOS, pabd);

Parameters

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.

Return Values

Always returns TRUE.

Remarks

This message causes the system to send the ABN_POSCHANGED notification message to all appbars.


ABM_WINDOWPOSCHANGED

Notifies the system when an appbar's position has changed. An appbar should call this message in response to the WM_WINDOWPOSCHANGED message.

Syntax

SHAppBarMessage(ABM_WINDOWPOSCHANGED, pabd);

Parameters

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.

Return Values

Always returns TRUE.

Remarks

This message is ignored if the hWnd member of the structure pointed to by pabd identifies an autohide appbar.


ABN_FULLSCREENAPP

Notifies an appbar when a full-screen application is opening or closing. This notification is sent in the form of an application-defined message that is set by the ABM_NEW message.

Syntax

ABN_FULLSCREENAPP
    fOpen = (BOOL) lParam;

Parameters

fOpen
Flag specifying whether a full-screen application is opening or closing. This parameter is TRUE if the application is opening or FALSE if it is closing.

Return Values

No return value.

Remarks

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.


ABN_POSCHANGED

Notifies an appbar when an event has occurred that may affect 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.

Syntax

ABN_POSCHANGED

Return Values

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.


ABN_STATECHANGE

Notifies an appbar that the taskbar's autohide or always-on-top state has changed—that is, the user has selected or cleared the "Always on top" or "Auto hide" check box on the taskbar's property sheet.

Syntax

ABN_STATECHANGE

Return Value

No return value.

Remarks

An appbar can use this notification message to set its state to conform to that of the taskbar, if desired.


ABN_WINDOWARRANGE

Notifies an appbar that the user has selected the Cascade, Tile Horizontally, or Tile Vertically command from the taskbar's context menu.

Syntax

ABN_WINDOWARRANGE
    fBeginning = (BOOL) lParam;

Parameters

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.


CPL_DBLCLK

Sent to the CPlApplet function of a Control Panel application when the user double-clicks the icon of a dialog box supported by the application.

Syntax

CPL_DBLCLK
    uAppNum = (UINT) lParam1;
    lData = (LONG) lParam2;

Parameters

uAppNum
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 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 Values

If the CPlApplet function 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_SELECT


CPL_EXIT

Sent once to the CPlApplet function of a Control Panel application before the DLL containing the Control Panel application is released.

Syntax

CPL_EXIT

Return Values

If the CPlApplet function 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

See also FreeLibrary


CPL_GETCOUNT

Sent to the CPlApplet function of a Control Panel application to retrieve the number of dialog boxes supported by the application.

Syntax

CPL_GETCOUNT

Return Values

The CPlApplet function returns the number of dialog boxes that the Control Panel application supports.

Remarks

This message is sent immediately after the CPL_INIT message.


CPL_INIT

Sent to the CPlApplet function of a Control Panel application to prompt it to perform global initialization, especially memory allocation.

Syntax

CPL_INIT

Return Values

If initialization succeeds, the CPlApplet function should return nonzero. Otherwise, it should return zero.

If CPlApplet 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

Sent to the CPlApplet function of a Control Panel application to request information about a dialog box that the application supports.

Syntax

CPL_INQUIRE
    uAppNum = (UINT) lParam1;
    lpcpli = (LPCPLINFO) lParam2;

Parameters

uAppNum
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
Address of 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 the CPlApplet function processes this message successfully, it should return zero.

Remarks

The Control Panel sends the CPL_INQUIRE message once for each dialog box supported by your application. The Control Panel also sends a CPL_NEWINQUIRE message for each dialog box. These messages are sent immediately after the CPL_GETCOUNT message. However, the system does not guarantee the order in which the CPL_INQUIRE and CPL_NEWINQUIRE messages are sent.

You can perform initialization for the dialog box when you receive CPL_INQUIRE. If you must allocate memory, do so in response to the CPL_INIT message.

On Windows 95 and Windows NT version 4.0, the system caches the information returned in the CPLINFO structure used by CPL_INQUIRE. This provides significantly better performance because the system only needs to load your application the first time the Control Panel starts up. On the other hand, the CPL_NEWINQUIRE message returns information in a form that the system cannot cache. For this reason, most CPlApplet functions should process CPL_INQUIRE and ignore CPL_NEWINQUIRE.

The only applications that should use CPL_NEWINQUIRE are those that need to change their icon or display strings based on the state of the computer. In this case, your CPL_INQUIRE handler should specify the CPL_DYNAMIC_RES value for the idIcon, idName, or idInfo members of the CPLINFO structure, rather than specifying a valid resource identifier. This causes the Control Panel to send the CPL_NEWINQUIRE message each time it needs the icon and display strings, allowing you to specify information based on the current state of the computer. Of course, this is significantly slower than using cached information.


CPL_NEWINQUIRE

Sent to the CPlApplet function of a Control Panel application to request information about a dialog box that the application supports.

For better performance, most applications should ignore CPL_NEWINQUIRE and process the CPL_INQUIRE message instead.

Syntax

CPL_NEWINQUIRE
    uAppNum = (UINT) lParam1;
    lpncpli = (LPNEWCPLINFO) lParam2;

Parameters

uAppNum
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
Address of a NEWCPLINFO structure. The Control Panel application should fill this structure with information about the dialog box.

Return Values

If the CPlApplet function processes this message successfully, it should return zero.

Remarks

The Control Panel sends the CPL_NEWINQUIRE message once for each dialog box supported by your application. The Control Panel also sends a CPL_INQUIRE message for each dialog box. These messages are sent immediately after the CPL_GETCOUNT message. However, the system does not guarantee the order in which the CPL_INQUIRE and CPL_NEWINQUIRE messages are sent.

You can perform initialization for the dialog box when you receive CPL_INQUIRE. If you must allocate memory, do so in response to the CPL_INIT message.

The CPL_NEWINQUIRE message was introduced in Windows version 3.1 as a replacement for CPL_INQUIRE. However, CPL_INQUIRE is the preferred message for Windows 95 and Windows NT version 4.0. This is because CPL_NEWINQUIRE returns information in a form that the system cannot cache. Consequently, applications that process CPL_NEWINQUIRE must be loaded each time the Control Panel needs the information, resulting in a significant reduction in performance.

The only applications that should use CPL_NEWINQUIRE are those that need to change their icon or display strings based on the state of the computer. In this case, your CPL_INQUIRE handler should specify the CPL_DYNAMIC_RES value for the idIcon, idName, or idInfo members of the CPLINFO structure, rather than specifying a valid resource identifier. This causes the Control Panel to send the CPL_NEWINQUIRE message each time it needs the icon and display strings, allowing you to specify information based on the current state of the computer. Of course, this is significantly slower than using cached information.


CPL_SELECT

Obsolete. This message was used by versions of Windows earlier than Windows 95 and Windows NT version 4.0.


CPL_STOP

Sent to the CPlApplet function of a Control Panel application when the controlling application of the Control Panel closes. The controlling application sends the message once for each dialog box that the application supports.

Syntax

CPL_STOP
    uAppNum = (UINT) lParam1;
    lData = (LONG) lParam2;

Parameters

uAppNum
Dialog box number.
lData
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 Values

If the CPlApplet function 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


FM_GETDRIVEINFO

Sent by a File Manager extension to retrieve drive information from the active File Manager window.

Syntax

FM_GETDRIVEINFO
    wParam = 0;
    lParam = (LPARAM) (LPFMS_GETDRIVEINFO) lpfmsgdi;

Parameters

lpfmsgdi
Address of an FMS_GETDRIVEINFO structure that receives drive information.

Return Values

Returns 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


FM_GETFILESEL

Sent by a File Manager extension to retrieve information about a selected file from the active File Manager window (either the directory window or the Search Results window).

Syntax

FM_GETFILESEL
    wParam = (WPARAM) index;
    lParam = (LPARAM) (LPFMS_GETFILESEL) lpfmsgfs;

Parameters

index
Zero-based index of the selected file to retrieve.
lpfmsgfs
Address of an FMS_GETFILESEL structure that receives information about the selection.

Return Value

Returns 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, FM_GETFILESELLFN, FM_GETSELCOUNTLFN


FM_GETFILESELLFN

Sent by a File Manager extension 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 file name.

Syntax

FM_GETFILESELLFN
    wParam = (WPARAM) index;
    lParam = (LPARAM) (LPFMS_GETFILESEL) lpfmsgfs;

Parameters

index
Zero-based index of the selected file to retrieve.
lpfmsgfs
Address of an FMS_GETFILESEL structure that receives information about the selection.

Return Values

Returns the zero-based index of the selected file that was retrieved.

Remarks

Only extensions that support long file names (for example, network-aware extensions) should use this message.

An extension can use the FM_GETSELCOUNTLFN message to get the count of selected files.

See Also

FMExtensionProc, FM_GETFILESEL, FM_GETSELCOUNT


FM_GETFOCUS

Sent by a File Manager extension to retrieve the type of File Manager window that has the input focus.

Syntax

FM_GETFOCUS
    wParam = 0;
    lParam = 0;

Return Values

Returns the type of File Manager window that has the input focus. It can be one of the following values:
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

Sent by a File Manager extension to retrieve a count of the selected files in the active File Manager window (either the directory window or the Search Results window).

Syntax

FM_GETSELCOUNT
    wParam = 0;
    lParam = 0;

Return Values

Returns the number of selected files.

See Also

FM_GETFILESEL, FM_GETFILESELLFN, FM_GETSELCOUNTLFN


FM_GETSELCOUNTLFN

Sent by a File Manager extension 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 file names.

Syntax

FM_GETSELCOUNTLFN
    wParam = 0;
    lParam = 0;

Return Values

Returns the number of selected files.

Remarks

Only extensions that support long file names (for example, network-aware extensions) should use this message.

See Also

FM_GETFILESEL, FM_GETFILESELLFN, FM_GETSELCOUNT


FM_REFRESH_WINDOWS

Sent by a File Manager extension to cause File Manager to repaint either its active window or all of its windows.

Syntax

FM_REFRESH_WINDOWS
    wParam = (WPARAM) (BOOL) fRepaint;
    lParam = 0;

Parameters

fRepaint
Value that indicates 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 Values

  • No return 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

Sent by a File Manager extension (or another application) to cause File Manager to reload all extension DLLs listed in the [AddOns] section of the Winfile.ini file.

Syntax

FM_RELOAD_EXTENSIONS
    wParam = 0;
    lParam = 0;

Return Values

No return 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

FMExtensionProc


FMEVENT_HELPMENUITEM

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's hwnd parameter.

Syntax

FMEVENT_HELPMENUITEM
    uItem = (UINT) lParam;

Parameters

uItem
Value that 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 Values

An extension DLL procedure should return zero if it processes this message.

See Also

FMExtensionProc, FMEVENT_HELPSTRING


FMEVENT_HELPSTRING

Sent to a File Manager extension DLL procedure when File Manager wants a Help string for a menu or toolbar command item.

Syntax

FMEVENT_HELPSTRING
    lpfmshs = (LPFMS_HELPSTRING) lParam;

Parameters

lpfmshs
Address of 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 Values

An extension DLL procedure should return zero if it processes this message.

See Also

FMExtensionProc, FMEVENT_HELPMENUITEM


FMEVENT_INITMENU

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.

Syntax

FMEVENT_INITMENU
    hmenu = (HMENU) lParam;

Parameters

hmenu
Handle to 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

Sent to an extension DLL when File Manager is loading the DLL.

Syntax

FMEVENT_LOAD
    lpfmsld = (LPFMS_LOAD) lParam;

Parameters

lpfmsld
Address of an FMS_LOAD structure that specifies the menu item delta value.

Return Values

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


FMEVENT_SELCHANGE

Sent to an extension DLL when the user selects a file name in the File Manager directory window or Search Results window.

Syntax

FMEVENT_SELCHANGE

Return Values

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

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.

Syntax

FMEVENT_TOOLBARLOAD
    lpfmstbl = (LPFMS_TOOLBARLOAD) lParam;

Parameters

lpfmstbl
Address of 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 Values

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


FMEVENT_UNLOAD

Sent to an extension DLL when File Manager is unloading the DLL.

Syntax

FMEVENT_UNLOAD

Return Values

  • 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

Sent to an extension DLL when the user chooses the Refresh command from the View menu in File Manager. The extension can use this notification to update its menu.

Syntax

FMEVENT_USER_REFRESH

Return Values

An extension DLL should return zero if it processes this message.

See Also

FMExtensionProc


NIM_ADD

Adds an icon to the taskbar status area.

Syntax

fAdded = Shell_NotifyIcon(NIM_ADD, pnid);

Parameters

pnid
Address of a NOTIFYICONDATA structure that contains information about the icon to add.

Return Values

Returns TRUE if successful, or FALSE otherwise.


NIM_DELETE

Deletes an icon from the taskbar status area.

Syntax

fDeleted = Shell_NotifyIcon(NIM_DELETE, pnid);

Parameters

pnid
Address of a NOTIFYICONDATA structure that contains information about the icon to delete.

Return Values

Returns TRUE if successful, or FALSE otherwise.


NIM_MODIFY

Changes the icon, tooltip text, or notification message identifier for an icon in the taskbar status area.

Syntax

fModified = Shell_NotifyIcon(NIM_MODIFY, pnid);

Parameters

pnid
Address of a NOTIFYICONDATA structure that contains the information used to change the icon, tooltip text, or notification message identifier for the icon.

Return Values

Returns TRUE if successful, or FALSE otherwise.


WM_CPL_LAUNCH

Sent by an application to the Windows Control Panel to request that a Control Panel application be started.

Syntax

WM_CPL_LAUNCH
    hwnd = (HWND) wParam;
    lpszAppName = (LPSTR) lParam;

Parameters

hwnd
Handle to the window that is sending the request. The WM_CPL_LAUNCHED message is returned to this window.
lpszAppName
Address of a string containing the name of the Control Panel application to open.

Return Values

Returns TRUE if successful, or FALSE otherwise.


WM_CPL_LAUNCHED

Sent when a Control Panel application that was 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.

Syntax

WM_CPL_LAUNCHED
    fAppStarted = (BOOL) wParam;

Parameters

fAppStarted
Value that indicates whether the application was started. If the application was started, this parameter is TRUE; otherwise, it is FALSE.

Return Values

The return value is ignored.


WM_DROPFILES

Sent when the user drops a file on the window of an application that has registered itself as a recipient of dropped files.

Syntax

WM_DROPFILES
    hDrop = (HANDLE) wParam;

Return Values

An application should return zero if it processes this message.

Parameters

hDrop
Handle to 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.

See Also

DragAcceptFiles


WM_HELP

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.

Syntax

WM_HELP
    lphi = (LPHELPINFO) lParam;

Parameters

lphi
Address of a HELPINFO structure that contains information about the menu item, control, dialog box, or window for which Help is requested.

Return Values

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.


WM_TCARD

WM_TCARD
    idAction = wParam;
    dwActionData = lParam;

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.

  • The return value is ignored; use zero.
idAction
Value that indicates the action the user has taken. This can be one of these values:
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
If idAction specifies HELP_TCARD_DATA, this parameter is a long integer specified by the Help author. Otherwise, this parameter is zero.


Structures and Enumerations

This section describes the Microsoft® Windows® shell structures and enumerations.

Structures
APPBARDATA
BROWSEINFO
CIDA
CMINVOKECOMMANDINFO
CPLINFO
DESKBANDINFO
DROPFILES
EXT_BUTTON
FILEDESCRIPTOR
FILEGROUPDESCRIPTOR
FMS_GETDRIVEINFO
FMS_GETFILESEL
FMS_LOAD
FMS_TOOLBARLOAD
FOLDERSETTINGS
FVSHOWINFO
HELPINFO
HELPWININFO
ITEMIDLIST
MULTIKEYHELP
NEWCPLINFO
NOTIFYICONDATA
NRESARRAY
SHDESCRIPTIONID
SHELLEXECUTEINFO
SHELLFLAGSTATE
SHFILEINFO
SHFILEOPSTRUCT
SHITEMID
SHNAMEMAPPING
SHQUERYRBINFO
SOARCINFO
SOBITMAPHEADER
SOBORDER
SOCOLUMN
SOCPARCANGLE
SOCPPIEANGLE
SOCPTEXTATPOINT
SODATACELL
SOEMBEDDEDGRAPHIC
SOEMBEDDEDOBJECT
SOEMBEDINFO
SOFIELD
SOFILTERINFO
SOGROUPINFO
SOLOGBRUSH
SOLOGFONT
SOLOGPEN
SOPARAINDENTS
SOPATHINFO
SOPOINT
SOPOLYINFO
SORECT
SOTAB
SOTABLECELLINFO
SOTEXTATARCANGLE
SOTEXTATPOINT
SOTEXTCELL
SOTEXTINRECT
SOTRANSFORM
SOVECTORHEADER
STRRET
SV2CVW2_PARAMS (No documentation available at this time.)
Enumerations
FOLDERFLAGS
FOLDERVIEWMODE
SHCONTF
SHGNO


APPBARDATA

typedef struct _AppBarData {
    DWORD  cbSize;
    HWND   hWnd;
    UINT   uCallbackMessage;
    UINT   uEdge;
    RECT   rc;
    LPARAM lParam;
} APPBARDATA, *PAPPBARDATA;

Contains information about a system appbar message. This structure is used with the SHAppBarMessage function.

cbSize
Contains the size of the structure, in bytes.
hWnd
Contains the handle to the appbar window.
uCallbackMessage
Application-defined message identifier. The application uses the specified identifier for notification messages that it sends to the appbar identified by the hWnd member. This member is used when sending the ABM_NEW message.
uEdge
Value 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 to contain 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.


BROWSEINFO

typedef struct _browseinfo {
    HWND hwndOwner;
    LPCITEMIDLIST pidlRoot;
    LPSTR pszDisplayName;
    LPCSTR lpszTitle;
    UINT ulFlags;
    BFFCALLBACK lpfn;
    LPARAM lParam;
    int iImage;
} BROWSEINFO, *PBROWSEINFO, *LPBROWSEINFO;

Contains parameters for the SHBrowseForFolder function and receives information about the folder selected by the user.

hwndOwner
Handle to the owner window for the dialog box.
pidlRoot
Address of an ITEMIDLIST structure specifying the location of the root folder from which to browse. Only the specified folder and its subfolders appear in the dialog box. This member can be NULL; in that case, the namespace root (the desktop folder) is used.
pszDisplayName
Address of a buffer to receive 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
Flags specifying the options for the dialog box. This member can include zero or a combination of the following values:
BIF_BROWSEFORCOMPUTER | Only return computers. If the user selects anything other than a computer, the OK button is grayed.
BIF_BROWSEFORPRINTER | Only return printers. If the user selects anything other than a printer, the OK button is grayed.
BIF_BROWSEINCLUDEFILES | The browse dialog will display files as well as folders.
BIF_DONTGOBELOWDOMAIN | Do not include network folders below the domain level in the tree view control.
BIF_EDITBOX | Version 4.71. The browse dialog includes an edit control in which the user can type the name of an item.
BIF_RETURNFSANCESTORS | Only return file system ancestors. If the user selects anything other than a file system ancestor, the OK button is grayed.
BIF_RETURNONLYFSDIRS | Only return file system directories. If the user selects folders that are not part of the file system, the OK button is grayed.
BIF_STATUSTEXT | Include a status area in the dialog box. The callback function can set the status text by sending messages to the dialog box.
BIF_VALIDATE | Version 4.71. If the user types an invalid name into the edit box, the browse dialog will call the application's BrowseCallbackProc with the BFFM_VALIDATEFAILED message. This flag is ignored if BIF_EDITBOX is not specified.
lpfn
Address of an application-defined function that the dialog box calls when an event occurs. For more information, see 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 to receive the image associated with the selected folder. The image is specified as an index to the system image list.


CIDA

typedef struct _IDA {
    UINT cidl;
    UINT aoffset[1];
} CIDA, * LPIDA;

Contains one variable-sized element of an ITEMIDLIST. This structure is used with the "Shell IDList Array" clipboard format.

cidl
Number of array elements.
aoffset
Array of offsets relative to the beginning of this structure. The first element is the offset of the ITEMIDLIST structure for a folder (absolute from the root). If the ITEMIDLIST for the folder is empty (Mkid.cb is 0), the parent folder is the desktop itself. Subsequent elements are offsets of ITEMIDLIST structures for file objects (relative from the parent folder).


CMINVOKECOMMANDINFO

typedef struct _CMInvokeCommandInfo{
    DWORD cbSize;
    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.

cbSize
Contains the size of this structure, in bytes.
fMask
Zero, or one or more of the following flags:
CMIC_MASK_HOTKEY | The dwHotKey member is valid.
CMIC_MASK_ICON | The hIcon member is valid.
CMIC_MASK_FLAG_NO_UI | The system is prevented from displaying user interface elements (for example, error messages) while carrying out a command.
hwnd
Handle to the window that is the owner of the context menu. An extension can also use this handle as the owner of any message boxes or dialog boxes it displays.
lpVerb
A 32-bit value that contains zero in the high-order word and a 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_VIEWDETAILS | "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
Set of SW_ values to pass to the ShowWindow function if the command displays a window or starts an application.
dwHotKey
Optional hot key to assign to any application activated by the command. If the fMask parameter 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.

The address of this structure is passed to the IContextMenu::InvokeCommand method.


CPLINFO

typedef struct tagCPLINFO {
    int  idIcon;
    int  idName;
    int  idInfo;
    LONG lData;
} CPLINFO;

Contains resource information and an application-defined value for a dialog box supported by a Control Panel application. The CPlApplet function of the Control Panel application returns this information to the Control Panel in response to a CPL_INQUIRE message.

idIcon
Resource identifier of the icon that represents the dialog box.
idName
Resource identifier of the string containing the short name for the dialog box. This name is intended to be displayed below the icon.
idInfo
Resource identifier of the string containing the description for the dialog box that is intended to be displayed when the application icon is selected.
lData
Data defined by the application. When the Control Panel sends the CPL_DBLCLK and CPL_STOP messages, it passes this value back to your application.

If the icon or display strings of the dialog box can change based on the state of the computer, you can specify the CPL_DYNAMIC_RES value for the idIcon, idName, or idInfo members rather than specifying a valid resource identifier. This causes the Control Panel to send the CPL_NEWINQUIRE message each time it needs the icon and display strings. Using this technique is significantly slower, however, because the Control Panel will need to load your application each time it sends the CPL_NEWINQUIRE message.


DESKBANDINFO

typedef struct {
    DWORD       dwMask;
    POINTL      ptMinSize;
    POINTL      ptMaxSize;
    POINTL      ptIntegral;
    POINTL      ptActual;
    WCHAR       wszTitle[256];
    DWORD       dwModeFlags;
    COLORREF    crBkgnd;
} DESKBANDINFO;

Contains and receives information for a band object. This structure is used with the IDeskBand::GetBandInfo method.

dwMask
Set of flags that determine which members of this structure are being requested. This will be a combination of the following values:
DBIM_MINSIZE | ptMinSize is being requested.
DBIM_MAXSIZE | ptMaxSize is being requested.
DBIM_INTEGRAL | ptIntegral is being requested.
DBIM_ACTUAL | ptActual is being requested.
DBIM_TITLE | wszTitle is being requested.
DBIM_MODEFLAGS | dwModeFlags is being requested.
DBIM_BKCOLOR | crBkgnd is being requested.
ptMinSize
POINTL structure that receives the minimum size of the band object. The minimum width is placed in the x member and the minimum height is placed in the y member.
ptMaxSize
POINTL structure that receives the maximum size of the band object. The maximum width is placed in the x member and the maximum height is placed in the y member. If there is no limit for one or both of the maximum sizes, (LONG)-1 should be used.
ptIntegral
POINTL structure that receives the sizing step value of the band object. The horizontal step value is placed in the x member and the vertical step value is placed in the y member. The step value determines in what increments the band will be resized. This member is ignored if dwModeFlags does not contain DBIMF_VARIABLEHEIGHT.
ptActual
POINTL structure that receives the ideal size of the band object. The ideal width is placed in the x member and the ideal height is placed in the y member. The band container will attempt to use these values, but the band is not guaranteed to be this size.
wszTitle
WCHAR buffer that receives the title of the band.
dwModeFlags
Receives a set of flags that define the mode of operation for the band object. This must be one or a combination of the following values:
DBIMF_NORMAL | The band is normal in all respects. The other mode flags modify this flag.
DBIMF_VARIABLEHEIGHT | The height of the band object can be changed. The ptIntegral member defines the step value by which the band object can be resized.
DBIMF_DEBOSSED | The band object is displayed with a sunken appearance.
DBIMF_BKCOLOR | The band will be displayed with the background color specified in crBkgnd.
crBkgnd
Receives the background color of the band. This member is ignored if dwModeFlags does not contain the DBIMF_BKCOLOR flag.

Version 4.71


DROPFILES

typedef struct _DROPFILES {
    DWORD pFiles;
    POINT pt;
    BOOL fNC;
    BOOL fWide;
} 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.

pFiles
Offset of the file list from the beginning of this structure, in bytes.
pt
Drop point. The coordinates depend on fNC.
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.
fWide
Value that indicates if the file contains wide characters. This value is nonzero if it does contain wide characters, or zero otherwise.


EXT_BUTTON

Contains information about a button that a File Manager extension dynamic-link library is adding to the toolbar of File Manager.

Syntax

typedef struct _EXT_BUTTON {
    WORD idCommand;
    WORD idsHelp;
    WORD fsStyle;
} EXT_BUTTON;

Members

idCommand
Command identifier for the button.
idsHelp
Identifier of the Help string for the button.
fsStyle
Style of the button.

See Also

FMEVENT_TOOLBARLOAD, FMS_TOOLBARLOAD


FILEDESCRIPTOR

Describes the properties of a file that is being copied by means of the clipboard during an OLE drag-and-drop operation.

Syntax

typedef struct _FILEDESCRIPTOR {
    DWORD    dwFlags;
    CLSID    clsid;
    SIZEL    sizel;
    POINTL   pointl;
    DWORD    dwFileAttributes;
    FILETIME ftCreationTime;
    FILETIME ftLastAccessTime;
    FILETIME ftLastWriteTime;
    DWORD    nFileSizeHigh;
    DWORD    nFileSizeLow;
    TCHAR    cFileName[MAX_PATH];
} FILEDESCRIPTOR, *LPFILEDESCRIPTOR;

Members

dwFlags
Array of flags that indicate which of the other structure members contain valid data. This member can be a combination of the following 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.
clsid
File class identifier.
sizel
Width and height of the file icon.
pointl
Screen coordinates of the file object.
dwFileAttributes
File attribute flags. This will be a combination of the FILE_ATTRIBUTE_ values described in GetFileAttributes.
ftCreationTime
FILETIME structure that contains the time of file creation.
ftLastAccessTime
FILETIME structure that contains the time that the file was last accessed.
ftLastWriteTime
FILETIME structure that contains the time of the last write operation.
nFileSizeHigh
High-order DWORD of the file size, in bytes.
nFileSizeLow
Low-order DWORD of the file size, in bytes.
cFileName
Null-terminated string that contains the name of the file.


FILEGROUPDESCRIPTOR

Defines the CF_FILEGROUPDESCRIPTOR clipboard format.

Syntax

typedef struct _FILEGROUPDESCRIPTOR {
    UINT cItems;
    FILEDESCRIPTOR fgd[1];
} FILEGROUPDESCRIPTOR, * LPFILEGROUPDESCRIPTOR;

Members

cItems
Number of elements in fgd.
fgd
Array of FILEDESCRIPTOR structures that contain the file information.


FMS_GETDRIVEINFO

Contains information about the drive selected in the active File Manager window (the directory window or the Search Results window).

Syntax

typedef struct _FMS_GETDRIVEINFO {
    DWORD dwTotalSpace;
    DWORD dwFreeSpace;
    TCHAR  szPath[260];
    TCHAR  szVolume[14];
    TCHAR  szShare[128];
} FMS_GETDRIVEINFO;

Members

dwTotalSpace
Total amount of storage space, in bytes, on the disk associated with the drive.
dwFreeSpace
Amount of free storage space, in bytes, on the disk associated with the drive.
szPath
Null-terminated path of the current directory.
szVolume
Null-terminated volume label of the disk associated with the drive.
szShare
Null-terminated name of the network resource (if the drive is being accessed through a network).

See Also

FMExtensionProc, FM_GETDRIVEINFO


FMS_GETFILESEL

Contains information about a selected file in the active File Manager window (the directory window or the Search Results window).

Syntax

typedef struct _FMS_GETFILESEL {
    FILETIME ftTime;
    DWORD    dwSize;
    BYTE     bAttr;
    TCHAR     szName[260];
} FMS_GETFILESEL;

Members

ftTime
Time and date the file was created.
dwSize
Size, in bytes, of the file.
bAttr
Attributes of the file.
szName
Null-terminated full path and file name of the selected file.

See Also

FMExtensionProc


FMS_LOAD

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.

Syntax

typedef struct _FMS_LOAD {
    DWORD dwSize;
    TCHAR  szMenuName[MENU_TEXT_LEN];
    HMENU hMenu;
    UINT  wMenuDelta;
} FMS_LOAD;

Members

dwSize
Length, in bytes, of the structure.
szMenuName
Null-terminated name for a menu item that appears on the menu bar in File Manager.
hMenu
Identifer of the pop-up menu added to the menu bar in File Manager.
wMenuDelta
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

Contains information about custom buttons to be added to the File Manager toolbar. The buttons are provided by a File Manager extension DLL.

Syntax

typedef struct _FMS_TOOLBARLOAD {
    DWORD        dwSize;
    LPEXT_BUTTON lpButtons;
    WORD         cButtons;
    WORD         cBitmaps;
    WORD         idBitmap;
    HBITMAP      hBitmap;
} FMS_TOOLBARLOAD;

Members

dwSize
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
Address of an array of EXT_BUTTON structures.
cButtons
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
Number of buttons represented by the given bitmap.
idBitmap
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 and then uses it to display the buttons.
hBitmap
Handle to a bitmap that File Manager will use to obtain and display button images if idBitmap is 0.

See Also

FMEVENT_TOOLBARLOAD


FOLDERSETTINGS

Contains folder view information.

Syntax

typedef struct {
    UINT     ViewMode;
    UINT     fFlags;
}FOLDERSETTINGS; *LPFOLDERSETTINGS;

Members

ViewMode
Folder view mode. This can be one of the FOLDERVIEWMODE values.
fFlags
Set of flags that indicate the options for the folder. This can be zero or a combination of the FOLDERFLAGS values.

Remarks

These settings assume a particular user interface, which the shell's folder view has. A shell extension can use these settings if they apply to the view implemented by the extension.

See Also

IShellView::CreateViewWindow, IShellView::GetCurrentInfo


FVSHOWINFO

typedef struct {
    DWORD cbSize;
    HWND hwndOwner;
    int iShow;
    DWORD dwFlags;
    RECT rect;
    LPUNKNOWN punkRel;
    OLECHAR strNewFile[MAX_PATH];
} FVSHOWINFO, *LPFVSHOWINFO;

Contains information that the file viewer uses to display a file.

cbSize
Size of the structure, in bytes.
hwndOwner
Window handle to the owner of the window in which the file will be displayed.
iShow
Show command for the window. This parameter is one of the SW_ values detailed in ShowWindow.
dwFlags
Flags that determine what the file viewer displays. This member can be one or more of the following 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 continue to display the previous file or terminate.
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 the strNewFile member. 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 | The rect member contains valid data.
rect
RECT structure that specifies the size and position of the file viewer's window. This member is valid only if the dwFlags member includes the FVSIF_RECT value.
punkRel
Address of an interface that has its Release method 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.


HELPINFO

Contains information about an item for which context-sensitive Help has been requested.

Syntax

typedef  struct  tagHELPINFO {
    UINT     cbSize;
    int      iContextType
    int      iCtrlId;
    HANDLE   hItemHandle;
    DWORD    dwContextId;
    POINT    MousePos;
} HELPINFO, FAR *LPHELPINFO;

Members

cbSize
Structure size, in bytes.
iContextType
Type of context for which Help is requested. This member can be one of the following values:
HELPINFO_MENUITEM | Help requested for a menu item.
HELPINFO_WINDOW | Help requested for a control or window.
iCtrlId
Identifier of the window or control if iContextType is HELPINFO_WINDOW, or identifier of the menu item if iContextType is HELPINFO_MENUITEM.
hItemHandle
Identifier of the child window or control if iContextType is HELPINFO_WINDOW, or identifier of the associated menu if iContextType is HELPINFO_MENUITEM.
dwContextId
Help context identifier of the window or control.
MousePos
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.


HELPWININFO

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.

Syntax

typedef struct {
    int   wStructSize;
    int   x;
    int   y;
    int   dx;
    int   dy;
    int   wMax;
    TCHAR rgchMember[2];
} HELPWININFO;

Members

wStructSize
Structure size, in bytes.
x
X-coordinate of the upper-left corner of the window, in screen coordinates.
y
Y-coordinate of the upper-left corner of the window, in screen coordinates.
dx
Window width, in pixels.
dy
Window height, in pixels.
wMax
How to show the window. This member must be one of the following values:
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
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.


ITEMIDLIST

typedef struct _ITEMIDLIST {
    SHITEMID mkid;
} ITEMIDLIST, * LPITEMIDLIST;
typedef const ITEMIDLIST * LPCITEMIDLIST;

Contains a list of item identifiers.

mkid
List of item identifiers.


MULTIKEYHELP

Specifies a keyword to search for and the keyword table to be searched by Windows Help.

Syntax

typedef struct tagMULTIKEYHELP {
    DWORD  mkSize;
    TCHAR  mkKeylist;
    TCHAR  szKeyphrase[1];
} MULTIKEYHELP;

Members

mkSize
Structure size, in bytes.
mkKeylist
Single character that identifies the keyword table to search.
szKeyphrase
Null-terminated text string that specifies the keyword to locate in the keyword table.

See Also

WinHelp


NEWCPLINFO

Contains resource information and an application-defined value for a dialog box supported by a Control Panel application.

Syntax

typedef struct tagNEWCPLINFO {
    DWORD dwSize;
    DWORD dwFlags;
    DWORD dwHelpContext;
    LONG  lData;
    HICON hIcon;
    TCHAR  szName[32];
    TCHAR  szInfo[64];
    TCHAR  szHelpFile[128];
} NEWCPLINFO;

Members

dwSize
Length of the structure, in bytes.
dwFlags
This member is ignored.
dwHelpContext
This member is ignored.
lData
Data defined by the application. When the Control Panel sends the CPL_DBLCLK and CPL_STOP messages, it passes this value back to your application.
hIcon
Identifier of the icon that represents the dialog box. This icon is intended to be displayed by the application that controls the Control Panel application.
szName
Null-terminated string that contains the dialog box name. The name is intended to be displayed below the icon.
szInfo
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
This member is ignored.

Remarks

The CPlApplet function of the Control Panel application returns this information to the Control Panel in response to a CPL_NEWINQUIRE message.

See Also

CPLINFO


NOTIFYICONDATA

typedef struct _NOTIFYICONDATA {
    DWORD cbSize;
    HWND hWnd;
    UINT uID;
    UINT uFlags;
    UINT uCallbackMessage;
    HICON hIcon;
    char szTip[64];
} NOTIFYICONDATA, *PNOTIFYICONDATA;

Contains information that the system needs to process taskbar status area messages.

cbSize
Size of this structure, in bytes.
hWnd
Handle to the window that will receive notification messages associated with an icon in the taskbar status area.
uID
Application-defined identifier of the taskbar icon.
uFlags
Array of flags that indicate which of the other members contain valid data. This member can be a combination of the following:
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 this identifier for notification messages that it sends to the window identified in hWnd. These notifications are sent when a mouse event occurs in the bounding rectangle of the icon.
hIcon
Handle to the icon to add, modify, or delete.
szTip
Tooltip text to display for the icon.


NRESARRAY

Defines the CF_NETRESOURCE clipboard format.

Syntax

typedef struct _NRESARRAY {
    UINT        cItems;
    NETRESOURCE nr[1];
} NRESARRAY, * LPNRESARRAY;

Members

cItems
Number of elements in the nr array.
nr
Array of NETRESOURCE structures that contain information about network resources. The string members (LPSTR types) in the structure contain offsets instead of addresses.


SHDESCRIPTIONID

typedef struct SHDESCRIPTIONID{
    DWORD   dwDescriptionId;
    CLSID   clsid;
} SHDESCRIPTIONID, *LPSHDESCRIPTIONID;

Receives item data in response to a call to SHGetDataFromIDList.

dwDescriptionId
Receives a value that determines what type the item is. This can be one of the following values:
SHDID_ROOT_REGITEM | The item is a registered item on the desktop.
SHDID_FS_FILE | The item is a file.
SHDID_FS_DIRECTORY | The item is a folder.
SHDID_FS_OTHER | The item is an unidentified item in the file system.
SHDID_COMPUTER_DRIVE35 | The item is a 3.5-inch floppy drive.
SHDID_COMPUTER_DRIVE525 | The item is a 5.25-inch floppy drive.
SHDID_COMPUTER_REMOVABLE | The item is a removable disk drive.
SHDID_COMPUTER_FIXED | The item is a fixed disk drive.
SHDID_COMPUTER_NETDRIVE | The item is a drive that is mapped to a network share.
SHDID_COMPUTER_CDROM | The item is a CD-ROM drive.
SHDID_COMPUTER_RAMDISK | The item is a RAM disk.
SHDID_COMPUTER_OTHER | The item is an unidentified system device.
SHDID_NET_DOMAIN | The item is a network domain.
SHDID_NET_SERVER | The item is a network server.
SHDID_NET_SHARE | The item is a network share.
SHDID_NET_RESTOFNET | Not currently used.
SHDID_NET_OTHER | The item is an unidentified network resource.
clsid
Receives the CLSID of the object to which the item belongs.


SHELLEXECUTEINFO

typedef struct _SHELLEXECUTEINFO{
    DWORD cbSize;
    ULONG fMask;
    HWND hwnd;
    LPCTSTR lpVerb;
    LPCTSTR lpFile;
    LPCTSTR lpParameters;
    LPCTSTR lpDirectory;
    int nShow;
    HINSTANCE hInstApp;

    // Optional members
    LPVOID lpIDList;
    LPCSTR lpClass;
    HKEY hkeyClass;
    DWORD dwHotKey;
    HANDLE hIcon;
    HANDLE hProcess;
} SHELLEXECUTEINFO, FAR *LPSHELLEXECUTEINFO;

Contains information used by the ShellExecuteEx function.

cbSize
Size of the structure, in bytes.
fMask
Array of flags that indicate the content and validity of the other structure members. This can be a combination of the following values:
SEE_MASK_CLASSKEY | Use the class key given by the hkeyClass member.
SEE_MASK_CLASSNAME | Use the class name given by the lpClass member.
SEE_MASK_CONNECTNETDRV | Validate the share and connect to a drive letter. The lpFile member is a Universal Naming Convention (UNC) path of a file on a network.
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. This flag overrides the SEE_MASK_IDLIST flag.
SEE_MASK_NOCLOSEPROCESS | Leave the process running after the ShellExecuteEx function exits. The hProcess member receives the handle to the process.
hwnd
Window handle to any message boxes that the system may produce while executing this function.
lpVerb
Address of 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
Address of a null-terminated string that specifies the name of the file to open or print. The function can open an executable file or a document file, but it can only print a document file. If the path is not included with the name, the current directory is assumed.
lpParameters
Address of 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 the lpFile member specifies a document file, this member should be NULL.

lpDirectory
Address of 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 the lpFile specifies an executable file, this member specifies how the application is to be shown when it is opened.
hInstApp
Receives a value greater than 32 if successful, or an error value that is less than or equal to 32 otherwise. Error values can be one of the following:
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 an 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 is busy.
SE_ERR_NOASSOC | File association not available.
lpIDList
Address of an ITEMIDLIST structure to contain an item identifier list uniquely identifying the file to execute. This member is ignored if the fMask member is not set to SEE_MASK_IDLIST.
lpClass
Address of a null-terminated string specifying the name of a file class or a globally unique identifier (GUID).This member is ignored if fMask is not set to SEE_MASK_CLASSNAME.
hkeyClass
Handle to the registry key for the file class. This member is 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. This member is ignored if fMask is not set to SEE_MASK_HOTKEY.
hIcon
Handle to the icon for the file class. This member is 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.


SHELLFLAGSTATE

typedef struct {
    BOOL fShowAllObjects : 1;
    BOOL fShowExtensions : 1;
    BOOL fNoConfirmRecycle : 1;
    BOOL fShowSysFiles : 1;
    BOOL fShowCompColor : 1;
    BOOL fDoubleClickInWebView : 1;
    BOOL fDesktopHTML : 1;
    BOOL fWin95Classic : 1;
    BOOL fDontPrettyPath : 1;
    BOOL fShowAttribCol : 1;
    BOOL fMapNetDrvBtn : 1;
    BOOL fShowInfoTip : 1;
    BOOL fHideIcons : 1;
    UINT fRestFlags : 3;
} SHELLFLAGSTATE, * LPSHELLFLAGSTATE;

Contains a set of flags that indicate the current shell settings. This structure is used with the SHGetSettings function.

fShowAllObjects
Nonzero if the Show All Files option is enabled or zero otherwise.
fShowExtensions
Nonzero if the Hide File Extensions for Known File Types option is disabled or zero otherwise.
fNoConfirmRecycle
Nonzero if the Display Delete Confirmation Dialog box in the Recycle Bin is enabled or zero otherwise.
fShowSysFiles
Nonzero if the Do Not Show Hidden Files option is selected or zero otherwise.
fShowCompColor
Nonzero if the Display Compressed Files and Folders with Alternate Color option is enabled or zero otherwise.
fDoubleClickInWebView
Nonzero if the Double-Click to Open an Item option is enabled or zero otherwise.
fDesktopHTML
Nonzero if the Active Desktop – View as Web Page option is enabled or zero otherwise.
fWin95Classic
Nonzero if the Classic Style option is enabled or zero otherwise.
fDontPrettyPath
Nonzero if the Allow All Uppercase Names option is enabled or zero otherwise.
fShowAttribCol
Nonzero if the Show File Attributes in Detail View option is enabled or zero otherwise.
fMapNetDrvBtn
Nonzero if the Show Map Network Drive Button in Toolbar option is enabled or zero otherwise.
fShowInfoTip
Nonzero if the Show Info Tips for Items in Folders & Desktop option is enabled or zero otherwise.
fHideIcons
Not used.
fRestFlags
Not used.

Version 4.71


SHFILEINFO

typedef struct _SHFILEINFO{
    HICON hIcon;
    int   iIcon;
    DWORD dwAttributes;
    char  szDisplayName[MAX_PATH];
    char  szTypeName[80];
} SHFILEINFO;

Contains information about a file object.

hIcon
Handle to the icon that represents the file.
iIcon
Index of the icon image within the system image list.
dwAttributes
Array of values that indicates the attributes of the file object. For information about these values, see the IShellFolder::GetAttributesOf method.
szDisplayName
String that contains the name of the file as it appears in the Windows shell, or the path and file name of the file that contains the icon representing the file.
szTypeName
String that describes the type of file.

This structure is used with the SHGetFileInfo function.


SHFILEOPSTRUCT

typedef struct _SHFILEOPSTRUCT{
    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.

hwnd
Window handle to the dialog box to display information about the status of the file operation.
wFunc
Operation to perform. This member can be one of the following values:
FO_COPY | Copies the files specified in the pFrom member to the location specified in the pTo member.
FO_DELET | Deletes the files specified in pFrom. (pTo is ignored.)
FO_MOVE | Moves the files specified in pFrom to the location specified in pTo.
FO_RENAME | Renames the files specified in pFrom.
pFrom
Address of a buffer to specify one or more source file names. Multiple names must be null-separated. The list of names must be double null-terminated.
pTo
Address of a buffer to contain the name of the destination file or directory. The buffer can contain multiple destination file names if the fFlags member specifies FOF_MULTIDESTFILES. Multiple names must be null-separated. The list of names must be double null-terminated.
fFlags
Flags that control the file operation. This member can be a combination of the following flags:
FOF_ALLOWUNDO | Preserve Undo information, if possible. If pFrom does not contain fully qualified path and filenames, this flag is ignored.
FOF_CONFIRMMOUSE | Not currently implemented.
FOF_FILESONLY | Perform the operation on files only if a wildcard file name (*.*) is specified.
FOF_MULTIDESTFILES | 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 | Respond 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_NOCOPYSECURITYATTRIBS | Version 4.71. Microsoft® Windows NT® only. The security attributes of the file will not be copied.
FOF_NOERRORUI | No user interface will be displayed if an error occurs.
FOF_RENAMEONCOLLISION | Give the file being operated on a new name in a move, copy, or rename operation if a file with 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 file names.
FOF_WANTMAPPINGHANDLE | If FOF_RENAMEONCOLLISION is specified, the hNameMappings member will be filled in if any files were renamed.
fAnyOperationsAborted
Value that receives TRUE if the user aborted any file operations before they were completed, or FALSE otherwise.
hNameMappings
Handle to a file name 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 the fFlags member includes the FOF_WANTMAPPINGHANDLE flag. The handle must be freed by using the SHFreeNameMappings function.
lpszProgressTitle
Address of a string to use as the title of a progress dialog box. This member is used only if fFlags includes the FOF_SIMPLEPROGRESS flag.

If the pFrom or pTo members are unqualified names, the current directories are taken from the global current drive and directory settings as managed by the GetCurrentDirectory and SetCurrentDirectory functions.


SHITEMID

typedef struct _SHITEMID {
    USHORT cb;
    BYTE   abID[1];
} SHITEMID, * LPSHITEMID;
typedef const SHITEMID  * LPCSHITEMID;

Defines an item identifier.

cb
Size of identifier, in bytes, including cb itself.
abID
Variable-length item identifier.


SHNAMEMAPPING

typedef struct _SHNAMEMAPPING {
    LPSTR pszOldPath;
    LPSTR pszNewPath;
    int   cchOldPath;
    int   cchNewPath;
} SHNAMEMAPPING, FAR *LPSHNAMEMAPPING;

Contains the old and new path names for each file that was moved, copied, or renamed by the SHFileOperation function.

pszOldPath
Address of a character buffer that contains the old path name.
pszNewPath
Address of a character buffer that contains the new path name.
cchOldPath
Number of characters in pszOldPath.
cchNewPath
Number of characters in pszNewPath.

See also SHFILEOPSTRUCT


SHQUERYRBINFO

typedef struct _SHQUERYRBINFO {
    DWORD cbSize;
    __int64 i64Size;
    __int64 i64NumItems;
} SHQUERYRBINFO, FAR *LPSHQUERYRBINFO;

Contains the size and item count information retrieved by the SHQueryRecycleBin function.

cbSize
Size of the structure, in bytes. This member must be filled in prior to calling the function.
i64Size
Total size of all the objects in the specified Recycle Bin, in bytes.
i64NumItems
Total number of items in the specified Recycle Bin.


SOARCINFO

Contains information that defines the arc to be drawn.

Syntax

typedef struct SOARCINFOtag {
    SORECT Rect;
    SOANGLE StartAngle;
    SOANGLE EndAngle;
} SOARCINFO, VWPTR *PSOARCINFO;

Members

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

Contains information about the bitmap to be output.

Syntax

typedef struct SOBITMAPHEADERtag {
    WORD wStructSize;
    WORD wImageFlags;
    WORD wImageWidth;
    WORD wImageLength;
    WORD wTileWidth;
    WORD wTileLength;
    WORD wBitsPerPixel;
    WORD wNPlanes;
    WORD wHDpi;
    WORD wVDpi;
} SOBITMAPHEADER, VWPTR *PSOBITMAPHEADER;

Members

wStructSize
Size, in bytes, of the structure.
wImageFlags
Image flags. This member can be one (and only one) of the color format values combined with one or more of the 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
Width, in pixels, of the image.
wImageLength
Height, in pixels, of the image.
wTileWidth
Width, in pixels, of the tile.
wTileLength
Height, 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

Contains information about the border around a cell in table.

Syntax

typedef struct SOBORDERtag {
    WORD wWidth;
    SOCOLORREF rgbColor;
    WORD wFlags;
} SOBORDER, VWPTR * PSOBORDER;

Members

wWidth
Width, in TWIPS, of the border.
rgbColor
Color of the border. This member can be an 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 following values:
SO_BORDERNONE
SO_BORDERDOUBLE
SO_BORDERHAIRLINE
SO_BORDERTHICK
SO_BORDERSHADOW
SO_BORDERDOTTED


SOCOLUMN

Contains information about the columns that are contained in a spreadsheet.

Syntax

typedef struct SOCOLUMNtag {
    WORD wStructSize;
    LONG dwWidth;
    char szName[40];
} SOCOLUMN, VWPTR * PSOCOLUMN;

Members

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

Contains information defining an arc for use in vector graphics output.

Syntax

typedef struct SOCPARCANGLEtag {
    SOPOINT Center;
    SOANGLE SweepAngle;
} SOCPARCANGLE, VWPTR *PSOCPARCANGLE;

Members

Center
Center point of the arc.
SweepAngle
Sweep angle of the arc.


SOCPPIEANGLE

Contains information defining a pie shape for use in vector graphics output.

Syntax

typedef struct SOCPPIEANGLEtag {
    INT nRadius;
    SOANGLE StartAngle;
    SOANGLE SweepAngle;
} SOCPPIEANGLE, VWPTR *PSOCPPIEANGLE;

Members

nRadius
Radius of the pie shape.
StartAngle
Starting angle of the pie shape.
SweepAngle
Sweep angle of the pie shape.


SOCPTEXTATPOINT

Contains information defining the format and length of text for use in vector graphics output.

Syntax

typedef struct SOCPTEXTATPOINTtag {
    WORD wFormat;
    INT nTextLength;
} SOCPTEXTATPOINT, VWPTR *PSOCPTEXTATPOINT;

Members

wFormat
Format of the text.
nTextLength
Text length, in characters.


SODATACELL

Contains information about the data to be placed in a cell of a spreadsheet.

Syntax

typedef struct SODATACELLtag {
    WORD wStructSize;
    WORD wStorage;
    WORD wDisplay;
    DWORD dwSubDisplay;
    WORD wPrecision;
    WORD wAlignment;
    WORD wAttribute;
    union {
        SOINT32S Int32S;
        SOINT32U Int32U;
        BYTE IEEE4[4];
        BYTE IEEE8[8];
        BYTE IEEE10[10];
        BYTE BCD8[8];
    } uStorage;
} SODATACELL, VWPTR * PSODATACELL;

Members

wStructSize
Size, in bytes, of the structure.
wStorage
Storage type. This member can be one of these values:
SO_CELLBCD8I | Packed BCD excess-63. See BCD8 for more information.
SO_CELLEMPTY | The cell is empty.
SO_CELLERROR | The cell has an error condition.
SO_CELLIEEE4I | IEEE 4-byte in Intel® (PC) ordering. See IEEE4 for more information.
SO_CELLIEEE8I | IEEE 8-byte in Intel (PC) ordering. See IEEE8 for more information.
SO_CELLIEEE10I | IEEE 10-byte in Intel (PC) ordering. See IEEE10 for more information.
SO_CELLINT32S | 32-bit signed integer. See Int32S for more information.
SO_CELLINT32U | 32-bit unsigned integer. See Int32U for more information.
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 | Comma as thousands separator.
SO_CELL1000SEP_NONE | No thousands 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 contain one value for each of these: 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
4-byte array representing an IEEE 4-byte floating-point number.
IEEE8
8-byte array representing an IEEE 8-byte floating-point number.
IEEE10
10-byte array representing an IEEE 10-byte floating-point number.
BCD8
8-byte array representing an excess-63 floating-point packed BCD.


SOEMBEDDEDGRAPHIC

Contains information about the size and positioning of an embedded graphics object.

Syntax

typedef struct SOEMBEDDEDGRAPHICtag {
    SOPOINT Size;
    SORECT Crop;
    SOPOINT ScaledSize;
    WORD wBorder;
    DWORD dwFlags;
} SOEMBEDDEDGRAPHIC;

Members

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 one or both of these values:
SO_CENTERIMAGE | The image is centered in its final rectangle.
SO_MAINTAINASPECT | The image aspect ratio is preserved.


SOEMBEDDEDOBJECT

Contains information about an embedded object.

Syntax

typedef struct SOEMBEDDEDOBJECTtag {
    WORD wStructSize;
    WORD wObjectType;
    char szFile[144];
    WORD wFIType;
    DWORD dwFileOffset;
    SOEMBEDINFO Info;
} SOEMBEDDEDOBJECT, VWPTR * PSOEMBEDDEDOBJECT;

Members

wStructSize
Size, in bytes, of the structure.
wObjectType
Type of object. This member can be the SOEMBED_GRAPHIC or SO_UNKNOWN value.
szFile
Null-terminated string specifying the path and file name of the file that contains the object. If the object is in the current file, this member is NULL.
wFIType
Identifier for the 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

Contains information specific to embedded graphics objects.

Syntax

typedef union SOEMBEDINFOtag {
    SOEMBEDDEDGRAPHIC Graphic;
} SOEMBEDINFO;

Members

Graphic
SOEMBEDDEDGRAPHIC structure that defines the embedded graphic object.


SOFIELD

Contains information about a field in a database.

Syntax

typedef struct SOFIELDtag {
    WORD wStructSize;
    LONG dwWidth;
    char szName[40];
    WORD wStorage;
    WORD wDisplay;
    DWORD dwSubDisplay;
    WORD wPrecision;
    WORD wAlignment;
} SOFIELD, VWPTR * PSOFIELD;

Members

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. See BCD8 for more information.
SO_CELLEMPTY | The cell is empty.
SO_CELLERROR | The cell has an error condition.
SO_CELLIEEE4I | IEEE 4-byte in Intel® (PC) ordering. See IEEE4 for more information.
SO_CELLIEEE8I | IEEE 8-byte in Intel (PC) ordering. See IEEE8 for more information.
SO_CELLIEEE10I | IEEE 10-byte in Intel (PC) ordering. See IEEE10 for more information.
SO_CELLINT32S | 32-bit signed integer. See Int32S for more information.
SO_CELLINT32U | 32-bit unsigned integer. See Int32U for more information.
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

Contains information identifying the file parser.

Syntax

typedef struct SOFILTERINFOtag {
    INT wFilterCharSet;
    U_BYTE szFilterName[32];
} SOFILTERINFO;

Members

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

Contains information about a group for use with vector graphics output.

Syntax

typedef struct SOGROUPINFOtag {
    WORD wStructSize;
    SORECT BoundingRect;
    INT nTransforms;
} SOGROUPINFO, VWPTR *PSOGROUPINFO;

Members

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

Contains information defining a logical brush for use with vector graphics output.

Syntax

typedef struct SOLOGBRUSHtag {
    WORD lbStyle;
    SOCOLORREF lbColor;
    INT lbHatch;
} SOLOGBRUSH, VWPTR *PSOLOGBRUSH;

Members

lbStyle
Brush style. This member can be one of the following values:
SOBS_HATCHED | Hatched brush.
SOBS_HOLLOW | Hollow brush.
SOBS_SOLID | Solid brush.
lbColor
Color of the brush. This member can be an RGB or palette-relative value. To set this member, use the SORGB or SOPALETTERGB macro.
lbHatch
Hatch style. This member is used only if lbStyle is SO_HATCHED. This member can be one of the following values:
SOHS_BDIAGONAL | A 45-degree upward, left-to-right hatch.
SOHS_CROSS | Horizontal and vertical cross-hatch.
SOHS_DIAGCROSS | 45-degree cross-hatch.
SOHS_FDIAGONAL | A 45-degree downward, left-to-right hatch.
SOHS_HORIZONTAL | Horizontal hatch.
SOHS_VERTICAL | Vertical hatch.

See Also

LOGBRUSH


SOLOGFONT

Contains information that defines a logical font for use with vector graphics output.

Syntax

typedef struct SOLOGFONTtag {
    INT lfHeight;
    INT lfWidth;
    INT lfEscapement;
    INT lfOrientation;
    INT lfWeight;
    BYTE lfItalic;
    BYTE lfUnderline;
    BYTE lfStrikeOut;
    BYTE lfCharSet;
    BYTE lfOutputPrecision;
    BYTE lfClipPrecision;
    BYTE lfQuality;
    BYTE lfPitchAndFamily;
    BYTE lfFaceName[SOLF_FACESIZE];
} SOLOGFONT, VWPTR *PSOLOGFONT;

Remarks

For a description of the members, see the LOGFONT structure.

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


SOLOGPEN

Contains information that defines a logical pen for use with vector graphics output.

Syntax

typedef struct SOLOGPENtag {
    INT loPenStyle;
    SOPOINT loWidth;
    SOCOLORREF loColor;
} SOLOGPEN, VWPTR *PSOLOGPEN;

Members

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

Remarks

For a complete definition of the members, see the LOGPEN structure.

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


SOPARAINDENTS

Contains information about paragraph indents for use with vector graphics output.

Syntax

typedef struct SOPARAINDENTStag {
    INT FirstLineIndent;
    INT LeftIndent;
    INT RightIndent;
} SOPARAINDENTS, VWPTR *PSOPARAINDENTS;

Members

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

Contains information about a path for use with vector graphics output.

Syntax

typedef struct SOPATHINFOtag {
    WORD wStructSize;
    SORECT BoundingRect;
    INT nTransforms;
} SOPATHINFO, VWPTR *PSOPATHINFO;

Members

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

Contains coordinates for a point.

Syntax

typedef struct SOPOINTtag {
    INT x;
    INT y;
} SOPOINT, VWPTR *PSOPOINT;

Members

x
X-coordinate for the point.
y
Y-coordinate for the point.


SOPOLYINFO

Contains information about the format type and the number of vertices of a polyline, polygon, spline, or Bezier curve.

Syntax

typedef struct SOPOLYINFOtag {
    WORD wFormat;
    INT nPoints;
} SOPOLYINFO, VWPTR *PSOPOLYINFO;

Members

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

Contains the dimensions of a rectangle.

Syntax

typedef struct SORECTtag {
    INT left;
    INT top;
    INT right;
    INT bottom;
} SORECT, VWPTR *PSORECT;

Members

left
X-coordinate of upper left corner.
top
Y-coordinate of upper left corner.
right
X-coordinate of lower right corner.
bottom
Y-coordinate of lower right corner.


SOTAB

Contains information about tab stops.

Syntax

typedef struct SOTABtag {
    WORD wType;
    WORD wChar;
    WORD wLeader;
    LONG dwOffset;
} SOTAB, VWPTR * PSOTAB;

Members

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

Contains information about cells in a table.

Syntax

typedef struct SOTABLECELLINFOtag {
    WORD wWidth;
    WORD wMerge;
    WORD wShading;
    PSOBORDER pLeftBorder;
    PSOBORDER pRightBorder;
    PSOBORDER pTopBorder;
    PSOBORDER pBottomBorder;
} SOTABLECELLINFO, VWPTR *PSOTABLECELLINFO;

Members

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

Contains information about text for use with vector graphics output.

Syntax

typedef struct SOTEXTATARCANGLEtag {
    SOARCINFO ArcInfo;
    WORD wFormat;
    INT nTextLength;
} SOTEXTATARCANGLE, VWPTR *PSOTEXTATARCANGLE;

Members

ArcInfo
Arc information that defines the bounding rectangle of the arc relative to the text baseline. Only the starting angle is used to locate the point; the ending angle is ignored.
wFormat
Alignment format, which indicates 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 the text string that follows the structure.


SOTEXTATPOINT

Contains information about text at a point.

Syntax

typedef struct SOTEXTATPOINTtag {
    SOPOINT Point;
    WORD wFormat;
    INT nTextLength;
} SOTEXTATPOINT, VWPTR *PSOTEXTATPOINT;

Members

Point
Point that locates the text.
wFormat
Alignment format, which indicates 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

Contains information about the alignment and attributes of text in a spreadsheet cell.

Syntax

typedef struct SOTEXTCELLtag {
    WORD wStructSize;
    WORD wAlignment;
    WORD wAttribute;
} SOTEXTCELL, VWPTR * PSOTEXTCELL;

Members

wStructSize
Size, in bytes, of the structure.
wAlignment
Alignment. This member can be one of the following values:
SO_CELLLEFT | Indicates the text is aligned left within the cell.
SO_CELLRIGHT | Indicates the text is aligned right within the cell.
SO_CELLCENTER | Indicates the text is centered within the cell.
SO_CELLFILL | Indicates the text is aligned to fill the cell.
wAttribute
Attributes. This member can be a combination of the following values:
SO_CELLBOLD | Indicates the text is bold.
SO_CELLITALIC | Indicates the text is italic.
SO_CELLUNDERLINE | Indicates the text is underlined.
SO_CELLSTRIKEOUT | Indicates the text is drawn as strikeout.


SOTEXTINRECT

Contains information about text for use with vector graphics output.

Syntax

typedef struct SOTEXTINRECTtag {
    SORECT Rect;
    WORD wFormat;
    INT nTextLength;
} SOTEXTINRECT, VWPTR *PSOTEXTINRECT;

Members

Rect
Rectangle in which text is formatted.
wFormat
Format of the string. This member can be a combination of these values:
SODT_BOTTOMSODT_NOPREFIX
SODT_CALCRECTSODT_RIGHT
SODT_CENTERSODT_SINGLELINE
SODT_EXPANDTABSSODT_TABSTOP
SODT_EXTERNALLEADINGSODT_TOP
SODT_LEFTSODT_VCENTER
SODT_NOCLIPSODT_WORDBREAK
nTextLength
Length of the text string that follows the structure.


SOTRANSFORM

Contains information about a transformation for use with vector graphics output.

Syntax

typedef struct SOTRANSFORMtag {
    WORD wTransformFlags;
    SOPOINT Origin;
    INT xOffset;
    INT yOffset;
    SORATIO xScale;
    SORATIO yScale;
    SORATIO xSkew;
    SORATIO ySkew;
    SOANGLE RotationAngle;
} SOTRANSFORM, VWPTR *PSOTRANSFORM;

Members

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

SOTF_ROTATE may be combined only with SOTF_XOFFSET and SOTF_YOFFSET. Also, no other values may be combined with SOTF_NOTRANSFORM.

Origin
Point of origin for all transformations except SOTF_XOFFSET and SOTF_YOFFSET.
xOffset and yOffset
Offset values to use for the SOTF_XOFFSET and SOTF_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 is 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 is 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 number of degrees about the given origin. This value must be set by using the SOANGLETENTHS macro. A SOANGLE variable should not be set directly.

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

Contains information defining the size and attributes of the rectangle in which vector graphics are drawn.

Syntax

typedef struct SOVECTORHEADERtag {
    WORD wStructSize;
    SORECT BoundingRect;
    WORD wHDPI;
    WORD wVDPI;
    WORD wImageFlags;
    SOCOLOR BkgColor;
} SOVECTORHEADER, VWPTR *PSOVECTORHEADER;

Members

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.


STRRET

Contains strings returned from the IShellFolder interface methods.

Syntax

typedef struct _STRRET {
   UINT uType;
   union
   {
      LPWSTR pOleStr;
      LPSTR pStr;
      UINT uOffset;
      char cStr[MAX_PATH];
   } DUMMYUNIONNAME;
} STRRET, *LPSTRRET;

Members

uType
Value that specifies the desired format of the string. This can be one of the following values:
STRRET_CSTR | The string is returned in the cStr member.
STRRET_OFFSET | The uOffset member value indicates the number of bytes from the beginning of the item identifier list where the string is located.
STRRET_WSTR | The string is at the address pointed to in the pOleStr member.
pOleStr
Address of the OLE string. This memory must be allocated with the shell's allocator (see SHGetMalloc). It is the calling application's responsibility to free this memory when it is no longer needed. The shell's allocator must be used to free the memory.
pStr
This member is not used.
uOffset
Offset into item identifier list.
cStr
Buffer to receive the display name.

See Also

IShellFolder::GetDisplayNameOf


FOLDERFLAGS

typedef enum{
    FWF_AUTOARRANGE         = 0x0001,
    FWF_ABBREVIATEDNAMES    = 0x0002,
    FWF_SNAPTOGRID          = 0x0004,
    FWF_OWNERDATA           = 0x0008,
    FWF_BESTFITWINDOW       = 0x0010,
    FWF_DESKTOP             = 0x0020,
    FWF_SINGLESEL           = 0x0040,
    FWF_NOSUBFOLDERS        = 0x0080,
    FWF_TRANSPARENT         = 0x0100,
    FWF_NOCLIENTEDGE        = 0x0200,
    FWF_NOSCROLL            = 0x0400,
    FWF_ALIGNLEFT           = 0x0800,
    FWF_NOICONS             = 0x1000,
    FWF_SINGLECLICKACTIVATE = 0x8000
} FOLDERFLAGS;

Set of flags used to specify folder view options.

FWF_AUTOARRANGE
Automatically arrange the elements in the view. This implies LVS_AUTOARRANGE if the list view control is used to implement the view.
FWF_ABBREVIATEDNAMES
Names should be abbreviated. This flag is not currently supported.
FWF_SNAPTOGRID
Items should be arranged on a grid. This flag is not currently supported.
FWF_OWNERDATA
This flag is not currently supported.
FWF_BESTFITWINDOW
Enable the best-fit window mode. Let the view size the window so that its contents fit inside the view window in the best possible manner.
FWF_DESKTOP
Make the folder behave like the desktop. This value applies only to the desktop view and is not used for typical shell folders.
FWF_SINGLESEL
Do not allow more than a single item to be selected. This is used in the common dialogs.
FWF_NOSUBFOLDERS
Do not show subfolders.
FWF_TRANSPARENT
Draw transparently. This is used only for the desktop.
FWF_NOCLIENTEDGE
Do not add the WS_EX_CLIENTEDGE value to the view. This is used only for the desktop.
FWF_NOSCROLL
Do not add scroll bars. This is used only for the desktop.
FWF_ALIGNLEFT
The view should be left-aligned. This implies LVS_ALIGNLEFT if the list view control is used to implement the view.
FWF_NOICONS
The view should not display icons.
FWF_SINGLECLICKACTIVATE
This flag is not currently supported.


FOLDERVIEWMODE

typedef enum {
    FVM_ICON      = 1,
    FVM_SMALLICON = 2,
    FVM_LIST      = 3,
    FVM_DETAILS   = 4
} FOLDERVIEWMODE;

Set of constants used to specify the folder view type.

FVM_ICON
The view should display large icons.
FVM_SMALLICON
The view should display small icons.
FVM_LIST
Object names are displayed in a list view.
FVM_DETAILS
Object names and other selected information, such as the size or date last updated, are shown.


SHCONTF

typedef enum tagSHCONTF{
    SHCONTF_FOLDERS = 32,
    SHCONTF_NONFOLDERS = 64,
    SHCONTF_INCLUDEHIDDEN = 128,
} SHCONTF;

Determines the type of items included in an enumeration. These values are used with the IShellFolder::EnumObjects method.

SHCONTF_FOLDERS
Include items that are folders in the enumeration.
SHCONTF_NONFOLDERS
Include items that are not folders in the enumeration.
SHCONTF_INCLUDEHIDDEN
Include hidden items in the enumeration.


SHGNO

typedef enum tagSHGDN {
    SHGDN_NORMAL = 0,
    SHGDN_INFOLDER = 1,
    SHGDN_INCLUDE_NONFILESYS = 0x2000,
    SHGDN_FORADDRESSBAR = 0x4000,
    SHGDN_FORPARSING = 0x8000,
} SHGNO;

Defines the values used with the IShellFolder::GetDisplayNameOf and IShellFolder::SetNameOf methods.

This enumeration consists of two sets of values. The first set is contained in bits 0 through 7 and specifies if the name is relative to this folder or if the name is a full name. The following are valid values in this set:
SHGDN_NORMAL | Name is a full name. That is, the name is relative to the desktop and not to any specific folder.
SHGDN_INFOLDER | Name is relative to the folder that is processing the name.

The second set of values is contained in bits 8 through 15. These values are modifiers to the first set and specify the name retrieval options. The following are valid values in this set:
SHGDN_NORMAL | Name will be used for generic display.
SHGDN_FORADDRESSBAR | Name will be used for display in the address bar combo box.
SHGDN_FORPARSING | Name will be used for parsing. That is, it can be passed to ParseDisplayName.
SHGDN_INCLUDE_NONFILESYS | If this flag is set, the calling application is interested in names of any types of items. If this flag is not set, the calling application is only interested in items that are part of the file system. If this flag is not set and the item is not part of the file system, this method should fail.

See also Display Names


Common Controls

This section describes the common controls and the programming elements used to create and manipulate them. This section includes the enhancements that are available with Microsoft® Internet Explorer 3.0x and 4.0. All of the APIs, messages, and structures necessary to create and manipulate the controls are included here. The information in this section supersedes the common control information in the Platform SDK documentation.

Common Controls

Custom Draw

Animation Controls

ComboBoxEx Controls

Date and Time Picker Controls

Drag List Boxes

Flat Scroll Bars

Header Controls

Hot Key Controls

Image Lists

IP Address Controls

List View Controls

Month Calendar Controls

Pager Controls

Progress Bar Control

Property Sheets

Rebar Controls

Status Bars

Tab Controls

Toolbar Controls

Tooltip Controls

Trackbar Controls

Tree View Controls

Up-Down Controls


Common Controls

The common controls are a set of windows that are implemented 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 I/O tasks.

Using Common Controls

Common Control Updates in Internet Explorer

Common Control Reference

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

Common Control DLL Versions

Because of ongoing enhancements, different versions of Comctl32.dll implement different features. Throughout this document, programming elements are marked with a version number. This version number indicates that the programming element is implemented in that version and later versions of Comctl32.dll. If no version number is specified, the programming element is implemented in all versions. The following table outlines the different versions of Comctl32.dll and the distribution platform.

Version | Distribution platform
4.00 | Microsoft® Windows® 95/Windows NT® 4.0
4.70 | Microsoft® Internet Explorer 3.x
4.71 | Microsoft® Internet Explorer 4.0
4.72 | Microsoft® Internet Explorer 4.01

The following function retrieves the major and minor version numbers of the Comctl32.dll that is installed on the local system.

#include <windows.h>
#include <shlwapi.h>

HRESULT GetComCtlVersion(LPDWORD pdwMajor, LPDWORD pdwMinor)
{
HINSTANCE   hComCtl;

if(   IsBadWritePtr(pdwMajor, sizeof(DWORD)) ||
      IsBadWritePtr(pdwMinor, sizeof(DWORD)))
   return E_INVALIDARG;

//load the DLL
hComCtl = LoadLibrary(TEXT("comctl32.dll"));

if(hComCtl)
   {
   HRESULT           hr = S_OK;
   DLLGETVERSIONPROC pDllGetVersion;

   /*
   You must get this function explicitly because earlier versions of the DLL
   don't implement this function. That makes the lack of implementation of the
   function a version marker in itself.
   */
   pDllGetVersion = (DLLGETVERSIONPROC)GetProcAddress(hComCtl, TEXT("DllGetVersion"));

   if(pDllGetVersion)
      {
      DLLVERSIONINFO    dvi;

      ZeroMemory(&dvi, sizeof(dvi));
      dvi.cbSize = sizeof(dvi);

      hr = (*pDllGetVersion)(&dvi);

      if(SUCCEEDED(hr))
         {
         *pdwMajor = dvi.dwMajorVersion;
         *pdwMinor = dvi.dwMinorVersion;
         }
      else
         {
         hr = E_FAIL;
         }
      }
   else
      {
      /*
      If GetProcAddress failed, then the DLL is a version previous to the one
      shipped with IE 3.x.
      */
      *pdwMajor = 4;
      *pdwMinor = 0;
      }

   FreeLibrary(hComCtl);

   return hr;
   }

return E_FAIL;
}

Structure sizes for different common control versions

Ongoing enhancements to common controls has resulted in the need to extend many of the structures. This results in the size of the structures changing between different versions of Commctrl.h. Because most of the common control structures take a structure size as one of the parameters, this can result in a message or function failing if the size is not recognized. To remedy this, structure size constants have been defined to aid in targeting different version of Comctl32.dll. The following list defines the new structure size constants.

HDITEM_V1_SIZE | The size of the HDITEM structure in version 4.00.
LVCOLUMN_V1_SIZE | The size of the LVCOLUMN structure in version 4.00.
LVHITTESTINFO_V1_SIZE | The size of the LVHITTESTINFO structure in version 4.00.
LVITEM_V1_SIZE | The size of the LVITEM structure in version 4.00.
NMLVCUSTOMDRAW_V3_SIZE | The size of the NMLVCUSTOMDRAW structure in version 4.70.
NMTTDISPINFO_V1_SIZE | The size of the NMTTDISPINFO structure in version 4.00.
NMTVCUSTOMDRAW_V3_SIZE | The size of the NMTVCUSTOMDRAW structure in version 4.70.
PROPSHEETHEADER_V1_SIZE | The size of the PROPSHEETHEADER structure in version 4.00.
PROPSHEETPAGE_V1_SIZE | The size of the PROPSHEETPAGE structure in version 4.00.
REBARBANDINFO_V3_SIZE | The size of the REBARBANDINFO structure in version 4.70.
TTTOOLINFO_V1_SIZE | The size of the TOOLINFO structure in version 4.00.
TVINSERTSTRUCT_V1_SIZE | The size of the TVINSERTSTRUCT structure in version 4.00.

Project Versions

To ensure that your application is compatible with different targeted versions of the common control DLL (Comctl32.dll), a version macro was added to Commctrl.h. This version macro is used to define, exclude, or redefine certain common control definitions for different versions of the DLL. The macro name is _WIN32_IE and you, the developer, are responsible for defining the macro as a hexadecimal number. This version number defines the target version of the application that is using the DLL. The following are the currently available version numbers and the effect each has on your application.

Version | Description
0x0200 | The application will be compatible with Comctl32.dll version 4.00 and later. The application will not, however, be able to implement the common control features that were added after version 4.00 of Comctl32.dll.
0x0300 | The application will be compatible with Comctl32.dll version 4.70 and later. The application will not, however, be able to implement the common control features that were added after version 4.70 of Comctl32.dll.
0x0400 | The application will be compatible with Comctl32.dll version 4.71 and later. The application will not, however, be able to implement the common control features that were added after version 4.71 of Comctl32.dll.
0x0401 | The application will be compatible with Comctl32.dll version 4.72 and later. The application will not, however, be able to implement the common control features that were added after version 4.72 of Comctl32.dll.

The most effective way to define this macro in your project is to add the following to the compiler directives in your make file (substitute the desired version number for 0x0400):

/D _WIN32_IE=0x0400

Another method that can be used to define this macro in your project is to add a line similar to the following in your source code before including Commctrl.h (substitute the desired version number for 0x0400):

#define _WIN32_IE 0x0400
#include <commctrl.h>

If you do not define this macro in your project, Commctrl.h will automatically define it as 0x0400.

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 Common Control Styles section.

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 (or even change to a combination of old and new colors) while the color of other buttons in the system changes.

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 the WM_HSCROLL and WM_VSCROLL messages to notify its parent of changes, 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.

Note Not all controls will send WM_NOTIFY messages. In particular, the standard Windows controls (edit controls, combo boxes, list boxes, buttons, scroll bars, and static controls) do not send WM_NOTIFY messages. Consult the documentation for the control to determine if it will send any WM_NOTIFY messages and, if it does, which notification codes it will send.

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. See the documentation for the control of interest to determine which notification codes it will send and what format they take.

Common Control Updates in Internet Explorer

Common controls in Microsoft® Internet Explorer support the following new features.

Common Control Initialization
The common controls are now initialized with the InitCommonControlsEx function. This function allows you to specify which controls should be initialized for your application instead of initializing all of the controls. The InitCommonControls function is still supported, but new applications should use InitCommonControlsEx.
New Common Control Styles
There are four new common control styles defined. These are CCS_LEFT, CCS_RIGHT, CCS_VERT, and CCS_NOMOVEX. For more information, see Common Control Styles.


Common Control Reference

This section contains information about the programming elements used with common controls.

Common Control Window Classes

Common Control Styles

Functions
GetEffectiveClientRect
InitCommonControls
InitCommonControlsEx
ShowHideMenuCtl

Messages
WM_NOTIFY
WM_NOTIFYFORMAT

Utility Macros
FORWARD_WM_NOTIFY
HANDLE_WM_NOTIFY
INDEXTOSTATEIMAGEMASK

Notifications
NM_CHAR
NM_CLICK
NM_CUSTOMDRAW
NM_DBLCLK
NM_HOVER
NM_KEYDOWN
NM_KILLFOCUS
NM_NCHITTEST
NM_OUTOFMEMORY
NM_RCLICK
NM_RDBLCLK
NM_RELEASEDCAPTURE
NM_RETURN
NM_SETCURSOR
NM_SETFOCUS
NM_TOOLTIPSCREATED

Structures
COLORSCHEME
INITCOMMONCONTROLSEX
NMCHAR
NMHDR
NMKEY
NMMOUSE
NMOBJECTNOTIFY
NMTOOLTIPSCREATED


Common Control Window Classes

The following window class names are provided by the common control library:
ANIMATE_CLASS | Creates animation controls. These controls silently display an audio video interleaved (AVI) clip.
DATETIMEPICK_CLASS | Creates date and time picker controls. These controls provide a simple and intuitive interface to exchange date and time information with a user.
HOTKEY_CLASS | Creates hot key controls. These controls make it easy for the user to define hot keys.
MONTHCAL_CLASS | Creates month calendar controls. These controls provide a simple and intuitive way for a user to select a date from a familiar interface.
PROGRESS_CLASS | Creates progress bars. These controls indicate the progress of a lengthy operation.
REBARCLASSNAME | Creates rebar controls. These controls act as a container for child windows.
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_COMBOBOXEX | Creates ComboBoxEx controls. These controls provide an extension of the combo box control that provides native support for item images.
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_IPADDRESS | Creates IP address controls. These controls are similar to an edit control, but they allow you to enter a numeric address in Internet protocol (IP) format.
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_PAGESCROLLER | Creates pager controls. These controls are used to contain and scroll another window.
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.
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, which allows 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_LEFT | Version 4.70. Causes the control to be displayed vertically on the left side of the parent window.
CCS_NODIVIDER | Prevents a two-pixel highlight from being drawn at the top of the control.
CCS_NOMOVEX | Version 4.70. Causes the control to resize and move itself vertically, but not horizontally, in response to a WM_SIZE message. If CCS_NORESIZE is used, this style does not apply.
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_RIGHT | Version 4.70. Causes the control to be displayed vertically on the right side of the parent window.
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.
CCS_VERT | Version 4.70. Causes the control to be displayed vertically.


Common Control Functions

The following functions are used with the common controls.

GetEffectiveClientRect

InitCommonControls

InitCommonControlsEx

ShowHideMenuCtl


GetEffectiveClientRect

void GetEffectiveClientRect(
    HWND hWnd,
    LPRECT lprc,
    LPINT lpInfo
   );

Calculates the dimensions of a rectangle in the client area.

  • No return value.
hWnd
Handle to the window that has the client area to check.
lprc
Address of a RECT structure that receives the dimensions of the rectangle.
lpInfo
Address of an array of integers that identify controls in the client area. Each control requires a pair of consecutive elements. The first element of the pair must be nonzero and the second element of the pair must be the control identifier. The last element pair in the array must be zero to identify the end of the array.


InitCommonControls

void InitCommonControls(VOID);

Registers and initializes the common control window classes. This function is obsolete. New applications should use the InitCommonControlsEx function.

  • No return value.


InitCommonControlsEx

BOOL InitCommonControlsEx(
    LPINITCOMMONCONTROLSEX lpInitCtrls
);

Registers specific common control classes from the common control dynamic-link library (DLL).

  • Returns TRUE if successful, or FALSE otherwise.
lpInitCtrls
Address of an INITCOMMONCONTROLSEX structure that contains information specifying which control classes will be registered.

Note The effect of each call to InitCommonControlsEx is cumulative. For example, if InitCommonControlsEx is called with the ICC_UPDOWN_CLASS flag, then is later called with the ICC_HOTKEY_CLASS flag, the result is that both the up-down and hot key common control classes are registered and available to the application.

Version 4.70


ShowHideMenuCtl

BOOL ShowHideMenuCtl(
    HWND hWnd,
    UINT uFlags,
    LPINT lpInfo
   );

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.

  • Returns nonzero if successful, or zero otherwise.
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
Address of 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.


Common Control Messages Common Control Messages *
  * Previous Topic: ShowHideMenuCtl
  * Next Topic: WM_NOTIFY

Common Control Messages

The following messages are used with the common controls.

WM_NOTIFY

WM_NOTIFYFORMAT


WM_NOTIFY

WM_NOTIFY
    idCtrl = (int) wParam;
    pnmh = (LPNMHDR) lParam;

Sent by a common control to its parent window when an event has occurred in the control or the control requires some kind of information.

  • The return value is ignored except for notification messages that specify otherwise.
idCtrl
Identifier of the common control sending the message. This identifier is not guaranteed to be unique. An application should use the hwndFrom or idFrom member of the NMHDR structure (passed as the lParam parameter) to identify the control.
pnmh
Address of 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.

Not all controls will send WM_NOTIFY messages. In particular, the standard Windows controls (edit controls, combo boxes, list boxes, buttons, scroll bars, and static controls) do not send WM_NOTIFY messages. Consult the documentation for the control to determine if it will send any WM_NOTIFY messages and, if it will, which notification codes it will send.


WM_NOTIFYFORMAT

WM_NOTIFYFORMAT
    hwndFrom = (HWND) wParam;
    Command = lParam;

Used to determine if a window accepts ANSI or Unicode structures in the WM_NOTIFY notification message. WM_NOTIFYFORMAT messages are sent from a common control to its parent window and from the parent window to the common control.

  • Returns one of the following:
    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.

hwndFrom
Handle to the window that is sending the WM_NOTIFYFORMAT message. If Command is NF_QUERY, this parameter is the handle to a control. If Command is NF_REQUERY, this parameter is the handle to the parent window of a control.
Command
Command value that specifies the nature of the WM_NOTIFYFORMAT message. This will be one of the following values:
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 during the creation of a control and in response to an NF_REQUERY command.
NF_REQUERY | The message is a request for a control to send an NF_QUERY form of this message to its parent window. This command is sent from the parent window. The parent window is asking the control to requery it about the type of structures to use in WM_NOTIFY messages.

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.

Not all controls will send WM_NOTIFYFORMAT messages. In particular, the standard Windows controls (edit controls, combo boxes, list boxes, buttons, scroll bars, and static controls) do not send WM_NOTIFYFORMAT messages. Consult the documentation for the control to determine if it will send the WM_NOTIFYFORMAT message.


Common Control Utility Macros

The following macros are used with common controls.

FORWARD_WM_NOTIFY

HANDLE_WM_NOTIFY

INDEXTOSTATEIMAGEMASK


FORWARD_WM_NOTIFY

VOID FORWARD_WM_NOTIFY(
    hwnd,
    idFrom,
    pnmhdr,
    fn
   );

Sends or posts the WM_NOTIFY message.

  • Returns a value whose meaning depends on the fn parameter.
hwnd
Handle to the window that receives the WM_NOTIFY message.
idFrom
Identifier of the control sending the message.
pnmhdr
Address of 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.

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


HANDLE_WM_NOTIFY

HANDLE_WM_NOTIFY(
    hwnd,
    wParam,
    lParam,
    fn
   );

Calls a function that processes the WM_NOTIFY message.

  • Returns a value whose meaning depends on the fn parameter.
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.

The HANDLE_WM_NOTIFY macro is defined as follows:

#define HANDLE_WM_NOTIFY(hwnd, wParam, lParam, fn) \
    (fn)((hwnd), (int)(wParam), (NMHDR FAR*)(lParam))


INDEXTOSTATEIMAGEMASK

UINT INDEXTOSTATEIMAGEMASK(
    UINT i
   );

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.

i
Index of a state image.

The INDEXTOSTATEIMAGEMASK macro is defined as follows:

#define INDEXTOSTATEIMAGEMASK(i) ((i) << 12)


Common Control Notification Messages

The following notifications are used with common controls.

NM_CHAR

NM_CLICK

NM_DBLCLK

NM_HOVER

NM_KEYDOWN

NM_KILLFOCUS

NM_NCHITTEST

NM_OUTOFMEMORY

NM_RCLICK

NM_RDBLCLK

NM_RELEASEDCAPTURE

NM_RETURN

NM_SETCURSOR

NM_SETFOCUS

NM_TOOLTIPSCREATED


NM_CHAR

NM_CHAR
    lpnmc = (LPNMCHAR) lParam;

Sent by a control when a character key is processed. This notification message is sent in the form of a WM_NOTIFY message.

  • The return value is ignored by the control.
lpnmc
Address of an NMCHAR structure that contains additional information about the character that caused the notification message.

Version 4.71


NM_CLICK

NM_CLICK
    lpnmh = (LPNMHDR) lParam;

Notifies a control's parent window that the user has clicked the left mouse button within the control. NM_CLICK is sent in the form of a WM_NOTIFY message.

  • The return value is ignored by the control.
lpnmh
Address of an NMHDR structure that contains additional information about this notification message.


NM_DBLCLK

NM_DBLCLK
    lpnmh = (LPNMHDR) lParam;

Notifies a control's parent window 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.

  • The return value is ignored by the control.
lpnmh
Address of an NMHDR structure that contains additional information about this notification message.


NM_HOVER

NM_HOVER
    lpnmh = (LPNMHDR) lParam;

Sent by a control when the mouse hovers over an item. This notification message is sent in the form of a WM_NOTIFY message.

  • Unless otherwise specified, return zero to allow the control to process the hover normally, or nonzero to prevent the hover from being processed.
lpnmh
Address of an NMHDR structure that contains additional information about this notification message.

Version 4.70


NM_KEYDOWN

NM_KEYDOWN
    lpnmk = (LPNMKEY) lParam;

Sent by a control when the control has the keyboard focus and the user presses a key. This notification message is sent in the form of a WM_NOTIFY message.

  • Return nonzero to prevent the control from processing the key, or zero otherwise.
lpnmk
Address of an NMKEY structure that contains additional information about the key that caused the notification message.

Version 4.71


NM_KILLFOCUS

NM_KILLFOCUS
    lpnmh = (LPNMHDR) lParam;

Notifies a control's parent window that the control has lost the input focus. NM_KILLFOCUS is sent in the form of a WM_NOTIFY message.

  • The return value is ignored by the control.
lpnmh
Address of an NMHDR structure that contains additional information about this notification message.


NM_NCHITTEST

NM_NCHITTEST
    lpnmmouse = (LPNMMOUSE) lParam;

Sent by a control when the control receives a WM_NCHITTEST message. This notification message is sent in the form of a WM_NOTIFY message.

  • Unless otherwise specified, return zero to allow the control to perform default processing of the hit test message, or return one of the HT* values documented under WM_NCHITTEST to override the default hit test processing.
lpnmmouse
Address of a NMMOUSE structure that contains information about the notification. The pt member contains the mouse coordinates of the hit test message.

Version 4.71


NM_OUTOFMEMORY

NM_OUTOFMEMORY
    lpnmh = (LPNMHDR) lParam;

Notifies a control's parent window 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.

  • The return value is ignored by the control.
lpnmh
Address of an NMHDR structure that contains additional information about this notification message.


NM_RCLICK

NM_RCLICK
    lpnmh = (LPNMHDR) lParam;

Notifies a control's parent window that the user has clicked the right mouse button within the control. NM_RCLICK is sent in the form of a WM_NOTIFY message.

  • The return value is ignored by the control.
lpnmh
Address of an NMHDR structure that contains additional information about this notification message.


NM_RDBLCLK

NM_RDBLCLK
    lpnmh = (LPNMHDR) lParam;

Notifies a control's parent window 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.

  • The return value is ignored by the control.
lpnmh
Address of an NMHDR structure that contains additional information about this notification message.


NM_RELEASEDCAPTURE

NM_RELEASEDCAPTURE
    lpnmh = (LPNMHDR) lParam;

Notifies a control's parent window that the control is releasing mouse capture. This notification is sent in the form of a WM_NOTIFY message.

  • Unless otherwise specified, the control ignores the return value from this notification.
lpnmh
Address of an NMHDR structure that contains additional information about this notification message.

Version 4.71


NM_RETURN

NM_RETURN
    lpnmh = (LPNMHDR) lParam;

Notifies a control's parent window 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.

  • The return value is ignored by the control.
lpnmh
Address of an NMHDR structure that contains additional information about this notification message.


NM_SETCURSOR

NM_SETCURSOR
    lpnmm = (LPNMMOUSE) lParam;

Notifies a control's parent window that the control is setting the cursor in response to a WM_SETCURSOR message. This notification is sent in the form of a WM_NOTIFY message.

  • Unless otherwise specified, return nonzero to allow the control to set the cursor or zero to prevent the control from setting the cursor.
lpnmm
Address of an NMMOUSE structure that contains additional information about this notification message.

Version 4.71


NM_SETFOCUS

NM_SETFOCUS
    lpnmh = (LPNMHDR) lParam;

Notifies a control's parent window that the control has received the input focus. NM_SETFOCUS is sent in the form of a WM_NOTIFY message.

  • The return value is ignored by the control.
lpnmh
Address of an NMHDR structure that contains additional information about this notification message.


NM_TOOLTIPSCREATED

Notifies a control's parent window that the control has created a tooltip control. This notification is sent in the form of a WM_NOTIFY message.

Syntax

NM_TOOLTIPSCREATED
    lpnmttc = (LPNMHDR) lParam;

Parameters

lpnmttc
Address of an NMTOOLTIPSCREATED structure that contains additional information about this notification message.

Return Value

Unless otherwise specified, the control ignores the return value from this notification.

Remarks

Version 4.72


Common Control Structures

The following structures are used with common controls.

COLORSCHEME

INITCOMMONCONTROLSEX

NMCHAR

NMHDR

NMKEY

NMMOUSE

NMOBJECTNOTIFY

NMTOOLTIPSCREATED


COLORSCHEME

typedef struct tagCOLORSCHEME{
    DWORD dwSize;
    COLORREF clrBtnHighlight;
    COLORREF clrBtnShadow;
} COLORSCHEME, *LPCOLORSCHEME;

Contains information for the drawing of buttons in a toolbar or rebar.

dwSize
Size of this structure, in bytes.
clrBtnHighlight
COLORREF value that represents the highlight color of the buttons.
clrBtnShadow
COLORREF value that represents the shadow color of the buttons.

Version 4.71


INITCOMMONCONTROLSEX

typedef struct tagINITCOMMONCONTROLSEX {
    DWORD dwSize;
    DWORD dwICC;
} INITCOMMONCONTROLSEX, *LPINITCOMMONCONTROLSEX;

Carries information used to load common control classes from the dynamic-link library (DLL). This structure is used with the InitCommonControlsEx function.

dwSize
Size of the structure, in bytes.
dwICC
Set of bit flags that indicate which common control classes will be loaded from the DLL. This value can be a combination of the following:
ICC_ANIMATE_CLASS | Load animate control class.
ICC_BAR_CLASSES | Load toolbar, status bar, trackbar, and tooltip control classes.
ICC_COOL_CLASSES | Load rebar control class.
ICC_DATE_CLASSES | Load date and time picker control class.
ICC_HOTKEY_CLASS | Load hot key control class.
ICC_INTERNET_CLASSES | Load IP address class.
ICC_LISTVIEW_CLASSES | Load list view and header control classes.
ICC_PAGESCROLLER_CLASS | Load pager control class.
ICC_PROGRESS_CLASS | Load progress bar control class.
ICC_TAB_CLASSES | Load tab and tooltip control classes.
ICC_TREEVIEW_CLASSES | Load tree view and tooltip control classes.
ICC_UPDOWN_CLASS | Load up-down control class.
ICC_USEREX_CLASSES | Load ComboBoxEx class.
ICC_WIN95_CLASSES | Load animate control, header, hot key, list view, progress bar, status bar, tab, tooltip, toolbar, trackbar, tree view, and up-down control classes.

Version 4.70


NMCHAR

typedef struct tagNMCHAR{
    NMHDR hdr;
    UINT ch;
    DWORD dwItemPrev;
    DWORD dwItemNext;
} NMCHAR, FAR *LPNMCHAR;

Contains information used with character notification messages.

hdr
NMHDR structure that contains additional information about this notification.
ch
Character that is being processed.
dwItemPrev
32-bit value that is determined by the control that is sending the notification.
dwItemNext
32-bit value that is determined by the control that is sending the notification.

Version 4.71


NMHDR

typedef struct tagNMHDR {
    HWND hwndFrom;
    UINT idFrom;
    UINT code;
} NMHDR;

Contains information about a notification message.

hwndFrom
Window handle to the control sending a message.
idFrom
Identifier of the control sending a message.
code
Notification code. This member can be a control-specific notification code or it can be one of the common notification codes.


NMKEY

typedef struct tagNMKEY {
    NMHDR hdr;
    UINT nVKey;
    UINT uFlags;
} NMKEY, FAR *LPNMKEY;

Contains information used with key notification messages.

hdr
NMHDR structure that contains additional information about this notification.
nVKey
Virtual key code of the key that caused the event.
uFlags
Flags associated with the key. These are the same flags that are passed in the high word of the lParam parameter of the WM_KEYDOWN message.

Version 4.71


NMMOUSE

typedef struct tagNMMOUSE {
    NMHDR   hdr;
    DWORD   dwItemSpec;
    DWORD   dwItemData;
    POINT   pt;
} NMMOUSE, FAR* LPNMMOUSE;

Contains information used with mouse notification messages.

hdr
NMHDR structure that contains additional information about this notification.
dwItemSpec
Control-specific item identifier.
dwItemData
Control-specific item data.
pt
POINT structure that contains the screen coordinates of the mouse when the click occurred.

Version 4.71


NMOBJECTNOTIFY

typedef struct tagNMOBJECTNOTIFY {
    NMHDR     hdr;
    int       iItem;
    IID*      piid;
    IUnknown* pObject;
    HRESULT   hResult;
} NMOBJECTNOTIFY, FAR* LPNMOBJECTNOTIFY;

Contains information used with the TBN_GETOBJECT, TCN_GETOBJECT, and PSN_GETOBJECT notification messages.

hdr
NMHDR structure that contains additional information about this notification.
iItem
Control-specific item identifier. This value will comply to item identification standards for the control sending the notification. However, this member is not used with the PSN_GETOBJECT notification message.
piid
Interface identifier of the requested object.
pObject
Address of an object provided by the window processing the notification message. The application processing the notification message sets this member.
hResult
COM success or failure flags. The application processing the notification message sets this member.

Version 4.71


NMTOOLTIPSCREATED

Contains information used with NM_TOOLTIPSCREATED notification messages.

Syntax

typedef struct tagNMTOOLTIPSCREATED {
    NMHDR hdr;
    HWND hwndToolTips;
} NMTOOLTIPSCREATED, * LPNMTOOLTIPSCREATED;

Parameters

hdr
NMHDR structure that contains additional information about this notification.
hwndToolTips
Window handle to the tooltip control created.

Remarks

Version 4.71


Custom Draw

Custom draw is not a common control; it is a service that many common controls provide. Custom draw services allow an application greater flexibility in customizing a control's appearance. Your application can harness custom draw notifications to easily change the font used to display items or manually draw an item without having to do a full-blown owner draw.

About Custom Draw

Using Custom Draw

Custom Draw Reference

About Custom Draw

This section contains general information about custom draw functionality and provides a conceptual overview of how an application can support custom draw.

Currently, the following controls support custom draw functionality:

  • Header controls
  • List view controls
  • Rebar controls
  • Toolbar controls
  • Tooltip controls
  • Trackbar controls
  • Tree view controls

Note Custom draw is implemented in version 4.70 and later of Comctl32.dll.

About Custom Draw Notification Messages

All common controls that support custom draw send NM_CUSTOMDRAW notification messages at specific points during drawing operations. These notifications describe drawing operations that apply to the entire control as well as drawing operations specific to items within the control. Like many notification messages, NM_CUSTOMDRAW notifications are sent as WM_NOTIFY messages.

The lParam parameter of a custom draw notification message will be the address of an NMCUSTOMDRAW structure or a control-specific structure that contains an NMCUSTOMDRAW structure as its first member. The following table illustrates the relationship between the controls and the structures they use.
Structure | Used by
NMCUSTOMDRAW | Rebar, trackbar, and header controls
NMLVCUSTOMDRAW | List view controls
NMTBCUSTOMDRAW | Toolbar controls
NMTTCUSTOMDRAW | Tooltip controls
NMTVCUSTOMDRAW | Tree view controls

Paint Cycles, Drawing Stages, and Notification Messages

Like all Microsoft® Windows® applications, common controls periodically paint and erase themselves based on messages received from the system or other applications. The process of a control painting or erasing itself is called a paint cycle. Controls that support custom draw send NM_CUSTOMDRAW notification messages periodically through each paint cycle. This notification message is accompanied by an NMCUSTOMDRAW structure or another structure that contains an NMCUSTOMDRAW structure as its first member.

One piece of information that the NMCUSTOMDRAW structure contains is the current stage of the paint cycle. This is referred to as the draw stage and is represented by the value in the structure's dwDrawStage member. A control informs its parent about four basic draw stages. These basic, or global, draw stages are represented in the structure by the following flag values (defined in Commctrl.h).
Global draw stage values
CDDS_PREPAINT | Before the paint cycle begins.
CDDS_POSTPAINT | After the paint cycle is complete.
CDDS_PREERASE | Before the erase cycle begins.
CDDS_POSTERASE | After the erase cycle is complete.

Each of the preceding values can be combined with the CDDS_ITEM flag to specify draw stages specific to items. For convenience, Commctrl.h contains the following item-specific values.
Item-specific draw stage values
CDDS_ITEMPREPAINT | Before an item is drawn.
CDDS_ITEMPOSTPAINT | After an item has been drawn.
CDDS_ITEMPREERASE | Before an item is erased.
CDDS_ITEMPOSTERASE | After an item has been erased.

Your application must process the NM_CUSTOMDRAW notification message and then return a specific value that informs the control what it must do. See the following sections for more information about these return values.

Taking Advantage of Custom Draw Services

The key to harnessing custom draw functionality is in responding to the NM_CUSTOMDRAW notification messages that a control sends. The return values your application sends in response to these notifications determine the control's behavior for that paint cycle.

This section contains information about how your application can use NM_CUSTOMDRAW notification return values to determine the control's behavior. Details are broken into the following topics:

  • Responding to the prepaint notification
  • Requesting item-specific notifications
  • Drawing the item yourself
  • Changing fonts and colors

Responding to the prepaint notification

At the beginning of each paint cycle, the control sends the NM_CUSTOMDRAW notification message, specifying the CDDS_PREPAINT value in the dwDrawStage member of the accompanying NMCUSTOMDRAW structure. The value that your application returns to this first notification dictates how and when the control sends subsequent custom draw notifications for the rest of that paint cycle. Your application can return a combination of the following flags in response to the first notification.
Return value | Effect
CDRF_DODEFAULT | The control will draw itself. It will not send additional NM_CUSTOMDRAW notifications for this paint cycle. This flag cannot be used with any other flag.
CDRF_NOTIFYITEMDRAW | The control will notify the parent of any item-specific drawing operations. It will send NM_CUSTOMDRAW notification messages before and after it draws items.
CDRF_NOTIFYPOSTPAINT | The control will send an NM_CUSTOMDRAW notification when the painting cycle for the entire control is complete.
CDRF_SKIPDEFAULT | The control will not perform any painting at all.

Requesting item-specific notifications

If your application returns CDRF_NOTIFYITEMDRAW to the initial prepaint custom draw notification, the control will send notifications for each item it draws during that paint cycle. These item-specific notifications will have the CDDS_ITEMPREPAINT value in the dwDrawStage member of the accompanying NMCUSTOMDRAW structure. You can request that the control send another notification when it is finished drawing the item by returning CDRF_NOTIFYPOSTPAINT to these item-specific notifications. Otherwise, return CDRF_DODEFAULT and the control will not notify the parent window until it starts to draw the next item.

Drawing the item yourself

If your application draws the entire item, return CDRF_SKIPDEFAULT. This allows the control to skip items that it does not need to draw, thereby decreasing system overhead. Keep in mind that returning this value means the control will not draw any portion of the item.

Changing fonts and colors

Your application can use custom draw to change an item's font. Simply select the HFONT you want into the device context specified by the hdc member of the NMCUSTOMDRAW structure associated with the custom draw notification. Since the font you select might have different metrics than the default font, make sure you include the CDRF_NEWFONT bit in the return value for the notification message. For more information on using this functionality, see the sample code in Using Custom Draw. The font that your application specifies is used to display that item when it is not selected. Custom draw does not allow you to change the font attributes for selected items.

To change text colors for all controls that support custom draw except for the list view and tree view, simply set the desired text and background colors in the device context supplied in the custom draw notification structure with the SetTextColor and SetBkColor functions. To modify the text colors in the list view or tree view, you need to place the desired color values in the clrText and clrTextBk members of the NMLVCUSTOMDRAW or NMTVCUSTOMDRAW structure.

Using Custom Draw

The following application-defined function processes custom draw notification messages sent by a child list view control. Upon receiving the prepaint notification (CDDS_PREPAINT), the function requests item-specific notifications by returning CDRF_NOTIFYITEMDRAW. When it receives the subsequent item-specific notifications, it selects a previously created font into the provided device context and specifies new colors before returning CDRF_NEWFONT.

LRESULT DoNotify(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
   LPNMLISTVIEW  pnm    = (LPNMLISTVIEW)lParam;

   switch (pnm->hdr.code){
      case NM_CUSTOMDRAW:{
         LPNMLVCUSTOMDRAW  lplvcd = (LPNMLVCUSTOMDRAW)lParam;

         /*
         CDDS_PREPAINT is at the beginning of the paint cycle. You
         implement custom draw by returning the proper value. In this
         case, we're requesting item-specific notifications.
         */
         if(lplvcd->nmcd.dwDrawStage == CDDS_PREPAINT)
            // Request prepaint notifications for each item.
            return CDRF_NOTIFYITEMDRAW;

         /*
         Because we returned CDRF_NOTIFYITEMDRAW in response to
         CDDS_PREPAINT, CDDS_ITEMPREPAINT is sent when the control is
         about to paint an item.
         */
         if(lplvcd->nmcd.dwDrawStage == CDDS_ITEMPREPAINT){
            /*
            To change the font, select the desired font into the
            provided HDC. We're changing the font for every third item
            in the control, starting with item zero.
            */
            if(!(lplvcd->nmcd.dwItemSpec % 3))
               SelectObject(lplvcd->nmcd.hdc, g_hNewFont);
            else
               return(CDRF_DODEFAULT);

            /*
            To change the text and background colors in a list view
            control, set the clrText and clrTextBk members of the
            NMLVCUSTOMDRAW structure to the desired color.

            This differs from most other controls that support
            CustomDraw. To change the text and background colors for
            the others, call SetTextColor and SetBkColor on the provided HDC.
            */
            lplvcd->clrText = RGB(150, 75, 150);
            lplvcd->clrTextBk = RGB(255,255,255);

            /*
            We changed the font, so we're returning CDRF_NEWFONT. This
            tells the control to recalculate the extent of the text.
            */
            return CDRF_NEWFONT;
            }
         }

      default:
         break;
   }

   return 0;
}


Custom Draw Reference

This section contains information about the API elements used for performing custom draw.

Notifications
NM_CUSTOMDRAW
NM_CUSTOMDRAW (header)
NM_CUSTOMDRAW (list view)
NM_CUSTOMDRAW (rebar)
NM_CUSTOMDRAW (toolbar)
NM_CUSTOMDRAW (tooltip)
NM_CUSTOMDRAW (trackbar)
NM_CUSTOMDRAW (tree view)

Structures
NMCUSTOMDRAW
NMLVCUSTOMDRAW
NMTBCUSTOMDRAW
NMTTCUSTOMDRAW
NMTVCUSTOMDRAW


Notification Messages

This section contains information about the notification message sent by controls that support custom draw.

NM_CUSTOMDRAW


NM_CUSTOMDRAW

NM_CUSTOMDRAW
#ifdef LIST_VIEW_CUSTOM_DRAW
    lpNMCustomDraw = (LPNMLVCUSTOMDRAW) lParam;
#elif TOOL_TIPS_CUSTOM_DRAW
    lpNMCustomDraw = (LPNMTTCUSTOMDRAW) lParam;
#elif TREE_VIEW_CUSTOM_DRAW
    lpNMCustomDraw = (LPNMTVCUSTOMDRAW) lParam;
#elif TOOL_BAR_CUSTOM_DRAW
    lpNMCustomDraw = (LPNMTBCUSTOMDRAW) lParam;
#else
    lpNMCustomDraw = (LPNMCUSTOMDRAW) lParam;
#endif

Sent by some common controls to notify their parent windows about drawing operations. This notification is sent in the form of a WM_NOTIFY message.

Currently, the following controls support custom draw functionality: header, list view, rebar, toolbar, tooltip, trackbar, and tree view.

  • The value your application can return depends on the current drawing stage. The dwDrawStage member of the associated NMCUSTOMDRAW structure holds a value that specifies the drawing stage. You must return one of the following values.

    When dwDrawStage equals CDDS_PREPAINT:
    CDRF_DODEFAULT
    The control will draw itself. It will not send any additional NM_CUSTOMDRAW messages for this paint cycle.
    CDRF_NOTIFYITEMDRAW
    The control will notify the parent of any item-related drawing operations. It will send NM_CUSTOMDRAW notification messages before and after drawing items.
    CDRF_NOTIFYPOSTERASE
    The control will notify the parent after erasing an item.
    CDRF_NOTIFYPOSTPAINT
    The control will notify the parent after painting an item.
    CDRF_NOTIFYSUBITEMDRAW
    Version 4.71. The control will notify the parent when a list view subitem is being drawn.

    When dwDrawStage equals CDDS_ITEMPREPAINT:
    CDRF_NEWFONT
    Your application specified a new font for the item; the control will use the new font. For more information on changing fonts, see Changing fonts and colors.
    CDRF_SKIPDEFAULT
    Your application drew the item manually. The control will not draw the item.

lpNMCustomDraw
Address of a custom draw-related structure that contains information about the drawing operation. List view controls use the NMLVCUSTOMDRAW structure, tooltip controls use the NMTTCUSTOMDRAW structure, tree view controls use the NMTVCUSTOMDRAW structure, toolbar controls use the NMTBCUSTOMDRAW structure, and all other supported controls use the NMCUSTOMDRAW structure.

Version 4.70

See also Using Custom Draw


Custom Draw Structures

This section contains information about the structures used by controls that support custom draw.

NMCUSTOMDRAW


NMCUSTOMDRAW

typedef struct tagNMCUSTOMDRAWINFO {
    NMHDR  hdr;
    DWORD  dwDrawStage;
    HDC    hdc;
    RECT   rc;
    DWORD  dwItemSpec;
    UINT   uItemState;
    LPARAM lItemlParam;
} NMCUSTOMDRAW, FAR * LPNMCUSTOMDRAW;

Contains information specific to an NM_CUSTOMDRAW notification message.

hdr
NMHDR structure that contains information about this notification message.
dwDrawStage
Current drawing stage. This value is one of the following.
Global draw stage values
CDDS_POSTERASE | After the erasing cycle is complete.
CDDS_POSTPAINT | After the painting cycle is complete.
CDDS_PREERASE | Before the erasing cycle begins.
CDDS_PREPAINT | Before the painting cycle begins.
Item-specific draw stage values
CDDS_ITEM | Indicates that the dwItemSpec, uItemState, and lItemlParam members are valid.
CDDS_ITEMPOSTERASE | After an item has been erased.
CDDS_ITEMPOSTPAINT | After an item has been drawn.
CDDS_ITEMPREERASE | Before an item is erased.
CDDS_ITEMPREPAINT | Before an item is drawn.
CDDS_SUBITEM | Version 4.71. Flag combined with CDDS_ITEMPREPAINT or CDDS_ITEMPOSTPAINT if a subitem is being drawn. This will only be set if CDRF_NOTIFYSUBITEMDRAW is returned from CDDS_PREPAINT.
hdc
Handle to the control's device context. Use this HDC to perform any GDI functions.
rc
RECT structure that describes the bounding rectangle of the area being drawn.
dwItemSpec
Item number. What is contained in this member will depend on the type of control that is sending the notification. See the NM_CUSTOMDRAW notification reference for the specific control to determine what, if anything, is contained in this member.
uItemState
Current item state. This value is a combination of the following:
CDIS_CHECKED | The item is checked.
CDIS_DEFAULT | The item is in its default state.
CDIS_DISABLED | The item is disabled.
CDIS_FOCUS | The item is in focus.
CDIS_GRAYED | The item is grayed.
CDIS_HOT | The item is currently under the pointer ("hot").
CDIS_INDETERMINATE | The item is in an indeterminate state.
CDIS_MARKED | The item is marked. The meaning of this is up to the implementation.
CDIS_SELECTED | The item is selected.
lItemlParam
Application-defined item data.

Version 4.70


Animation Control Reference

This section contains information about the programming elements used with animation controls.

Animation Control Styles

Messages
ACM_OPEN
ACM_PLAY
ACM_STOP

Macros
Animate_Create
Animate_Close
Animate_Open
Animate_OpenEx
Animate_Play
Animate_Seek
Animate_Stop

Notifications
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 AVI clip is opened.
ACS_CENTER | Centers the animation in the animation control's window.
ACS_TIMER | By default, the control creates a thread to play the AVI clip. If you set this flag, the control plays the clip without creating a thread; internally the control uses a Win32 timer to synchronize playback.
ACS_TRANSPARENT | Draws the animation using a transparent background rather than the background color specified in the animation clip.


Animation Control Messages

Following are the messages that an application sends to an animation control.

ACM_OPEN

ACM_PLAY

ACM_STOP


ACM_OPEN

ACM_OPEN
#if (_WIN32_IE >= 0x0400)
    wParam = (WPARAM)(HINSTANCE)hinst;
#else
    wParam = 0;
#endif
    lParam = (LPARAM) (LPSTR) lpszName;

Opens an AVI clip and displays its first frame in an animation control. You can send this message explicitly or use the Animate_Open or Animate_OpenEx macro.

  • Returns nonzero if successful, or zero otherwise.
hinst
Version 4.71. Instance handle to the module that the resource should be loaded from. If this value is NULL, the resource is loaded from the module that created the animation control.
lpszName
Address of 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. The control loads the AVI resource from the module specified by the instance handle passed to the CreateWindow function, the Animate_Create macro, or the dialog box creation function that created the control. In Version 4.71 and later, the resource is loaded from the module specified by hinst.

The AVI file or resource specified by lpszName must not contain audio.

If this parameter is NULL, the system closes the AVI file that was previously opened for the specified animation control, if any.

You can only open silent AVI clips. ACM_OPEN and Animate_Open fail if lpszSource specifies an AVI clip that contains sound.

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 and Animate_Close macros are defined in Commctrl.h.


ACM_PLAY

ACM_PLAY
    wParam = (WPARAM) (UINT) cRepeat;
    lParam = (LPARAM) MAKELONG(wFrom, wTo);

Plays an AVI clip in an animation control. The control plays the clip in the background while the thread continues executing. You can send this message explicitly or by using the Animate_Play macro.

  • Returns nonzero if successful, or zero otherwise.
cRepeat
Number of times to replay the AVI clip. A value of -1 means replay the clip indefinitely.
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.

You can use Animate_Seek to direct the animation control to display a particular frame of the AVI clip.

The Animate_Play and Animate_Seek macros are defined in Commctrl.h.


ACM_STOP

ACM_STOP
    wParam = 0;
    lParam = 0;

Stops playing an AVI clip in an animation control. You can send this message explicitly or by using the Animate_Stop macro.

  • Returns nonzero if successful, or zero otherwise.


Animation Control Macros

Following are the macros that an application can use with animation controls.

Animate_Close

Animate_Create

Animate_Open

Animate_OpenEx

Animate_Play

Animate_Seek

Animate_Stop


Animate_Close

BOOL Animate_Close(
    HWND hwnd
);

Closes an AVI clip and displays its first frame in an animation control. You can use this macro or send the ACM_OPEN message explicitly.

  • Always returns FALSE.
hwnd
Handle to the animation control.

You can use Animate_Close to close an AVI file or AVI resource that was previously opened for the specified animation control.

The Animate_Close macro is defined in Commctrl.h.

See also Animate_Open, MAKEINTRESOURCE


Animate_Create

HWND Animate_Create(
    HWND hwndP,
    UINT id,
    DWORD dwStyle,
    HINSTANCE hInstance
);

Creates an animation control. Animate_Create calls the CreateWindow function to create the animation control.

  • Returns the handle to the animation control.
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.

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.


Animate_Open

BOOL Animate_Open(
    HWND hwnd,
    LPSTR lpszName
);

Opens an AVI clip and displays its first frame in an animation control. You can use this macro or send the ACM_OPEN message explicitly.

  • Returns nonzero if successful, or zero otherwise.
hwnd
Handle to the animation control.
lpszName
Address of 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. The control loads an AVI resource from the module specified by the instance handle passed to the CreateWindow function, the Animate_Create macro, or the dialog box creation function that created the control.

The AVI file or resource specified by lpszName must not contain audio.

If this parameter is NULL, the system closes the AVI file that was previously opened for the specified animation control, if any.

You can only open silent AVI clips. ACM_OPEN and Animate_Open will fail if lpszSource specifies an AVI clip that contains sound.

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 in Commctrl.h.


Animate_OpenEx

BOOL Animate_OpenEx(
    HWND hwnd,
    HINSTANCE hinst,
    LPSTR lpszName
);

Opens an AVI clip from a resource in a specified module and displays its first frame in an animation control. You can use this macro or send the ACM_OPEN message explicitly.

  • Returns nonzero if successful, or zero otherwise.
hwnd
Handle to the animation control.
hinst
Instance handle to the module that the resource should be loaded from. If this value is NULL, the resource is loaded from the module that created the animation control.
lpszName
Address of 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. The control loads the AVI resource from the module specified by hinst.

The AVI file or resource specified by lpszName must not contain audio.

If this parameter is NULL, the system closes the AVI file that was previously opened for the specified animation control, if any.

You can only open silent AVI clips. ACM_OPEN and Animate_Open will fail if lpszSource specifies an AVI clip that contains sound.

You can use Animate_Close to close an AVI file or AVI resource that was previously opened for the specified animation control.

The Animate_OpenEx macro is defined in Commctrl.h.

Version 4.71


Animate_Play

BOOL Animate_Play(
    HWND hwndAnim,
    UINT wFrom,
    UINT wTo,
    UINT cRepeat
);

Plays an AVI clip in an animation control. The control plays the clip in the background while the thread continues executing. You can use this macro or send the ACM_PLAY message explicitly.

  • Returns nonzero if successful, or zero otherwise.
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.
cRepeat
Number of times to replay the AVI clip. A value of -1 means replay the clip indefinitely.

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 in Commctrl.h.


Animate_Seek

BOOL Animate_Seek(
    HWND hwndAnim,
    UINT wFrame
);

Directs an animation control to display a particular frame of an AVI clip. The control displays the clip in the background while the thread continues executing. You can use this macro or send the ACM_PLAY message explicitly.

  • Returns nonzero if successful, or zero otherwise.
hwndAnim
Handle to the animation control in which to display the AVI frame.
wFrame
Zero-based index of the frame to display.

The Animate_Seek macro is defined in Commctrl.h.

See also Animate_Play


Animate_Stop

BOOL Animate_Stop(
    HWND hwnd
);

Stops playing an AVI clip in an animation control. You can use this macro or send the ACM_STOP message explicitly.

  • Returns nonzero if successful, or zero otherwise.
hwnd
Handle to the animation control.

The Animate_Stop macro is defined in Commctrl.h.


Animation Control Notifications

Following are the notification messages that the animation control sends to an application.

ACN_START

ACN_STOP


ACN_START

ACN_START

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.

  • The return value is ignored.


ACN_STOP

ACN_STOP

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.

  • The return value is ignored.


ComboBoxEx Controls

A ComboBoxEx control is an extension of the combo box control that provides native support for item images. To make item images easily accessible, the control provides image list support. By using this control, you can provide the functionality of a combo box without having to manually draw item graphics.

About ComboBoxEx Controls

Using ComboBoxEx Controls

ComboBoxEx Control Reference

About ComboBoxEx Controls

Effectively, a ComboBoxEx control creates a child combo box and performs owner draw tasks for you based on an assigned image list. Therefore, the CBS_OWNERDRAWFIXED style is implied and you need not use it when creating the control. Because image lists are used to provide item graphics, the CBS_OWNERDRAWVARIABLE style cannot be used.

A ComboBoxEx control must be initialized by calling the InitCommonControlsEx function, specifying ICC_USEREX_CLASSES in the accompanying INITCOMMONCONTROLSEX structure.

You can create a ComboBoxEx control by using the CreateWindowEx function and specifying WC_COMBOBOXEX as the window class. The class is registered when the InitCommonControlsEx function is called as explained above.

ComboBoxEx controls are created without a default image list. To use item images, you must create an image list for the ComboBoxEx control and assign it to the control using the CBEM_SETIMAGELIST message. If you do not assign an image list to the ComboBoxEx control, the control displays item text only.

ComboBoxEx Control Styles

ComboBoxEx controls only support the following styles. All other styles are ignored by the controls.

  • CBS_SIMPLE
  • CBS_DROPDOWN
  • CBS_DROPDOWNLIST
  • WS_CHILD

Because the ComboBoxEx control performs owner draw tasks for you based on an assigned image list, the CBS_OWNERDRAWFIXED style is implied; you need not use it when creating the control. Because image lists are used to provide item graphics, the CBS_OWNERDRAWVARIABLE style cannot be used. The ComboBoxEx control also supports extended styles that provide additional features.

ComboBoxEx Control Items

ComboBoxEx controls maintain item information using a COMBOBOXEXITEM structure. This structure includes members for item indexes, image indexes (normal, selection state, and overlay), indentation values, text strings, and item-specific values.

The ComboBoxEx control provides easy access to and manipulation of items through messaging. To add or delete an item, send the CBEM_INSERTITEM or CBEM_DELETEITEM message. You can modify items currently in the control using the CBEM_SETITEM message.

Callback Items

ComboBoxEx controls support callback item attributes. You can specify an item as a callback item when you add it to the control using CBEM_INSERTITEM. When you assign values to an item's COMBOBOXEXITEM structure, you must specify the appropriate callback flag values. The following are COMBOBOXEXITEM structure members and their corresponding callback flag values.
Member | Callback value
pszText | LPSTR_TEXTCALLBACK
iImage | I_IMAGECALLBACK
iSelectedImage | I_IMAGECALLBACK
iOverlay | I_IMAGECALLBACK
iIndent | I_INDENTCALLBACK

The control will request information about callback items by sending CBEN_GETDISPINFO notification messages. This notification is sent in the form of a WM_NOTIFY message. When your application processes this message, it must provide the requested information for the control. If you set the mask member of the accompanying COMBOBOXEXITEM structure to CBEIF_DI_SETITEM, the control will store the item data and will not request it again.

ComboBoxEx Control Image Lists

If you want a ComboBoxEx control to display icons with items, you must provide an image list. ComboBoxEx controls support up to three images for an item—one for its selected state, one for its nonselected state, and one for an overlay image. Assign an existing image list to a ComboBoxEx control using the CBEM_SETIMAGELIST message.

The COMBOBOXEXITEM structure contains members that represent the image indexes for each image list (selected, unselected, and overlay). For each item, set these members to display the desired images. It is not necessary to specify image indexes for each type of image. You can mix and match image types as you like, but always set the mask member of the COMBOBOXEXITEM structure to indicate which members are being used. The control ignores members that have not been flagged as valid.

About ComboBoxEx Control Notification Messages

A ComboBoxEx control sends notification messages to report changes within itself or to request callback item information. The parent of the control receives all WM_COMMAND messages from the combo box contained within the ComboBoxEx control. The ComboBoxEx control sends its own notifications using WM_NOTIFY messages. As a result, the control's owner must be prepared to process both forms of notification messages.

Following are the ComboBoxEx-specific notification messages.
Notification | Description
CBEN_BEGINEDIT | Signals that the user has activated the drop-down list or clicked in the control's edit box.
CBEN_ENDEDIT | Signals that the user has selected an item from the drop-down list or has concluded an edit operation within the edit box.
CBEN_DELETEITEM | Reports that an item was deleted.
CBEN_GETDISPINFO | Requests information about an item's attributes.
CBEN_INSERTITEM | Signals that an item was inserted in the control.

ComboBoxEx Control Message Forwarding

The following are the standard combo box messages that a ComboBoxEx control forwards to its child combo box. Some of these messages may be processed by the ComboBoxEx control either before or after the message has been forwarded.

  • CB_DELETESTRING
  • CB_FINDSTRINGEXACT
  • CB_GETCOUNT
  • CB_GETCURSEL
  • CB_GETDROPPEDCONTROLRECT
  • CB_GETDROPPEDSTATE
  • CB_GETITEMDATA
  • CB_GETITEMHEIGHT
  • CB_GETLBTEXT
  • CB_GETLBTEXTLEN
  • CB_GETEXTENDEDUI
  • CB_LIMITTEXT
  • CB_RESETCONTENT
  • CB_SELECTSTRING
  • CB_SETCURSEL
  • CB_SETDROPPEDWIDTH
  • CB_SETEXTENDEDUI
  • CB_SETITEMDATA
  • CB_SETITEMHEIGHT
  • CB_SHOWDROPDOWN

Following are the windows messages that a ComboBoxEx control forwards to its parent window:

  • WM_COMMAND (This includes all of the CBN_ notifications.)
  • WM_NOTIFY

Using ComboBoxEx Controls

This section contains sample code and information about the following topics related to ComboBoxEx controls:

  • Creating a ComboBoxEx Control
  • Preparing ComboBoxEx Items and Images
  • Supporting Callback Items
  • Processing ComboBoxEx Notifications

Creating a ComboBoxEx Control

To create a ComboBoxEx control, call the CreateWindowEx function, using WC_COMBOBOXEX as the window class. You must first register the window class by calling the InitCommonControlsEx function, while specifying the ICC_USEREX_CLASSES bit in the accompanying INITCOMMONCONTROLSEX structure.

The following application-defined function creates a ComboBoxEx control with the CBS_DROPDOWN style in the main window.

// CreateComboEx - Registers the ComboBoxEx window class and creates
// a ComboBoxEx control in the client area of the main window.
//
// g_hwndMain - A handle to the main window.
// g_hinst    - A handle to the program instance.

HWND WINAPI CreateComboEx(void)
{
    HWND hwnd;
    INITCOMMONCONTROLSEX icex;

    icex.dwSize = sizeof(INITCOMMONCONTROLSEX);
    icex.dwICC = ICC_USEREX_CLASSES;

    InitCommonControlsEx(&icex);

    hwnd = CreateWindowEx(0, WC_COMBOBOXEX, NULL,
                    WS_BORDER | WS_VISIBLE |
                    WS_CHILD | CBS_DROPDOWN,
                    // No size yet--resize after setting image list.
                    0,      // Vertical position of Combobox
                    0,      // Horizontal position of Combobox
                    0,      // Sets the width of Combobox
                    100,    // Sets the height of Combobox
                    g_hwndMain,
                    NULL,
                    g_hinst,
                    NULL);
    return (hwnd);
}

Preparing ComboBoxEx Items and Images

To add an item to a ComboBoxEx control, first define a COMBOBOXEXITEM structure. Set the mask member of the structure to indicate which members you want the control to use. Set the specified members of the structure to the values you want, and then send the CBEM_INSERTITEM message to add the item to the control.

The following application-defined function adds 15 items to an existing ComboBoxEx control. Note that the mask member of the COMBOBOXEXITEM structure includes flag values that tell the control to display images for each item.

#define MAX_ITEMS 15

// AddItems - Uses the CBEM_INSERTITEM message to add items to an
// existing ComboBoxEx control.

BOOL WINAPI AddItems(HWND hwndCB)
{
    //  Declare and init locals.
    COMBOBOXEXITEM cbei;
    int iCnt;

    typedef struct {
        int iImage;
        int iSelectedImage;
        int iIndent;
        LPTSTR pszText;
    } ITEMINFO, *PITEMINFO;

    ITEMINFO IInf[] = {
        { 0, 3,  0, "first"},
        { 1, 4,  1, "second"},
        { 2, 5,  2, "third"},
        { 0, 3,  0, "fourth"},
        { 1, 4,  1, "fifth"},
        { 2, 5,  2, "sixth"},
        { 0, 3,  0, "seventh"},
        { 1, 4,  1, "eighth"},
        { 2, 5,  2, "ninth"},
        { 0, 3,  0, "tenth"},
        { 1, 4,  1, "eleventh"},
        { 2, 5,  2, "twelfth"},
        { 0, 3,  0, "thirteenth"},
        { 1, 4,  1, "fourteenth"},
        { 2, 5,  2, "fifteenth"}
    };

    // Set the mask common to all items.
    cbei.mask = CBEIF_TEXT | CBEIF_INDENT |
                CBEIF_IMAGE| CBEIF_SELECTEDIMAGE;

    for(iCnt=0;iCnt<MAX_ITEMS;iCnt++){
        // Initialize the COMBOBOXEXITEM struct.
        cbei.iItem          = iCnt;
        cbei.pszText        = IInf[iCnt].pszText;
        cbei.cchTextMax     = sizeof(IInf[iCnt].pszText);
        cbei.iImage         = IInf[iCnt].iImage;
        cbei.iSelectedImage = IInf[iCnt].iSelectedImage;
        cbei.iIndent        = IInf[iCnt].iIndent;

        // Tell the ComboBoxEx to add the item. Return FALSE if
        // this fails.
        if(SendMessage(hwndCB,CBEM_INSERTITEM,0,(LPARAM)&cbei) == -1)
            return FALSE;
    }

    // Assign the existing image list to the ComboBoxEx control
    // and return TRUE.
    SendMessage(hwndCB,CBEM_SETIMAGELIST,0,(LPARAM)g_himl);

    // Set size of control to make sure it's displayed correctly now
    // that the image list is set.
    SetWindowPos(hwndCB,NULL,20,20,250,120,SWP_NOACTIVATE);

    return TRUE;
}

Supporting Callback Items

If your application is going to use callback items in a ComboBoxEx control, it must be prepared to handle the CBEN_GETDISPINFO notification message. A ComboBoxEx control sends this notification whenever it needs the owner to provide specific item information. For more information about callback items, see Callback Items.

The following application-defined function processes CBEN_GETDISPINFO by providing attributes for a given item. Note that it sets the mask member of the incoming COMBOBOXEXITEM structure to CBEIF_DI_SETITEM. Setting mask to this value makes the control retain the item information so it will not need to request the information again.

// DoItemCallback - Processes CBEN_GETDISPINFO by providing item
// attributes for a given callback item.

void WINAPI DoItemCallback(PNMCOMBOBOXEX pNMCBex)
{
    DWORD dwMask = pNMCBex->ceItem.mask;

    if(dwMask & CBEIF_TEXT)
        ;// Provide item text.

    if(dwMask & CBEIF_IMAGE)
        ;// Provide an item image index.

    /*
     * Provide other callback information as desired.
     */

    // Make the ComboBoxEx control hold onto the item information.
    pNMCBex->ceItem.mask = CBEIF_DI_SETITEM;
}

Processing ComboBoxEx Notifications

A ComboBoxEx control notifies its parent window of events by sending WM_NOTIFY messages. Because the control uses a child combo box, it forwards all WM_COMMAND notification messages it receives to the parent window to be processed. Therefore, your application must be prepared to process WM_NOTIFY messages from the ComboBoxEx and WM_COMMAND messages forwarded from the ComboBoxEx's child combo box control.

The example in this section handles the WM_NOTIFY and WM_COMMAND messages from a ComboBoxEx control by calling a corresponding application-defined function to process them.

LRESULT CALLBACK WndProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch(msg){
        case WM_COMMAND:
            // If this is an "old style" combo box notification, handle it.
            if((HWND)lParam == g_hwndCB)
                DoOldNotify(hwnd,  wParam);
            break;

        case WM_NOTIFY:
            return (DoCBEXNotify(hwnd, lParam));

        case WM_PAINT:
            hdc = BeginPaint(hwnd, &ps);
            EndPaint(hwnd, &ps);
            break;

        case WM_DESTROY:
            PostQuitMessage(0);
            break;

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


ComboBoxEx Control Reference

This section contains information about the programming elements used with ComboBoxEx controls.

ComboBoxEx control extended styles

Messages
CBEM_DELETEITEM
CBEM_GETCOMBOCONTROL
CBEM_GETEDITCONTROL
CBEM_GETEXTENDEDSTYLE
CBEM_GETIMAGELIST
CBEM_GETITEM
CBEM_GETUNICODEFORMAT
CBEM_HASEDITCHANGED
CBEM_INSERTITEM
CBEM_SETEXTENDEDSTYLE
CBEM_SETIMAGELIST
CBEM_SETITEM
CBEM_SETUNICODEFORMAT

Notifications
CBEN_BEGINEDIT
CBEN_DELETEITEM
CBEN_DRAGBEGIN
CBEN_ENDEDIT
CBEN_GETDISPINFO
CBEN_INSERTITEM
NM_SETCURSOR (ComboBoxEx)

Structures
COMBOBOXEXITEM
NMCBEDRAGBEGIN
NMCBEENDEDIT
NMCOMBOBOXEX


ComboBoxEx control extended styles

ComboBoxEx controls support most standard combo box control styles. Additionally, ComboBoxEx controls support the following extended styles, which you can set and retrieve by using CBEM_SETEXTENDEDSTYLE and CBEM_GETEXTENDEDSTYLE messages:
CBES_EX_CASESENSITIVE | String searches in the list will be case sensitive. This includes searches as a result of text being typed in the edit box and the CB_FINDSTRINGEXACT message.
CBES_EX_NOEDITIMAGE | The edit box will not display an item image.
CBES_EX_NOEDITIMAGEINDENT | The edit box will not indent text to make room for an item image.
CBES_EX_NOSIZELIMIT | Allows the ComboBoxEx control to be vertically sized smaller than its contained combo box control. If the ComboBoxEx is sized smaller than the combo box, the combo box will be clipped.
CBES_EX_PATHWORDBREAKPROC | Windows NT only. The edit box will use the slash (/), backslash (\), and period (.) characters as word delimiters. This makes keyboard shortcuts for word-by-word cursor movement (CTRL+ARROW) effective in path names and URLs.


ComboBoxEx Control Messages

This section contains information about the messages used with ComboBoxEx controls.

CBEM_DELETEITEM

CBEM_GETCOMBOCONTROL

CBEM_GETEDITCONTROL

CBEM_GETEXTENDEDSTYLE

CBEM_GETIMAGELIST

CBEM_GETITEM

CBEM_GETUNICODEFORMAT

CBEM_HASEDITCHANGED

CBEM_INSERTITEM

CBEM_SETEXTENDEDSTYLE

CBEM_SETIMAGELIST

CBEM_SETITEM

CBEM_SETUNICODEFORMAT


CBEM_DELETEITEM

CBEM_DELETEITEM
    wParam = (WPARAM)(int) iIndex;
    lParam = 0;

Removes an item from a ComboBoxEx control.

  • Returns an INT value that represents the number of items remaining in the control. If iIndex is invalid, the message returns CB_ERR.
iIndex
Zero-based index of the item to be removed.

This message maps to the combo box control message CB_DELETESTRING.


CBEM_GETCOMBOCONTROL

CBEM_GETCOMBOCONTROL
    wParam = 0;
    lParam = 0;

Retrieves the handle to the child combo box control.

  • Returns the handle to the combo box control within the ComboBoxEx control.


CBEM_GETEDITCONTROL

CBEM_GETEDITCONTROL
    wParam = 0;
    lParam = 0;

Retrieves the handle to the edit control portion of a ComboBoxEx control. A ComboBoxEx control uses an edit box when it is set to the CBS_DROPDOWN style.

  • Returns the handle to the edit control within the ComboBoxEx control if it uses the CBS_DROPDOWN style. Otherwise, the message returns NULL.


CBEM_GETEXTENDEDSTYLE

CBEM_GETEXTENDEDSTYLE
    wParam = 0;
    lParam = 0;

Retrieves the extended styles that are in use for a ComboBoxEx control.

  • Returns a DWORD value that contains the ComboBoxEx control extended styles in use for the control.


CBEM_GETIMAGELIST

CBEM_GETIMAGELIST
    wParam = 0;
    lParam = 0;

Retrieves the handle to an image list assigned to a ComboBoxEx control.

  • Returns the handle to the image list assigned to the control if successful, or NULL otherwise.


CBEM_GETITEM

CBEM_GETITEM
    wParam = 0;
    lParam = (LPARAM)(PCOMBOBOXEXITEM) pCBItem;

Retrieves item information for a given ComboBoxEx item.

  • Returns nonzero if successful, or zero otherwise.
pCBItem
Address of a COMBOBOXEXITEM structure that will receive the item information. When the message is sent, the iItem and mask members of the structure must be set to indicate the index of the target item and the type of information to be retrieved. Setting the iItem member to -1 will retrieve the item displayed in the edit control.


CBEM_GETUNICODEFORMAT

CBEM_GETUNICODEFORMAT
    wParam = 0;
    lParam = 0;

Retrieves the UNICODE character format flag for the control.

  • Returns the UNICODE format flag for the control. If this value is nonzero, the control is using UNICODE characters. If this value is zero, the control is using ANSI characters.

See also CBEM_SETUNICODEFORMAT


CBEM_HASEDITCHANGED

CBEM_HASEDITCHANGED
    wParam = 0;
    lParam = 0;

Determines if the user has changed the contents of the ComboBoxEx edit control by typing. A ComboBoxEx control uses an edit box when it is set to the CBS_DROPDOWN style.

  • Returns nonzero if the user has typed in the control's edit box, or zero otherwise.


CBEM_INSERTITEM

CBEM_INSERTITEM
    wParam = 0;
    lParam = (LPARAM)(const COMBOBOXEXITEM FAR *) lpcCBItem;

Inserts a new item in a ComboBoxEx control.

  • Returns the index at which the new item was inserted if successful, or -1 otherwise.
lpcCBItem
Address of a COMBOBOXEXITEM structure that contains information about the item to be inserted. When the message is sent, the iItem member must be set to indicate the zero-based index at which to insert the item. To insert an item at the end of the list, set the iItem member to -1.


CBEM_SETEXTENDEDSTYLE

CBEM_SETEXTENDEDSTYLE
    wParam = (WPARAM)(DWORD) dwExMask;
    lParam = (LPARAM)(DWORD) dwExStyle;

Sets extended styles within a ComboBoxEx control.

  • Returns a DWORD value that contains the extended styles previously used for the control.
dwExMask
A DWORD value that indicates which styles in dwExStyle are to be affected. Only the extended styles in dwExMask will be changed. If this parameter is zero, then all of the styles in dwExStyle will be affected.
dwExStyle
A DWORD value that contains the ComboBoxEx control extended styles to set for the control.

dwExMask allows you to modify one or more extended styles without having to retrieve the existing styles first. For example, if you pass CBES_EX_NOEDITIMAGE for dwExMask and 0 for dwExStyle, the CBES_EX_NOEDITIMAGE style will be cleared, but all other styles will remain the same.


CBEM_SETIMAGELIST

CBEM_SETIMAGELIST
    wParam = 0;
    lParam = (LPARAM)(HIMAGELIST) himl;

Sets an image list for a ComboBoxEx control.

  • Returns the handle to the image list previously associated with the control, or returns NULL if no image list was previously set.
himl
Handle to the image list to be set for the control.

Note The height of images within your image list might change the size requirements of the ComboBoxEx control. It is recommended that you resize the control after sending this message to ensure that it is displayed properly.


CBEM_SETITEM

CBEM_SETITEM
    wParam = 0;
    lParam = (LPARAM) (const COMBOBOXEXITEM FAR *) lpcCBItem;

Sets the attributes for an item in a ComboBoxEx control.

  • Returns nonzero if successful, or zero otherwise.
lpcCBItem
Address of a COMBOBOXEXITEM structure that contains the item information to be set. When the message is sent, the mask member of the structure must be set to indicate which attributes are valid and the iItem member must specify the zero-based index of the item to be modified. Setting the iItem member to -1 will modify the item displayed in the edit control.


CBEM_SETUNICODEFORMAT

CBEM_SETUNICODEFORMAT
    wParam = (WPARAM)(BOOL)fUnicode;
    lParam = 0;

Sets the UNICODE character format flag for the control. This message allows you to change the character set used by the control at run time rather than having to re-create the control.

  • Returns the previous UNICODE format flag for the control.
fUnicode
Determines the character set that is used by the control. If this value is nonzero, the control will use UNICODE characters. If this value is zero, the control will use ANSI characters.

See also CBEM_GETUNICODEFORMAT


ComboBoxEx Control Notification Messages

This section contains information about the notification messages sent by ComboBoxEx controls.

CBEN_BEGINEDIT

CBEN_DELETEITEM

CBEN_DRAGBEGIN

CBEN_ENDEDIT

CBEN_GETDISPINFO

CBEN_INSERTITEM

NM_SETCURSOR (ComboBoxEx)


CBEN_BEGINEDIT

CBEN_BEGINEDIT
    lpnmhdr = (LPNMHDR) lParam;

Sent when the user activates the drop-down list or clicks in the control's edit box. This notification is sent in the form of a WM_NOTIFY message.

  • The application processing this notification must return zero.
lpnmhdr
Address of an NMHDR structure that contains information about the notification.


CBEN_DELETEITEM

CBEN_DELETEITEM
    pCBEx= (PNMCOMBOBOXEX) lParam;

Sent when an item has been deleted. This notification is sent in the form of a WM_NOTIFY message.

  • The application processing this notification must return zero.
pCBEx
Address of an NMCOMBOBOXEX structure that contains information about the notification and the deleted item.


CBEN_DRAGBEGIN

CBEN_DRAGBEGIN
    lpnmdb = (LPNMCBEDRAGBEGIN) lParam;

Sent when the user begins dragging the image of the item displayed in the edit portion of the control. This notification is sent in the form of a WM_NOTIFY message.

  • The return value is ignored.
lpnmdb
Address of a NMCBEDRAGBEGIN structure that contains information about the notification.

If the receiving application implements drag-and-drop functionality from the control, the application will begin the drag-and-drop operation in response to this notification.


CBEN_ENDEDIT

CBEN_ENDEDIT
    pnmEditInfo = (PNMCBEENDEDIT) lParam;

Sent when the user has concluded an operation within the edit box or has selected an item from the control's drop-down list. This notification is sent in the form of a WM_NOTIFY message.

  • To accept the notification and allow the control to display the selected item, return FALSE. To abort the edit selection, return TRUE.
pnmEditInfo
Address of an NMCBEENDEDIT structure that contains information about how the user concluded the edit operation.


CBEN_GETDISPINFO

CBEN_GETDISPINFO
    pDispInfo = (PNMCOMBOBOXEX) lParam;

Sent to retrieve display information about a callback item. This notification is sent in the form of a WM_NOTIFY message.

  • The application processing this notification must return zero.
pDispInfo
Address of an NMCOMBOBOXEX structure that contains information about the notification.

The NMCOMBOBOXEX structure contains a COMBOBOXEXITEM structure. The mask member specifies the information being requested by the control.

Fill the appropriate members of the structure to return the requested information to the control. If your message handler sets the mask member of the COMBOBOXEXITEM structure to CBEIF_DI_SETITEM, the header control stores the information and will not request it again.


CBEN_INSERTITEM

CBEN_INSERTITEM
    pNMInfo = (PNMCOMBOBOXEX) lParam;

Sent when a new item has been inserted in the control. This notification is sent in the form of a WM_NOTIFY message.

  • The application processing this notification must return zero.
pNMInfo
Address of an NMCOMBOBOXEX structure containing information about the notification and the item that was inserted.


NM_SETCURSOR (ComboBoxEx)

NM_SETCURSOR
    lpnmm = (LPNMMOUSE) lParam;

Notifies a ComboBoxEx control's parent window that the control is setting the cursor in response to a WM_SETCURSOR message. This notification is sent in the form of a WM_NOTIFY message.

  • Return nonzero to allow the control to set the cursor, or zero to prevent the control from setting the cursor.
lpnmm
Address of an NMMOUSE structure that contains additional information about this notification message.

Version 4.71


ComboBoxEx Control Structures

This section contains information about the structures used with ComboBoxEx controls.

COMBOBOXEXITEM

NMCBEENDEDIT

NMCBEDRAGBEGIN

NMCOMBOBOXEX


COMBOBOXEXITEM

typedef struct {
    UINT    mask;
    int     iItem;
    LPTSTR  pszText;
    int     cchTextMax;
    int     iImage;
    int     iSelectedImage;
    int     iOverlay;
    int     iIndent;
    LPARAM  lParam;
} COMBOBOXEXITEM, *PCOMBOBOXEXITEM;

Contains information about an item in a ComboBoxEx control.

mask
Set of bit flags that specify attributes of this structure or of an operation that is using this structure. The flags specify members that are valid or must be filled in. This member can be a combination of the following values:
CBEIF_DI_SETITEM | The control should store the item data and not ask for it again. This flag is used only with the CBEN_GETDISPINFO notification message.
CBEIF_IMAGE | The iImage member is valid or must be filled in.
CBEIF_INDENT | The iIndent member is valid or must be filled in.
CBEIF_LPARAM | The lParam member is valid or must be filled in.
CBEIF_OVERLAY | The iOverlay member is valid or must be filled in.
CBEIF_SELECTEDIMAGE | The iSelectedImage member is valid or must be filled in.
CBEIF_TEXT | The pszText member is valid or must be filled in.
iItem
Zero-based index of the item.
pszText
Address of a character buffer that contains or receives the item's text. If text information is being retrieved, this member must be set to the address of a character buffer that will receive the text. The size of this buffer must also be indicated in cchTextMax. If this member is set to LPSTR_TEXTCALLBACK, the control will request the information by using the CBEN_GETDISPINFO notification messages.
cchTextMax
Length of pszText, in characters. If text information is being set, this member is ignored.
iImage
Zero-based index of an image within the image list. The specified image will be displayed for the item when it is not selected. If this member is set to I_IMAGECALLBACK, the control will request the information by using CBEN_GETDISPINFO notification messages.
iSelectedImage
Zero-based index of an image within the image list. The specified image will be displayed for the item when it is selected. If this member is set to I_IMAGECALLBACK, the control will request the information by using CBEN_GETDISPINFO notification messages.
iOverlay
One-based index of an overlay image within the image list. If this member is set to I_IMAGECALLBACK, the control will request the information by using CBEN_GETDISPINFO notification messages.
iIndent
Number of indent spaces to display for the item. Each indentation equals 10 pixels. If this member is set to I_INDENTCALLBACK, the control will request the information by using CBEN_GETDISPINFO notification messages.
lParam
32-bit value specific to the item.


NMCBEENDEDIT

typedef struct {
    NMHDR  hdr;
    BOOL   fChanged;
    int    iNewSelection;
    TCHAR  szText[CBEMAXSTRLEN]; // CBEMAXSTRLEN is 260
    int    iWhy;
} NMCBEENDEDIT, *PNMCBEENDEDIT;

Contains information about the conclusion of an edit operation within a ComboBoxEx control. This structure is used with the CBEN_ENDEDIT notification message.

hdr
NMHDR structure that contains information about the notification message.
fChanged
Value indicating whether the contents of the control's edit box have changed. This value is nonzero if the contents have been modified, or zero otherwise.
iNewSelection
Zero-based index of the item that will be selected after completing the edit operation. This value can be CB_ERR if no item will be selected.
szText
Zero-terminated string that contains the text from within the control's edit box.
iWhy
Value that specifies the action that generated the CBEN_ENDEDIT notification message. This value can be one of the following:
CBENF_DROPDOWN | The user activated the drop-down list.
CBENF_ESCAPE | The user pressed ESC.
CBENF_KILLFOCUS | The edit box lost the keyboard focus.
CBENF_RETURN | The user completed the edit operation by pressing ENTER.


NMCBEDRAGBEGIN

typedef struct {
    NMHDR hdr;
    int iItemid;
    TCHAR szText[CBEMAXSTRLEN];
}NMCBEDRAGBEGIN, *LPNMCBEDRAGBEGIN;

Contains information used with the CBEN_DRAGBEGIN notification message.

hdr
NMHDR structure that contains information about the notification message.
iItemid
Zero-based index of the item being dragged. This value will always be -1, indicating that the item being dragged is the item displayed in the edit portion of the control.
szText
Character buffer that contains the text of the item being dragged.


NMCOMBOBOXEX

typedef struct {
    NMHDR hdr;
    COMBOBOXEXITEM ceItem;
} NMCOMBOBOXEX, *PNMCOMBOBOXEX;

Holds information specific to ComboBoxEx items for use with notification messages.

hdr
NMHDR structure that contains information about the notification message.
ceItem
COMBOBOXEXITEM structure that holds item information specific to the current notification. Upon receiving a notification message, the COMBOBOXEXITEM structure holds information required for the owner to respond. The members of this structure are often used as fields for the owner to return values in response to the notification.


Date and Time Picker Controls

A date and time picker (DTP) control provides a simple and intuitive interface through which to exchange date and time information with a user. For example, with a DTP control you can ask the user to enter a date and then retrieve his or her selection with ease.

About Date and Time Picker Controls

Using Date and Time Picker Controls

Date and Time Picker Control Reference

About Date and Time Picker Controls

You can create a date and time picker control by calling the CreateWindowEx function and specifying DATETIMEPICK_CLASS as the window class. The class is registered when the date and time picker class is loaded from the common control dynamic-link library (DLL). Register this class by calling the InitCommonControlsEx function, while specifying the ICC_DATE_CLASSES bit flag in the accompanying INITCOMMONCONTROLSEX structure.

Note Date and time picker controls are implemented in version 4.70 and later of Comctl32.dll.

Date and Time Picker User Interface

The client area of a date and time picker (DTP) control displays date and time information and acts as the interface through which users modify the information. The control's display consists of fields that are defined by the control's format string. Additionally, the control will display a check box when the DTS_SHOWNONE style is in use.

Each field in the control displays a portion of the date and time information that the control stores internally. The user can click a field to set keyboard focus and then provide keyboard input to change the information represented by that field. The DTP control automatically updates internal information based on the user's input. The control recognizes the following as valid input.
Input Category | Description
Arrow Keys | The control accepts arrow keys to navigate the fields in the control and change values. The user can press the LEFT ARROW or RIGHT ARROW keys to move through the control. If the user attempts to move past the last field in a given direction, the keyboard focus "wraps around" to the field on the opposite side of the control. The UP ARROW and DOWN ARROW keys change values in the current field incrementally.
End and Home | The control accepts the VK_END and VK_HOME virtual keys to change the value within the current field to its upper and lower limits, respectively.
Function Keys | The F2 key activates edit mode. The F4 key causes the control to display a drop-down month calendar control (pressing ALT+DOWN ARROW does this as well).
Numbers | The control accepts numeric input in two-character segments. If the value entered by the user is invalid (like setting the month to 14), the control rejects it and resets the display to the previous value.
Plus and Minus | The control accepts the VK_ADD and VK_SUBTRACT virtual keys from the numeric keypad to increment and decrement the value in the current field.

DTP controls that do not use the DTS_UPDOWN style display an arrow button. If the user clicks this button, a month calendar control drops down. The user can select a specific date by clicking an area of the calendar.

Date and Time Picker Control Styles

Date and time picker (DTP) controls have several styles that determine a control's appearance and behavior. The control styles are specified when creating the control by including the desired control styles in the dwStyle parameter of the CreateWindowEx call. You can change DTP control styles after you have created the control. To retrieve or change the window style, use the GetWindowLong and SetWindowLong functions.

You can set the display format of the DTP control using styles. The control defaults to the DTS_SHORTDATEFORMAT style, which produces output like "4/19/96". The DTS_LONGDATEFORMAT style causes the control to display date information like "Friday, April 19, 1996". Using the DTS_TIMEFORMAT style causes the control to display the time instead of the date in a format such as "5:31:42 PM".

Format Strings

A date and time picker (DTP) control relies on a format string to determine how it will display fields of information. By default, a DTP control can display information in any of three preset formats. Also, you can customize a DTP control's display using custom format strings.

Custom format strings provide greater flexibility for your application. In a custom format string, you can specify the order in which the control will display fields of information or indicate specific callback fields. The format characters that comprise the format string define the DTP control's display and field layout.

Preset DTP display formats

A DTP control can display information fields in three preset formats or according to a custom format string. Although the preset formats are format strings, they are set using the following window styles.
Style | Description
DTS_LONGDATEFORMAT | The control displays the date in long format. The default format string for this style is defined by LOCALE_SLONGDATEFORMAT, which produces output like "Friday, April 19, 1996".
DTS_SHORTDATEFORMAT | The control displays the date in short format, the default style setting. The default format string for this style is defined by LOCALE_SSHORTDATE, which produces output like "4/19/96".
DTS_TIMEFORMAT | The control displays the time. The default format string for this style is defined by LOCALE_STIMEFORMAT, which produces output like "5:31:42 PM".

Custom format strings

You can customize the display of a date and time picker (DTP) control using custom format strings. DTP controls support specified format characters that you can combine to create a format string. To assign the format string to the DTP control, use the DTM_SETFORMAT message.

You can add body text to the format string. For example, if you want the control to display the current date with the format "Today is: 04:22:31 Tuesday Mar 23, 1996", the format string is "'Today is: 'hh':'m':'s ddddMMMdd', 'yyy".

Note that segments of nonformat characters in the preceding example are delimited by single quotation marks. Failure to surround body text in this way will result in unpredictable display by the DTP.

Format characters

Date and time picker (DTP) controls support the following format characters.
String Fragment | Description
"d" | The one- or two-digit day.
"dd" | The two-digit day. Single-digit day values are preceded by a zero.
"ddd" | The three-character weekday abbreviation.
"dddd" | The full weekday name.
"h" | The one- or two-digit hour in 12-hour format.
"hh" | The two-digit hour in 12-hour format. Single-digit values are preceded by a zero.
"H" | The one- or two-digit hour in 24-hour format.
"HH" | The two-digit hour in 24-hour format. Single-digit values are preceded by a zero.
"m" | The one- or two-digit minute.
"mm" | The two-digit minute. Single-digit values are preceded by a zero.
"M" | The one- or two-digit month number.
"MM" | The two-digit month number. Single-digit values are preceded by a zero.
"MMM" | The three-character month abbreviation.
"MMMM" | The full month name.
"t" | The one-letter AM/PM abbreviation (that is, AM is displayed as "A").
"tt" | The two-letter AM/PM abbreviation (that is, AM is displayed as "AM").
"X" | The callback field. The control still uses the other valid format characters and queries the owner to fill in the "X" portion. So the owner must be prepared to handle the DTN_WMKEYDOWN, DTN_FORMAT, and DTN_FORMATQUERY notification messages. Multiple "X" characters can be used in series to signify unique callback fields.
"y" | The one-digit year (that is, 1996 would be displayed as "6").
"yy" | The last two digits of the year (that is, 1996 would be displayed as "96").
"yyy" | The full year (that is, 1996 would be displayed as "1996").

Callback fields

In addition to the standard format characters that define date and time picker (DTP) fields, you can customize your output by specifying certain parts of a format string as callback fields. To declare a callback field, include one or more "X" characters (ASCII Code 88) anywhere in the body of the format string. Like other DTP control fields, callback fields are displayed in left-to-right order based on their location in the format string.

You can create callback fields that are unique to each other by repeating the "X" character. Thus, the format string "XXddddMMMdd', 'yyyXXX" contains two unique callback fields, "XX" and "XXX". Remember, callback fields are treated as valid fields, so your application must be prepared to handle DTN_WMKEYDOWN notification messages.

When the DTP control parses the format string and encounters a callback field, it sends DTN_FORMAT and DTN_FORMATQUERY notification messages. The callback field string is included with the notifications so the receiving application can determine which callback field is being queried. The owner of the control must respond to these notifications to ensure that the custom information is properly displayed.

Date and Time Picker Control Notification Messages

A date and time picker (DTP) control sends notification messages when it receives user input or processes and reacts to callback fields. The parent of the control receives these notification messages in the form of WM_NOTIFY messages.

The following notification messages are used with DTP controls.
Notification | Description
DTN_CLOSEUP | Indicates that the drop-down month calendar is about to be removed.
DTN_DATETIMECHANGE | Signals a change within the DTP control.
DTN_DROPDOWN | Indicates that the drop-down month calendar is about to be displayed.
DTN_FORMAT | Requests text to display in a portion of the format string described as a callback field.
DTN_FORMATQUERY | Requests information about the maximum allowable size of the text to be displayed in a callback field.
DTN_USERSTRING | Signals the end of a user's edit operation within the control. This notification is sent only by DTP controls that use the DTS_APPCANPARSE style.
DTN_WMKEYDOWN | Signals that the user has pressed a key in a callback field of the DTP control.

Using Date and Time Picker Controls

This section provides information and sample code for implementing a date and time picker control.

Creating a Date and Time Picker Control

To create a date and time picker (DTP) control, use the CreateWindowEx function, specifying DATETIMEPICK_CLASS as the window class. You must first register the window class by calling the InitCommonControlsEx function, while specifying the ICC_DATE_CLASSES bit in the accompanying INITCOMMONCONTROLSEX structure.

The following example creates a DTP control in an existing modeless dialog box. It uses the DTS_SHOWNONE style to allow the user to simulate deactivation of the date within the control.

//  CreateDatePick creates a DTP control within a dialog box.
//  Returns the handle to the new DTP control if successful, or NULL
//  otherwise.
//
//    hwndMain - The handle to the main window.
//    g_hinst - global handle to the program instance.
HWND WINAPI CreateDatePick(hwndMain)
{
    HWND hwndDP = NULL;
    INITCOMMONCONTROLSEX icex;

    icex.dwSize = sizeof(icex);
    icex.dwICC = ICC_DATE_CLASSES;

    InitCommonControlsEx(&icex);

    hwndDlg = CreateDialog  (g_hinst,
                             MAKEINTRESOURCE(IDD_DIALOG1),
                             hwndMain,
                             DlgProc);

    if(hwnDlg)
        hwndDP = CreateWindowEx(0,
                             DATETIMEPICK_CLASS,
                             "DateTime",
                             WS_BORDER|WS_CHILD|WS_VISIBLE|DTS_SHOWNONE,
                             20,50,220,20,
                             hwndDlg,
                             NULL,
                             g_hinst,
                             NULL);
    return (hwndDP);
}

Processing Date and Time Picker Notifications

The following example processes the DTN_DATETIMECHANGE, DTN_FORMAT, DTN_FORMATQUERY, and DTN_WMKEYDOWN notifications by calling the DoDateTimeChange, DoFormatQuery, DoFormat, and DoWMKeydown application-defined functions.

Other topics in this chapter provide additional information on these notifications. See Supporting Callback Fields and Processing the DTN_DATETIMECHANGE Notification Message for additional information.

BOOL WINAPI DoNotify(HWND hwnd, WPARAM wParam, LPARAM lParam)
{
    LPNMHDR hdr = (LPNMHDR)lParam;

    switch(hdr->code){
        case DTN_DATETIMECHANGE:{
            LPNMDATETIMECHANGE lpChange = (LPNMDATETIMECHANGE)lParam;
            DoDateTimeChange(lpChange);
        }
        break;

        case DTN_FORMATQUERY:{
            LPNMDATETIMEFORMATQUERY lpDTFQuery = (LPNMDATETIMEFORMATQUERY)lParam;

            // Process DTN_FORMATQUERY to ensure that the control
            // displays callback information properly.
            DoFormatQuery(hdr->hwndFrom, lpDTFQuery);
        }
        break;

        case DTN_FORMAT:{
            LPNMDATETIMEFORMAT lpNMFormat = (LPNMDATETIMEFORMAT) lParam;

            // Process DTN_FORMAT to supply information about callback
            // fields (fields) in the DTP control.
            DoFormat(hdr->hwndFrom, lpNMFormat);
        }
        break;

        case DTN_WMKEYDOWN:{
            LPNMDATETIMEWMKEYDOWN lpDTKeystroke =
                            (LPNMDATETIMEWMKEYDOWN)lParam;

            // Process DTN_WMKEYDOWN to respond to a user's keystroke in
            // a callback field.
            DoWMKeydown(hdr->hwndFrom, lpDTKeystroke);
        }
        break;
    }
    // All of the above notifications require the owner to return zero.
    return FALSE;
}

Processing the DTN_DATETIMECHANGE Notification

A date and time picker (DTP) control sends the DTN_DATETIMECHANGE message whenever a change occurs. This message will be generated if the user changes one of the fields in the control or changes the state of the control's check box (DTS_SHOWNONE only).

The following example is an application-defined function designed to update a static control within a dialog box. The text within the static control is changed to reflect the current state of the DTP control.

void WINAPI DoDateTimeChange(LPNMDATETIMECHANGE lpChange)
{
    // If the user has unchecked the DTP's check box, change the
    // text in a static control to show the appropriate message.
    //
    // g_hwndDlg - a program-global address of a dialog box.

    if(lpChange->dwFlags == GDT_NONE)
        SetDlgItemText(g_hwndDlg, IDC_STATUS, "Disabled");
    else
        SetDlgItemText(g_hwndDlg, IDC_STATUS, "Active");
}

Supporting Callback Fields in a DTP control

If you plan to use callback fields with the date and time picker (DTP) controls in your application, you must be prepared to handle DTN_FORMATQUERY, DTN_FORMAT, and DTN_WMKEYDOWN notification messages. For additional information about callback fields, see Callback fields.

This section contains information about how your application can process these notification messages. There are several examples of source code for application-defined functions. The following list shows notification messages with sample functions that process them.
Notification Message | Sample Function
DTN_FORMATQUERY | DoFormatQuery
DTN_FORMAT | DoFormat
DTN_WMKEYDOWN | DoWMKeydown

The DoFormatQuery application-defined function

A date and time picker (DTP) control sends a DTN_FORMATQUERY notification message to request information about the maximum possible size of a callback field within the control. Handling this message ensures that all fields are displayed properly. The following DoFormatQuery application-defined function processes the DTN_FORMATQUERY notification message by calculating the width of the widest possible string for a given callback field.

//
//  DoFormatQuery processes DTN_FORMATQUERY messages to ensure that the
//  DTP control displays callback fields properly.
//
void WINAPI DoFormatQuery(
 HWND hwndDP,
 LPNMDATETIMEFORMATQUERY lpDTFQuery)
{
    HDC hdc;
    HFONT hFont, hOrigFont;

    //  Prepare the device context for GetTextExtentPoint32 call.
    hdc = GetDC(hwndDP);

    hFont = FORWARD_WM_GETFONT(hwndDP, SendMessage);

    if(!hFont)
        hFont = (HFONT)GetStockObject(DEFAULT_GUI_FONT);

    hOrigFont = SelectObject(hdc, hFont);

    // Check to see if this is the callback segment desired. If so,
    // use the longest text segment to determine the maximum
    // width of the callback field, and then place the information into
    // the NMDATETIMEFORMATQUERY structure.
    if(!lstrcmp("XX",lpDTFQuery->pszFormat))
    GetTextExtentPoint32 (hdc,
                          "366",  // widest date string
                          3,
                          &lpDTFQuery->szMax);

    // Reset the font in the device context; then release the context.
    SelectObject(hdc,hOrigFont);
    ReleaseDC(hwndDP, hdc);
}

The DoFormat application-defined function

A date and time picker (DTP) control sends the DTN_FORMAT notification to request text that will be displayed in a callback field of the control. By handling this notification message, you allow the DTP control to display information that it does not natively support.

The following DoFormat application-defined function processes DTN_FORMAT notification messages by providing a text string for a callback field. DoFormat calls the GetDayNum application-defined function to request the day number to be used in the callback string.

//  DoFormat processes DTN_FORMAT to provide the text for a callback
//  field in a DTP control. In this example, the callback field
//  contains a value for the day of year. The function calls the
//  application-defined function GetDayNum (below) to retrieve
//  the correct value.
//
void WINAPI DoFormat(HWND hwndDP, LPNMDATETIMEFORMAT lpDTFormat)
{
    wsprintf(lpDTFormat->szDisplay,"%d",GetDayNum(&lpDTFormat->st));
}

The GetDayNum application-defined function

The application-defined sample function DoFormat calls the following GetDayNum application-defined function to request the day number based on the current date. GetDayNum returns an INT value that represents the current day of the year, from 0 to 366. This function calls another application-defined function, IsLeapYr, during processing.

//
//  GetDayNum is an application-defined function that retrieves the
//  correct day of year value based on the contents of a given
//  SYSTEMTIME structure. This function calls the IsLeapYr function to
//  check if the current year is a leap year. The function returns an
//  integer value that represents the day of year.
//
int WINAPI GetDayNum(SYSTEMTIME *st)
{
    int iNormYearAccum[] = {31,59,90,120,151,181,
                            212,243,273,304,334,365};

    int iLeapYearAccum[] = {31,60,91,121,152,182,
                            213,244,274,305,335,366};
    int iDayNum;

    if(IsLeapYr(st->wYear))
        iDayNum=iLeapYearAccum[st->wMonth-2]+st->wDay;
    else
        iDayNum=iNormYearAccum[st->wMonth-2]+st->wDay;

    return (iDayNum);
}

The IsLeapYr application-defined function

The application-defined sample function GetDayNum calls the IsLeapYr function to determine whether the current year is a leap year. IsLeapYr returns a BOOL value that is TRUE if it is a leap year and FALSE otherwise.

//
//  IsLeapYr determines if a given year value is a leap year. The
//  function returns TRUE if the current year is a leap year, and
//  FALSE otherwise.
//
BOOL WINAPI IsLeapYr(int iYear)
{
    int iQuotient;
    BOOL fLeapYr = FALSE;

    // If the year is evenly divisible by 4 and not by 100, then this
    // is a leap year.
    if(!(iYear%4) && (iYear%100))
        fLeapYr = TRUE;
    else{
        // If the year is evenly divisible by 4 and 100, then check to
        // see if the quotient of year divided by 100 is also evenly
        // divisible by 4. If it is, then this is a leap year.
        if(!(iYear%4) && !(iYear%100)){
            iQuotient = iYear/100;
            if(!(iQuotient%4)) fLeapYr = TRUE;
        }
    }
    return (fLeapYr);
}

The DoWMKeydown application-defined function

Date and time picker (DTP) controls send the DTN_WMKEYDOWN message to report that the user has typed input in a callback field. Handling this message allows you to emulate the same keyboard responses supported for standard DTP fields or provide custom responses. The following DoWMKeydown application-defined function provides an example of how DTN_WMKEYDOWN notifications can be handled.

//
//  DoWMKeydown increments or decrements the day of month according
//  to user keyboard input.
//
void WINAPI DoWMKeydown(
 HWND hwndDP,
 LPNMDATETIMEWMKEYDOWN lpDTKeystroke)
{
    int delta =1;

    if(!lstrcmp(lpDTKeystroke->pszFormat,"XX")){
        switch(lpDTKeystroke->nVirtKey){
            case VK_DOWN:
            case VK_SUBTRACT:
                delta = -1;  // fall through

            case VK_UP:
            case VK_ADD:
                lpDTKeystroke->st.wDay += delta;
                break;
        }
    }
}


Date and Time Picker Control Reference

This section contains information about the following API elements used with date and time picker controls.

Date and time picker control styles

Messages
DTM_GETMCCOLOR
DTM_GETMCFONT
DTM_GETMONTHCAL
DTM_GETRANGE
DTM_GETSYSTEMTIME
DTM_SETFORMAT
DTM_SETMCCOLOR
DTM_SETMCFONT
DTM_SETRANGE
DTM_SETSYSTEMTIME

Utility Macros
DateTime_GetMonthCal
DateTime_GetMonthCalColor
DateTime_GetMonthCalFont
DateTime_GetRange
DateTime_GetSystemtime
DateTime_SetFormat
DateTime_SetMonthCalColor
DateTime_SetMonthCalFont
DateTime_SetRange
DateTime_SetSystemtime

Notifications
DTN_CLOSEUP
DTN_DATETIMECHANGE
DTN_DROPDOWN
DTN_FORMAT
DTN_FORMATQUERY
DTN_USERSTRING
DTN_WMKEYDOWN
NM_KILLFOCUS (date time)
NM_SETFOCUS (date time)

Structures
NMDATETIMECHANGE
NMDATETIMEFORMAT
NMDATETIMEFORMATQUERY
NMDATETIMESTRING
NMDATETIMEWMKEYDOWN


Date and time picker control styles

The following window styles are specific to date and time picker (DTP) controls:
DTS_APPCANPARSE | Allows the owner to parse user input and take necessary action. It enables users to edit within the client area of the control when they press the F2 key. The control sends DTN_USERSTRING notification messages when users are finished.
DTS_LONGDATEFORMAT | Displays the date in long format. The default format string for this style is defined by LOCALE_SLONGDATEFORMAT, which produces output like "Friday, April 19, 1996".
DTS_RIGHTALIGN | The drop-down month calendar will be right-aligned with the control instead of left-aligned, which is the default.
DTS_SHOWNONE | It is possible to have no date currently selected in the control. With this style, the control displays a check box that users can check once they have entered or selected a date. Until this check box is checked, the application will not be able to retrieve the date from the control because, in essence, the control has no date. This state can be set with the DTM_SETSYSTEMTIME message or verified with the DTM_GETSYSTEMTIME message.
DTS_SHORTDATEFORMAT | Displays the date in short format. The default format string for this style is defined by LOCALE_SSHORTDATE, which produces output like "4/19/96".
DTS_TIMEFORMAT | Displays the time. The default format string for this style is defined by LOCALE_STIMEFORMAT, which produces output like "5:31:42 PM".
DTS_UPDOWN | Appears to the right of the DTP control to modify date values. This style can be used instead of the drop-down month calendar, which is the default style.


Date and Time Picker Control Messages

This section contains information about the messages that are used to manipulate a date and time picker (DTP) control.

DTM_GETMCCOLOR

DTM_GETMCFONT

DTM_GETMONTHCAL

DTM_GETRANGE

DTM_GETSYSTEMTIME

DTM_SETFORMAT

DTM_SETMCCOLOR

DTM_SETMCFONT

DTM_SETRANGE

DTM_SETSYSTEMTIME


DTM_GETMCCOLOR

DTM_GETMCCOLOR
    wParam = (WPARAM)(INT)iColor;
    lParam = 0;

Retrieves the color for a given portion of the month calendar within a date and time picker (DTP) control. You can send this message explicitly or use the DateTime_GetMonthCalColor macro.

  • Returns a COLORREF value that represents the color setting for the specified portion of the month calendar control if successful. The message returns -1 if unsuccessful.
iColor
INT value specifying which month calendar color to retrieve. This value can be one of the following:
MCSC_BACKGROUND | Retrieve the background color displayed between months.
MCSC_MONTHBK | Retrieve the background color displayed within the month.
MCSC_TEXT | Retrieve the color used to display text within a month.
MCSC_TITLEBK | Retrieve the background color displayed in the calendar's title.
MCSC_TITLETEXT | Retrieve the color used to display text within the calendar's title.
MCSC_TRAILINGTEXT | Retrieve the color used to display header day and trailing day text. Header and trailing days are the days from the previous and following months that appear on the current month calendar.

Version 4.70


DTM_GETMCFONT

DTM_GETMCFONT
    wParam = 0;
    lParam = 0;

Retrieves the font that the date and time picker (DTP) control's child month calendar control is currently using. You can send this message explicitly or use the DateTime_GetMonthCalFont macro.

  • Returns an HFONT value that is the handle to the current font.

Version 4.71


DTM_GETMONTHCAL

DTM_GETMONTHCAL
    wParam = 0;
    lParam = 0;

Retrieves the handle to a date and time picker's (DTP) child month calendar control. You can send this message explicitly or use the DateTime_GetMonthCal macro.

  • Returns the handle to a DTP control's child month calendar control if successful, or NULL otherwise.

DTP controls create a child month calendar control when the user clicks the drop-down arrow. When the month calendar is no longer needed, it is destroyed. So your application must not rely on a static handle to the DTP control's child month calendar.

Version 4.70

See also DTN_CLOSEUP, DTN_DROPDOWN


DTM_GETRANGE

DTM_GETRANGE
    wParam = 0;
    lParam = (LPARAM) lpSysTimeArray;

Retrieves the current minimum and maximum allowable system times for a date and time picker (DTP) control. You can send this message explicitly or use the DateTime_GetRange macro.

  • Returns a DWORD value that is a combination of GDTR_MIN or GDTR_MAX. The first element of the SYSTEMTIME array contains the minimum allowable time if GDTR_MIN is set. The second element of the SYSTEMTIME array contains the maximum allowable time if GDTR_MAX is set.
lpSysTimeArray
Address of a two-element array of SYSTEMTIME structures.

Version 4.70


DTM_GETSYSTEMTIME

DTM_GETSYSTEMTIME
    wParam = 0;
    lParam = (LPARAM) lpSysTime;

Retrieves the currently selected time from a date and time picker (DTP) control and places it in a specified SYSTEMTIME structure. You can send this message explicitly or use the DateTime_GetSystemtime macro.

  • Returns GDT_VALID if the time information was placed successfully in the given structure; or the message can return GDT_NONE if the control was set to the DTS_SHOWNONE style and the control check box was not selected.
lpSysTime
Address of the SYSTEMTIME structure that receives the system time information. This parameter must be a valid address; it cannot be NULL.

Version 4.70


DTM_SETFORMAT

DTM_SETFORMAT
    wParam = 0;
    lParam = (LPARAM) lpszFormat;

Sets the display of a date and time picker (DTP) control based on a given format string. You can send this message explicitly or use the DateTime_SetFormat macro.

  • Returns nonzero if successful, or zero otherwise.
lpszFormat
Address of a zero-terminated format string that defines the desired display. Setting this parameter to NULL will reset the control to the default format string for the current style.

It is acceptable to include extra characters within the format string to produce a more rich display. However, any nonformat characters must be enclosed within single quotes. For example, the format string "'Today is: 'hh':'m':'s ddddMMMdd', 'yyy" would produce output like "Today is: 04:22:31 Tuesday Mar 23, 1996".

Version 4.70

Note A DTP control tracks locale changes when it is using the default format string. If you set a custom format string, it will not be updated in response to locale changes.


DTM_SETMCCOLOR

DTM_SETMCCOLOR
    wParam = (WPARAM)(INT) iColor;
    lParam = (LPARAM)(COLORREF) clr;

Sets the color for a given portion of the month calendar within a date and time picker (DTP) control. You can send this message explicitly or use the DateTime_SetMonthCalColor macro.

  • Returns a COLORREF value that represents the previous color setting for the specified portion of the month calendar control if successful. Otherwise, the message returns -1.
iColor
INT value specifying which month calendar color to set. This value can be one of the following:
MCSC_BACKGROUND | Set the background color displayed between months.
MCSC_MONTHBK | Set the background color displayed within the month.
MCSC_TEXT | Set the color used to display text within a month.
MCSC_TITLEBK | Set the background color displayed in the calendar's title.
MCSC_TITLETEXT | Set the color used to display text within the calendar's title.
MCSC_TRAILINGTEXT | Set the color used to display header day and trailing day text. Header and trailing days are the days from the previous and following months that appear on the current month calendar.
clr
COLORREF value representing the color that will be set for the specified area of the month calendar.

Version 4.70


DTM_SETMCFONT

DTM_SETMCFONT
    wParam = (WPARAM)(HFONT) hFont;
    lParam = (LPARAM) MAKELONG(fRedraw, 0);

Sets the font to be used by the date and time picker (DTP) control's child month calendar control. You can send this message explicitly or use the DateTime_SetMonthCalFont macro.

  • The return value for this message is not used.
hFont
Handle to the font that will be set.
fRedraw
Specifies whether the control should be redrawn immediately upon setting the font. Setting this parameter to TRUE causes the control to redraw itself.

Version 4.71


DTM_SETRANGE

DTM_SETRANGE
    wParam = (WPARAM) flags;
    lParam = (LPARAM) lpSysTimeArray;

Sets the minimum and maximum allowable system times for a date and time picker (DTP) control. You can send this message explicitly or use the DateTime_SetRange macro.

  • Returns nonzero if successful, or zero otherwise.
flags
Value specifying which range values are valid. This parameter can be a combination of the following values:
GDTR_MIN | The first element in the SYSTEMTIME structure array is valid and will be used to set the minimum allowable system time.
GDTR_MAX | The second element in the SYSTEMTIME structure array is valid and will be used to set the maximum allowable system time.
lpSysTimeArray
Address of a two-element array of SYSTEMTIME structures. The first element of the SYSTEMTIME array contains the minimum allowable time. The second element of the SYSTEMTIME array contains the maximum allowable time. It is not necessary to fill an array element that is not specified in the flags parameter.

Version 4.70


DTM_SETSYSTEMTIME

DTM_SETSYSTEMTIME
    wParam = (WPARAM) flag;
    lParam = (LPARAM) lpSysTime;

Sets the time in a date and time picker (DTP) control. You can send this message explicitly or use the DateTime_SetSystemtime macro.

  • Returns nonzero if successful, or zero otherwise.
flag
Value specifying the action that should be performed. This value must be set to one of the following:
GDT_VALID | Set the DTP control according to the data within the structure that lpSysTime points to.
GDT_NONE | Set the DTP control to "no date" and clear its check box. When this flag is specified, lpSysTime is ignored. This flag applies only to DTP controls that are set to the DTS_SHOWNONE style.
lpSysTime
Address of a SYSTEMTIME structure containing the system time used to set the DTP control.

Version 4.70


Date and Time Picker Control Macros

This section contains information about the macros that are used to manipulate a date and time picker (DTP) control.

DateTime_GetMonthCal

DateTime_GetMonthCalColor

DateTime_GetMonthCalFont

DateTime_GetRange

DateTime_GetSystemtime

DateTime_SetFormat

DateTime_SetMonthCalColor

DateTime_SetMonthCalFont

DateTime_SetRange

DateTime_SetSystemtime


DateTime_GetMonthCal

HWND DateTime_GetMonthCal(
    HWND hwndDP);

Retrieves the handle to a date and time picker's (DTP) child month calendar control. You can use this macro or send the DTM_GETMONTHCAL message explicitly.

  • Returns the handle to a DTP control's child month calendar control.
hwndDP
Handle to a DTP control.

DTP controls create a child month calendar control when the user clicks the drop-down arrow. When the month calendar is no longer needed, it is destroyed. So your application must not rely on a static handle to the DTP's child month calendar.

Version 4.70

See also DTN_CLOSEUP, DTN_DROPDOWN


DateTime_GetMonthCalColor

COLORREF DateTime_GetMonthCalColor(
    HWND hwndDP,
    int iColor);

Retrieves the color for a given portion of the month calendar within a date and time picker (DTP) control. You can use this macro or send the DTM_GETMCCOLOR message explicitly.

  • Returns a COLORREF value that represents the color setting for the specified portion of the month calendar control if successful. Otherwise, the macro returns -1.
hwndDP
Handle to a DTP control.
iColor
INT value specifying which month calendar color to retrieve. This value can be one of the following:
MCSC_BACKGROUND | Retrieve the background color displayed between months.
MCSC_MONTHBK | Retrieve the background color displayed within the month.
MCSC_TEXT | Retrieve the color used to display text within a month.
MCSC_TITLEBK | Retrieve the background color displayed in the calendar's title.
MCSC_TITLETEXT | Retrieve the color used to display text within the calendar's title.
MCSC_TRAILINGTEXT | Retrieve the color used to display header day and trailing day text. Header and trailing days are the days from the previous and following months that appear on the current month calendar.

Version 4.70


DateTime_GetMonthCalFont

HFONT DateTime_GetMonthCalFont(
    HWND hwndDP);

Retrieves the font that the date and time picker (DTP) control's child month calendar control is currently using. You can use this macro or send the DTM_GETMCFONT message explicitly.

  • Returns an HFONT value that is the handle to the current font.
hwndDP
Handle to a DTP control.

Version 4.71


DateTime_GetRange

DWORD DateTime_GetRange(
    HWND hwndDT,
    LPSYSTEMTIME lpSysTimeArray);

Retrieves the current minimum and maximum allowable system times for a date and time picker (DTP) control. You can use this macro, or send the DTM_GETRANGE message explicitly.

  • Returns a DWORD value that is a combination of GDTR_MIN or GDTR_MAX. The first element of the SYSTEMTIME array contains the minimum allowable time. The second element of the SYSTEMTIME array contains the maximum allowable time.
hwndDT
Address of a DTP control.
lpSysTimeArray
Address of a two-element array of SYSTEMTIME structures.

Version 4.70


DateTime_GetSystemtime

DWORD DateTime_GetSystemtime(
    HWND hwndDP,
    LPSYSTEMTIME lpSysTime);

Retrieves the currently selected time from a date and time picker (DTP) control and places it in a specified SYSTEMTIME structure. You can use this macro, or send the DTM_GETSYSTEMTIME message explicitly.

  • Returns a DWORD value that equals GDT_VALID if the time information was successfully placed in the given structure; or the message can return GDT_NONE if the control was set to the DTS_SHOWNONE style and the control check box was not selected.
hwndDP
Handle to a DTP control.
lpSysTime
Address of the SYSTEMTIME structure that receives the system time information.

Version 4.70


DateTime_SetFormat

void DateTime_SetFormat(
    HWND hwndDT,
    LPCTSTR lpszFormat);

Sets the display of a date and time picker (DTP) control based on a given format string. You can use this macro or send the DTM_SETFORMAT message explicitly.

  • Returns nonzero if successful, or zero otherwise.
hwndDT
Handle to a DTP control.
lpszFormat
Address of a zero-terminated format string that defines the desired display. Setting this parameter to NULL will reset the control to the default format string for the current style.

It is acceptable to include extra characters within the format string to produce a more rich display. However, any nonformat characters must be enclosed within single quotes. For example, the format string "'Today is: 'hh':'m':'s ddddMMMdd', 'yyy" would produce output like "Today is: 04:22:31 Tuesday Mar 23, 1996".

Version 4.70

Note A DTP control tracks locale changes when it is using the default format string. If you set a custom format string, it will not be updated in response to locale changes.


DateTime_SetMonthCalColor

COLORREF DateTime_SetMonthCalColor(
    HWND     hwndDP,
    int      iColor,
    COLORREF clr);

Sets the color for a given portion of the month calendar within a date and time picker (DTP) control. You can use this macro or send the DTM_SETMCCOLOR message explicitly.

  • Returns a COLORREF value that represents the previous color setting for the specified portion of the month calendar control if successful. Otherwise, this message returns -1.
hwndDP
Handle to a DTP control.
iColor
INT value specifying which month calendar color to set. This value can be one of the following:
Value | Meaning
MCSC_BACKGROUND | Set the background color displayed between months.
MCSC_MONTHBK | Set the background color displayed within the month.
MCSC_TEXT | Set the color used to display text within a month.
MCSC_TITLEBK | Set the background color displayed in the calendar's title.
MCSC_TITLETEXT | Set the color used to display text within the calendar's title.
MCSC_TRAILINGTEXT | Set the color used to display header day and trailing day text. Header and trailing days are the days from the previous and following months that appear on the current month calendar.
clr
COLORREF value that represents the color that will be set for the specified area of the month calendar.

Version 4.70


DateTime_SetMonthCalFont

void DateTime_SetMonthCalFont(
    HWND   hwndDP,
    HFONT  hFont,
    LPARAM MAKELONG(fRedraw,0);

Sets the font to be used by the date and time picker (DTP) control's child month calendar control. You can use this macro or explicitly send the DTM_SETMCFONT message.

hwndDP
Handle to a DTP control.
hFont
Handle to the font that will be set.
fRedraw
Specifies whether the control should be redrawn immediately upon setting the font. Setting this parameter to TRUE causes the control to redraw itself.

Version 4.71


DateTime_SetRange

BOOL DateTime_SetRange(
    HWND hwndDT,
    DWORD flags,
    LPSYSTEMTIME lpSysTimeArray);

Sets the minimum and maximum allowable system times for a date and time picker (DTP) control. You can use this macro or send the DTM_SETRANGE message explicitly.

  • Returns nonzero if successful, or zero otherwise.
hwndDT
Handle to a DTP control.
flags
Value that specifies which range values are valid. This value can be a combination of the following:
GDTR_MIN | The first element in the SYSTEMTIME structure array is valid and will be used to set the minimum allowable system time.
GDTR_MAX | The second element in the SYSTEMTIME structure array is valid and will be used to set the maximum allowable system time.
lpSysTimeArray
Address of a two-element array of SYSTEMTIME structures. The first element of the SYSTEMTIME array contains the minimum allowable time. The second element of the SYSTEMTIME array contains the maximum allowable time. It is not necessary to fill an array element that is not specified in the flags parameter.

Version 4.70


DateTime_SetSystemtime

BOOL DateTime_SetSystemtime(
    HWND hwndDT,
    DWORD flag,
    LPSYSTEMTIME lpSysTime);

Sets a date and time picker (DTP) control to a given date and time. You can use this macro or send the DTM_SETSYSTEMTIME message explicitly.

  • Returns nonzero if successful, or zero otherwise.
hwndDT
Handle to a DTP control.
flag
Value that specifies the action that should be performed. This should be set to one of the following values:
GDT_VALID | Set the DTP control according to the data within the SYSTEMTIME structure pointed to by lpSysTime.
GDT_NONE | Set the DTP control to "no date" and clear its check box. When this flag is specified, lpSysTime is ignored. This flag applies only to DTP controls that are set to the DTS_SHOWNONE style.
lpSysTime
Address of a SYSTEMTIME structure that contains the system time information by which to set the DTP control.

Version 4.70


Date and Time Picker Control Notification Messages

This section contains information about the notification messages sent by date and time picker (DTP) controls.

DTN_CLOSEUP

DTN_DATETIMECHANGE

DTN_DROPDOWN

DTN_FORMAT

DTN_FORMATQUERY

DTN_USERSTRING

DTN_WMKEYDOWN

NM_KILLFOCUS (date time)

NM_SETFOCUS (date time)


DTN_CLOSEUP

DTN_CLOSEUP
    lpNmhdr = (LPMNHDR)lParam;

Sent by a date and time picker (DTP) control when the user closes the drop-down month calendar. The month calendar is closed when the user chooses a date from the month calendar or clicks the drop-down arrow while the calendar is open.

  • The return value for this notification is not used.
lpNmhdr
Address of an NMHDR structure that contains information about the notification message.

DTP controls do not maintain a static child month calendar control. The DTP control destroys the child month calendar control prior to sending this notification. So your application must not rely on a static window handle for the control's child month calendar.

Version 4.70

See also DTN_DROPDOWN, DTM_GETMONTHCAL


DTN_DATETIMECHANGE

DTN_DATETIMECHANGE
    lpChange = (LPNMDATETIMECHANGE) lParam;

Sent by a date and time picker (DTP) control whenever a change occurs. This notification message is sent in the form of a WM_NOTIFY message.

  • The owner of the control must return zero.
lpChange
Address of an NMDATETIMECHANGE structure containing information about the change that took place in the control.

Version 4.70


DTN_DROPDOWN

DTN_DROPDOWN
    lpNmhdr = (LPNMHDR)lParam;

Sent by a date and time picker (DTP) control when the user activates the drop-down month calendar.

  • The return value for this notification is not used.
lpNmhdr
Address of an NMHDR structure that contains information about the notification message.

DTP controls do not maintain a static child month calendar control. The DTP control creates a new month calendar control before sending this notification message. Additionally, the DTP control destroys the child control when it is not active (visible). So your application must not rely on a static window handle for the control's child month calendar.

Version 4.70

See also DTN_CLOSEUP, DTM_GETMONTHCAL


DTN_FORMAT

DTN_FORMAT
    lpNMFormat = (LPNMDATETIMEFORMAT) lParam;

Sent by a date and time picker (DTP) control to request text to be displayed in a callback field. This notification message is sent in the form of a WM_NOTIFY message.

  • The owner of the control must return zero.
lpNMFormat
Address of an NMDATETIMEFORMAT structure containing information regarding this instance of the notification message. The structure contains the substring that defines the callback field and receives the formatted string that the control will display.

Handling this message allows the owner of the control to provide a custom string that the control will display. (For additional information about callback fields, see Callback fields.)

Version 4.70


DTN_FORMATQUERY

DTN_FORMATQUERY
    lpDTFormatQuery = (LPNMDATETIMEFORMATQUERY) lParam;

Sent by a date and time picker (DTP) control to retrieve the maximum allowable size of the string that will be displayed in a callback field. This notification message is sent in the form of a WM_NOTIFY message.

  • The owner of the control must calculate the maximum possible width of the text that will be displayed in the callback field, set the szMax member of the NMDATETIMEFORMATQUERY structure, and return zero.
lpDTFormatQuery
Address of an NMDATETIMEFORMATQUERY structure containing information about the callback field. The structure contains a substring that defines a callback field and receives the maximum allowable size of the string that will be displayed in the callback field.

Handling this message prepares the control to adjust for the maximum size of the string that will be displayed in a particular callback field. This enables the control to properly display output at all times, reducing flicker within the control's display. (For additional information about callback fields, see Callback fields.)

Version 4.70


DTN_USERSTRING

DTN_USERSTRING
    lpDTstring = (LPNMDATETIMESTRING) lParam;

Sent by a date and time picker (DTP) control when a user finishes editing a string in the control. This notification message is only sent by DTP controls that are set to the DTS_APPCANPARSE style. This message is sent in the form of a WM_NOTIFY message.

  • The owner of the control must return zero.
lpDTstring
Address of an NMDATETIMESTRING structure that contains information about the instance of the notification message.

Handling this message allows the owner to provide custom responses to strings entered into the control by the user. The owner must be prepared to parse the input string and take action if necessary.

Version 4.70


DTN_WMKEYDOWN

DTN_WMKEYDOWN
    lpDTKeystroke = (LPNMDATETIMEWMKEYDOWN)lParam;

Sent by a date and time picker (DTP) control when the user types in a callback field. This message is sent in the form of a WM_NOTIFY message.

  • The owner of the control must return zero.
lpDTKeystroke
Address of an NMDATETIMEWMKEYDOWN structure containing information about this instance of the notification. The structure includes information about the key that the user typed, the substring that defines the callback field, and the current system date and time.

Handling this message allows the owner of the control to provide specific responses to keystrokes within the callback fields of the control.

Version 4.70


NM_KILLFOCUS (date time)

NM_KILLFOCUS
    lpnmh = (LPNMHDR) lParam;

Notifies a date and time picker control's parent window that the control has lost the input focus. NM_KILLFOCUS is sent in the form of a WM_NOTIFY message.

  • The return value is ignored.
lpnmh
Address of an NMHDR structure that contains additional information about this notification message.


NM_SETFOCUS (date time)

NM_SETFOCUS
    lpnmh = (LPNMHDR) lParam;

Notifies a date and time picker control's parent window that the control has received the input focus. NM_SETFOCUS is sent in the form of a WM_NOTIFY message.

  • The return value is ignored.
lpnmh
Address of an NMHDR structure that contains additional information about this notification message.


Date and Time Picker Control Structures

This section contains information about the structures used with date and time picker (DTP) controls.

NMDATETIMECHANGE

NMDATETIMEFORMAT

NMDATETIMEFORMATQUERY

NMDATETIMESTRING

NMDATETIMEWMKEYDOWN


NMDATETIMECHANGE

typedef struct tagNMDATETIMECHANGE {
    NMHDR       nmhdr;
    DWORD       dwFlags;
    SYSTEMTIME  st;
} NMDATETIMECHANGE, FAR * LPNMDATETIMECHANGE;

Contains information about a change that has taken place in a date and time picker (DTP) control. This structure is used with the DTN_DATETIMECHANGE notification message.

nmhdr
NMHDR structure that contains information about the notification message.
dwFlags
Value that indicates if the control was set to "no date" status (for DTS_SHOWNONE only). This flag also specifies whether the contents of the st member are valid and contain current time information. This value can be one of the following:
GDT_NONE | The control is set to "no date" status. The "no date" status applies only to controls that are set to the DTS_SHOWNONE style.
GDT_VALID | The control is not set to the "no date" status. The st member contains the current date and time.
st
SYSTEMTIME structure that contains information about the current system date and time.

Version 4.70


NMDATETIMEFORMAT

typedef struct tagNMDATETIMEFORMAT{
    NMHDR       nmhdr;
    LPCTSTR     pszFormat;
    SYSTEMTIME  st;
    LPCTSTR     pszDisplay;
    TCHAR       szDisplay[64];
} NMDATETIMEFORMAT, FAR * LPNMDATETIMEFORMAT;

Contains information about a portion of the format string that defines a callback field within a date and time picker (DTP) control. It carries the substring that defines the callback field and contains a buffer to receive the string that will be displayed in the callback field. This structure is used with the DTN_FORMAT notification message.

nmhdr
NMHDR structure that contains information about the notification message.
pszFormat
Address of the substring that defines a DTP control callback field The substring comprises one or more "X" characters, followed by a NULL character. (For additional information about callback fields, see Callback fields.)
st
SYSTEMTIME structure that contains information about the current system date and time.
pszDisplay
Address of a null-terminated string that contains the display text of the control. By default, this is the address of the szDisplay member of this structure.

It is legal to set this member to point to an existing string. If so, the application is not required to place a string into the szDisplay member.

szDisplay
64-character buffer that is to receive the zero-terminated string that the DTP control will display. It is not necessary to fill the entire buffer.

Version 4.70


NMDATETIMEFORMATQUERY

typedef struct tagNMDATETIMEFORMATQUERY{
    NMHDR nmhdr;
    LPCTSTR pszFormat;
    SIZE szMax;
} NMDATETIMEFORMATQUERY, FAR * LPNMDATETIMEFORMATQUERY;

Contains information about a date and time picker (DTP) control callback field. It contains a substring (taken from the control's format string) that defines a callback field. The structure receives the maximum allowable size of the text that will be displayed in the callback field. This structure is used with the DTN_FORMATQUERY notification message.

nmhdr
NMHDR structure that contains information about this notification message.
pszFormat
Address of a substring that defines a DTP control callback field. The substring is one or more "X" characters followed by a NULL. (For additional information about callback fields, see Callback fields.)
szMax
SIZE structure that must be filled with the maximum size of the text that will be displayed in the callback field.

Version 4.70


NMDATETIMESTRING

typedef struct tagNMDATETIMESTRING{
    NMHDR      nmhdr;
    LPCTSTR    pszUserString;
    SYSTEMTIME st;
    DWORD      dwFlags;
} NMDATETIMESTRING, FAR * LPNMDATETIMESTRING;

Contains information specific to an edit operation that has taken place in a date and time picker (DTP) control. This message is used with the DTN_USERSTRING notification message.

nmhdr
NMHDR structure that contains information about this notification message.
pszUserString
Address of the zero-terminated string that the user entered.
st
SYSTEMTIME structure that must be filled in by the owner when handling the DTN_USERSTRING notification message.
dwFlags
Return field. Set this member to GDT_VALID to indicate that the st member is valid or to GDT_NONE to set the control to "no date" status (DTS_SHOWNONE style only).

Version 4.70


NMDATETIMEWMKEYDOWN

typedef struct tagNMDATETIMEWMKEYDOWN{
    NMHDR      nmhdr;
    int        nVirtKey;
    LPCTSTR    pszFormat;
    SYSTEMTIME st;
} NMDATETIMEWMKEYDOWN, FAR * LPNMDATETIMEWMKEYDOWN;

Carries information used to describe and handle a DTN_WMKEYDOWN notification message.

nmhdr
NMHDR structure that contains information about the notification message.
nVirtKey
Virtual key code that represents the key that the user pressed.
pszFormat
Zero-terminated substring, taken from the format string, that defines the callback field. The substring is one or more "X" characters, followed by a NULL.
st
SYSTEMTIME structure containing the current date and time from the DTP control. The owner of the control must modify the time information based on the user's keystroke.

Version 4.70


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 by dragging the items into position.

Using Drag List Boxes

Drag List Box Reference

Using Drag List Boxes

Drag list boxes have the same window styles and process the same messages as standard list boxes. To create a drag list box, 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 Box Messages

A drag list box notifies the 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 this message when the MakeDragList function is called. To get the message identifier (numeric value) of the drag list message, call the RegisterWindowMessage function and specify 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 address of 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.

Drag List Box Notification Messages

The drag list notification message, which is identified by the uNotification member of the DRAGLISTINFO structure included with the drag list message, can be DL_BEGINDRAG, DL_DRAGGING, DL_CANCELDRAG, or DL_DROPPED.

The DL_BEGINDRAG notification message is sent when the cursor is on a list item and the user clicks the left mouse button. 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 first 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.

Functions
DrawInsert
LBItemFromPt
MakeDragList

Notifications
DL_BEGINDRAG
DL_CANCELDRAG
DL_DRAGGING
DL_DROPPED

Structures
DRAGLISTINFO


Functions

The following references are drag list box functions.

DrawInsert

LBItemFromPt

MakeDragList


DrawInsert

void DrawInsert(
    HWND handParent,
    HWND hLB,
    int nItem
   );

Draws the insert icon in the parent window of the specified drag list box.

  • No return value.
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.


LBItemFromPt

int LBItemFromPt(
    HWND hLB,
    POINT pt,
    BOOL bAutoScroll
   );

Retrieves the index of the item at the specified point in a list box.

  • Returns the item identifier if the point is over a list item, or -1 otherwise.
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.

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.


MakeDragList

BOOL MakeDragList(
    HWND hLB
   );

Changes the specified single-selection list box to a drag list box.

  • Returns nonzero if successful, or zero otherwise.
hLB
Handle to the single-selection list box.


Notifications

The following references are drag list box notifications.

DL_BEGINDRAG

DL_CANCELDRAG

DL_DRAGGING

DL_DROPPED


DL_BEGINDRAG

DL_BEGINDRAG
    idCtl = (WPARAM)(int) wParam;
    pDragInfo = (LPARAM)(LPDRAGLISTINFO) lParam;

Notifies the drag list box's parent window that the user has clicked the left mouse button on an item. A drag list box sends DL_BEGINDRAG in the form of a drag list message.

  • Return TRUE to begin the drag operation, or FALSE to prevent the drag operation.
idCtl
Control identifier of the drag list box.
pDragInfo
Address of a DRAGLISTINFO structure that contains the DL_BEGINDRAG notification code, the handle to the drag list box, and the cursor position.

When processing this notification message, a window procedure typically determines the list item at the specified cursor position by using the LBItemFromPt function. It 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.


DL_CANCELDRAG

DL_CANCELDRAG
    idCtl = (WPARAM)(int) wParam;
    pDragInfo = (LPARAM)(LPDRAGLISTINFO) lParam;

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.

  • No return value.
idCtl
Control identifier of the drag list box.
pDragInfo
Address of a DRAGLISTINFO structure that contains the DL_CANCELDRAG notification code, the handle to the drag list box, and the cursor position.

By processing the DL_CANCELDRAG notification message, an application can reset its internal state to indicate that dragging is not in effect.


DL_DRAGGING

DL_DRAGGING
    idCtl = (WPARAM)(int) wParam;
    pDragInfo = (LPARAM)(LPDRAGLISTINFO) lParam;

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.

  • 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.
idCtl
Control identifier of the drag list box.
pDragInfo
Address of a DRAGLISTINFO structure that contains the DL_DRAGGING notification code, the handle to the drag list box, and the cursor position.

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.


DL_DROPPED

DL_BEGINDRAG
    idCtl = (WPARAM)(int) wParam;
    pDragInfo = (LPARAM)(LPDRAGLISTINFO) lParam;

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.

  • No return value.
idCtl
Control identifier of the drag list box.
pDragInfo
Address of a DRAGLISTINFO structure that contains the DL_DROPPED notification code, the handle to the drag list box, and the cursor position.

This notification is normally processed by inserting the item being dragged into the list in front of the item under the cursor. To retrieve the index of the item at the cursor position, use the LBItemFromPt function. Note that the DL_DROPPED notification message is sent even if the cursor is not on a list item. In that case, LBItemFromPt returns -1.


Structures Structures *
  * Previous Topic: DL_DROPPED
  * Next Topic: DRAGLISTINFO

Structures

The following reference is a drag list box structure.

DRAGLISTINFO


DRAGLISTINFO

Typedef struct {
    UINT uNotification;
    HWND hWnd;
    POINT ptCursor;
} DRAGLISTINFO, FAR *LPDRAGLISTINFO;

Contains information about a drag event. The pointer to DRAGLISTINFO is passed as the lParam parameter of the drag list message.

uNotification
Notification code that specifies the type of drag event. This member can be one of the following values:
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 the drag list box.
ptCursor
POINT structure that contains the current x- and y-coordinates of the mouse cursor.


Flat Scroll Bars

Microsoft® Internet Explorer Version 4.0 introduces a new visual technology called flat scroll bars. Functionally, flat scroll bars behave just like normal scroll bars. The only difference is they are not displayed three-dimensionally.

The following illustration shows a window that contains flat scroll bars.

Window that contains flat scroll bars.

Note Flat scroll bar APIs are implemented in version 4.71 and later of Comctl32.dll.

Using Flat Scroll Bars

Flat Scroll Bars Reference

Using Flat Scroll Bars

This section describes how to implement flat scroll bars in your application.

Before You Begin

To use the flat scroll bar APIs, you must include Commctrl.h in your source files and link with Comctl32.lib.

Adding Flat Scroll Bars to a Window

To add flat scroll bars to a window, call InitializeFlatSB, passing the handle to the window. Instead of using the standard scroll bar APIs to manipulate your scroll bars, you must use the FlatSB_xxxx versions. There are flat scroll bar APIs for setting and retrieving the scroll information, range, and position. If flat scroll bars haven't been initialized for your window, the flat scroll bar APIs will defer to the corresponding standard APIs, if any exist. This allows you to turn flat scroll bars on and off without having to write conditional code.

Enhancing Flat Scroll Bars

FlatSB_SetScrollProp allows you to modify the flat scroll bars to customize the look of your window. You can set the width of a vertical scroll bar and the height of a horizontal scroll bar. You can also set the width (horizontal scroll bar) and the height (vertical scroll bar) of the scroll bar's direction arrows.

FlatSB_SetScrollProp also allows you to customize how the flat scroll bars are displayed. By changing the WSB_PROP_VSTYLE and WSB_PROP_HSTYLE properties, you can set the type of scroll bar that you wish to use. Three styles are available:

FSB_ENCARTA_MODE | A standard flat scroll bar is displayed. When the mouse moves over a direction button or the thumb, that portion of the scroll bar will be displayed in 3-D.
FSB_FLAT_MODE | A standard flat scroll bar is displayed. When the mouse moves over a direction button or the thumb, that portion of the scroll bar will be displayed in inverted colors.
FSB_REGULAR_MODE | A normal, nonflat scroll bar is displayed. No special visual effects will be applied.

Removing Flat Scroll Bars

If you wish to remove flat scroll bars from your window, call the UninitializeFlatSB API, passing the handle to the window. This API only removes flat scroll bars from your window at run time. You do not need to call this API when your window is destroyed.


Flat Scroll Bars Reference

This section contains information on the following new APIs for controlling flat scroll bars:

InitializeFlatSB
FlatSB_EnableScrollBar
FlatSB_GetScrollInfo
FlatSB_GetScrollPos
FlatSB_GetScrollProp
FlatSB_GetScrollRange
FlatSB_SetScrollInfo
FlatSB_SetScrollPos
FlatSB_SetScrollProp
FlatSB_SetScrollRange
FlatSB_ShowScrollBar
UninitializeFlatSB


InitializeFlatSB

BOOL InitializeFlatSB(
    HWND hwnd
);

Initializes flat scroll bars for a particular window.

  • Returns nonzero if successful, or zero otherwise.
hwnd
Handle to the window that will receive flat scroll bars.

This API must be called before any other flat scroll bar APIs are called. The window will receive flat scroll bars by default. The scroll bar style can be changed with the FlatSB_SetScrollProp API.

Version 4.71


FlatSB_EnableScrollBar

BOOL FlatSB_EnableScrollBar(
    HWND hwnd,
    int wSBflags,
    UINT wArrows
);

Enables or disables one or both flat scroll bar direction buttons. If flat scroll bars are not initialized for the window, this function calls the standard EnableScrollBar API.

  • Returns nonzero if the scroll bar changes, or zero otherwise.
hwnd
Handle to the window that contains the flat scroll bar. This window handle must have been passed previously in a call to InitializeFlatSB.
wSBflags
Parameter that specifies the scroll bar type. It can be one of the following values:
SB_BOTH | Enables or disables the direction buttons on the horizontal and vertical scroll bars.
SB_HORZ | Enables or disables the direction buttons on the horizontal scroll bar.
SB_VERT | Enables or disables the direction buttons on the vertical scroll bar.
wArrows
Parameter that specifies whether the scroll bar arrows are enabled or disabled and indicates which arrows are enabled or disabled. It can be one of the following values:
ESB_DISABLE_BOTH | Disables both direction buttons on the specified scroll bar.
ESB_DISABLE_DOWN | Disables the down direction button on the vertical scroll bar.
ESB_DISABLE_LEFT | Disables the left direction button on the horizontal scroll bar.
ESB_DISABLE_LTUP | Disables the left direction button on the horizontal scroll bar or the up direction button on the vertical scroll bar.
ESB_DISABLE_RIGHT | Disables the right direction button on the horizontal scroll bar.
ESB_DISABLE_RTDN | Disables the right direction button on the horizontal scroll bar or the down direction button on the vertical scroll bar.
ESB_DISABLE_UP | Disables the up direction button on the vertical scroll bar.
ESB_ENABLE_BOTH | Enables both direction buttons on the specified scroll bar.

Version 4.71


FlatSB_GetScrollInfo

BOOL FlatSB_GetScrollInfo(
    HWND hwnd,
    int fnBar,
    LPSCROLLINFO lpsi
);

Retrieves the information for a flat scroll bar. If flat scroll bars are not initialized for the window, this function calls the standard GetScrollInfo API.

  • Returns nonzero if successful, or zero otherwise.
hwnd
Handle to the window that contains the flat scroll bar. This window handle must have been passed previously in a call to InitializeFlatSB.
fnBar
Parameter that specifies the scroll bar type. It can be one of the following values:
SB_HORZ | Retrieves the information for the horizontal scroll bar.
SB_VERT | Retrieves the information for the vertical scroll bar.
lpsi
Address of a SCROLLINFO structure that will receive the information for the specified scroll bar. The cbSize and fMask members of the structure must be filled out prior to calling FlatSB_GetScrollInfo. The fMask member specifies which properties should be retrieved and can be any combination of the following values:
SIF_PAGE | Retrieves the page information for the flat scroll bar. This will be placed in the nPage member of the SCROLLINFO structure.
SIF_POS | Retrieves the position information for the flat scroll bar. This will be placed in the nPos member of the SCROLLINFO structure.
SIF_RANGE | Retrieves the range information for the flat scroll bar. This will be placed in the nMin and nMax members of the SCROLLINFO structure.
SIF_ALL | A combination of SIF_PAGE, SIF_POS, and SIF_RANGE.

Version 4.71


FlatSB_GetScrollPos

int FlatSB_GetScrollPos(
    HWND hwnd,
    int code
);

Retrieves the thumb position in a flat scroll bar. If flat scroll bars are not initialized for the window, this function calls the standard GetScrollPos API.

  • Returns the current thumb position of the specified flat scroll bar.
hwnd
Handle to the window that contains the flat scroll bar. This window handle must have been passed previously in a call to InitializeFlatSB.
code
Parameter that specifies the scroll bar type. It can be one of the following values:
SB_HORZ | Retrieves the thumb position of the horizontal scroll bar.
SB_VERT | Retrieves the thumb position of the vertical scroll bar.

Version 4.71


FlatSB_GetScrollProp

BOOL FlatSB_GetScrollProp(
    HWND hwnd,
    UINT index,
    LPINT pValue
);

Retrieves the properties for a flat scroll bar. This function can also be used to determine if InitializeFlatSB has been called for this window.

  • Returns nonzero if successful, or zero otherwise. If index is WSB_PROP_HSTYLE, the return is nonzero if InitializeFlatSB has been called for this window, or zero otherwise.
hwnd
Handle to the window that contains the flat scroll bar. This window handle must have been passed previously in a call to InitializeFlatSB.
index
Parameter that determines what pValue represents and which property is being retrieved. It can be one of the following values:
WSB_PROP_CXHSCROLL | pValue is an address of an INT value that receives the width, in pixels, of the direction buttons in a horizontal scroll bar.
WSB_PROP_CXHTHUMB | pValue is an address of an INT value that receives the width, in pixels, of the thumb in a horizontal scroll bar.
WSB_PROP_CXVSCROLL | pValue is an address of an INT value that receives the width, in pixels, of a vertical scroll bar.
WSB_PROP_CYHSCROLL | pValue is an address of an INT value that receives the height, in pixels, of a horizontal scroll bar.
WSB_PROP_CYVSCROLL | pValue is an address of an INT value that receives the height, in pixels, of the direction buttons in a vertical scroll bar.
WSB_PROP_CYVTHUMB | pValue is an address of an INT value that receives the height, in pixels, of the thumb in a vertical scroll bar.
WSB_PROP_HBKGCOLOR | pValue is an address of a COLORREF value that receives the background color in a horizontal scroll bar.
WSB_PROP_HSTYLE pValue is an address of an INT value that receives one of the following visual effects for the horizontal scroll bar.
FSB_ENCARTA_MODE | A standard flat scroll bar is displayed. When the mouse moves over a direction button or the thumb, that portion of the scroll bar is displayed in 3-D.
FSB_FLAT_MODE | A standard flat scroll bar is displayed. When the mouse moves over a direction button or the thumb, that portion of the scroll bar is displayed in inverted colors.
FSB_REGULAR_MODE | A normal, nonflat scroll bar is displayed. No special visual effects are applied.
WSB_PROP_PALETTE | pValue is an address of an HPALETTE value that receives the palette that a scroll bar uses when drawing.
WSB_PROP_VBKGCOLOR | pValue is an address of a COLORREF value that receives the background color in a vertical scroll bar.
WSB_PROP_VSTYLE pValue is an address of an INT value that receives one of the following visual effects for the vertical scroll bar.
FSB_ENCARTA_MODE | A standard flat scroll bar is displayed. When the mouse moves over a direction button or the thumb, that portion of the scroll bar is displayed in 3-D.
FSB_FLAT_MODE | A standard flat scroll bar is displayed. When the mouse moves over a direction button or the thumb, that portion of the scroll bar is displayed in inverted colors.
FSB_REGULAR_MODE | A normal, nonflat scroll bar is displayed. No special visual effects are applied.
WSB_PROP_WINSTYLE | pValue is an address of an INT value that receives the WS_HSCROLL and WS_VSCROLL style bits contained by the current window.
pValue
Address that receives the requested data. This parameter depends on the flag passed in index.

Version 4.71


FlatSB_GetScrollRange

BOOL FlatSB_GetScrollRange(
    HWND hwnd,
    int code,
    LPINT lpMinPos,
    LPINT lpMaxPos
);

Retrieves the scroll range for a flat scroll bar. If flat scroll bars are not initialized for the window, this function calls the standard GetScrollRange API.

  • Returns nonzero if successful, or zero otherwise.
hwnd
Handle to the window that contains the flat scroll bar. This window handle must have been passed previously in a call to InitializeFlatSB.
code
Parameter that specifies the scroll bar type. It can be one of the following values:
SB_HORZ | Retrieves the scroll range of the horizontal scroll bar.
SB_VERT | Retrieves the scroll range of the vertical scroll bar.
lpMinPos
Address of an INT value that receives the minimum scroll range value.
lpMaxPos
Address of an INT value that receives the maximum scroll range value.

Version 4.71


FlatSB_SetScrollInfo

int FlatSB_SetScrollInfo(
    HWND hwnd,
    int fnBar,
    LPSCROLLINFO lpsi,
    BOOL fRedraw
);

Sets the information for a flat scroll bar. If flat scroll bars are not initialized for the window, this function calls the standard SetScrollInfo API.

  • Returns the current scroll position. If the call to FlatSB_SetScrollInfo changes the scroll position, then the previous position is returned.
hwnd
Handle to the window that contains the flat scroll bar. This window handle must have been passed previously in a call to InitializeFlatSB.
fnBar
Parameter that specifies the scroll bar type. It can be one of the following values:
SB_HORZ | Sets the information for the horizontal scroll bar.
SB_VERT | Sets the information for the vertical scroll bar.
lpsi
Address of a SCROLLINFO structure that contains the new information for the specified scroll bar. The cbSize and fMask members of the structure must be filled in prior to calling FlatSB_SetScrollInfo. The fMask member specifies which members of the structure contain valid information and can be any combination of the following values:
SIF_DISABLENOSCROLL | Disables the scroll bar if the new information would cause the scroll bar to be removed.
SIF_PAGE | Sets the page information for the flat scroll bar. The nPage member of the SCROLLINFO structure must contain the new page value.
SIF_POS | Sets the position information for the flat scroll bar. The nPos member of the SCROLLINFO structure must contain the new position value.
SIF_RANGE | Sets the range information for the flat scroll bar. The nMin and nMax members of the SCROLLINFO structure must contain the new range values.
SIF_ALL | A combination of SIF_PAGE, SIF_POS, and SIF_RANGE.
fRedraw
Parameter that specifies whether the scroll bar should be redrawn immediately to reflect the change. If this parameter is TRUE, the scroll bar is redrawn; if it is FALSE, the scroll bar is not redrawn.

Version 4.71


FlatSB_SetScrollPos

int FlatSB_SetScrollPos(
    HWND hwnd,
    int code,
    int nPos,
    BOOL fRedraw
);

Sets the current position of the thumb in a flat scroll bar. If flat scroll bars are not initialized for the window, this function calls the standard SetScrollPos API.

  • Returns the previous position of the thumb in the specified flat scroll bar.
hwnd
Handle to the window that contains the flat scroll bar. This window handle must have been passed previously in a call to InitializeFlatSB.
code
Parameter that specifies the scroll bar type. It can be one of the following values:
SB_HORZ | Sets the thumb position of the horizontal scroll bar.
SB_VERT | Sets the thumb position of the vertical scroll bar.
nPos
Parameter that specifies the new thumb position.
fRedraw
Parameter that specifies whether the scroll bar should be redrawn immediately to reflect the change. If this parameter is TRUE, the scroll bar is redrawn; if it is FALSE, the scroll bar is not redrawn.

Version 4.71


FlatSB_SetScrollProp

BOOL FlatSB_SetScrollProp(
    HWND hwnd,
    UINT index,
    int newValue,
    BOOL fRedraw
);

Sets the properties for a flat scroll bar.

  • Returns nonzero if successful, or zero otherwise.
hwnd
Handle to the window that contains the flat scroll bar. This window handle must have been passed previously in a call to InitializeFlatSB.
index
Parameter that determines what newValue represents and which property is being set. This parameter can be one of the following values:
WSB_PROP_CXHSCROLL | newValue is an INT value that represents the width, in pixels, of the direction buttons in a horizontal scroll bar.
WSB_PROP_CXHTHUMB | newValue is an INT value that represents the width, in pixels, of the thumb in a horizontal scroll bar.
WSB_PROP_CXVSCROLL | newValue is an INT value that represents the width, in pixels, of the vertical scroll bar.
WSB_PROP_CYHSCROLL | newValue is an INT value that represents the height, in pixels, of the horizontal scroll bar.
WSB_PROP_CYVSCROLL | newValue is an INT value that represents the height, in pixels, of the direction buttons in a vertical scroll bar.
WSB_PROP_CYVTHUMB | newValue is an INT value that represents the height, in pixels, of the thumb in a vertical scroll bar.
WSB_PROP_HBKGCOLOR | newValue is a COLORREF value that represents the background color in a horizontal scroll bar.
WSB_PROP_HSTYLE newValue is one of the following values that changes the visual effects for the horizontal scroll bar.
FSB_ENCARTA_MODE | A standard flat scroll bar is displayed. When the mouse moves over a direction button or the thumb, that portion of the scroll bar will be displayed in 3-D.
FSB_FLAT_MODE | A standard flat scroll bar is displayed. When the mouse moves over a direction button or the thumb, that portion of the scroll bar will be displayed in inverted colors.
FSB_REGULAR_MODE | A normal, nonflat scroll bar is displayed. No special visual effects will be applied.
WSB_PROP_PALETTE | newValue is an HPALETTE value that represents the new palette that the scroll bar should use when drawing.
WSB_PROP_VBKGCOLOR | newValue is a COLORREF value that represents the background color in a vertical scroll bar.
WSB_PROP_VSTYLE newValue is one of the following values that changes the visual effects for the vertical scroll bar:
FSB_ENCARTA_MODE | A standard flat scroll bar is displayed. When the mouse moves over a direction button or the thumb, that portion of the scroll bar will be displayed in 3-D.
FSB_FLAT_MODE | A standard flat scroll bar is displayed. When the mouse moves over a direction button or the thumb, that portion of the scroll bar will be displayed in inverted colors.
FSB_REGULAR_MODE | A normal, nonflat scroll bar is displayed. No special visual effects will be applied.
newValue
New value to set. This parameter depends on the flag passed in index.
fRedraw
Parameter that specifies whether the scroll bar should be redrawn immediately to reflect the change. If this parameter is TRUE, the scroll bar is redrawn; if it is FALSE, the scroll bar is not redrawn.

Version 4.71


FlatSB_SetScrollRange

int FlatSB_SetScrollRange(
    HWND hwnd,
    int code,
    int nMinPos,
    int nMaxPos,
    BOOL fRedraw
);

Sets the scroll range of a flat scroll bar. If flat scroll bars are not initialized for the window, this function calls the standard SetScrollRange API.

  • Returns nonzero if successful, or zero otherwise.
hwnd
Handle to the window that contains the flat scroll bar. This window handle must have been passed previously in a call to InitializeFlatSB.
code
Parameter that specifies the scroll bar type. It can be one of the following values:
SB_HORZ | Sets the scroll range of the horizontal scroll bar.
SB_VERT | Sets the scroll range of the vertical scroll bar.
nMinPos
Parameter that specifies the new minimum scroll range value.
nMaxPos
Parameter that specifies the new maximum scroll range value.
fRedraw
Parameter that specifies whether the scroll bar should be redrawn immediately to reflect the change. If this parameter is TRUE, the scroll bar is redrawn; if it is FALSE, the scroll bar is not redrawn.

Version 4.71


FlatSB_ShowScrollBar

BOOL FlatSB_ShowScrollBar(
    HWND hwnd,
    int code,
    BOOL fShow
);

Shows or hides a flat scroll bar. If flat scroll bars are not initialized for the window, this function calls the standard ShowScrollBar API.

  • Returns nonzero if successful, or zero otherwise.
hwnd
Handle to the window that contains the flat scroll bar. This window handle must have been passed previously in a call to InitializeFlatSB.
code
Parameter that specifies the scroll bar type. It can be one of the following values:
SB_BOTH | Shows or hides the horizontal and vertical scroll bars.
SB_HORZ | Shows or hides the horizontal scroll bar.
SB_VERT | Shows or hides the vertical scroll bar.
fShow
Parameter that specifies whether the scroll bar should be shown or hidden. If this parameter is nonzero, the scroll bar will be shown; if it is zero, the scroll bar will be hidden.

Version 4.71


UninitializeFlatSB

HRESULT UninitializeFlatSB(
    HWND hwnd
);

Uninitializes flat scroll bars for a particular window. The specified window will revert to having standard scroll bars.

  • Returns one of the following values:
    E_FAIL | One of the window's scroll bars is currently in use. The operation cannot be completed at this time.
    S_FALSE | The window doesn't have flat scroll bars initialized.
    S_OK | The operation was successful.
hwnd
Handle to the window with the flat scroll bars that will be uninitialized.

Version 4.71


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 that give detailed information about files in a directory.

Header control with labeled columns.

Using Header Controls

Header Control Updates in Internet Explorer

Header Control Reference

Using Header Controls

You can create a header control by using the CreateWindowEx function, specifying the WC_HEADER window class and the appropriate header styles. 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.

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 HDLAYOUT 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, 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

A header control typically has several header items that define the columns of the control. You add an item to a header control by sending the HDM_INSERTITEM message to the control. The message includes the address of an HDITEM structure. This structure defines the properties of the header item, which can include a string, a bitmapped image, an initial size, and an application-defined 32-bit value.

The fmt member of an item's HDITEM structure can include either the HDF_STRING or HDF_BITMAP flag to indicate whether the control displays the item's string or bitmap. If you want to display both a string and a bitmap, create an owner-drawn item by setting the fmt member to include the HDF_OWNERDRAW flag. The HDITEM 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.

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 HDITEM 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 an address of 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 to the header control.
hDC | Handle to 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.

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 | Uninitializes the header control.
WM_ERASEBKGND | Fills the background of the header control using the control's current background color.
WM_GETDLGCODE | Returns a combination of the DLGC_WANTTAB and DLGC_WANTARROWS values.
WM_GETFONT | Returns the handle to 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 the HDN_BEGINTRACK notification message and begins dragging the divider. If the cursor is on an item, the item is displayed in the pressed state.
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 displays the item at the new position. If the left mouse button is down and the cursor is on an item, the item is displayed in the pressed state.
WM_NCCREATE | Allocates and initializes an internal data structure.
WM_NCDESTROY | Frees the resources allocated by the header control after the header control is uninitialized.
WM_PAINT | Paints the invalid region of the header control. If the wParam parameter is non-NULL, the control assumes that the value is an HDC and paints using that device context.
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.

Creating a Header Control

The following example demonstrates how to create a header control and position it along the top of the parent window's client area. The control is initially hidden. The HDM_LAYOUT message is used to calculate the size and position of the control within the parent window. The control is then repositioned and made visible.

    // DoCreateHeader - creates a header control that is positioned along
    //     the top of the parent window's client area.
    // Returns the handle to the header control.
    // hwndParent - handle to the parent window.
    //
    // Global variable
    //    g_hinst - handle to the application instance
    extern HINSTANCE g_hinst;

    HWND DoCreateHeader(HWND hwndParent)
    {
        HWND hwndHeader;
        RECT rcParent;
        HDLAYOUT 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 HDITEM 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 an item into a header control.
    // Returns the index of the new item.
    // hwndHeader - handle to 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)
    {
        HDITEM 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 Updates in Internet Explorer

Header controls in Microsoft® Internet Explorer support the following new features.

Image Lists
New messages for this feature include HDM_GETIMAGELIST and HDM_SETIMAGELIST. The header control structure HDITEM has been updated to support image lists. Image lists can be used with current bitmap support.
Callback Items
Currently, callback support includes header item text and images. Setting a header item's text to the LPSTR_TEXTCALLBACK value or its image to the I_IMAGECALLBACK value will cause the control to send an HDN_GETDISPINFO message to request callback information as needed. HDN_GETDISPINFO is supported by the new NMHDDISPINFO structure.
Custom Item Ordering
The new messages that support this feature are: HDM_GETORDERARRAY, HDM_SETORDERARRAY, and HDM_ORDERTOINDEX.
Drag-and-Drop Manipulation
Drag-and-drop reordering of header items is now available. Implement drag-and-drop support by including the HDS_DRAGDROP style when creating the control. By default, the header control automatically handles drag-and-drop overhead and graphic effects. However, the owner of the control can manually support drag-and-drop manipulation by handling the HDN_BEGINDRAG and HDN_ENDDRAG notification messages. While handling these notifications, the owner might need to send HDM_CREATEDRAGIMAGE and HDM_SETHOTDIVIDER messages.
Hot Tracking
When this feature is enabled, the item that is under the pointer will be highlighted. To enable hot tracking in a header control, create it with the HDS_HOTTRACK style.
Text, Bitmaps, and Images
Items can simultaneously display item text, a bitmap, and an image.


Header Control Reference

This section contains information about the programming elements used with header controls.

Header Control Styles

Messages
HDM_CREATEDRAGIMAGE
HDM_DELETEITEM
HDM_GETIMAGELIST
HDM_GETITEM
HDM_GETITEMCOUNT
HDM_GETITEMRECT
HDM_GETORDERARRAY
HDM_GETUNICODEFORMAT
HDM_HITTEST
HDM_INSERTITEM
HDM_LAYOUT
HDM_ORDERTOINDEX
HDM_SETHOTDIVIDER
HDM_SETIMAGELIST
HDM_SETITEM
HDM_SETORDERARRAY
HDM_SETUNICODEFORMAT

Utility Macros
Header_CreateDragImage
Header_DeleteItem
Header_GetImageList
Header_GetItem
Header_GetItemCount
Header_GetItemRect
Header_GetOrderArray
Header_GetUnicodeFormat
Header_InsertItem
Header_Layout
Header_OrderToIndex
Header_SetHotDivider
Header_SetImageList
Header_SetItem
Header_SetOrderArray
Header_SetUnicodeFormat

Notifications
HDN_BEGINDRAG
HDN_BEGINTRACK
HDN_DIVIDERDBLCLICK
HDN_ENDDRAG
HDN_ENDTRACK
HDN_GETDISPINFO
HDN_ITEMCHANGED
HDN_ITEMCHANGING
HDN_ITEMCLICK
HDN_ITEMDBLCLICK
HDN_TRACK
NM_CUSTOMDRAW (header)
NM_RCLICK (header)
NM_RELEASEDCAPTURE (header)

Structures
HD_HITTESTINFO
HD_ITEM
HD_LAYOUT
HD_NOTIFY
HDHITTESTINFO
HDITEM
HDLAYOUT
NMHDDISPINFO
NMHEADER


Header Control Styles

Header controls have a number of styles, described below, 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.

HDS_BUTTONS
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.
HDS_DRAGDROP
Version 4.70. Allows drag-and-drop reordering of header items.
HDS_FULLDRAG
Version 4.70. Causes the header control to display column contents even while the user resizes a column.
HDS_HIDDEN
Indicates a header control that is intended to be hidden. This style does not hide the control. Instead, when you send the HDM_LAYOUT message to a header control with the HDS_HIDDEN style, the control returns zero in the cy member of the WINDOWPOS structure. You would then hide the control by setting its height to zero. This can be useful when you want to use the control as an information container instead of a visual control.
HDS_HORZ
Creates a header control with a horizontal orientation.
HDS_HOTTRACK
Version 4.70. Enables hot tracking.


Header Control Messages

This section includes information about the messages for header controls.

HDM_CREATEDRAGIMAGE

HDM_DELETEITEM

HDM_GETIMAGELIST

HDM_GETITEM

HDM_GETITEMCOUNT

HDM_GETITEMRECT

HDM_GETORDERARRAY

HDM_GETUNICODEFORMAT

HDM_HITTEST

HDM_INSERTITEM

HDM_LAYOUT

HDM_ORDERTOINDEX

HDM_SETHOTDIVIDER

HDM_SETIMAGELIST

HDM_SETITEM

HDM_SETORDERARRAY

HDM_SETUNICODEFORMAT


HDM_CREATEDRAGIMAGE

HDM_CREATEDRAGIMAGE
    wParam = (WPARAM) (int) iIndex;
    lParam = 0;

Creates a semi-transparent version of an item's image for use as a dragging image. You can send this message explicitly or use the Header_CreateDragImage macro.

  • Returns a handle to an image list that contains the new image as its only element.
iIndex
Zero-based index of the item within the header control. The image assigned to this item is the basis for the transparent image.

Version 4.70


HDM_DELETEITEM

HDM_DELETEITEM
    wParam = (WPARAM) (int) index;
    lParam = 0;

Deletes an item from a header control. You can send this message explicitly or use the Header_DeleteItem macro.

  • Returns TRUE if successful, or FALSE otherwise.
index
Index of the item to delete.


HDM_GETIMAGELIST

HDM_GETIMAGELIST
    wParam = 0;
    lParam = 0;

Retrieves the handle to the image list that has been set for an existing header control. You can send this message explicitly or use the Header_GetImageList macro.

  • Returns a handle to the image list set for the header control.

Version 4.70


HDM_GETITEM

HDM_GETITEM
    wParam = (WPARAM) (int) index;
    lParam = (LPARAM) (LPHDITEM) phdi;

Retrieves information about an item in a header control. You can send this message explicitly or use the Header_GetItem macro.

  • Returns TRUE if successful, or FALSE otherwise.
index
Index of the item for which information is to be retrieved.
phdi
Address of an HDITEM 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.


HDM_GETITEMCOUNT

HDM_GETITEMCOUNT
    wParam = 0;
    lParam = 0;

Retrieves a count of the items in a header control. You can send this message explicitly or use the Header_GetItemCount macro.

  • Returns the number of items if successful, or -1 otherwise.


HDM_GETITEMRECT

HDM_GETITEMRECT
    wParam = (WPARAM) (int) iIndex;
    lParam = (LPARAM) lpItemRect;

Retrieves the bounding rectangle for a given item in a header control. You can send this message explicitly or use the Header_GetItemRect macro.

  • Returns nonzero if successful, or zero otherwise.
iIndex
Zero-based index of the header control item for which to retrieve the bounding rectangle.
lpItemRect
Address of a RECT structure that receives the bounding rectangle information.

Version 4.70


HDM_GETORDERARRAY

HDM_GETORDERARRAY
    wParam = (WPARAM) (int) iSize;
    lParam = (LPARAM) (LPINT) lpiArray;

Retrieves the current left-to-right order of items in a header control. You can send this message explicitly or use the Header_GetOrderArray macro.

  • Returns nonzero if successful, and the buffer at lpiArray receives the item number for each item in the header control in the order in which they appear from left to right. Otherwise, the message returns zero.
iSize
Number of integer elements that lpiArray can hold. This value must be equal to the number of items in the control (see HDM_GETITEMCOUNT).
lpiArray
Address of an array of integers that receive the index values for items in the header. The number of elements in this array is specified in iSize and must be equal to or greater than the number of items in the control. For example, the following code fragment will reserve enough memory to hold the index values.
int iItems,
    *lpiArray;

// Get memory for buffer.
(iItems = SendMessage(hwndHD, HDM_GETITEMCOUNT, 0,0))!=-1)
    if(!(lpiArray = calloc(iItems,sizeof(int))))
MessageBox(hwnd, "Out of memory.","Error", MB_OK);

Version 4.70


HDM_GETUNICODEFORMAT

HDM_GETUNICODEFORMAT
    wParam = 0;
    lParam = 0;

Retrieves the UNICODE character format flag for the control. You can send this message explicitly or use the Header_GetUnicodeFormat macro.

  • Returns the UNICODE format flag for the control. If this value is nonzero, the control is using UNICODE characters. If this value is zero, the control is using ANSI characters.

See also HDM_SETUNICODEFORMAT


HDM_HITTEST

HDM_HITTEST
    wParam = 0;
    lParam = (LPARAM) (LPHDHITTESTINFO) phdhti;

Tests a point to determine which header item, if any, is at the specified point.

  • Returns the index of the item at the specified position, if any, or – 1 otherwise.
phdhti
Address of an HDHITTESTINFO structure that contains the position to test and receives information about the results of the test.


HDM_INSERTITEM

HDM_INSERTITEM
    wParam = (WPARAM) (int) index;
    lParam = (LPARAM) (const LPHDITEM) phdi;

Inserts a new item into a header control. You can send this message explicitly or use the Header_InsertItem macro.

  • Returns the index of the new item if successful, or -1 otherwise.
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
Address of an HDITEM structure that contains information about the new item.


HDM_LAYOUT

HDM_LAYOUT
    wParam = 0;
    lParam = (LPARAM) (LPHDLAYOUT) playout;

Retrieves the correct size and position of a header control within the parent window. You can send this message explicitly or use the Header_Layout macro.

  • Returns TRUE if successful, or FALSE otherwise.
playout
Address of an HDLAYOUT 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.


HDM_ORDERTOINDEX

HDM_ORDERTOINDEX
    wParam = (WPARAM) iOrder;
    lParam = 0;

Retrieves an index value for an item based on its order in the header control. You can send this message explicitly or use the Header_OrderToIndex macro.

  • Returns INT that indicates the item index. If iOrder is invalid (negative or too large), the return equals iOrder.
iOrder
Order in which the item appears within the header control, from left to right. For example, the index value of the item in the far left column would be 0. The value for the next item to the right would be 1, and so on.

Version 4.70


HDM_SETHOTDIVIDER

HDM_SETHOTDIVIDER
    wParam = (WPARAM) flag;
    lParam = (LPARAM) dwInputValue;

Changes the color of a divider between header items to indicate the destination of an external drag-and-drop operation. You can send this message explicitly or use the Header_SetHotDivider macro.

  • Returns a value equal to the index of the divider that the control highlighted.
flag
Value specifying the type of value represented by dwInputValue. This value can be one of the following:
TRUE | Indicates that dwInputValue holds the client coordinates of the pointer.
FALSE | Indicates that dwInputValue holds a divider index value.
dwInputValue
Value held in dwInputValue is interpreted depending on the value of flag.

If flag is TRUE, dwInputValue represents the x- and y-coordinates of the pointer. The x-coordinate is in the low word, and the y-coordinate is in the high word. When the header control receives the message, it highlights the appropriate divider based on the dwInputValue coordinates.

If flag is FALSE, dwInputValue represents the integer index of the divider to be highlighted.

This message creates an effect that a header control automatically produces when it has the HDS_DRAGDROP style. The HDM_SETHOTDIVIDER message is intended to be used when the owner of the control handles drag-and-drop operations manually.

Version 4.70


HDM_SETIMAGELIST

HDM_SETIMAGELIST
    wParam = 0;
    lParam = (LPARAM) himl;

Assigns an image list to an existing header control. You can send this message explicitly or use the Header_SetImageList macro.

  • Returns the handle to the image list previously associated with the control. Returns NULL upon failure or if no image list was set previously.
himl
Handle to an image list.

Version 4.70


HDM_SETITEM

HDM_SETITEM
    wParam = (WPARAM)(int) iIndex;
    lParam = (LPARAM)(const LPHDITEM) phdItem;

Sets the attributes of the specified item in a header control. You can send this message explicitly or use the Header_SetItem macro.

  • Returns nonzero upon success, or zero otherwise.
iIndex
Current index of the item whose attributes are to be changed.
phdItem
Address of an HDITEM structure that contains item information. When this message is sent, the mask member of the structure must be set to indicate which attributes are being set.

The HDITEM structure that supports this message supports item order and image list information. By using these members, you can control the order in which items are displayed and specify images to appear with items.


HDM_SETORDERARRAY

HDM_SETORDERARRAY
    wParam = (WPARAM) (int) iSize;
    lParam = (LPARAM) lpiArray;

Sets the left-to-right order of header items. You can send this message explicitly or use the Header_SetOrderArray macro.

  • Returns nonzero if successful, or zero otherwise.
iSize
Size of the buffer at lpiArray, in elements. This value must equal the value returned by HDM_GETITEMCOUNT.
lpiArray
Address of an array that specifies the order in which items should be displayed, from left to right. For example, if the contents of the array are {2,0,1}, the control displays item 2, item 0, and item 1, from left to right.

Version 4.70


HDM_SETUNICODEFORMAT

HDM_SETUNICODEFORMAT
    wParam = (WPARAM)(BOOL)fUnicode;
    lParam = 0;

Sets the UNICODE character format flag for the control. This message allows you to change the character set used by the control at run time rather than having to re-create the control. You can send this message explicitly or use the Header_SetUnicodeFormat macro.

  • Returns the previous UNICODE format flag for the control.
fUnicode
Determines the character set that is used by the control. If this value is nonzero, the control will use UNICODE characters. If this value is zero, the control will use ANSI characters.

See also HDM_GETUNICODEFORMAT


Header Control Macros

This section contains information about header control macros.

Header_CreateDragImage

Header_DeleteItem

Header_GetImageList

Header_GetItem

Header_GetItemCount

Header_GetItemRect

Header_GetOrderArray

Header_GetUnicodeFormat

Header_InsertItem

Header_Layout

Header_OrderToIndex

Header_SetHotDivider

Header_SetImageList

Header_SetItem

Header_SetOrderArray

Header_SetUnicodeFormat


Header_CreateDragImage

HIMAGELIST Header_CreateDragImage(
    HWND hwndHD,
    int iIndex
);

Creates a transparent version of an item image within an existing header control. You can use this macro or send the HDM_CREATEDRAGIMAGE message explicitly.

  • Returns a handle to an image list that contains the new image as its only element.
hwndHD
Handle to a header control.
iIndex
Zero-based index of the item within the header control. The image assigned to this item is used as the basis for the transparent image.

Version 4.70


Header_DeleteItem

BOOL Header_DeleteItem(
    hwndHD,
    index
   );

Deletes an item from a header control. You can use this macro or send the HDM_DELETEITEM message explicitly.

  • Returns TRUE if successful, or FALSE otherwise.
hwndHD
Handle to the header control.
index
Index of the item to delete.

The Header_DeleteItem macro is defined as follows:

#define Header_DeleteItem(hwndHD, index)     \
      (BOOL)SendMessage((hwndHD), HDM_DELETEITEM, (WPARAM)(int)(index), 0L)


Header_GetImageList

HIMAGELIST Header_GetImageList(HWND hwndHD);

Retrieves the handle to the image list that has been set for an existing header control. You can use this macro or send the HDM_GETIMAGELIST message explicitly.

  • Returns the handle to the image list that is set for the header control.
hwndHD
Handle to a header control.

Version 4.70


Header_GetItem

BOOL Header_GetItem(
    hwndHD,
    index,
    phdi
   );

Retrieves information about an item in a header control. You can use this macro or send the HDM_GETITEM message explicitly.

  • Returns TRUE if successful, or FALSE otherwise.
hwndHD
Handle to the header control.
index
Index of the item for which information is to be retrieved.
phdi
Address of an HDITEM 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.

The Header_GetItem macro is defined as follows:

#define Header_GetItem(hwndHD, index, phdi)      \
    (BOOL)SendMessage((hwndHD), HDM_GETITEM,   \
    (WPARAM)(int)(index), (LPARAM)(LPHDITEM)(phdi))


Header_GetItemCount

int Header_GetItemCount(
    hwndHD
   );

Retrieves a count of the items in a header control. You can use this macro or send the HDM_GETITEMCOUNT message explicitly.

  • Returns the number of items if successful, or -1 otherwise.
hwndHD
Handle to the header control.

The Header_GetItemCount macro is defined as follows:

#define Header_GetItemCount(hwndHD)   \
       (int)SendMessage((hwndHD), HDM_GETITEMCOUNT, 0, 0L)


Header_GetItemRect

BOOL Header_GetItemRect(
    HWND hwndHD,
    int iIndex,
    LPRECT lpItemRect
);

Retrieves the bounding rectangle for a given item in a header control. You can use this macro or send the HDM_GETITEMRECT message explicitly.

  • Returns nonzero if successful, or zero otherwise.
hwndHD
Handle to a header control.
iIndex
Zero-based index of the header control item for which to retrieve the bounding rectangle.
lpItemRect
Address of a RECT structure that receives the bounding rectangle information.

Version 4.70


Header_GetOrderArray

BOOL Header_GetOrderArray(
    HWND hwndHD,
    int iSize,
    int *lpiArray
);

Retrieves the current left-to-right order of items in a header control. You can use this macro or send the HDM_GETORDERARRAY message explicitly.

  • Returns nonzero if successful, and the buffer at lpiArray receives the item number of each item in the header control in the order in which they appear from left to right. Returns zero otherwise.
hwndHD
Handle to a header control.
iSize
Number of integer elements that lpiArray can hold. This value must be equal to or greater than the number of items in the control (see HDM_GETITEMCOUNT).
lpiArray
Address of an array of integers that receive the index values for items in the header. The number of elements in this array is specified in iSize and must be equal to or greater than the number of items in the control. For example, the following code fragment will reserve enough memory to hold the index values.
int iItems,
    *lpiArray;

// Get memory for buffer
if((iItems = SendMessage(hwndHD, HDM_GETITEMCOUNT, 0,0))!=-1)
    if(!(lpiArray = calloc(iItems,sizeof(int))))
MessageBox(hwnd, "Out of memory.","Error", MB_OK);

Version 4.70


Header_GetUnicodeFormat

BOOL Header_GetUnicodeFormat(
    HWND hwnd
);

Retrieves the UNICODE character format flag for the control. You can use this macro or send the HDM_GETUNICODEFORMAT message explicitly.

  • Returns the UNICODE format flag for the control. If this value is nonzero, the control is using UNICODE characters. If this value is zero, the control is using ANSI characters.
hwnd
Handle to the control.

See also Header_SetUnicodeFormat


Header_InsertItem

int Header_InsertItem(
    hwndHD,
    index,
    phdi
   );

Inserts a new item into a header control. You can use this macro or send the HDM_INSERTITEM message explicitly.

  • Returns the index of the new item if successful, or -1 otherwise.
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
Address of an HDITEM structure that contains information about the new item.

The Header_InsertItem macro is defined as follows:

#define Header_InsertItem(hwndHD, index, phdi) \
    (int)SendMessage((hwndHD), HDM_INSERTITEM, (WPARAM)(int)(index), \
    (LPARAM)(const LPHDITEM)(phdi))


Header_Layout

BOOL Header_Layout(
    hwndHD,
    playout
   );

Retrieves the correct size and position of a header control within the parent window. You can use this macro or send the HDM_LAYOUT message explicitly.

  • Returns TRUE if successful, or FALSE otherwise.
hwndHD
Handle to the header control.
playout
Address of an HDLAYOUT 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.

The Header_Layout macro is defined as follows:

#define Header_Layout(hwndHD, playout) \
    (BOOL)SendMessage((hwndHD), HDM_LAYOUT, 0, \
    (LPARAM)(PLHDLAYOUT)(playout))


Header_OrderToIndex

int Header_OrderToIndex(
    HWND hwndHD,
    int iOrder
);

Retrieves an index value for an item based on its order in the header control. You can use this macro or send the HDM_ORDERTOINDEX message explicitly.

  • Returns an INT that specifies the index of the item. If iOrder is invalid (negative or too large), the return equals iOrder.
hwndHD
Handle to a header control.
iOrder
Order that the item appears within the header control, from left to right. The index value of the item in the far left column would be 0, the next item to the right would be 1, and so on.

Version 4.70


Header_SetHotDivider

int Header_SetHotDivider(
    HWND hwndHD,
    BOOL flag,
    DWORD dwInputValue
);

Changes the color of a divider between header items to indicate the destination of an external drag-and-drop operation. You can use this macro or send the HDM_SETHOTDIVIDER message explicitly.

  • Returns the index of the divider that the control highlighted.
hwndHD
Handle to a header control.
flag
Value specifying how dwInputValue is to be interpreted. The value in this field can be one of the following:
TRUE | Indicates that dwInputValue holds client coordinates of the pointer.
FALSE | Indicates that dwInputValue holds a divider index value.
dwInputValue
Value held here is interpreted depending on the value of flag.

If flag is TRUE, dwInputValue represents the x- and y- client coordinates of the pointer. The x-coordinate is in the low word, and the y-coordinate is in the high word. Upon receiving the message, the header control highlights the appropriate divider based on the dwInputValue coordinates.

If flag is FALSE, dwInputValue represents the integer index of the divider that will be highlighted.

A header control set to the HDS_DRAGDROP style produces this effect automatically. This message is intended to be used when the owner of the control handles drag-and-drop operations manually.

Version 4.70


Header_SetImageList

HIMAGELIST Header_SetImageList(
    HWND hwndHD,
    HIMAGELIST himl
);

Assigns an image list to an existing header control. You can use this macro or send the HDM_SETIMAGELIST message explicitly.

  • Returns the handle to the image list previously assigned to the header control, or NULL if there is no previous image list.
hwndHD
Handle to a header control.
himl
Handle to an image list.

Version 4.70


Header_SetItem

BOOL Header_SetItem(
    hwndHD,
    iIndex;
    phdItem
);

Sets the attributes of the specified item in a header control. You can use this macro or send the HDM_SETITEM message explicitly.

  • Returns nonzero if successful, or zero otherwise.
hwndHD
Handle to a header control.
iIndex
Current index of the item whose attributes are to be changed.
phdItem
Address of an HDITEM structure that contains item information. When this message is sent, the mask member of the structure must be set to indicate which attributes are being set.

The HDITEM structure that supports this macro supports item order and image list information. By using these members, you can control the order in which items are displayed and specify images to appear with items.


Header_SetOrderArray

BOOL Header_SetOrderArray(
    HWND hwndHD,
    int iSize,
    int *lpiArray
);

Sets the left-to-right order of header items. You can use this macro or send the HDM_SETORDERARRAY message explicitly.

  • Returns nonzero if successful, or zero otherwise.
hwndHD
Handle to a header control.
iSize
Size of the buffer at lpiArray, in elements. This value must equal the value returned by HDM_GETITEMCOUNT.
lpiArray
Address of an array that specifies the order in which items should be displayed, from left to right. For example, if the contents of the array are {2,0,1}, the control displays item 2, item 0, and item 1, from left to right.

Version 4.70


Header_SetUnicodeFormat

BOOL Header_SetUnicodeFormat(
    HWND hwnd,
    BOOL fUnicode
);

Sets the UNICODE character format flag for the control. This message allows you to change the character set used by the control at run time rather than having to re-create the control. You can use this macro or send the HDM_SETUNICODEFORMAT message explicitly.

  • Returns the previous UNICODE format flag for the control.
hwnd
Handle to the control.
fUnicode
Determines the character set that is used by the control. If this value is nonzero, the control will use UNICODE characters. If this value is zero, the control will use ANSI characters.

See also Header_GetUnicodeFormat


Header Control Notification Messages

This section contains information about the notification messages sent by header controls.

HDN_BEGINDRAG

HDN_BEGINTRACK

HDN_DIVIDERDBLCLICK

HDN_ENDDRAG

HDN_ENDTRACK

HDN_GETDISPINFO

HDN_ITEMCHANGED

HDN_ITEMCHANGING

HDN_ITEMCLICK

HDN_ITEMDBLCLICK

HDN_TRACK

NM_CUSTOMDRAW (header)

NM_RCLICK (header)

NM_RELEASEDCAPTURE (header)


HDN_BEGINDRAG

HDN_BEGINDRAG
   pNMHeader = (LPNMHEADER) lParam;

Sent by a header control when a drag operation has begun on one of its items. This notification message is sent only by header controls that are set to the HDS_DRAGDROP style. This notification is sent in the form of a WM_NOTIFY message.

  • To allow the header control to automatically manage drag-and-drop operations, return FALSE. If the owner of the control is manually performing drag-and-drop reordering, return TRUE.
pNMHeader
Address of an NMHEADER structure containing information about the header item that is being dragged.

A header control defaults to automatically managing drag-and-drop reordering. Returning TRUE to indicate external (manual) drag-and-drop management allows the owner of the control to provide custom services as part of the drag-and-drop process.

Version 4.70


HDN_BEGINTRACK

HDN_BEGINTRACK
    phdn = (LPNMHEADER) lParam;

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.

  • Returns FALSE to allow tracking of the divider, or TRUE to prevent tracking.
phdn
Address of an NMHEADER structure that contains information about the header control and the item whose divider is to be dragged.


HDN_DIVIDERDBLCLICK

HDN_DIVIDERDBLCLICK
    phdn = (LPNMHEADER) lParam;

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.

  • No return value.
phdn
Address of an NMHEADER structure that contains information about the header control and the item whose divider was double-clicked.


HDN_ENDDRAG

HDN_ENDDRAG
   pNMHeader = (LPNMHEADER) lParam;

Sent by a header control when a drag operation has ended on one of its items. This notification is sent as a WM_NOTIFY message. Only header controls that are set to the HDS_DRAGDROP style send this notification.

  • To allow the control to automatically place and reorder the item, return FALSE. To prevent the item from being placed, return TRUE.
pNMHeader
Address of an NMHEADER structure containing information about the header item that was being dragged.

If the owner is performing external (manual) drag-and-drop management, it must return FALSE. The owner then must reorder header items manually by sending HDM_SETITEM or HDM_SETORDERARRAY.

Version 4.70


HDN_ENDTRACK

HDN_ENDTRACK
    phdn = (LPNMHEADER) lParam;

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.

  • No return value.
phdn
Address of an NMHEADER structure that contains information about the header control and the item whose divider was dragged.


HDN_GETDISPINFO

HDN_GETDISPINFO
   pDispInfo = (LPNMHDDISPINFO) lParam;

Sent to the owner of a header control when the control needs information about a callback header item. This notification is sent as a WM_NOTIFY message.

pDispInfo
Address of an NMHDDISPINFO structure. On input, the fields of the structure specify what information is required and the item of interest.

Fill the appropriate members of the structure to return the requested information to the header control. If your message handler sets the mask member of the NMHDDISPINFO structure to HDI_DI_SETITEM, the header control stores the information and will not request it again.

Version 4.70


HDN_ITEMCHANGED

HDN_ITEMCHANGED
    phdr = (LPNMHEADER) lParam;

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.

  • No return value.
phdr
Address of an NMHEADER structure that contains information about the header control, including the attributes that have changed.


HDN_ITEMCHANGING

HDN_ITEMCHANGING
    phdr = (LPNMHEADER) lParam;

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.

  • Returns FALSE to allow the changes, or TRUE to prevent them.
phdr
Address of an NMHEADER structure that contains information about the header control and the header item, including the attributes that are about to change.


HDN_ITEMCLICK

HDN_ITEMCLICK
    phdr = (LPNMHEADER) lParam;

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.

  • No return value.
phdr
Address of an NMHEADER 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.

A header control sends this notification message after the user releases the left mouse button.


HDN_ITEMDBLCLICK

HDN_ITEMDBLCLICK
    pnmhdr = (LPNMHEADER) lParam;

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 are set to the HDS_BUTTONS style send this notification.

  • No return value.
pnmhdr
Address of an NMHEADER structure that contains information about this notification.


HDN_TRACK

HDN_TRACK
    phdr = (LPNMHEADER) lParam;

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.

  • Returns FALSE to continue tracking the divider, or TRUE to end tracking.
phdr
Address of an NMHEADER structure that contains information about the header control and the item whose divider is being dragged.


NM_CUSTOMDRAW (header)

NM_CUSTOMDRAW
    lpNMCustomDraw = (LPNMCUSTOMDRAW) lParam;

Sent by a header control to notify its parent window about drawing operations. This notification is sent in the form of a WM_NOTIFY message.

  • The value your application can return depends on the current drawing stage. The dwDrawStage member of the associated NMCUSTOMDRAW structure holds a value that specifies the drawing stage. You must return one of the following values.

    When dwDrawStage equals CDDS_PREPAINT:
    CDRF_DODEFAULT
    The control will draw itself. It will not send any additional NM_CUSTOMDRAW messages for this paint cycle.
    CDRF_NOTIFYITEMDRAW
    The control will notify the parent of any item-related drawing operations. It will send NM_CUSTOMDRAW notification messages before and after drawing items.
    CDRF_NOTIFYITEMERASE
    The control will notify the parent when an item will be erased. It will send NM_CUSTOMDRAW notification messages before and after erasing items.
    CDRF_NOTIFYPOSTERASE
    The control will notify the parent after erasing an item.
    CDRF_NOTIFYPOSTPAINT
    The control will notify the parent after painting an item.
    CDRF_NOTIFYSUBITEMDRAW
    Version 4.71. The control will notify the parent when a list view sub-item is being drawn.

    When dwDrawStage equals CDDS_ITEMPREPAINT:
    CDRF_NEWFONT
    Your application specified a new font for the item; the control will use the new font. For more information on changing fonts, see Changing fonts and colors.
    CDRF_SKIPDEFAULT
    Your application drew the item manually. The control will not draw the item.

lpNMCustomDraw
Address of an NMCUSTOMDRAW structure that contains information about the drawing operation. The dwItemSpec member of this structure contains the index of the item being drawn and the lItemlParam member of this structure contains the item's lParam.

Version 4.70

See also Using Custom Draw


NM_RCLICK (header)

NM_RCLICK
    lpnmh = (LPNMHDR) lParam;

Notifies a tree view control's parent window that the user has clicked the right mouse button within the control. This notification is sent in the form of a WM_NOTIFY message.

  • Return nonzero to not allow the default processing, or zero to allow the default processing.
lpnmh
Address of an NMHDR structure that contains additional information about this notification message.


NM_RELEASEDCAPTURE (header)

NM_RELEASEDCAPTURE
    lpnmh = (LPNMHDR) lParam;

Notifies a header control's parent window that the control is releasing mouse capture. This notification is sent in the form of a WM_NOTIFY message.

  • The control ignores the return value from this notification.
lpnmh
Address of an NMHDR structure that contains additional information about this notification message.

Version 4.71


Header Control Structures

This section contains information on the structures used to support header controls.

HDHITTESTINFO

HDITEM

HDLAYOUT

NMHDDISPINFO

NMHEADER


HDHITTESTINFO

typedef struct _HD_HITTESTINFO {
    POINT pt;
    UINT flags;
    int iItem;
} HDHITTESTINFO, FAR *LPHDHITTESTINFO;

Contains information about a hit test. This structure is used with the HDM_HITTEST message. This structure supersedes the HD_HITTESTINFO structure.

pt
POINT structure that contains the point to be 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:
HHT_NOWHERE | The point is inside the header control's bounding rectangle 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 header control's bounding rectangle.
HHT_TOLEFT | The point is to the left of the header control's bounding rectangle.
HHT_TORIGHT | The point is to the right of the header control's bounding rectangle.

Two of these values can be combined, such as when the position is above and to the left of the client area.

iItem
If the hit test is successful, contains the index of the item at the hit test point.


HDITEM

typedef struct _HDITEM {
    UINT    mask;
    int     cxy;
    LPTSTR  pszText;
    HBITMAP hbm;
    int     cchTextMax;
    int     fmt;
    LPARAM  lParam;
#if (_WIN32_IE >= 0x0300)
    int     iImage;
    int     iOrder;
#endif
} HDITEM, FAR * LPHDITEM;

Contains information about an item in a header control. This structure supersedes the HD_ITEM structure.

mask
Flags indicating which other structure members contain valid data or must be filled in. This member can be a combination of the following values:
HDI_BITMAP | The hbm member is valid.
HDI_FORMAT | The fmt member is valid.
HDI_HEIGHT | The cxy member is valid and specifies the item's height.
HDI_IMAGE | Version 4.70. The iImage member is valid and specifies the image to be displayed with the item.
HDI_LPARAM | The lParam member is valid.
HDI_ORDER | Version 4.70. The iOrder member is valid and specifies the item's order value.
HDI_TEXT | The pszText and cchTextMax members are valid.
HDI_WIDTH | The cxy member is valid and specifies the item's width.
cxy
Width or height of the item.
pszText
Address of an item string. If this member is set to LPSTR_TEXTCALLBACK, the control will request text information for this item by sending an HDN_GETDISPINFO notification message.
hbm
Handle to the item bitmap.
cchTextMax
Length of the item string, in characters.
fmt
Set of bit flags that specify the item's format.

This member can include one of the following text justification or right-to-left reading order bit flags:
HDF_CENTER | The item's contents are centered.
HDF_LEFT | The item's contents are left-aligned.
HDF_RIGHT | The item's contents are right-aligned.
HDF_RTLREADING | Text is displayed using right-to-left reading order for Hebrew or Arabic systems.

The flag from the preceding list is combined with one of the following values:
HDF_BITMAP | The item displays a bitmap.
HDF_BITMAP_ON_RIGHT | Version 4.70. The bitmap appears to the right of text. This does not affect an image from an image list assigned to the header item.
HDF_IMAGE | Version 4.70. The item displays an image from the image list.
HDF_OWNERDRAW | The header control's owner draws the item.
HDF_STRING | The item displays a string.

Additionally, the following flag can be combined with any of the preceding flags:
HDF_IMAGE The item displays an image from an image list.

You can use the HDF_JUSTIFYMASK mask to isolate the text justification portion of the fmt member.

lParam
Application-defined item data.
iImage
Version 4.70. Zero-based index of an image within the image list. The specified image will be displayed in the header item in addition to any image specified in the hbm field. If iImage is set to I_IMAGECALLBACK, the control requests text information for this item by using an HDN_GETDISPINFO notification message.
iOrder
Version 4.70. Order in which the item appears within the header control, from left to right. That is, the value for the far left item is 0. The value for the next item to the right is 1, and so on.

The header control can display text, an image, and a bitmap for an item all at the same time. The alignment flags determine the order in which they appear. With HDF_LEFT or HDF_CENTER, the order is image, text, and then bitmap. With HDF_RIGHT the order is bitmap, image, and then text.


HDLAYOUT

typedef struct _HD_LAYOUT {
    RECT FAR*      prc;
    WINDOWPOS FAR* pwpos;
} HDLAYOUT, FAR *LPHDLAYOUT;

Contains information used to set the size and position of a header control. This structure is used with the HDM_LAYOUT message. This structure supersedes the HD_LAYOUT structure.

prc
Address of a RECT structure that contains the coordinates of a rectangle that the header control will occupy.
pwpos
Address of a WINDOWPOS structure that receives information about the appropriate size and position of the header control.


NMHDDISPINFO

typedef struct tagNMHDDISPINFO {
    NMHDR   hdr;
    int     iItem;
    UINT    mask;
    LPTSTR  pszText;
    int     cchTextMax;
    int     iImage;
    LPARAM  lParam;
} NMHDDISPINFO, FAR* LPNMHDDISPINFO;

Contains information used in handling HDN_GETDISPINFO notification messages.

hdr
NMHDR structure containing information about this notification message.
iItem
Zero-based index of the item in the header control.
mask
Set of bit flags specifying which members of the structure must be filled in by the owner of the header control. This value can be a combination of the following values:
HDI_TEXT | The pszText field must be filled in.
HDI_IMAGE | The iImage field must be filled in.
HDI_LPARAM | The lParam field must be filled in.
HDI_DI_SETITEM | A return value. Indicates that the header control should store the item information and not ask for it again.
pszText
Address of a null-terminated string containing the text that will be displayed for the header item.
cchTextMax
Size of the buffer that pszText points to.
iImage
Zero-based index of an image within the image list. The specified image will be displayed with the header item, but it does not take the place of the item's bitmap. If iImage is set to I_IMAGECALLBACK, the control requests image information for this item by using an HDN_GETDISPINFO notification message.
lParam
32-bit value to associate with the item.

Version 4.70


NMHEADER

typedef struct tagNMHEADER{
    NMHDR    hdr;
    int      iItem;
    int      iButton;
    HDITEM  FAR* pitem;
} NMHEADER, FAR* LPNMHEADER;

Contains information about header control notification messages. This structure supersedes the HD_NOTIFY structure.

hdr
NMHDR structure that contains information about the notification message.
iItem
Zero-based index of the header item that is the focus of the notification message.
iButton
Value specifying the index of the mouse button used to generate the notification message. This member can be one of the following values:
0 | Left button
1 | Right button
2 | Middle button
pitem
Address of an HDITEM structure containing information specific to the item indicated by iItem.


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.

Using Hot Key Controls

Hot Key Control Reference

Using 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 presses 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 may provide 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.

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 entered accidentally 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;
}

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

Hot Key Control Notifications

The hot key control does not send any notification messages via the WM_NOTIFY message. It will, however, send the EN_CHANGE notification via the WM_COMMAND message when the user changes the contents of the control.

Retrieving and Setting a Hot Key

After the user has chosen a hot key, an application should retrieve it 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;
    }
}

Default Hot Key Message Processing

This section describes the window messages handled by the window procedure for the pre defined 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, clears any 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. All 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. All other keys are set as hot keys without their validity being checked first.
WM_SYSKEYUP | Retrieves the virtual key code.


Hot Key Control Reference

This section contains information about the following programming elements used with hot key controls.

Hot Key Control Messages

The following messages are associated with hot key controls.

HKM_GETHOTKEY

HKM_SETHOTKEY

HKM_SETRULES


HKM_GETHOTKEY

HKM_GETHOTKEY
    wParam = 0;
    lParam = 0;

Retrieves the virtual key code and modifier flags of a hot key from a hot key control.

  • 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:
    HOTKEYF_ALT | ALT key
    HOTKEYF_CONTROL | CTRL key
    HOTKEYF_EXT | Extended key
    HOTKEYF_SHIFT | SHIFT key

The 16-bit value returned by this message can be used as the wParam parameter in the WM_SETHOTKEY message.


HKM_SETHOTKEY

HKM_SETHOTKEY
    wParam = MAKEWORD(bVKHotKey, bfMods);
    lParam = 0;

Sets the hot key combination for a hot key control.

  • No return value.
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.

See also WM_GETHOTKEY


HKM_SETRULES

HKM_SETRULES
    wParam = (WPARAM) fwCombInv;
    lParam = MAKELPARAM(fwModInv, 0);

Defines the invalid combinations and the default modifier combination for a hot key control.

  • No return value.
fwCombInv
Array of flags that specify invalid key combinations. This parameter can be a combination of the following values:
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.

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.


Image Lists

An image list is a collection of images of the same size, 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 can also include a monochrome bitmap that contains masks used to draw images transparently (icon style).

Using Image Lists

Image List Updates in Internet Explorer

Image List Reference

Using Image Lists

The Microsoft® Win32® application programming interface (API) provides image list functions that enable you to create and destroy image lists, add and remove images, replace and merge images, draw images, and drag images.

To use the image list functions, 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, 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.

Creating and Destroying Image Lists

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 common control DLL contains the executable code for the image list functions.

In ImageList_Create, you specify the initial number of images that will be in an image list as well as the number of images by which the list can grow. So if you attempt to add more images than you initially specified, the image list automatically grows to accommodate the new images.

If ImageList_Create succeeds, it returns a handle to 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.

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 to the new image list.
    // hinst - handle to 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 to new image list
        HICON hicon;           // handle to 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;
    }

Adding and Removing Images

You can add bitmapped images, icons, or cursors to an image list. You add bitmapped images by specifying the handles to 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 1. 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 to 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 to an image list, the index of the image to draw, the handle to 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.

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 to the window in which to draw the image.
    // himl - handle to 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;
    }

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 to 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 to 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 the 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. Be careful, however, not to obliterate the dragged image.

The ImageList_SetDragCursorImage function 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 a temporary, internal image list and then copies the specified drag image to the internal list. You can retrieve the handle to 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.

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 to the window in which the bitmap is dragged.
    // ptCur - coordinates of the cursor.
    // himl - handle to 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 to the window in which the bitmap is dragged.
    // himl - handle to 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 Information

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

Image Overlays

Every image list includes a list of indexes to use as overlays. An overlay is an image that is drawn transparently over another image. Any image currently in the image list can be used as an overlay. You can specify up to four overlays per image list. This limit has been expanded to 15 in version 4.71.

You add the index of an image to the list of overlays by using the ImageList_SetOverlayImage function, specifying the handle to the image list, the index of the existing image, and the desired overlay index. This, in effect, tells the image list that "the image at index x can be used as an overlay, and I want to refer to the overlay as overlay index y." The overlay indexes are one-based rather than zero-based because an overlay index of zero means that no overlay will be used.

You specify an overlay when drawing an image with the ImageList_Draw or ImageList_DrawEx function. The overlay is specified by performing a logical OR operation between the desired drawing flags and the result of the INDEXTOOVERLAYMASK macro. The INDEXTOOVERLAYMASK macro takes the overlay index and formats it for inclusion with the flags for these functions. This will draw the image with the specified overlay. The following example demonstrates how an overlay is added and specified when drawing the image.

ImageList_SetOverlayImage(himl, 0, 3);
ImageList_Draw(himl, 1, hdc, 0, 0, ILD_MASK | INDEXTOOVERLAYMASK(3));

This will draw image 1 and then overlay that image with image 0. Because 3 is the overlay index that you specified in the ImageList_SetOverlayImage call, 3 is placed in the INDEXTOOVERLAYMASK macro.

Image List Updates in Internet Explorer

The following features were added to the image list by Microsoft® Internet Explorer.

Copying Images
Copy or swap images within an image list using the ImageList_Copy function. This function allows you to indicate whether the source image should be copied to the destination index or the source and destination images should be swapped. Currently, this is allowed only within a single image list.
Duplicating Image Lists
Take an existing image list and duplicate all of its parameters and contents into a new image list using the ImageList_Duplicate function. The image list returned by this function is an exact duplicate of the original image list and must be destroyed separately. Changes made to one image list do not affect the other.
Dynamic Resizing of Image Lists
Modify the number of images in an image list on the fly using the ImageList_SetImageCount function. If the number of images is increased, you must use the ImageList_Replace function to place images in the added slots. If the number of images is reduced, the images beyond the new size are freed and are no longer available.
Extended Drawing of Images
You now have more control over the drawing of images with the ImageList_DrawIndirect function. This function takes an IMAGELISTDRAWPARAMS structure that specifies the details that will be used when drawing the image. With this function, you can now specify things like ROP codes when drawing.


Image List Reference

This section contains information about the programming elements used with image lists.

Functions
ImageList_Add
ImageList_AddMasked
ImageList_BeginDrag
ImageList_Copy
ImageList_Create
ImageList_Destroy
ImageList_DragEnter
ImageList_DragLeave
ImageList_DragMove
ImageList_DragShowNolock
ImageList_Draw
ImageList_DrawEx
ImageList_DrawIndirect
ImageList_Duplicate
ImageList_EndDrag
ImageList_GetBkColor
ImageList_GetDragImage
ImageList_GetIcon
ImageList_GetIconSize
ImageList_GetImageCount
ImageList_GetImageInfo
ImageList_LoadImage
ImageList_Merge
ImageList_Read
ImageList_Remove
ImageList_Replace
ImageList_ReplaceIcon
ImageList_SetBkColor
ImageList_SetDragCursorImage
ImageList_SetIconSize
ImageList_SetImageCount
ImageList_SetOverlayImage
ImageList_Write

Macros
ImageList_AddIcon
ImageList_ExtractIcon
ImageList_LoadBitmap
ImageList_RemoveAll
INDEXTOOVERLAYMASK

Structures
IMAGEINFO
IMAGELISTDRAWPARAMS


Image List Functions

This section contains information about the functions used with image lists.

ImageList_Add

ImageList_AddMasked

ImageList_BeginDrag

ImageList_Copy

ImageList_Create

ImageList_Destroy

ImageList_DragEnter

ImageList_DragLeave

ImageList_DragMove

ImageList_DragShowNolock

ImageList_Draw

ImageList_DrawEx

ImageList_DrawIndirect

ImageList_Duplicate

ImageList_EndDrag

ImageList_GetBkColor

ImageList_GetDragImage

ImageList_GetIcon

ImageList_GetIconSize

ImageList_GetImageCount

ImageList_GetImageInfo

ImageList_LoadImage

ImageList_Merge

ImageList_Read

ImageList_Remove

ImageList_Replace

ImageList_ReplaceIcon

ImageList_SetBkColor

ImageList_SetDragCursorImage

ImageList_SetIconSize

ImageList_SetImageCount

ImageList_SetOverlayImage

ImageList_Write


ImageList_Add

int ImageList_Add(
    HIMAGELIST himl,
    HBITMAP hbmImage,
    HBITMAP hbmMask
   );

Adds an image or images to an image list.

  • Returns the index of the first new image if successful, or -1 otherwise.
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.

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.


ImageList_AddMasked

int ImageList_AddMasked(
    HIMAGELIST himl,
    HBITMAP hbmImage,
    COLORREF crMask
   );

Adds an image or images to an image list, generating a mask from the specified bitmap.

  • Returns the index of the first new image if successful, or -1 otherwise.
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 1.

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.


ImageList_BeginDrag

BOOL ImageList_BeginDrag(
    HIMAGELIST himlTrack,
    int iTrack,
    int dxHotspot,
    int dyHotspot
   );

Begins dragging an image.

  • Returns nonzero if successful, or zero otherwise.
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.

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.


ImageList_Copy

BOOL ImageList_Copy(
    HIMAGELIST himlDst,
    int        iDst,
    HIMAGELIST himlSrc,
    int        iSrc,
    UINT       uFlags);

Copies images within a given image list.

  • Returns nonzero if successful, or zero otherwise.
himlDst and himlSrc
Handle to an image list that is the target of the copy operation. In current versions of Windows®, both parameters must be identical.
iDst
Zero-based index of the image to be used as the destination of the copy operation.
iSrc
Zero-based index of the image to be used as the source of the copy operation.
uFlags
Bit flag value that specifies the type of copy operation to be made. This parameter can be one of the following values:
ILCF_MOVE | The source image is copied to the destination image's index. This operation results in multiple instances of a given image.
ILCF_SWAP | The source and destination images exchange positions within the image list.

Version 4.70


ImageList_Create

HIMAGELIST ImageList_Create(
    int cx,
    int cy,
    UINT flags,
    int cInitial,
    int cGrow
   );

Creates a new image list.

  • Returns the handle to the image list if successful, or NULL otherwise.
cx
Width, in pixels, of each image.
cy
Height, in pixels, of each image.
flags
Set of bit flags that specify the type of image list to create. This parameter can be a combination of the following values, but it can include only one of the ILC_COLOR values.
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 | Use 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.
cInitial
Number of images that the image list initially contains.
cGrow
Number of images by which the image list can grow when the system needs to make room for new images. This parameter represents the number of new images that the resized image list can contain.


ImageList_Destroy

BOOL ImageList_Destroy(
    HIMAGELIST himl
   );

Destroys an image list.

  • Returns nonzero if successful, or zero otherwise.
himl
Handle to the image list to destroy.


ImageList_DragEnter

BOOL ImageList_DragEnter(
    HWND hwndLock,
    int x,
    int y
   );

Locks updates to the specified window during a drag operation and displays the drag image at the specified position within the window.

  • Returns nonzero if successful, or zero otherwise.
hwndLock
Handle to the window that owns the drag image.
x
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
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.

To begin a drag operation, use the ImageList_BeginDrag function.


ImageList_DragLeave

BOOL ImageList_DragLeave(
    HWND hwndLock
   );

Unlocks the specified window and hides the drag image, allowing the window to be updated.

  • Returns nonzero if successful, or zero otherwise.
hwndLock
Handle to the window that owns the drag image.


ImageList_DragMove

BOOL ImageList_DragMove(
    int x,
    int y
   );

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.

  • Returns nonzero if successful, or zero otherwise.
x
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
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.

To begin a drag operation, use the ImageList_BeginDrag function.


ImageList_DragShowNolock

BOOL ImageList_DragShowNolock(
    BOOL fShow
   );

Shows or hides the image being dragged.

  • Returns nonzero if successful, or zero otherwise.
fShow
Value specifying whether to show or hide the image being dragged. Specify TRUE to show the image or FALSE to hide the image.


ImageList_Draw

BOOL ImageList_Draw(
    HIMAGELIST himl,
    int i,
    HDC hdcDst,
    int x,
    int y,
    UINT fStyle
   );

Draws an image list item in the specified device context.

  • Returns nonzero if successful, or zero otherwise.
himl
Handle to the image list.
i
Index of the image to draw.
hdcDst
Handle to the destination device context.
x
X-coordinate at which to draw within the specified device context.
y
Y-coordinate at which to draw within the specified device context.
fStyle
Drawing style and, optionally, the overlay image. For information about specifying an overlay image index, see the comments section at the end of this topic. This parameter can be a combination of an overlay image index and one or more of the following values:
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.

An overlay image is drawn transparently over the primary image specified in the i parameter. To specify an overlay image in the fStyle parameter, use the INDEXTOOVERLAYMASK macro to shift the one-based index of the overlay image. Use the OR operator to logically combine the return value of the macro with the drawing style flags specified in the fStyle parameter. You must first specify this image as an overlay image by using the ImageList_SetOverlayImage function.


ImageList_DrawEx

BOOL ImageList_DrawEx(
    HIMAGELIST himl,
    int i,
    HDC hdcDst,
    int x,
    int y,
    int dx,
    int dy,
    COLORREF rgbBk,
    COLORREF rgbFg,
    UINT fStyle
   );

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.

  • Returns nonzero if successful, or zero otherwise.
himl
Handle to the image list
i
Index of the image to draw.
hdcDst
Handle to the destination device context.
x
X-coordinate at which to draw within the specified device context.
y
Y-coordinate at which to draw within the specified device context.
dx
Width of the portion of the image to draw relative to the upper-left corner of the image. If dx and dy are zero, the function draws the entire image. The function does not ensure that the parameters are valid.
dy
Height of the portion of the image to draw, relative to the upper-left corner of the image. If dx and dy 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:
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:
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
Drawing style and, optionally, the overlay image. For information about specifying an overlay image index, see the comments section at the end of this topic. This parameter can be a combination of an overlay image index and one or more of the following values:
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.

An overlay image is drawn transparently over the primary image specified in the i parameter. To specify an overlay image in the fStyle parameter, use the INDEXTOOVERLAYMASK macro to shift the one-based index of the overlay image. Use the OR operator to logically combine the return value of the macro with the drawing style flags specified in the fStyle parameter. You must first specify this image as an overlay image by using the ImageList_SetOverlayImage function.


ImageList_DrawIndirect

BOOL ImageList_DrawIndirect(
    IMAGELISTDRAWPARAMS* pimldp);

Draws an image list image based on an IMAGELISTDRAWPARAMS structure.

  • Returns nonzero if successful, and zero otherwise.
pimldp
Address of an IMAGELISTDRAWPARAMS structure that contains information about the draw operation.

Version 4.70


ImageList_Duplicate

HIMAGELIST ImageList_Duplicate(
    HIMAGELIST himl);

Creates a duplicate of an existing image list.

  • Returns the handle to the new duplicate image list if successful, or NULL otherwise.
himl
Handle to the image list to be duplicated. All information contained in the original image list is copied to the new image list.

Version 4.71


ImageList_EndDrag

BOOL ImageList_EndDrag(VOID)

Ends a drag operation.

  • Returns nonzero if successful, or zero otherwise.


ImageList_GetBkColor

COLORREF ImageList_GetBkColor(
    HIMAGELIST himl
   );

Retrieves the current background color for an image list.

  • The return value is the background color.
himl
Handle to the image list.


ImageList_GetDragImage

HIMAGELIST ImageList_GetDragImage(
    POINT FAR *ppt,
    POINT FAR *pptHotspot
   );

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.

  • Returns the handle to the image list if successful, or NULL otherwise.
ppt
Address of a POINT structure that receives the current drag position. Can be NULL.
pptHotspot
Address of a POINT structure that receives the offset of the drag image relative to the drag position. Can be NULL.

The temporary image list is destroyed when the ImageList_EndDrag function is called. To begin a drag operation, use the ImageList_BeginDrag function.


ImageList_GetIcon

HICON ImageList_GetIcon(
    HIMAGELIST himl,
    int i,
    UINT flags
   );

Creates an icon from an image and mask in an image list.

  • Returns the handle to the icon if successful, or NULL otherwise.
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.

It is the responsibility of the calling application to destroy the icon returned from this function using the DestroyIcon function.


ImageList_GetIconSize

BOOL ImageList_GetIconSize(
    HIMAGELIST himl,
    int FAR *cx,
    int FAR *cy
   );

Retrieves the dimensions of images in an image list. All images in an image list have the same dimensions.

  • Returns nonzero if successful, or zero otherwise.
himl
Handle to the image list.
cx
Address of an integer variable that receives the width, in pixels, of each image.
cy
Address of an integer variable that receives the height, in pixels, of each image.


ImageList_GetImageCount

int ImageList_GetImageCount(
    HIMAGELIST himl
   );

Retrieves the number of images in an image list.

  • Returns the number of images.
himl
Handle to the image list.


ImageList_GetImageInfo

BOOL ImageList_GetImageInfo(
    HIMAGELIST himl,
    int i,
    IMAGEINFO FAR *pImageInfo
   );

Retrieves information about an image.

  • Returns nonzero if successful, or zero otherwise.
himl
Handle to the image list.
i
Index of the image.
pImageInfo
Address of 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.


ImageList_LoadImage

HIMAGELIST ImageList_LoadImage(
    HINSTANCE hi,
    LPCTSTR lpbmp,
    int cx,
    int cGrow,
    COLORREF crMask,
    UINT uType,
    UINT uFlags
   );

Creates an image list from the specified bitmap, cursor, or icon resource.

  • Returns the handle to the image list if successful, or NULL otherwise.
hi
Handle to the instance that contains the resource. This parameter can be NULL if you are loading an image from a file or loading an OEM resource.
lpbmp
Identifies the image to load.

If the uFlags parameter includes LR_LOADFROMFILE, lpbmp is the address of a null-terminated string that names the file containing the image to load.

If the hi parameter is non-NULL and LR_LOADFROMFILE is not specified, lpbmp is the address of a null-terminated string that contains the name of the image resource in the hi module.

If hi is NULL and LR_LOADFROMFILE is not specified, the low-order word of this parameter must be the identifier of an OEM image to load. To create this value, use the MAKEINTRESOURCE macro with one of the OEM image identifiers defined in WINUSER.H. These identifiers have the following prefixes:
OBM_ for OEM bitmaps
OIC_ for OEM icons
OCR_ for OEM cursors

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
Number of images by which the image list can grow when the system needs 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. If this parameter is the CLR_DEFAULT value, the color of the pixel at the upper-left corner of the image is treated as the mask color.
uType
Flag that specifies the type of image to load. This parameter can be one of the following values:
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:
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 the one 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 (see the comments section at the end of this topic for more information):

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 color become the default window value color. This value applies only to images that have a corresponding color table. See the comments section at the end of this topic for more information.
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.

LR_LOADTRANSPARENT does not load the image transparently. It creates an opaque image list that only appears transparent because all of the "background" pixels have been changed to COLOR_WINDOW. If the images are drawn over a background that is not the color COLOR_WINDOW, the image will not draw properly. Also, LR_LOADTRANSPARENT and LR_LOADMAP3DCOLORS use the system colors that were in effect at the time that ImageList_LoadImage was called. If the system colors subsequently change, the application must reload the image to remap the colors.

See also LoadImage


ImageList_Merge

HIMAGELIST ImageList_Merge(
    HIMAGELIST himl1,
    int i1,
    HIMAGELIST himl2,
    int i2,
    int dx,
    int dy
   );

Creates a new image by combining two existing images. The function also creates a new image list in which to store the image.

  • Returns the handle to the new image list if successful, or NULL otherwise.
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.

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

HIMAGELIST ImageList_Read(
    LPSTREAM pstm
   );

Reads an image list from a stream.

  • Returns the handle to the image list if successful, or NULL otherwise.
pstm
Address of the stream.


ImageList_Remove

BOOL ImageList_Remove(
    HIMAGELIST himl,
    int i
   );

Removes an image from an image list.

  • Returns nonzero if successful, or zero otherwise.
himl
Handle to the image list.
i
Index of the image to remove. If this parameter is -1, the function removes all images.

When an image is removed, the indexes of the remaining images are adjusted so that the image indexes always range from zero to one less than the number of images in the image list. For example, if you remove the image at index 0, then image 1 becomes image 0, image 2 becomes image 1, and so on.

See also ImageList_RemoveAll


ImageList_Replace

BOOL ImageList_Replace(
    HIMAGELIST himl,
    int i,
    HBITMAP hbmImage,
    HBITMAP hbmMask
   );

Replaces an image in an image list with a new image.

  • Returns nonzero if successful, or zero otherwise.
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.

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.


ImageList_ReplaceIcon

int ImageList_ReplaceIcon(
    HIMAGELIST himl,
    int i,
    HICON hicon
   );

Replaces an image with an icon or cursor.

  • Returns the index of the image if successful, or -1 otherwise.
himl
Handle to the image list.
i
Index of the image to replace. If i is -1, the function appends the image to the end of the list.
hicon
Handle to the icon or cursor that contains the bitmap and mask for the new image.

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.


ImageList_SetBkColor

COLORREF ImageList_SetBkColor(
    HIMAGELIST himl,
    COLORREF clrBk
   );

Sets the background color for an image list.

  • Returns the previous background color if successful, or CLR_NONE otherwise.
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.


ImageList_SetDragCursorImage

BOOL ImageList_SetDragCursorImage(
    HIMAGELIST himlDrag,
    int iDrag,
    int dxHotspot,
    int dyHotspot
   );

Creates a new drag image by combining the specified image (typically a mouse cursor image) with the current drag image.

  • Returns nonzero if successful, or zero otherwise.
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.


ImageList_SetIconSize

BOOL ImageList_SetIconSize(
    HIMAGELIST himl,
    int cx,
    int cy
   );

Sets the dimensions of images in an image list and removes all images from the list.

  • Returns nonzero if successful, or zero otherwise.
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.


ImageList_SetImageCount

BOOL ImageList_SetImageCount(
    HIMAGELIST himl,
    UINT       uNewCount);

Resizes an existing image list.

  • Returns nonzero if successful, or zero otherwise.
himl
Handle to the image list that will be resized.
uNewCount
Value specifying the new size of the image list.

If an application expands an image list with this function, it must add new images by using the ImageList_Replace function. If your application does not add valid images at the new indexes, draw operations that use the new indexes will be unpredictable.

If you decrease the size of an image list by using this function, the truncated images are freed.

Version 4.70


ImageList_SetOverlayImage

BOOL ImageList_SetOverlayImage(
    HIMAGELIST himl,
    int iImage,
    int iOverlay
   );

Adds a specified image to the list of images to be used as overlay masks. An image list can have up to four overlay masks in version 4.70 and earlier and up to 15 in version 4.71. The function assigns an overlay mask index to the specified image.

  • Returns nonzero if successful, or zero otherwise.
himl
Handle to the image list.
iImage
Zero-based index of an image in the himl image list. This index identifies the image to use as an overlay mask.
iOverlay
One-based index of the overlay mask.

An overlay mask is an image drawn transparently over another image. To draw an overlay mask over an image, call the ImageList_Draw or ImageList_DrawEx function. The fStyle parameter of these functions can use the INDEXTOOVERLAYMASK macro to specify an overlay mask index.


ImageList_Write

BOOL ImageList_Write(
    HIMAGELIST himl,
    LPSTREAM pstm
   );

Writes an image list to a stream.

  • Returns nonzero if successful, or zero otherwise.
himl
Handle to the image list.
pstm
Address of the stream.


Image List Macros

This section contains information about the macros used with image lists.

ImageList_AddIcon

ImageList_ExtractIcon

ImageList_LoadBitmap

ImageList_RemoveAll

INDEXTOOVERLAYMASK


ImageList_AddIcon

int ImageList_AddIcon(
    HIMAGELIST himl,
    HICON hicon
   );

Adds an icon or cursor to an image list. ImageList_AddIcon calls the ImageList_ReplaceIcon function.

  • Returns the index of the new image if successful, or -1 otherwise.
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.

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)


ImageList_ExtractIcon

HICON ImageList_ExtractIcon(
    HINSTANCE hi,
    HIMAGELIST himl,
    int i
   );

Calls the ImageList_GetIcon function to create an icon or cursor based on an image and mask in an image list.

  • Returns the handle of the icon or cursor if successful, or NULL otherwise.
hi
This parameter is not used and should always be zero.
himl
Handle to the image list.
i
Index of the image.


ImageList_LoadBitmap

HIMAGELIST ImageList_LoadBitmap(
    HINSTANCE hi,
    LPCTSTR lpbmp,
    int cx,
    int cGrow,
    COLORREF crMask
   );

Calls the ImageList_LoadImage function to create an image list from the specified bitmap resource.

  • Returns the handle to the image list if successful, or NULL otherwise.
hi
Handle to the instance that contains the bitmap resource. This parameter is NULL if you are loading an OEM bitmap.
lpbmp
Identifies the image to load.
If the hi parameter is non-NULL, lpszName is the address of a null-terminated string that contains the name of the image resource in the hi module.
If hi is NULL, the low-order word of this parameter must be the identifier of an OEM bitmap to load. To create this value, use the MAKEINTRESOURCE macro with one of the OEM bitmap identifiers defined in WINUSER.H. These identifiers have the OBM_ prefix.
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
Number of images by which the image list can grow when the system needs 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 1. If this parameter is the CLR_NONE value, no mask is generated.


ImageList_RemoveAll

BOOL ImageList_Remove(
    HIMAGELIST himl
   );

Calls the ImageList_Remove function to remove all of the images from an image list.

  • Returns nonzero if successful, or zero otherwise.
himl
Handle to the image list.


INDEXTOOVERLAYMASK

UINT INDEXTOOVERLAYMASK(
    UINT iOverlay
   );

Prepares the index of an overlay mask so that the ImageList_Draw function can use it.

iOverlay
Index of an overlay mask.

The INDEXTOOVERLAYMASK macro is defined as follows:

#define INDEXTOOVERLAYMASK(i) ((i) << 8)


Image List Structures

This section contains information about the structures used with image lists.

IMAGEINFO

IMAGELISTDRAWPARAMS


IMAGEINFO

typedef struct _IMAGEINFO {
    HBITMAP hbmImage;
    HBITMAP hbmMask;
    int     Unused1;
    int     Unused2;
    RECT    rcImage;
} IMAGEINFO, FAR *LPIMAGEINFO;

Contains information about an image in an image list. This structure is used with the ImageList_GetImageInfo function.

hbmImage
Handle to the bitmap that contains the images.
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.
Unused1
Not used. This member should always be zero.
Unused2
Not used. This member should always be zero.
rcImage
Bounding rectangle of the specified image within the bitmap specified by hbmImage.


IMAGELISTDRAWPARAMS

typedef struct _IMAGELISTDRAWPARAMS {
    DWORD       cbSize;
    HIMAGELIST  himl;
    int         i;
    HDC         hdcDst;
    int         x;
    int         y;
    int         cx;
    int         cy;
    int         xBitmap;
    int         yBitmap;
    COLORREF    rgbBk;
    COLORREF    rgbFg;
    UINT        fStyle;
    DWORD       dwRop;
} IMAGELISTDRAWPARAMS, FAR * LPIMAGELISTDRAWPARAMS;

Contains information about an image list draw operation and is used with the ImageList_DrawIndirect function.

cbSize
Size of this structure, in bytes.
himl
Handle to the image list that contains the image to be drawn.
i
Zero-based index of the image to be drawn.
hdcDst
Handle to the destination device context.
x and y
Coordinates where the image will be drawn.
cx and cy
Values that specify the number of pixels to be drawn, relative to the upper-left corner of the drawing operation as specified by xBitmap and yBitmap. If cx and cy are zero, ImageList_DrawIndirect draws the entire valid section. The function does not ensure that the parameters are valid.
xBitmap and yBitmap
Coordinates that specify the upper-left corner of the drawing operation with respect to the image itself. Pixels of the image that are to the left of xBitmap and above yBitmap are not drawn.
rgbBk
Image background color. This parameter can be an application-defined RGB value or one of the following values:
CLR_DEFAULT | Default background color. The image is drawn using the image list background color.
CLR_NONE | No background color. The image is drawn transparently.

This parameter is used only if the image list identified by himl was created with the ILC_MASK value.

rgbFg
Image foreground color. This parameter can be an application-defined RGB value or one of the following values:
CLR_DEFAULT | Default foreground color. The image is drawn using the system highlight color as the foreground color.
CLR_NONE | No blend color. The image is blended with the color of the destination device context.

This parameter is used only if fStyle includes the ILD_BLEND25 or ILD_BLEND50 flag.

fStyle
Flag specifying the drawing style and, optionally, the overlay image. See the comments section at the end of this topic for information on the overlay image. This parameter can be one or more of the following values:
ILD_BLEND25
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_FOCUS
Same as ILD_BLEND25.
ILD_BLEND50
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_SELECTED
Same as ILD_BLEND50.
ILD_BLEND
Same as ILD_BLEND50.
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_ROP
Draws the image using the raster operation code specified by the dwRop member.
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.
dwRop
Value specifying a raster operation code. These codes define how the color data for the source rectangle will be combined with the color data for the destination rectangle to achieve the final color. This member is ignored if the fStyle member does not include the ILD_ROP flag.

Some common raster operation codes include:
BLACKNESS | Fills the destination rectangle using the color associated with index zero in the physical palette. (This color is black for the default physical palette.)
DSTINVERT | Inverts the destination rectangle.
MERGECOPY | Merges the source rectangle colors with the specified pattern by using the Boolean AND operator.
MERGEPAINT | Merges the inverted source rectangle colors with the destination rectangle colors by using the Boolean OR operator.
NOTSRCCOPY | Copies the inverted source rectangle to the destination.
NOTSRCERASE | Combines the source and destination rectangle colors by using the Boolean OR operator. Inverts the resultant color.
PATCOPY | Copies the specified pattern into the destination bitmap.
PATINVERT | Combines the specified pattern colors with the destination rectangle colors by using the Boolean XOR operator.
PATPAINT | Combines the pattern colors with the inverted source rectangle colors by using the Boolean OR operator. Combines the result with the destination rectangle colors by using the Boolean OR operator.
SRCAND | Combines the source and destination rectangle colors by using the Boolean AND operator.
SRCCOPY | Copies the source rectangle directly to the destination rectangle.
SRCERASE | Combines the destination rectangle's inverted colors with the source rectangle colors by using the Boolean AND operator.
SRCINVERT | Combines the source and destination rectangle colors by using the Boolean XOR operator.
SRCPAINT | Combines the source and destination rectangle colors by using the Boolean OR operator.
WHITENESS | Fills the destination rectangle using the color associated with index one in the physical palette. (This color is white for the default physical palette.)

An overlay image is an image that is drawn on top of the primary image specified in the i member of this structure. To specify an overlay image, logically OR the fStyle member with the INDEXTOOVERLAYMASK macro, passing the one-based index of the overlay image in the macro. This image must have been previously specified as an overlay image using the ImageList_SetOverlayImage API.

To extract the overlay image from the fStyle member, logically AND fStyle with the ILD_OVERLAYMASK value.

Version 4.70


IP Address Controls

An IP address control allows the user to enter an IP address in an easily understood format. This control also allows the application to obtain the address in numeric form rather than in text form.

About IP Address Controls

Using IP Address Controls

IP Address Control Reference

About IP Address Controls

Microsoft® Internet Explorer Version 4.0 introduces the IP address control, a new control similar to an edit control that allows the user to enter a numeric address in Internet protocol (IP) format. This format consists of four three-digit fields. Each field is treated individually; the field numbers are zero-based and proceed from left to right as shown in this figure.

The four three-digit fields of an IP address control

The control allows only numeric text to be entered in each of the fields. Once three digits have been entered in a given field, keyboard focus is automatically moved to the next field. If filling the entire field is not required by the application, the user can enter fewer than three digits. For example, if the field should only contain 21, typing 21 and pressing the RIGHT ARROW key will take the user to the next field.

The default range for each field is 0 to 255, but the application can set the range to any values between those limits with the IPM_SETRANGE message.

Note The IP address control is implemented in version 4.71 and later of Comctl32.dll.

Using IP Address Controls

This section describes how to implement an IP address control in your application.

Initializing an IP Address Control

To use an IP address control, call InitCommonControlsEx with the ICC_INTERNET_CLASSES flag set in the dwICC member of the INITCOMMONCONTROLSEX structure.

Creating an IP Address Control

Use the CreateWindow or the CreateWindowEx API to create an IP address control. The class name for the control is WC_IPADDRESS, which is defined in Commctrl.h. No IP address control-specific styles exist; however, because this is a child control, use the WS_CHILD style as a minimum.

Is an IP Address Control an Edit Control?

An IP address control is not an edit control and it will not respond to EM_ messages. It will, however, send the owner window the following edit control notifications through the WM_COMMAND message. Note that the IP address control will also send private IPN_ notifications through the WM_NOTIFY message.

Notification | Reason for notification
EN_SETFOCUS | Sent when the IP address control gains the keyboard focus.
EN_KILLFOCUS | Sent when the IP address control loses the keyboard focus.
EN_CHANGE | Sent when any field in the IP address control changes. Like the EN_CHANGE notification from a standard edit control, this notification is received after the screen has been updated.


IP Address Control Reference

This section contains information about the following API elements used with IP address controls.

Messages
IPM_CLEARADDRESS
IPM_GETADDRESS
IPM_ISBLANK
IPM_SETADDRESS
IPM_SETFOCUS
IPM_SETRANGE

Notifications
IPN_FIELDCHANGED

Utility Macros
MAKEIPRANGE
MAKEIPADDRESS
FIRST_IPADDRESS
SECOND_IPADDRESS
THIRD_IPADDRESS
FOURTH_IPADDRESS

Structures
NMIPADDRESS


Messages

This section contains information about the messages used with IP address controls.

IPM_CLEARADDRESS

IPM_GETADDRESS

IPM_ISBLANK

IPM_SETADDRESS

IPM_SETFOCUS

IPM_SETRANGE


IPM_CLEARADDRESS

IPM_CLEARADDRESS
    wParam = 0;
    lParam = 0;

Clears the contents of the IP address control.

  • The return value is not used.

Version 4.71


IPM_GETADDRESS

IPM_GETADDRESS
    wParam = 0;
    lParam = (LPARAM)(LPDWORD)pdwAddr;

Retrieves the address values for all four fields in the IP address control.

  • Returns the number of nonblank fields.
pdwAddr
Address of a DWORD value that receives the address. The field 3 value will be contained in bits 0 through 7. The field 2 value will be contained in bits 8 through 15. The field 1 value will be contained in bits 16 through 23. The field 0 value will be contained in bits 24 through 31. The FIRST_IPADDRESS, SECOND_IPADDRESS, THIRD_IPADDRESS, and FOURTH_IPADDRESS macros can also be used to extract the address information. Zero will be returned as the address for any blank fields.

Version 4.71


IPM_ISBLANK

IPM_ISBLANK
    wParam = 0;
    lParam = 0;

Determines if all fields in the IP address control are blank.

  • Returns nonzero if all fields are blank, or zero otherwise.

Version 4.71


IPM_SETADDRESS

IPM_SETADDRESS
    wParam = 0;
    lParam = (LPARAM)(DWORD)dwAddr;

Sets the address values for all four fields in the IP address control.

  • The return value is not used.
dwAddr
DWORD value that contains the new address. The field 3 value is contained in bits 0 through 7. The field 2 value is contained in bits 8 through 15. The field 1 value is contained in bits 16 through 23. The field 0 value is contained in bits 24 through 31. The MAKEIPADDRESS macro can also be used to create the address information.

This message does not generate an IPN_FIELDCHANGED notification.

Version 4.71


IPM_SETFOCUS

IPM_SETFOCUS
    wParam = (WPARAM)nField;
    lParam = 0;

Sets the keyboard focus to the specified field in the IP address control. All of the text in that field will be selected.

  • The return value is not used.
nField
Zero-based field index to which the focus should be set. If this value is greater than the number of fields, focus is set to the first blank field. If all fields are nonblank, focus is set to the first field.

Version 4.71


IPM_SETRANGE

IPM_SETRANGE
    wParam = (WPARAM)nField;
    lParam = (LPARAM)(WORD)wRange;

Sets the valid range for the specified field in the IP address control.

  • Returns nonzero if successful, or zero otherwise.
nField
Zero-based field index to which the range will be applied.
wRange
WORD value that contains the lower limit of the range in the low-order byte and the upper limit in the high-order byte. Both of these values are inclusive. The MAKEIPRANGE macro can also be used to create the range.

If the user enters a value in the field that is outside of this range, the control will send the IPN_FIELDCHANGED notification with the entered value. If the value is still outside of the range after sending the notification, the control will attempt to change the entered value to the closest range limit.

Version 4.71


Notifications

This section contains information about the notification messages sent by IP address controls.

IPN_FIELDCHANGED


IPN_FIELDCHANGED

IPN_FIELDCHANGED
    lpnmipa = (LPNMIPADDRESS) lParam;

Sent when the user changes a field in the control or moves from one field to another. This notification message is sent in the form of a WM_NOTIFY message.

  • The return value is ignored.
lpnmipa
Address of an NMIPADDRESS structure that contains information about the changed address. The iValue member of this structure will contain the entered value, even if it is out of the range of the field. You can modify this member to any value that is within the range for the field in response to this notification.

This notification is not sent in response to a IPM_SETADDRESS message.

Version 4.71


Utility Macros

This section contains information about the utility macros used with IP address controls.

MAKEIPRANGE

MAKEIPADDRESS

FIRST_IPADDRESS

SECOND_IPADDRESS

THIRD_IPADDRESS

FOURTH_IPADDRESS


MAKEIPRANGE

LPARAM MAKEIPRANGE(
    BYTE low,
    BYTE high
);

Packs two byte values into a single LPARAM suitable for use with the IPM_SETRANGE message.

  • Returns an LPARAM value that contains the range.
low
Lower limit of the range.
high
Upper limit of the range.

Version 4.71


MAKEIPADDRESS

LPARAM MAKEIPADDRESS(
    BYTE b0,
    BYTE b1,
    BYTE b2,
    BYTE b3
);

Packs four byte values into a single LPARAM suitable for use with the IPM_SETADDRESS message.

  • Returns an LPARAM value that contains the address.
b0
Field 0 address.
b1
Field 1 address.
b2
Field 2 address.
b3
Field 3 address.

Version 4.71


FIRST_IPADDRESS

BYTE FIRST_IPADDRESS(
    LPARAM lParam
);

Extracts the field 0 value from a packed IP address retrieved with the IPM_GETADDRESS message.

  • Returns a BYTE value that contains the field 0 value.
lParam
Packed IP address value.

Version 4.71


SECOND_IPADDRESS

BYTE SECOND_IPADDRESS(
    LPARAM lParam
);

Extracts the field 1 value from a packed IP address retrieved with the IPM_GETADDRESS message.

  • Returns a BYTE value that contains the field 1 value.
lParam
Packed IP address value.

Version 4.71


THIRD_IPADDRESS

BYTE THIRD_IPADDRESS(
    LPARAM lParam
);

Extracts the field 2 value from a packed IP address retrieved with the IPM_GETADDRESS message.

  • Returns a BYTE value that contains the field 2 value.
lParam
Packed IP address value.

Version 4.71


FOURTH_IPADDRESS

BYTE FOURTH_IPADDRESS(
    LPARAM lParam
);

Extracts the field 3 value from a packed IP address retrieved with the IPM_GETADDRESS message.

  • Returns a BYTE value that contains the field 3 value.
lParam
Packed IP address value.

Version 4.71


Structures

This section contains information about the structures used with IP address controls.

NMIPADDRESS


NMIPADDRESS

typedef struct tagNMIPADDRESS{
    NMHDR hdr;
    int iField;
    int iValue;
} NMIPADDRESS, *LPNMIPADDRESS;

Contains information for the IPN_FIELDCHANGED notification message.

hdr
NMHDR structure that contains additional information about the notification message.
iField
Zero-based number of the field that was changed.
iValue
New value of the field specified in the iField member. While processing the IPN_FIELDCHANGED notification, this member can be set to any value that is within the range of the field and the control will place this new value in the field.

Version 4.71


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 to arrange items and to display individual items. For example, additional information about each item can be displayed in columns to the right of the icon and label.

Using List View Controls

List View Updates in Internet Explorer

List View Control Reference


Using 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, see List View Notification Messages.

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. The following list contains more information about the four views.

View Name | 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. For a complete list of the list view window styles, see List view window styles.

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 to the new control if successful, or NULL
    //     otherwise.
    // hwndParent - handle to 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
    }

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 to 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 Image Lists

By default, a list view control does not display item images. To display item images, you must create image lists and associate them with the control. A list view control can have three image lists:

  • An image list that contains full-sized icons displayed when the control is in icon view.
  • An image list that contains small icons displayed when the control is in small icon view, list view, or report view.
  • An image list that contains state images, which are displayed to the left of the full-sized or small icon. You can use state images, such as checked and cleared check boxes, to indicate application-defined item states. State images are displayed in icon view, small icon view, list view, and report view.

For more information about icon view, small icon view, list view, and report view, see Views and Styles.

To assign an image list to a list view control, use the LVM_SETIMAGELIST message, specifying whether the image list contains full-sized icons, small icons, or state images. To retrieve the handle to an image list currently assigned to a list view control, use the LVM_GETIMAGELIST message. You can use the GetSystemMetrics function to determine appropriate dimensions for the full-sized and small icons. Use the ImageList_Create function to create an image list, and use other image list functions to add bitmaps to the image list. For more information, see Image Lists.

You only need to create the image list that the control will use. For example, if the list view control will never be in icon view, you do not need to create and assign a large image list because the large images will never be used. If you create both image lists, they must contain the same images in the same order. This is because a single value is used to identify a list view item's icon in both image lists. You can associate an icon index with an item when you call the ListView_InsertItem or ListView_SetItem macro.

The full-sized and small icon image lists can also contain overlay images, which are designed to be drawn transparently over the item icons.

To use overlay images in a list view control:

  1. Call the ImageList_SetOverlayImage function to assign an overlay image index to an image in the full-sized and small icon image lists. An overlay image is identified by a one-based index.
  2. You can associate an overlay image index with an item when you call the ListView_InsertItem or ListView_SetItem macro. Use the INDEXTOOVERLAYMASK macro to specify an overlay image index in the state member of the item's LVITEM structure. You must also set the LVIS_OVERLAYMASK bits in the stateMask member.

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.

To associate a state image with an item, use the INDEXTOSTATEIMAGEMASK macro to specify a state image index in the state member of the LVITEM structure. The index identifies an image in the control's state image list. Although image list indexes are zero-based, the control uses one-based indexes to identify state images. A state image index of zero indicates that an item has no state image.

By default, when a list view control is destroyed, it destroys the image lists assigned to it. 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.

The following example demonstrates how to create two image lists, add an icon to each, and assign them to a list view control by using the LVM_SETIMAGELIST message.

    // InitListViewImageLists - creates image lists for a list view.
    // Returns TRUE if successful, or FALSE otherwise.
    // hwndLV - handle to 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;
    }

Items and Subitems

Each item in a list view control has an icon, a label, a current state, and an application-defined value. By using list view messages, you can add, modify, and delete items as well as retrieve information about items. You can also find items with specific attributes.

Each item can also have one or more subitems. A subitem is a string that, in report view, is displayed in a column to the right of an item's icon and label. To specify the text of a subitem, use the LVM_SETITEMTEXT or LVM_SETITEM message. All items in a list view control have the same number of subitems. The number of subitems is determined by the number of columns in the list view control. When you add a column to a list view control, you specify its associated subitem index. For more information about list view columns, see Columns.

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

The example in this section demonstrates how to add a list view item for each line in a text file. A semicolon in the source text separates 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 LVITEM 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 LVITEM 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 to 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;
    LVITEM lvi;

    // Initialize LVITEM 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 LVITEM 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;
    }

Item States

An item's state is a value that specifies the item's availability, 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 LVITEM 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 LVM_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 LVITEM 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 LVITEM 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

For each of its items, a list view control typically stores the label text, the image list index of the item's icons, and a set of bit flags for the item's state. You can define callback items or change the control's callback mask to indicate that the application—rather than the control—stores some or all of this information. You may want to use callbacks if your application already stores some of this information.

A callback item in a list view control is an item for which the application stores the text, icon index, or both. You can define callback items when you send the LVM_INSERTITEM message to add an item to the list view control. If the application stores the text for the item or subitem, set the pszText member of the item's LVITEM structure to LPSTR_TEXTCALLBACK. If the application stores the icon index for an item, set the iImage member of the item's LVITEM structure to I_IMAGECALLBACK.

The callback mask of a list view control is a set of bit flags that specify the item states for which the application, rather than the control, stores the current data. The callback mask applies to all of the control's items, unlike the callback item designation, which applies to a specific item. The callback mask is zero by default, meaning that the list view control stores all item state information. After creating a list view control and initializing its items, you can send the LVM_SETCALLBACKMASK message to change the callback mask. To get the current callback mask, send the LVM_GETCALLBACKMASK message.

When a list view control must display or sort a list view item for which the application stores callback information, the control sends the LVN_GETDISPINFO notification message to the control's parent window. This message specifies an NMLVDISPINFO structure that specifies the type of information required and identifies the item or subitem of interest. The parent window must process LVN_GETDISPINFO to provide the requested data.

If the list view control detects a change in an item's callback information (that is, a change in the text, icon, or state information being tracked by the application), the control sends an LVN_SETDISPINFO notification message to notify you of the change.

If you change a callback item's attributes or state bits, you can use the LVM_UPDATE message to force the control to repaint the item. This message also causes the control to arrange its items if it has the LVS_AUTOARRANGE style. You can use the LVM_REDRAWITEMS message to redraw a range of items by invalidating the corresponding portions of the list view control's client area.

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

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.

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 to the list view control.
    BOOL WINAPI InitListViewColumns(HWND hwndLV)
    {
    extern char g_achTemp[256];     // temporary buffer
    LVCOLUMN lvc;
    int iCol;

    // Initialize the LVCOLUMN 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;
    }

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 the list view control calls to compare the relative order of any two items. The control passes to the comparison function the item data associated with each of the two items. The item data is the value that was specified in the lParam member of the item's LVITEM structure when it was inserted into the list. By specifying the appropriate item data and 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. Controls with these styles use the label text of the items to sort them in ascending or descending order. You cannot supply a comparison function when using these window styles. If a list view control has either of these styles, an LVM_INSERTITEM message will fail if you try to insert an item that has LPSTR_TEXTCALLBACK as the pszText member of its LVITEM structure.

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 so 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 NMLVDISPINFO structure. The item member of this structure is an LVITEM structure whose iItem member identifies the item. If editing is canceled, the pszText member of the LVITEM structure is NULL; otherwise, pszText is the address of the edited text. The parent window is responsible for updating the item's label if it wishes to keep the new label.

During label editing, you can get the handle to 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.

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((LPNMLVDISPINFO) lParam);
            break;

        // Process LVN_ENDLABELEDIT to change item labels after
        // in-place editing.
        case LVN_ENDLABELEDIT:
            return Main_OnEndLabelEdit(
                (LPNMLVDISPINFO) lParam
                );

        // Process LVN_COLUMNCLICK to sort items by column.
        case LVN_COLUMNCLICK:
            #define pnm ((LPNMLISTVIEW) 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 NMLVDISPINFO structure).
    VOID WINAPI Main_OnGetDispInfo(LPNMLVDISPINFO 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 NMLVDISPINFO structure).

    BOOL Main_OnEndLabelEdit(LPNMLVDISPINFO 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]);
    }

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 in other sections of this document.
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 initialization additional to WM_NCCREATE. 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 allocated during WM_CREATE.
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 to the current label font.
WM_HSCROLL | Scrolls the list view control horizontally.
WM_KEYDOWN | Processes the SPACEBAR, ENTER, and arrow keys and sends an LVN_KEYDOWN notification message to the parent window.
WM_KILLFOCUS | Repaints the focused list item, if any, and sends an 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. If the wParam parameter is non-NULL, the control assumes that the value is an HDC and paints using that device context.
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 will also arrange the list items.
WM_WININICHANGE | Processes changes to system metrics.


List View Updates in Internet Explorer

This section details the features that were added to the list view control by Microsoft® Internet Explorer. The following updates are described in this section:

  • Columns Update
  • Extended List View Styles
  • List View Working Areas
  • Virtual List View

Columns Update

List view controls now support new features for columns in report view. The new features are implemented by using the new members and mask values in the LVCOLUMN structure with standard column manipulation messages. The new features are column images and column ordering.

Column Images: List view controls can display images next to column titles. To implement this feature, specify the LVCF_IMAGE value and assign the proper value to the iImage member in the LVCOLUMN structure.

Column Ordering: List view controls can set the order in which columns are displayed. To implement this feature, specify the LVCF_ORDER value and assign the proper value to the iOrder member in the LVCOLUMN structure.

Extended List View Styles

Extended list view styles are not accessed in the same manner as standard window styles. That is, the SetWindowLong and GetWindowLong functions are not used to make extended style changes.

Two messages set and retrieve extended style information: LVM_SETEXTENDEDLISTVIEWSTYLE and LVM_GETEXTENDEDLISTVIEWSTYLE. Each message has a corresponding macro that can be used instead of sending the message explicitly. The macros are ListView_SetExtendedListViewStyle, ListView_SetExtendedListViewStyleEx, and ListView_GetExtendedListViewStyle.

List View Working Areas

List view controls now support working areas, which are rectangular virtual areas that the list view control uses to arrange its items. A working area is not a window and cannot have a visible border. By default, the list view has no working areas. When no working areas are present, the list view works exactly the same as before working areas were implemented.

By creating a working area, you can create an empty border on the left, top and/or right of the items or cause a horizontal scroll bar to be displayed when there normally wouldn't be one.

The number of current working areas can be obtained with the LVM_GETNUMBEROFWORKAREAS message. The working areas are changed with the LVM_SETWORKAREAS message and can be retrieved with the LVM_GETWORKAREAS message. Both of these messages take the address of an array of RECT structures as the lParam and the number of RECT structures as the wParam. The left and top members of these structures specify the coordinates of the upper-left corner (the origin) of the working area, and the right and bottom members specify the lower-right corner of the working area. All of the coordinates are in client coordinates of the list view. The maximum number of working areas allowed is defined by the LV_MAX_WORKAREAS value.

Changing the working area has no effect on list view controls that have the LVS_LIST or LVS_REPORT views, but the working areas will be maintained when the view type is changed. With the LVS_ICON and LVS_SMALLICON views, the working area can be modified to change the way the items are displayed. Making the width of the working area (right - left) greater than the client width of the control will cause the items to be wrapped at that width and the horizontal scroll bar to be displayed. Making the width of the working area narrower than the width of the control's client area will cause the items to be wrapped within the working area and not the client area. Setting the left and/or top members to a positive value will cause the items to be displayed starting at the working area, creating an empty space between the edge of the control and the items. An empty space can also be created between the right edge of the control and the items by making the width of the working area less than the client width of the control.

The following illustration is an example of a list view control that contains four working areas, each in a different quadrant of the client area and with a 25-pixel empty area around them.

List view control that contains four working areas.

Here is the same list view when set to LVS_SMALLICON view:

Same list view control set to LVS_SMALLICON view.

When a working area is created, items that lie within the working area become members of it. Similarly, if an item is moved into a working area, it becomes a member of the working area to which it was moved. If an item does not lie within any working area, it automatically becomes a member of the first (index 0) working area. If you want to create an item and have it placed within a specific working area, you will need to create the item and then move it into the desired working area using the LVM_SETITEMPOSITION or LVM_SETITEMPOSITION32 message.

To determine which working area an item is a member of, you retrieve the working areas, retrieve the position of the item, and compare its position to the working areas. The following function will return the index of the working area to which the item belongs. If the function fails, it will return -1. If the function succeeds, but the item isn't inside any of the working areas, the function will return 0, because all items that are not inside a working area automatically become a member of working area zero.

int GetItemWorkingArea(HWND hwndList, int iItem)
{
UINT     uRects = 0;
int      nReturn = -1;
LPRECT   pRects;
POINT    pt;

if(!ListView_GetItemPosition(hwndList, iItem, &pt))
   return nReturn;

ListView_GetNumberOfWorkAreas(hwndList, &uRects);

if(uRects)
   {
   pRects = (LPRECT)GlobalAlloc(GPTR, sizeof(RECT) * uRects);

   if(pRects)
      {
      UINT  i;

      nReturn = 0;

      ListView_GetWorkAreas(hwndList, uRects, pRects);

      for(i = 0; i < uRects; i++)
         {
         if(PtInRect((pRects + i), pt))
            {
            nReturn = i;
            break;
            }
         }

      GlobalFree((HGLOBAL)pRects);
      }
   }

return nReturn;
}

Multiple working areas can be used for creating different areas within a view to which items can be moved or dropped. With this method, you could create areas in a single view that have different meanings. The user could then categorize the items by placing them in a different area. An example of this would be a view of a file system that has an area for read/write files and another area for read-only files. If a file item were moved into the read-only area, it would automatically become read-only. Moving a file from the read-only area into the read/write area would make the file read/write.

Multiple working areas can intersect, but any items that lie within the intersection will become members of the area with the lower index. So it is best to avoid this situation. When sorting multiple work areas, the items will be sorted compared to the other items within the same working area.

The following example demonstrates how to create one working area that simulates a 25-pixel empty space around the left, top, and right sides of the items.

{
#define  EMPTY_SPACE   25

RECT  rcClient;

GetClientRect(hwndListView, &rcClient);

rcClient.left += EMPTY_SPACE;
rcClient.top += EMPTY_SPACE;
rcClient.right -= (EMPTY_SPACE * 2);

SendMessage(hwndListView, LVM_SETWORKAREAS, 1, (LPARAM)&rcClient);
}

The following example demonstrates how to create two working areas in the control that take up about half of the client area and have a 25-pixel border around each rectangle.

{
#define  EMPTY_SPACE   25

RECT  rcClient;
RECT  rcWork[2];

GetClientRect(hwndListView, &rcClient);

rcWork[0].left = rcClient.left + EMPTY_SPACE;
rcWork[0].top = rcClient.top + EMPTY_SPACE;
rcWork[0].right = (rcClient.right/2) - EMPTY_SPACE;
rcWork[0].bottom = rcClient.bottom;

rcWork[1].left = (rcClient.right/2) + EMPTY_SPACE;
rcWork[1].top = rcClient.top + EMPTY_SPACE;
rcWork[1].right = rcClient.right - EMPTY_SPACE;
rcWork[1].bottom = rcClient.bottom;

SendMessage(hwndListView, LVM_SETWORKAREAS, 2, (LPARAM)rcWork);
}

Virtual List View

This section contains information about the new list view control style, "virtual" list view (LVS_OWNERDATA).

This information has been divided into the following areas:

  • Virtual list view description
  • Creating a virtual list view control
  • Compatibility issues: styles and messages
  • Handling virtual list view control notification messages
  • Cache management

Virtual list view description

A virtual list view is a list view control that has the LVS_OWNERDATA style. The LVS_OWNERDATA style enables the control to handle an almost infinite number of items. Specifically, the control can support an item count up to a DWORD. This is possible because the overhead of managing item data is placed on the owner. This allows the virtual list view control to lend itself for use with large databases of information, where specific methods of accessing data are already in place.

A virtual list view control maintains very little item information itself. Except for the item selection and focus information, all item information must be managed by the owner of the control. All other item information is requested from the owner using LVN_GETDISPINFO notification messages.

Because this type of list control is intended for large data sets, it is recommended that you cache requested item data to improve retrieval performance. The list view provides a cache-hinting mechanism to assist in optimizing the cache. The hint is implemented in the form of an LVN_ODCACHEHINT notification message.

Creating a virtual list view control

Virtual list view controls are created using the CreateWindow or CreateWindowEx functions, specifying the LVS_OWNERDATA window style as part of the dwStyle function parameter.

The LVS_OWNERDATA style can be used with most other window styles, excluding the LVS_SORTASCENDING or LVS_SORTDESCENDING styles.

All virtual list view controls default to the LVS_AUTOARRANGE style.

Note Dynamically switching to and from the LVS_OWNERDATA style is not supported.

Compatibility issues: styles, states, and messages

List View Control Styles: All four of the list view styles (icon, small icon, list, and report view) support the LVS_OWNERDATA style. However, this style will not work with the LVS_SORTASCENDING or LVS_SORTDESCENDING style.

List View Item States: List view controls that have the LVS_OWNERDATA style do not store any item-specific information. Therefore, the only valid item state flags that can apply to an item are LVIS_SELECTED and LVIS_FOCUSED. No other state information will be stored for an item. One side effect of this is that state images cannot be used with list view controls that have the LVS_OWNERDATA style because the state image index for the item is stored in the item state field.

List View Messages: Most messages used to handle list view controls are fully supported. However, some messages have limitations or are unsupported when the LVS_OWNERDATA style is used. The following list summarizes the affected messages. Messages not listed here are fully supported.

Message | Limitation
LVM_ARRANGE | This message does not support the LVA_SNAPTOGRID style.
LVM_DELETEALLITEMS | This message sets the item count to zero and clears all internal selection variables, but it does not actually delete any items. A notification callback will be made.
LVM_DELETEITEM | This message is supported for selection integrity only and does not actually delete an item.
LVM_GETITEMSTATE | This message returns only focus and selection states (those states stored by the list view control).
LVM_GETNEXTITEM | This message does not support the list view search criteria LVNI_CUT, LVNI_HIDDEN, or LVNI_DROPHILITED. All other criteria are supported.
LVM_INSERTITEM | This message is supported for selection integrity only.
LVM_SETITEM | This message is not supported. To set the item state, use the LVM_SETITEMSTATE message.
LVM_SETITEMCOUNT | This message sets the number of items currently in the list. The owner must be prepared to supply data for any item up to the maximum set using this message, as requested by the list control by notification. The message parameters have been updated to support virtual list view controls.
LVM_SETITEMPOSITION | This message is not supported.
LVM_SETITEMSTATE | This message allows only the selection and focus states to be changed for the item.
LVM_SETITEMTEXT | This message is not supported.
LVM_SORTITEMS | This message is not supported.

Handling virtual list view control notification messages

List view controls with the LVS_OWNERDATA style send the same notification messages as other list view controls plus two new ones: LVN_ODCACHEHINT and LVN_ODFINDITEM. The following are the most common notifications sent by a list view control with the LVS_OWNERDATA style:

LVN_GETDISPINFO A virtual list view control maintains very little item information on its own. As a result, it often sends the LVN_GETDISPINFO notification message to request item information. This message is handled in much the same way as callback items in a standard list control. However, because the number of items supported by the control is probably very large, it is recommended that you cache item data to improve performance.

When handling LVN_GETDISPINFO, the owner of the control should first attempt to supply requested item information from the cache (for more information, see Cache management). If the requested item is not cached, the owner must be prepared to supply the information by other means.

LVN_ODCACHEHINT A virtual list view sends the LVN_ODCACHEHINT notification message to assist in optimizing the cache. The notification message provides inclusive index values for a range of items that it recommends be cached. Upon receiving the notification message, the owner must be prepared to load the cache with item information for the requested range so that the information will be readily available when LVN_GETDISPINFO is sent later.
LVN_ODFINDITEM The LVN_ODFINDITEM notification message is sent by a virtual list view control when the control needs the owner to find a particular callback item. The notification message is sent when the list view control receives quick key access or when it receives an LVM_FINDITEM message. Search information is sent in the form of an LVFINDINFO structure, which is a member of the NMLVFINDITEM structure.

The owner should be prepared to search for an item that matches the information given by the list view control. The owner should return the index of the item if successful, or -1 if no matching item is found.

Cache management

General Cache Information: A list view control with the LVS_OWNERDATA style will produce a large number of LVN_GETDISPINFO notification messages. To improve performance in looking up item information, it is recommended that the owner of the control keep information for certain items in a globally allocated cache. To create the cache using global memory, use the GlobalAlloc function.

To assist in optimizing the cache, a virtual list view control sends a notification message, LVN_ODCACHEHINT, that provides information about the recommended items to include within the cache. LVN_CACHEHINT is sent as a WM_NOTIFY message, with the lParam value acting as the address of an NMLVCACHEHINT structure.

The NMLVCACHEHINT structure includes two integer members, iFrom and iTo, that represent the inclusive endpoints of a range of items that will most likely be needed. The owner must be prepared to load the cache with the item information for each of the items within the recommended range.

Frequently Accessed Items: The list control will often need item information for the first item (offset 0). The LVN_ODCACHEHINT notification message may not always include item 0, but it should always be included in the cache.

The last items in the list will be accessed often. Therefore, the owner may want to keep a second cache that includes the items at the end of the list. The requested range from LVN_ODCACHEHINT can be checked against the end cache to make it available automatically instead of reloading the same end range each time. This documentation provides examples of simple application-defined functions that perform cache management and notification message processing. For more information on these examples, see Virtual list view sample code.

Virtual list view sample code

This section includes samples of application-defined functions and structures that implement aspects of a virtual list view control and perform cache management.
Name | Description
OnNotify function | Handles virtual list view notification messages.
PrepCache function | Performs basic cache management.
RetrieveItem function | Retrieves item information from the cache.
RndItem structure | Holds item information for use with a cache.

Note For demonstration purposes, it is assumed that the cache used in this sample is a dynamically allocated array of the user-defined structure RndItem. The list view control in the example is assumed to have three columns—one column for the item label and two columns for subitems.

Sample Function: OnNotify

This sample user-defined function handles notification messages commonly sent from a virtual list view control.

LRESULT OnNotify( HWND hwnd, NMHDR* pnmhdr )
{
    LRESULT lrt = FALSE;

    switch (pnmhdr->code){
        case LVN_GETDISPINFO:
            RndItem rndItem;
            NMLVDISPINFO* pLvdi = (LPNMLVDISPINFO) pnmhdr;
            if (-1 == pLvdi->item.iItem){
                OutputDebugString("LVOWNER: Request for -1 item?\n");
                DebugBreak();
            }

            //  Get information for item at index iItem.
            RetrieveItem( &rndItem, pLvdi->item.iItem );

            if(pLvdi->item.mask & LVIF_STATE){
                //  Fill in the state information.
                pLvdi->item.state |= rndItem.state;
            }

            if(pLvdi->item.mask & LVIF_IMAGE){
                //  Fill in the image information.
                pLvdi->item.iImage = rndItem.iIcon;
            }

            if(pLvdi->item.mask & LVIF_TEXT){
                //  Fill in the text information.
                switch (pLvdi->item.iSubItem){
                    case 0:
                        //  Copy the main item text.
                        lstrcpy( pLvdi->item.pszText, rndItem.Title );
                        break;

                    case 1:
                        //  Copy subitem 1 text.
                        lstrcpy( pLvdi->item.pszText, rndItem.SubText1 );
                        break;

                    case 2:
                        //  Copy subitem 2 text.
                        lstrcpy( pLvdi->item.pszText, rndItem.SubText2 );
                        break;

                    default:
                        break;
                }
            }
            lrt = FALSE;
            break;

    case LVN_ODCACHEHINT:
        NMLVCACHEHINT* pcachehint = (NMLVCACHEHINT*) pnmhdr;

        // Load the cache with the recommended range.
        PrepCache( pcachehint->iFrom, pcachehint->iTo );
        break;

    case LVN_ODFINDITEM:
        LPNMLVFINDITEM pnmfi = (LPNMLVFINDITEM)pnmhdr;

        // Call a user-defined function to find the index according
        // to LVFINDINFO. Set return value to -1 if no hits are found.
        break;

    default:
        break;

    return( lrt );
}

Sample Function: PrepCache

This sample function accepts the range values for the cache suggested by a virtual list view control. It performs a verification to determine that the requested range is not already cached, and then it allocates the required global memory and fills the cache if necessary.

void PrepCache( int iFrom, int iTo )
{
/*  Global Variables
 *    g_priCache[] is the main cache.
 *    g_iCache is the index of the first item in the main cache.
 *    c_cCache is the count of items in the main cache.
 *
 *    g_priEndCache[] is the cache of items at the end of the list.
 *    g_iEndCache is the index of the first item in the end cache.
 *    g_cEndCache is the count of items in the end cache.
 */

    //  Local Variables
    int i;
    BOOL fOLFrom = FALSE;
    BOOL fOLTo = FALSE;

    //  Check to see if this is the end cache.
    if ((iTo == g_cItems - 1) && ((iTo - iFrom) < 30))  // 30 entries wide{
        // Check to see if this is a portion of the current end cache.
        if ((g_cEndCache) &&
            (iFrom >= g_iEndCache) &&
            (iFrom < g_iEndCache+g_cEndCache))
            return;  //  if a part of current end cache, no loading is necessary

        //  This is a new end cache; free the old memory.
        if ( g_priEndCache )
            GlobalFree( g_priEndCache );

        //  Set the index and count values for the new end cache; then get the memory.
        g_iEndCache = iFrom;
        g_cEndCache = (iTo - iFrom + 1);
        g_priEndCache = (PRndItem)GlobalAlloc( GPTR, sizeof( RndItem ) * g_cEndCache );

        if (! g_priEndCache);
            //  Out of memory. Perform error handling operations.

        //  Loop to fill the cache with the recommended items.
        for (i=0; i<g_cEndCache; i++);
            //  Call function that accesses item information and
            //  fills a cache element here.
    }

    else{    //  Not a member of the current end cache. Try primary cache instead.

        //  Check to see if iFrom is within the primary cache.
        if ((g_cCache) &&
            (iFrom >= g_iCache) &&
            (iFrom < g_iCache+g_cCache))
            fOLFrom = TRUE;

        //  Check to see if iTo is within the primary cache.
        if ((g_cCache) &&
            (iTo >= g_iCache) &&
            (iTo <= g_iCache+g_cCache))
            fOLTo = TRUE;

        //  If both iFrom and iTo are within current cache, no work is needed.
        if (fOLFrom && fOLTo)
            return;

        //  Enlarge the cache size rather than make it specific to this hint.
        if (fOLFrom)
            iFrom = g_iCache;
        else if (fOLTo)
            iTo = g_iCache + g_cCache;

        //  A new primary cache is needed; free the old one.
        if ( g_priCache )
            GlobalFree( g_priCache );

        //  Set the index and count values for the new primary cache, and then get the memory.
        g_iCache = iFrom;
        g_cCache = (iTo - iFrom + 1);
        g_priCache = (PRndItem)GlobalAlloc( GPTR, sizeof( RndItem ) * g_cCache );

        if (!g_priEndCache);
            //  Out of memory. Do error handling.

        //  Loop to fill the cache with the recommended items.
        for (i=0; i<g_cEndCache; i++);
            //  Call function that accesses item information and
            //  fills a cache element here.
    }
}

Sample Function: RetrieveItem

This sample function accepts two parameters—the address of the user-defined structure RndItem and an integer value representing the index of the item in the list. It checks the index value to discover if the desired item is cached. If it is, the pointer that was passed to it is set to a location in the cache. If the item is not in the main or end cache, the item information must be located manually.

void RetrieveItem( PRndItem prndItem, int index )
{
/*  Global Variables
 *    g_priCache[] is the main cache.
 *    g_iCache is the index of the first item in the main cache.
 *    c_cCache is the count of items in the main cache.
 *
 *    g_priEndCache[] is the cache of items at the end of the list.
 *    g_iEndCache is the index of the first item in the end cache.
 *    g_cEndCache is the count of items in the end cache.
 */

    //  Check to see if the item is in the main cache.
    if ((index >= g_iCache) && (index < g_iCache + g_cCache))
        *prndItem = g_priCache[index-g_iCache];

    //  If it is not, check to see if the item is in the end area cache.
    else if ((index >= g_iEndCache)
              && (index < g_iEndCache + g_cEndCache))
        *prndItem = g_priEndCache[index-g_iEndCache];
    else{
        //  The item is not in either cache;
        //  you should get the item information manually.
    }
}

Sample Structure: RndItem

This sample user-defined structure holds information placed in the cache. The structure has the following form:

typedef struct _RndItem
{
    int   iIcon;
    TCHAR Title[SIZE];                // SIZE is a user-defined macro value.
    UINT  state;
    TCHAR SubText1[SIZE];
    TCHAR SubText2[SIZE];

} RndItem, *PRndItem;

iIcon
Bitmap to be assigned to this item. The value represents offset within a previously created image list.
Title
Text for the item label.
state
Item state value.
SubText1
Text for the label of the first subitem.
SubText2
Text for the label of the second subitem.


List View Control Reference

This section contains information about the programming elements used with list view controls.

List view window styles

Extended list view styles

List view item states
Messages
LVM_APPROXIMATEVIEWRECT
LVM_ARRANGE
LVM_CREATEDRAGIMAGE
LVM_DELETEALLITEMS
LVM_DELETECOLUMN
LVM_DELETEITEM
LVM_EDITLABEL
LVM_ENSUREVISIBLE
LVM_FINDITEM
LVM_GETBKCOLOR
LVM_GETBKIMAGE
LVM_GETCALLBACKMASK
LVM_GETCOLUMN
LVM_GETCOLUMNORDERARRAY
LVM_GETCOLUMNWIDTH
LVM_GETCOUNTPERPAGE
LVM_GETEDITCONTROL
LVM_GETEXTENDEDLISTVIEWSTYLE
LVM_GETHEADER
LVM_GETHOTCURSOR
LVM_GETHOTITEM
LVM_GETHOVERTIME
LVM_GETIMAGELIST
LVM_GETISEARCHSTRING
LVM_GETITEM
LVM_GETITEMCOUNT
LVM_GETITEMPOSITION
LVM_GETITEMRECT
LVM_GETITEMSPACING
LVM_GETITEMSTATE
LVM_GETITEMTEXT
LVM_GETNEXTITEM
LVM_GETNUMBEROFWORKAREAS
LVM_GETORIGIN
LVM_GETSELECTEDCOUNT
LVM_GETSELECTIONMARK
LVM_GETSTRINGWIDTH
LVM_GETSUBITEMRECT
LVM_GETTEXTBKCOLOR
LVM_GETTEXTCOLOR
LVM_GETTOOLTIPS
LVM_GETTOPINDEX
LVM_GETUNICODEFORMAT
LVM_GETVIEWRECT
LVM_GETWORKAREAS
LVM_HITTEST
LVM_INSERTCOLUMN
LVM_INSERTITEM
LVM_REDRAWITEMS
LVM_SCROLL
LVM_SETBKCOLOR
LVM_SETBKIMAGE
LVM_SETCALLBACKMASK
LVM_SETCOLUMN
LVM_SETCOLUMNORDERARRAY
LVM_SETCOLUMNWIDTH
LVM_SETEXTENDEDLISTVIEWSTYLE
LVM_SETHOTCURSOR
LVM_SETHOTITEM
LVM_SETHOVERTIME
LVM_SETICONSPACING
LVM_SETIMAGELIST
LVM_SETITEM
LVM_SETITEMCOUNT
LVM_SETITEMPOSITION
LVM_SETITEMPOSITION32
LVM_SETITEMSTATE
LVM_SETITEMTEXT
LVM_SETSELECTIONMARK
LVM_SETTEXTBKCOLOR
LVM_SETTEXTCOLOR
LVM_SETTOOLTIPS
LVM_SETUNICODEFORMAT
LVM_SETWORKAREAS
LVM_SORTITEMS
LVM_SUBITEMHITTEST
LVM_UPDATE

Utility Macros
ListView_ApproximateViewRect
ListView_Arrange
ListView_CreateDragImage
ListView_DeleteAllItems
ListView_DeleteColumn
ListView_DeleteItem
ListView_EditLabel
ListView_EnsureVisible
ListView_FindItem
ListView_GetBkColor
ListView_GetBkImage
ListView_GetCallbackMask
ListView_GetCheckState
ListView_GetColumn
ListView_GetColumnOrderArray
ListView_GetColumnWidth
ListView_GetCountPerPage
ListView_GetEditControl
ListView_GetExtendedListViewStyle
ListView_GetHeader
ListView_GetHotCursor
ListView_GetHotItem
ListView_GetImageList
ListView_GetISearchString
ListView_GetItem
ListView_GetItemCount
ListView_GetItemPosition
ListView_GetItemRect
ListView_GetItemSpacing
ListView_GetItemState
ListView_GetItemText
ListView_GetNextItem
ListView_GetNumberOfWorkAreas
ListView_GetOrigin
ListView_GetSelectedCount
ListView_GetSelectionMark
ListView_GetStringWidth
ListView_GetSubItemRect
ListView_GetTextBkColor
ListView_GetTextColor
ListView_GetToolTips
ListView_GetTopIndex
ListView_GetUnicodeFormat
ListView_GetViewRect
ListView_GetWorkAreas
ListView_HitTest
ListView_InsertColumn
ListView_InsertItem
ListView_RedrawItems
ListView_Scroll
ListView_SetBkColor
ListView_SetBkImage
ListView_SetCallbackMask
ListView_SetColumn
ListView_SetColumnOrderArray
ListView_SetColumnWidth
ListView_SetExtendedListViewStyle
ListView_SetExtendedListViewStyleEx
ListView_SetHotCursor
ListView_SetHotItem
ListView_SetIconSpacing
ListView_SetImageList
ListView_SetItem
ListView_SetItemCount
ListView_SetItemCountEx
ListView_SetItemPosition
ListView_SetItemPosition32
ListView_SetItemState
ListView_SetItemText
ListView_SetSelectionMark
ListView_SetTextBkColor
ListView_SetTextColor
ListView_SetToolTips
ListView_SetUnicodeFormat
ListView_SetWorkAreas
ListView_SortItems
ListView_SubItemHitTest
ListView_Update

Notifications
LVN_BEGINDRAG
LVN_BEGINLABELEDIT
LVN_BEGINRDRAG
LVN_COLUMNCLICK
LVN_DELETEALLITEMS
LVN_DELETEITEM
LVN_ENDLABELEDIT
LVN_GETDISPINFO
LVN_GETINFOTIP
LVN_HOTTRACK
LVN_INSERTITEM
LVN_ITEMACTIVATE
LVN_ITEMCHANGED
LVN_ITEMCHANGING
LVN_KEYDOWN
LVN_MARQUEEBEGIN
LVN_ODCACHEHINT
LVN_ODFINDITEM
LVN_ODSTATECHANGED
LVN_SETDISPINFO
NM_CLICK (list view)
NM_CUSTOMDRAW (list view)
NM_DBLCLK (list view)
NM_HOVER (list view)
NM_KILLFOCUS (list view)
NM_RCLICK (list view)
NM_RDBLCLK (list view)
NM_RELEASEDCAPTURE (list view)
NM_RETURN (list view)
NM_SETFOCUS (list view)

Structures
LV_COLUMN
LV_DISPINFO
LV_FINDINFO
LV_HITTESTINFO
LV_ITEM
LV_KEYDOWN
LVBKIMAGE
LVCOLUMN
LVFINDINFO
LVHITTESTINFO
LVITEM
NM_LISTVIEW
NMITEMACTIVATE
NMLISTVIEW
NMLVCACHEHINT
NMLVCUSTOMDRAW
NMLVDISPINFO
NMLVFINDITEM
NMLVGETINFOTIP
NMLVKEYDOWN
NMLVODSTATECHANGE

List view window styles

Extended list view styles

List view item states

List View Control Messages

List View Control Macros

List View Control Notification Messages

List View Control Structures


List view window styles

The following window styles are specific to list view controls.
LVS_ALIGNLEFT | Items are left-aligned in icon and small icon view.
LVS_ALIGNTOP | Items are aligned with the top of the list view control in icon and small icon view.
LVS_AUTOARRANGE | Icons are automatically kept arranged in icon and small icon view.
LVS_EDITLABELS | Item text can be edited in place. The parent window must process the LVN_ENDLABELEDIT notification message.
LVS_ICON | Icon view.
LVS_LIST | List view.
LVS_NOCOLUMNHEADER | Column headers are not displayed in report view. By default, columns have headers in report view.
LVS_NOLABELWRAP | Item text is displayed on a single line in icon view. By default, item text may wrap in icon view.
LVS_NOSCROLL | Scrolling is disabled. All items must be within the client area.
LVS_NOSORTHEADER | Column headers do not work like buttons. This style can be used if clicking a column header in report view does not carry out an action, such as sorting.
LVS_OWNERDATA | Version 4.70. Specifies a virtual list view control. For more information about this list control style, see Virtual list view description.
LVS_OWNERDRAWFIXED | The owner window can 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 | Report view. When using the LVS_REPORT style with a list view control, the first column is always left-aligned. You cannot use LVCFMT_RIGHT to change this alignment.
LVS_SHAREIMAGELISTS | The image list will not be deleted when the control is destroyed. This style enables the use of the same image lists with multiple list view controls.
LVS_SHOWSELALWAYS | The selection, if any, is always shown, even if the control does not have the focus.
LVS_SINGLESEL | Only one item at a time can be selected. By default, multiple items may be selected.
LVS_SMALLICON | Small icon view.
LVS_SORTASCENDING | Items are sorted based on item text in ascending order.
LVS_SORTDESCENDING | Items are sorted based on item text in descending order.

You can use the LVS_TYPEMASK mask 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 mask to isolate the window styles that specify the alignment of items: LVS_ALIGNLEFT and LVS_ALIGNTOP.

You can use the LVS_TYPESTYLEMASK mask to isolate the window styles that control item alignment (LVS_ALIGNLEFT and LVS_ALIGNTOP) and those that control header appearance and behavior (LVS_NOCOLUMNHEADER and LVS_NOSORTHEADER).


Extended list view styles

List view control styles have been extended. To use these new styles, use the LVM_SETEXTENDEDLISTVIEWSTYLE message or one of the ListView_SetExtendedListViewStyle or ListView_SetExtendedListViewStyleEx macros.
LVS_EX_CHECKBOXES Version 4.70. Enables check boxes for items in a list view control. Effectively, when set to this style, the control will create and set a state image list using DrawFrameControl. Check boxes are visible and functional with all list view modes. The state of the check box for a given item is obtained using the ListView_GetCheckState macro.

Note: To set the state of the item checkbox, use the following macro.

#ifndef ListView_SetCheckState
   #define ListView_SetCheckState(hwndLV, i, fCheck) \
      ListView_SetItemState(hwndLV, i, \
      INDEXTOSTATEIMAGEMASK((fCheck)+1), LVIS_STATEIMAGEMASK)
#endif
LVS_EX_FLATSB | Version 4.71. Enables flat scroll bars in the list view. If you need more control over the appearance of the list view's scroll bars, you should manipulate the list view's scroll bars directly using the Flat Scroll Bar APIs.
LVS_EX_FULLROWSELECT | Version 4.70. When an item is selected, the item and all its subitems are highlighted. This style is available only in conjunction with the LVS_REPORT style.
LVS_EX_GRIDLINES | Version 4.70. Displays gridlines around items and subitems. This style is available only in conjunction with the LVS_REPORT style.
LVS_EX_HEADERDRAGDROP | Version 4.70. Enables drag-and-drop reordering of columns in a list view control. This style is only available to list view controls that use the LVS_REPORT style.
LVS_EX_INFOTIP | Version 4.71. The list view control sends an LVN_GETINFOTIP notification message to the parent window before displaying an item's tooltip. This style is only available to list view controls that use the LVS_ICON style.
LVS_EX_MULTIWORKAREAS | Version 4.71. If the list view control has the LVS_AUTOARRANGE style, the control will not autoarrange its icons until one or more work areas are defined (see LVM_SETWORKAREAS). To be effective, this style must be set before any work areas are defined and any items have been added to the control.
LVS_EX_ONECLICKACTIVATE | Version 4.70. The list view control sends an LVN_ITEMACTIVATE notification message to the parent window when the user clicks an item. This style also enables hot tracking in the list view control. Hot tracking means that when the cursor moves over an item, it is highlighted but not selected.
LVS_EX_REGIONAL | Version 4.71. The list view will create a region that includes only the item icons and text and set its window region to that using SetWindowRgn. This will exclude any area that is not part of an item from the window region. This style is only available to list view controls that use the LVS_ICON style.
LVS_EX_SUBITEMIMAGES | Version 4.70. Allows images to be displayed for subitems. This style is available only in conjunction with the LVS_REPORT style.
LVS_EX_TRACKSELECT | Version 4.70. Enables hover selection in a list view control. Hover selection (also called track selection) means that an item is automatically selected when the cursor remains over the item for a certain period of time. The delay can be changed from the default system setting with the LVM_SETHOVERTIME message. This style applies to all styles of list view control.
LVS_EX_TWOCLICKACTIVATE | Version 4.70. The list view control sends an LVN_ITEMACTIVATE notification message to the parent window when the user double-clicks an item. This style also enables hot tracking in the list view control. Hot tracking means that when the cursor moves over an item, it is highlighted but not selected.
LVS_EX_UNDERLINECOLD | Version 4.71. Causes nonhot items to be displayed with underlined text. This style is ignored if LVS_EX_ONECLICKACTIVATE is not set.
LVS_EX_UNDERLINEHOT | Version 4.71. Causes hot items to be displayed with underlined text. This style is ignored if LVS_EX_ONECLICKACTIVATE or LVS_EX_TWOCLICKACTIVATE is not set.


List view item states

An item's state value consists of the item's state, an optional overlay mask index, and an optional state image mask index.

An item's state determines its appearance and functionality. The state can be zero or one or more of the following values:
LVIS_ACTIVATING | Version 4.71. The item is being activated in an LVN_ITEMACTIVATE notification.
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 also on the system colors used for selection.

You can use the LVIS_OVERLAYMASK mask to isolate the one-based index of the overlay image. You can use the LVIS_STATEIMAGEMASK mask to isolate the one-based index of the state image.


List View Control Messages

This section contains information about messages used with list view controls.

LVM_APPROXIMATEVIEWRECT

LVM_ARRANGE

LVM_CREATEDRAGIMAGE

LVM_DELETEALLITEMS

LVM_DELETECOLUMN

LVM_DELETEITEM

LVM_EDITLABEL

LVM_ENSUREVISIBLE

LVM_FINDITEM

LVM_GETBKCOLOR

LVM_GETBKIMAGE

LVM_GETCALLBACKMASK

LVM_GETCOLUMN

LVM_GETCOLUMNORDERARRAY

LVM_GETCOLUMNWIDTH

LVM_GETCOUNTPERPAGE

LVM_GETEDITCONTROL

LVM_GETEXTENDEDLISTVIEWSTYLE

LVM_GETHEADER

LVM_GETHOTCURSOR

LVM_GETHOTITEM

LVM_GETHOVERTIME

LVM_GETIMAGELIST

LVM_GETISEARCHSTRING

LVM_GETITEM

LVM_GETITEMCOUNT

LVM_GETITEMPOSITION

LVM_GETITEMRECT

LVM_GETITEMSPACING

LVM_GETITEMSTATE

LVM_GETITEMTEXT

LVM_GETNEXTITEM

LVM_GETNUMBEROFWORKAREAS

LVM_GETORIGIN

LVM_GETSELECTEDCOUNT

LVM_GETSELECTIONMARK

LVM_GETSTRINGWIDTH

LVM_GETSUBITEMRECT

LVM_GETTEXTBKCOLOR

LVM_GETTEXTCOLOR

LVM_GETTOOLTIPS

LVM_GETTOPINDEX

LVM_GETUNICODEFORMAT

LVM_GETVIEWRECT

LVM_GETWORKAREAS

LVM_HITTEST

LVM_INSERTCOLUMN

LVM_INSERTITEM

LVM_REDRAWITEMS

LVM_SCROLL

LVM_SETBKCOLOR

LVM_SETBKIMAGE

LVM_SETCALLBACKMASK

LVM_SETCOLUMN

LVM_SETCOLUMNORDERARRAY

LVM_SETCOLUMNWIDTH

LVM_SETEXTENDEDLISTVIEWSTYLE

LVM_SETHOTCURSOR

LVM_SETHOTITEM

LVM_SETHOVERTIME

LVM_SETICONSPACING

LVM_SETIMAGELIST

LVM_SETITEM

LVM_SETITEMCOUNT

LVM_SETITEMPOSITION

LVM_SETITEMPOSITION32

LVM_SETITEMSTATE

LVM_SETITEMTEXT

LVM_SETSELECTIONMARK

LVM_SETTEXTBKCOLOR

LVM_SETTEXTCOLOR

LVM_SETTOOLTIPS

LVM_SETUNICODEFORMAT

LVM_SETWORKAREAS

LVM_SORTITEMS

LVM_SUBITEMHITTEST

LVM_UPDATE


LVM_APPROXIMATEVIEWRECT

LVM_APPROXIMATEVIEWRECT
    wParam = (WPARAM)(INT) iCount;
    lParam = (LPARAM) MAKELPARAM(cx, cy);

Calculates the approximate width and height required to display a given number of items. You can send this message explicitly or use the ListView_ApproximateViewRect macro.

  • Returns a DWORD value that holds the approximate width and height needed to display the items, in pixels.
iCount
Number of items to be displayed in the control. If this parameter is set to -1, the message uses the total number of items in the control.
cx and cy
Proposed dimensions of the control, in pixels. Either parameter can be set to -1 to allow the message to use the current width or height value.

Setting the size of the list view control based on the dimensions provided by this message can optimize redraw and reduce flicker.

Version 4.70


LVM_ARRANGE

LVM_ARRANGE
    wParam = (WPARAM) (int) code;
    lParam = 0;

Arranges items in icon view. You can send this message explicitly or by using the ListView_Arrange macro.

  • Returns TRUE if successful, or FALSE otherwise.
code
Alignment. This can be one of the following values:
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.


LVM_CREATEDRAGIMAGE

LVM_CREATEDRAGIMAGE
    wParam = (WPARAM) (int) iItem;
    lParam = (LPARAM) (LPPOINT) lpptUpLeft;

Creates a drag image list for the specified item. You can send this message explicitly or by using the ListView_CreateDragImage macro.

  • Returns the handle to the drag image list if successful, or NULL otherwise.
iItem
Index of the item.
lpptUpLeft
Address of a POINT structure that receives the initial location of the upper-left corner of the image, in view coordinates.


LVM_DELETEALLITEMS

LVM_DELETEALLITEMS
    wParam = 0;
    lParam = 0;

Removes all items from a list view control. You can send this message explicitly or by using the ListView_DeleteAllItems macro.

  • Returns TRUE if successful, or FALSE otherwise.

When a list view control receives the LVM_DELETEALLITEMS message, it sends the LVN_DELETEALLITEMS notification message to its parent window.


LVM_DELETECOLUMN

LVM_DELETECOLUMN
    wParam = (WPARAM) (int) iCol;
    lParam = 0;

Removes a column from a list view control. You can send this message explicitly or by using the ListView_DeleteColumn macro.

  • Returns TRUE if successful, or FALSE otherwise.
iCol
Index of the column to delete.


LVM_DELETEITEM

LVM_DELETEITEM
    wParam = (WPARAM) (int) iItem;
    lParam = 0;

Removes an item from a list view control. You can send this message explicitly or by using the ListView_DeleteItem macro.

  • Returns TRUE if successful, or FALSE otherwise.
iItem
Index of the list view item to delete.


LVM_EDITLABEL

LVM_EDITLABEL
    wParam = (WPARAM) (int) iItem;
    lParam = 0;

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.

  • Returns the handle to the edit control that is used to edit the item text if successful, or NULL otherwise.
iItem
Index of the list view item. To cancel editing, set iItem to -1.

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


LVM_ENSUREVISIBLE

LVM_ENSUREVISIBLE
    wParam = (WPARAM) (int) i;
    lParam = (LPARAM) (BOOL) fPartialOK;

Ensures that a list view item is either entirely or partially visible, scrolling the list view control if necessary. You can send this message explicitly or by using the ListView_EnsureVisible macro.

  • Returns TRUE if successful, or FALSE otherwise.
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.


LVM_FINDITEM

LVM_FINDITEM
    wParam = (WPARAM) (int) iStart;
    lParam = (LPARAM) (const LPLVFINDINFO) plvfi;

Searches for a list view item with the specified characteristics. You can send this message explicitly or by using the ListView_FindItem macro.

  • Returns the index of the item if successful, or -1 otherwise.
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
Address of an LVFINDINFO structure that contains information about what to search for.


LVM_GETBKCOLOR

LVM_GETBKCOLOR
    wParam = 0;
    lParam = 0;

Retrieves the background color of a list view control. You can send this message explicitly or by using the ListView_GetBkColor macro.

  • Returns the background color of the list view control.


LVM_GETBKIMAGE

LVM_GETBKIMAGE
    wParam = 0;
    lParam = (LPARAM) (LPLVBKIMAGE) plvbki;

Retrieves the background image in a list view control. You can send this message explicitly or by using the ListView_GetBkImage macro.

  • Returns nonzero if successful, or zero otherwise.
plvbki
Address of an LVBKIMAGE structure that will receive the background image information.

Version 4.71

See also LVM_SETBKIMAGE


LVM_GETCALLBACKMASK

LVM_GETCALLBACKMASK
    wParam = 0;
    lParam = 0;

Retrieves the callback mask for a list view control. You can send this message explicitly or by using the ListView_GetCallbackMask macro.

  • Returns the callback mask.


LVM_GETCOLUMN

LVM_GETCOLUMN
    wParam = (WPARAM) (int) iCol;
    lParam = (LPARAM) (LPLVCOLUMN) pcol;

Retrieves the attributes of a list view control's column. You can send this message explicitly or by using the ListView_GetColumn macro.

  • Returns TRUE if successful, or FALSE otherwise.
iCol
Index of the column.
pcol
Address of an LVCOLUMN 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 address of the buffer that receives the item text and the cchTextMax member must specify the size of the buffer.


LVM_GETCOLUMNORDERARRAY

LVM_GETCOLUMNORDERARRAY
    wParam = (WPARAM) (int) iCount;
    lParam = (LPARAM) lpiArray;

Retrieves the current left-to-right order of columns in a list view control. You can send this message explicitly or use the ListView_GetColumnOrderArray macro.

  • If successful, returns nonzero, and the buffer at lpiArray receives the column index of each column in the control in the order they appear from left to right. Otherwise, the return value is zero.
iCount
Number of columns in the list view control.
lpiArray
Address of an array of integers that receives the index values of the columns in the list view control. The array must be large enough to hold iCount elements.

Version 4.70


LVM_GETCOLUMNWIDTH

LVM_GETCOLUMNWIDTH
    wParam = (WPARAM) (int) iCol;
    lParam = 0;

Retrieves the width of a column in report or list view. You can send this message explicitly or by using the ListView_GetColumnWidth macro.

  • Returns the column width if successful, or zero otherwise. If this message is sent to a list view control with the LVS_REPORT style and the specified column doesn't exist, the return value is undefined.
iCol
Index of the column. This parameter is ignored in list view.


LVM_GETCOUNTPERPAGE

LVM_GETCOUNTPERPAGE
    wParam = 0;
    lParam = 0;

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.

  • 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

LVM_GETEDITCONTROL
    wParam = 0;
    lParam = 0;

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.

  • Returns the handle to the edit control if successful, or NULL otherwise.

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.


LVM_GETEXTENDEDLISTVIEWSTYLE

LVM_GETEXTENDEDLISTVIEWSTYLE
    wParam = 0;
    lParam = 0;

Retrieves the extended styles that are currently in use for a given list view control. You can send this message explicitly or use the ListView_GetExtendedListViewStyle macro.

  • Returns a DWORD that represents the styles currently in use for a given list view control. This value can be a combination of extended styles.

Version 4.70


LVM_GETHEADER

LVM_GETHEADER
    wParam = 0;
    lParam = 0;

Retrieves the handle to the header control used by the list view control. You can send this message explicitly or use the ListView_GetHeader macro.

  • Returns the handle to the header control.

Version 4.70


LVM_GETHOTCURSOR

LVM_GETHOTCURSOR
    wParam = 0;
    lParam = 0;

Retrieves the HCURSOR value used when the pointer is over an item while hot tracking is enabled. You can send this message explicitly or use the ListView_GetHotCursor macro.

  • Returns an HCURSOR value that is the handle to the cursor that the list view control uses when hot tracking is enabled.

A list view control uses hot tracking and hover selection when the LVS_EX_TRACKSELECT style is set.

Version 4.70


LVM_GETHOTITEM

LVM_GETHOTITEM
    wParam = 0;
    lParam = 0;

Retrieves the index of the hot item. You can send this message explicitly or use the ListView_GetHotItem macro.

  • Returns the index of the item that is hot.

Version 4.70


LVM_GETHOVERTIME

LVM_GETHOVERTIME
    wParam = 0;
    lParam = 0;

Retrieves the amount of time that the mouse cursor must hover over an item before it is selected. You can send this message explicitly or use the ListView_GetHoverTime macro.

  • Returns the amount of time, in milliseconds, that the mouse cursor must hover over an item before it is selected. If the return value is (DWORD)-1, then the hover time is the default hover time.

The hover time only affects list view controls that have the LVS_EX_TRACKSELECT, LVS_EX_ONECLICKACTIVATE, or LVS_EX_TWOCLICKACTIVATE extended list view style.

Version 4.71


LVM_GETIMAGELIST

LVM_GETIMAGELIST
    wParam = (WPARAM) (int) iImageList;
    lParam = 0;

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.

  • Returns the handle to the specified image list if successful, or NULL otherwise.
iImageList
Image list to retrieve. This parameter can be one of the following values:
LVSIL_NORMAL | Image list with large icons.
LVSIL_SMALL | Image list with small icons.
LVSIL_STATE | Image list with state images.


LVM_GETISEARCHSTRING

LVM_GETISEARCHSTRING
    wParam = 0;
    lParam = (LPARAM) (LPSTR) lpsz;

Retrieves the incremental search string of a list view control. You can send this message explicitly or by using the ListView_GetISearchString macro.

  • Returns the number of characters in the incremental search string, or zero if the list view control is not in incremental search mode.
lpsz
Address of a buffer that receives the incremental search string.

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 time-out period is associated with each character that the user types. If the time-out period elapses before the user types another character, the incremental search string is reset.


LVM_GETITEM

LVM_GETITEM
    wParam = 0;
    lParam = (LPARAM) (LPLVITEM) pitem;

Retrieves some or all of a list view item's attributes. You can send this message explicitly or by using the ListView_GetItem macro.

  • Returns TRUE if successful, or FALSE otherwise.
pitem
Address of an LVITEM 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 LVITEM structure.
If the mask member specifies the LVIF_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.

If the mask member specifies the LVIF_STATE value, the stateMask member must specify the item state bits to retrieve. On output, the state member contains the values of the specified state bits.


LVM_GETITEMCOUNT

LVM_GETITEMCOUNT
    wParam = 0;
    lParam = 0;

Retrieves the number of items in a list view control. You can send this message explicitly or by using the ListView_GetItemCount macro.

  • Returns the number of items.


LVM_GETITEMPOSITION

LVM_GETITEMPOSITION
    wParam = (WPARAM) (int) i;
    lParam = (LPARAM) (POINT FAR *) ppt;

Retrieves the position of a list view item. You can send this message explicitly or by using the ListView_GetItemPosition macro.

  • Returns TRUE if successful, or FALSE otherwise.
i
Index of the list view item.
ppt
Address of a POINT structure that receives the position of the item's upper-left corner, in view coordinates.


LVM_GETITEMRECT

LVM_GETITEMRECT
    wParam = (WPARAM) (int) i;
    lParam = (LPARAM) (LPRECT) prc;

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.

  • Returns TRUE if successful, or FALSE otherwise.
i
Index of the list view item.
prc
Address of a RECT structure that receives the bounding rectangle. When the message is sent, the left member of this structure is used to determine the portion of the list view item for which to retrieve the bounding rectangle. This will be one of the code values defined in ListView_GetItemRect.

This parameter is specified by the left member of the RECT structure pointed to by prc.


LVM_GETITEMSPACING

LVM_GETITEMSPACING
    wParam = (WPARAM) (BOOL) fSmall;
    lParam = 0;

Determines the spacing between items in a list view control. You can send this message explicitly or by using the ListView_GetItemSpacing macro.

  • Returns the amount of spacing between items. The horizontal spacing is contained in the low-order WORD and the vertical spacing is contained in the high-order WORD.
fSmall
View for which to retrieve the item spacing. This parameter is TRUE for small icon view, or FALSE for icon view.


LVM_GETITEMSTATE

LVM_GETITEMSTATE
    wParam = (WPARAM) (int) i;
    lParam = (LPARAM) (UINT) mask;

Retrieves the state of a list view item. You can send this message explicitly or by using the ListView_GetItemState macro.

  • Returns the current state for the specified item. The only valid bits in the return value are those that correspond to the bits set in the mask parameter.
i
Index of the list view item.
mask
State information to retrieve. This parameter can be a combination 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 also on the system colors used for selection.
LVIS_OVERLAYMASK | Use this mask to retrieve the item's overlay image index.
LVIS_STATEIMAGEMASK | Use this mask to retrieve the item's state image index.

An item's state information includes a set of bit flags as well as image list indexes that indicate the item's state image and overlay image.

See also LVM_SETITEMSTATE


LVM_GETITEMTEXT

LVM_GETITEMTEXT
    wParam = (WPARAM) (int) iItem;
    lParam = (LPARAM) (LPLVITEM) pitem;

Retrieves the text of a list view item or subitem. You can send this message explicitly or by using the ListView_GetItemText macro.

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

iItem
Index of the list view item.
pitem
Address of an LVITEM 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.


LVM_GETNEXTITEM

LVM_GETNEXTITEM
    wParam = (WPARAM) (int) iStart;
    lParam = MAKELPARAM((UINT) flags, 0);

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.

  • Returns the index of the next item if successful, or -1 otherwise.
iStart
Index of the item to begin the search with, or -1 to find the first item that matches the specified flags. The specified item itself is excluded from the search.
flags
Specifies the relationship to the item specified in iStart. This can be one or a combination of the following values:

LVNI_ALL Searches for a subsequent item by index (the default value).

The physical relationship to iStart can be specified with one of the following values:
LVNI_ABOVE | Searches for an item that is above the specified item.
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 of the item to find can be specified with one or a combination of the following values:
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.


LVM_GETNUMBEROFWORKAREAS

LVM_GETNUMBEROFWORKAREAS
    wParam = 0;
    lParam = (LPARAM)(LPUINT) lpuWorkAreas;

Retrieves the number of working areas in a list view control. You can send this message explicitly or use the ListView_GetNumberOfWorkAreas macro.

  • The return value for this message is not used.
lpuWorkAreas
Address of a UINT value that receives the number of working areas in the list view control. If zero is placed in this variable, then no working areas are currently set. This value cannot be NULL.

Version 4.71


LVM_GETORIGIN

LVM_GETORIGIN
    wParam = 0;
    lParam = (LPARAM) (LPPOINT) lpptOrg;

Retrieves the current view origin for a list view control. You can send this message explicitly or by using the ListView_GetOrigin macro.

  • Returns TRUE if successful, or FALSE if the current view is list or report view.
lpptOrg
Address of a POINT structure that receives the view origin.


LVM_GETSELECTEDCOUNT

LVM_GETSELECTEDCOUNT
    wParam = 0;
    lParam = 0;

Determines the number of selected items in a list view control. You can send this message explicitly or by using the ListView_GetSelectedCount macro.

  • Returns the number of selected items.


LVM_GETSELECTIONMARK

LVM_GETSELECTIONMARK
    wParam = 0;
    lParam = 0;

Retrieves the selection mark from a list view control. You can send this message explicitly or use the ListView_GetSelectionMark macro.

  • Returns the zero-based selection mark, or -1 if there is no selection mark.

The selection mark is the item index from which a multiple selection starts.

Version 4.71

See also LVM_SETSELECTIONMARK


LVM_GETSTRINGWIDTH

LVM_GETSTRINGWIDTH
    wParam = 0;
    lParam = (LPARAM) (LPCSTR) psz;

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.

  • Returns the string width if successful, or zero otherwise.
psz
Address of a null-terminated string.

The LVM_GETSTRINGWIDTH message returns the exact width, in pixels, of the specified string. If you use the returned string width as the column width in the LVM_SETCOLUMNWIDTH message, the string will be truncated. To get the column width that can contain the string without truncating it, you must add padding to the returned string width.


LVM_GETSUBITEMRECT

LVM_GETSUBITEMRECT
    wParam = (WPARAM)(int) iItem;
    lParam = (LPARAM)(LPRECT) lpRect;

Retrieves information about the bounding rectangle for a subitem in a list view control. You can send this message explicitly or by using the ListView_GetSubItemRect macro (recommended). This message is intended to be used only with list view controls that use the LVS_REPORT style.

  • Returns nonzero if successful, or zero otherwise.
iItem
Index of the subitem's parent item.
lpRect
Address of a RECT structure that will receive the subitem bounding rectangle information. Its members must be initialized according to the following member/value relationships:
Member | Value
top | The one-based index of the subitem.
left | Flag value (see following). Indicates the portion of the list view subitem for which to retrieve the bounding rectangle.
Flag 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 entire item, including the icon and label. This is identical to LVIR_BOUNDS.

Version 4.70


LVM_GETTEXTBKCOLOR

LVM_GETTEXTBKCOLOR
    wParam = 0;
    lParam = 0;

Retrieves the text background color of a list view control. You can send this message explicitly or by using the ListView_GetTextBkColor macro.

  • Returns the background color of the text.


LVM_GETTEXTCOLOR

LVM_GETTEXTCOLOR
    wParam = 0;
    lParam = 0;

Retrieves the text color of a list view control. You can send this message explicitly or by using the ListView_GetTextColor macro.

  • Returns the text color.


LVM_GETTOOLTIPS

LVM_GETTOOLTIPS
    wParam = 0;
    lParam = 0;

Retrieves the tooltip control that the list view control uses to display tooltips. You can send this message explicitly or use the ListView_GetToolTips macro.

  • Returns the handle of the tooltip control.

See also LVM_SETTOOLTIPS


LVM_GETTOPINDEX

LVM_GETTOPINDEX
    wParam = 0;
    lParam = 0;

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.

  • Returns the index of the item if successful, or zero if the list view control is in icon or small icon view.


LVM_GETUNICODEFORMAT

LVM_GETUNICODEFORMAT
    wParam = 0;
    lParam = 0;

Retrieves the UNICODE character format flag for the control. You can send this message explicitly or use the ListView_GetUnicodeFormat macro.

  • Returns the UNICODE format flag for the control. If this value is nonzero, the control is using UNICODE characters. If this value is zero, the control is using ANSI characters.

See also LVM_SETUNICODEFORMAT


LVM_GETVIEWRECT

LVM_GETVIEWRECT
    wParam = 0;
    lParam = (LPARAM) (RECT FAR *) prc;

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.

  • Returns TRUE if successful, or FALSE otherwise.
prc
Address of a RECT structure that receives the bounding rectangle. All coordinates are relative to the visible area of the list view control.


LVM_GETWORKAREAS

LVM_GETWORKAREAS
    wParam = (WPARAM)(INT) nWorkAreas;
    lParam = (LPARAM)(LPRECT) lprc;

Retrieves the working areas from a list view control. You can send this message explicitly or use the ListView_GetWorkAreas macro.

  • The return value for this message is not used.
nWorkAreas
The number of RECT structures in the array at lprc.
lprc
Address of an array of RECT structures that receive the current working areas of the list view control. Values in these structures are in client coordinates. nWorkAreas specifies the number of structures in this array.

Version 4.71


LVM_HITTEST

LVM_HITTEST
    wParam = 0;
    lParam = (LPARAM) (LPLVHITTESTINFO) pinfo;

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.

  • Returns the index of the item at the specified position, if any, or -1 otherwise.
pinfo
Address of an LVHITTESTINFO structure that contains the position to hit test and receives information about the results of the hit test.


LVM_INSERTCOLUMN

LVM_INSERTCOLUMN
    wParam = (WPARAM) (int) iCol;
    lParam = (LPARAM) (const LPLVCOLUMN) pcol;

Inserts a new column in a list view control. You can send this message explicitly or by using the ListView_InsertColumn macro.

  • Returns the index of the new column if successful, or -1 otherwise.
iCol
Index of the new column.
pcol
Address of an LVCOLUMN structure that contains the attributes of the new column.


LVM_INSERTITEM

LVM_INSERTITEM
    wParam = 0;
    lParam = (LPARAM) (const LPLVITEM) pitem;

Inserts a new item in a list view control. You can send this message explicitly or by using the ListView_InsertItem macro.

  • Returns the index of the new item if successful, or -1 otherwise.
pitem
Address of an LVITEM structure that specifies the attributes of the list view item. The iItem member specifies the index of the new item.
You cannot use ListView_InsertItem or LVM_INSERTITEM to insert subitems; the iSubItem member of the LVITEM structure must be zero.

If a list view control has either the LVS_SORTASCENDING or LVS_SORTDESCENDING window style, an LVM_INSERTITEM message will fail if you try to insert an item that has LPSTR_TEXTCALLBACK as the pszText member of its LVITEM structure.


LVM_REDRAWITEMS

LVM_REDRAWITEMS
    wParam = (int) iFirst;
    lParam = (int) iLast;

Forces a list view control to redraw a range of items. You can send this message explicitly or by using the ListView_RedrawItems macro.

  • Returns TRUE if successful, or FALSE otherwise.
iFirst
Index of the first item to redraw.
iLast
Index of the last item to redraw.

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.


LVM_SCROLL

LVM_SCROLL
    wParam = (int) dx;
    lParam = (int) dy;

Scrolls the content of a list view control. You can send this message explicitly or by using the ListView_Scroll macro.

  • Returns TRUE if successful, or FALSE otherwise.
dx
Integer value that specifies the amount of horizontal scrolling in pixels. If the list view control is in list view, this value specifies the number of columns to scroll.
dy
Integer value that specifies the amount of vertical scrolling in pixels.

When the list view control is in report view, the control can only be scrolled vertically in whole line increments. Therefore, the dy parameter will be rounded to the nearest number of pixels that form a whole line increment. For example, if the height of a line is 16 pixels and 8 is passed for dy, the list will be scrolled by 16 pixels (1 line). If 7 is passed for dy, the list will be scrolled 0 pixels (0 lines).


LVM_SETBKCOLOR

LVM_SETBKCOLOR
    wParam = 0;
    lParam = (LPARAM) (COLORREF) clrBk;

Sets the background color of a list view control. You can send this message explicitly or by using the ListView_SetBkColor macro.

  • Returns TRUE if successful, or FALSE otherwise.
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.


LVM_SETBKIMAGE

LVM_SETBKIMAGE
    wParam = 0;
    lParam = (LPARAM)(LPLVBKIMAGE) plvbki;

Sets the background image in a list view control. You can send this message explicitly or by using the ListView_SetBkImage macro.

  • Returns nonzero if successful, or zero otherwise.
plvbki
Address of a LVBKIMAGE structure that contains the new background image information.

Because the list view control uses OLE COM to manipulate the background images, the calling application must call CoInitialize or OleInitialize before sending this message. It is best to call one of these functions when the application is initialized and call either CoUnitialize or OleUnitialize when the application is terminating.

Version 4.71

See also LVM_GETBKIMAGE


LVM_SETCALLBACKMASK

LVM_SETCALLBACKMASK
    wParam = (WPARAM) (UINT) mask;
    lParam = 0;

Changes the callback mask for a list view control. You can send this message explicitly or by using the ListView_SetCallbackMask macro.

  • Returns TRUE if successful, or FALSE otherwise.
mask
Value of the callback mask. The bits of the mask indicate the item states or images for which the application stores the current state data. This value can be any combination of the following constants:
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.
LVIS_SELECTED | The item is selected.
LVIS_OVERLAYMASK | The application stores the image list index of the current overlay image for each item.
LVIS_STATEIMAGEMASK | The application stores the image list index of the current state image for each item.

The callback mask of a list view control is a set of bit flags that specify the item states for which the application, rather than the control, stores the current data. The callback mask applies to all of the control's items, unlike the callback item designation, which applies to a specific item. The callback mask is zero by default, meaning that the list view control stores all item state information. After creating a list view control and initializing its items, you can send the LVM_SETCALLBACKMASK message to change the callback mask. To get the current callback mask, send the LVM_GETCALLBACKMASK message.

For more information about overlay images and state images, see List View Image Lists.

For more information on list view callbacks, see Callback Items and the Callback Mask.

See also LVN_GETDISPINFO


LVM_SETCOLUMN

LVM_SETCOLUMN
    wParam = (WPARAM) (int) iCol;
    lParam = (LPARAM) (const LPLVCOLUMN) pcol;

Sets the attributes of a list view column. You can send this message explicitly or by using the ListView_SetColumn macro.

  • Returns TRUE if successful, or FALSE otherwise.
iCol
Index of the column.
pcol
Address of an LVCOLUMN 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 address of a null-terminated string and the cchTextMax member is ignored.


LVM_SETCOLUMNORDERARRAY

LVM_SETCOLUMNORDERARRAY
    wParam = (WPARAM) (int) iCount;
    lParam = (LPARAM) (LPINT) lpiArray;

Sets the left-to-right order of columns in a list view control. You can send this message explicitly or use the ListView_SetColumnOrderArray macro.

  • Returns nonzero if successful, or zero otherwise.
iCount
Size, in elements, of the buffer at lpiArray.
lpiArray
Address of an array that specifies the order in which columns should be displayed, from left to right. For example, if the contents of the array are {2,0,1}, the control displays column 2, column 0, and column 1 in that order.

Version 4.70


LVM_SETCOLUMNWIDTH

LVM_SETCOLUMNWIDTH
    wParam = (WPARAM) (int) iCol;
    lParam = MAKELPARAM((int) cx, 0);

Changes the width of a column in report or list view. You can send this message explicitly or by using the ListView_SetColumnWidth macro.

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:
LVSCW_AUTOSIZE | Automatically sizes the column.
LVSCW_AUTOSIZE_USEHEADER | Automatically sizes the column to fit the header text.


LVM_SETEXTENDEDLISTVIEWSTYLE

LVM_SETEXTENDEDLISTVIEWSTYLE
    wParam = (WPARAM)dwExMask;
    lParam = (LPARAM)dwExStyle;

Sets extended styles in list view controls. You can send this message explicitly or use the ListView_SetExtendedListViewStyle or ListView_SetExtendedListViewStyleEx macros.

  • Returns a DWORD value that contains the previous extended list view control styles.
dwExMask
A DWORD value that indicates which styles in dwExStyle are to be affected. This parameter can be a combination of extended styles. Only the extended styles in dwExMask will be changed. All other styles will be maintained as they are. If this parameter is zero, then all of the styles in dwExStyle will be affected.
dwExStyle
Value specifying the extended list view control style. This parameter can be a combination of extended styles.

dwExMask allows you to modify one or more extended styles without having to retrieve the existing styles first. For example, if you pass LVS_EX_FULLROWSELECT for dwExMask and 0 for dwExStyle, the LVS_EX_FULLROWSELECT style will be cleared, but all other styles will remain the same.

For backward compatibility reasons, the ListView_SetExtendedListViewStyle macro has not been updated to use dwExMask. To use the dwExMask value, use the ListView_SetExtendedListViewStyleEx macro.

Version 4.70


LVM_SETHOTCURSOR

LVM_SETHOTCURSOR
    wParam = 0;
    lParam = (LPARAM)(HCURSOR) hCursor;

Sets the HCURSOR value that the list view control uses when the pointer is over an item while hot tracking is enabled. You can send this message explicitly or use the ListView_SetHotCursor macro.

  • Returns an HCURSOR value that is the previous hot cursor.
hCursor
Handle to the cursor to be set.

A list view control uses hot tracking and hover selection when the LVS_EX_TRACKSELECT style is set.

Version 4.70


LVM_SETHOTITEM

LVM_SETHOTITEM
    wParam = (WPARAM)(INT) iIndex;
    lParam = 0;

Sets the hot item for a list view control. You can send this message explicitly or use the ListView_SetHotItem macro.

  • Returns the index of the item that was previously hot.
iIndex
Zero-based index of the item to be set as the hot item.

Version 4.70


LVM_SETHOVERTIME

LVM_SETHOVERTIME
    wParam = 0;
    lParam = (LPARAM)(DWORD)dwHoverTime;

Sets the amount of time which the mouse cursor must hover over an item before it is selected. You can send this message explicitly or use the ListView_SetHoverTime macro.

  • Returns the previous hover time.
dwHoverTime
The new amount of time, in milliseconds, that the mouse cursor must hover over an item before it is selected. If this value is (DWORD)-1, then the hover time is set to the default hover time.

The hover time only affects list view controls that have the LVS_EX_TRACKSELECT, LVS_EX_ONECLICKACTIVATE, or LVS_EX_TWOCLICKACTIVATE extended list view style.

Version 4.71


LVM_SETICONSPACING

LVM_SETICONSPACING
    wParam = 0;
    lParam = (LPARAM) MAKELONG(cx, cy);

Sets the spacing between icons in list view controls that have the LVS_ICON style. You can send this message explicitly or by using the ListView_SetIconSpacing macro.

  • Returns a DWORD value that contains the previous cx in the low word and the previous cy in the high word.
cx
Distance, in pixels, to set between icons on the x-axis. Setting this value to -1 resets the cx parameter to default spacing.
cy
Distance, in pixels, to set between icons on the y-axis. Setting this value to -1 resets the cy parameter to default spacing.

Values for cx and cy are relative to the upper-left corner of an icon bitmap. Therefore, to set spacing between icons that do not overlap, the cx or cy values must include the size of the icon, plus the amount of empty space desired between icons. Values that do not include the width of the icon will result in overlaps.

Version 4.70


LVM_SETIMAGELIST

LVM_SETIMAGELIST
    wParam = (WPARAM) (int) iImageList;
    lParam = (LPARAM) (HIMAGELIST) himl;

Assigns an image list to a list view control. You can send this message explicitly or by using the ListView_SetImageList macro.

  • Returns the handle to the image list previously associated with the control if successful, or NULL otherwise.
iImageList
Type of image list. This parameter can be one of the following values:
LVSIL_NORMAL | Image list with large icons.
LVSIL_SMALL | Image list with small icons.
LVSIL_STATE | Image list with state images.
himl
Handle to the image list to assign.


LVM_SETITEM

LVM_SETITEM
    wParam = 0;
    lParam = (LPARAM) (const LPLVITEM) pitem;

Sets some or all of a list view item's attributes. You can also send LVM_SETITEM to set the text of a subitem. You can send this message explicitly or by using the ListView_SetItem macro.

  • Returns TRUE if successful, or FALSE otherwise.
pitem
Address of an LVITEM 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 address of 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.

To set the attributes of a list view item, set the iItem member of the LVITEM structure to the index of the item, and set the iSubItem member to zero. For an item, you can set the state, pszText, iImage, and lParam members of the LVITEM structure.

To set the text of a subitem, set the iItem and iSubItem members to indicate the specific subitem, and use the pszText member to specify the text. Alternatively, you can use the ListView_SetItemText macro to set the text of a subitem. You cannot set the state or lParam members for subitems because subitems do not have these attributes. In version 4.70 and later, you can set the iImage member for subitems. The subitem image will be displayed if the list view control has the LVS_EX_SUBITEMIMAGES extended style. Previous versions will ignore the subitem image.


LVM_SETITEMCOUNT

LVM_SETITEMCOUNT
    wParam = (WPARAM) (int) cItems;
    lParam = (LPARAM) dwFlags;

Causes the list view control to allocate memory for the specified number of items or sets the virtual number of items in a virtual list view control. This depends on how the list view control was created. You can send this message explicitly or use the ListView_SetItemCount or ListView_SetItemCountEx macros.

  • Returns nonzero if successful, or zero otherwise.
cItems
Number of items that the list view control will ultimately contain.
dwFlags
Version 4.70. Values that specify the behavior of the list view control after resetting the item count. This value can be a combination of the following:
LVSICF_NOINVALIDATEALL | The list view control will not repaint unless affected items are currently in view.
LVSICF_NOSCROLL | The list view control will not change the scroll position when the item count changes.

If the list view control was created without the LVS_OWNERDATA style, sending this message causes the control to allocate its internal data structures for the specified number of items. This prevents the control from having to allocate the data structures every time an item is added.

If the list view control was created with the LVS_OWNERDATA style (a virtual list view), sending this message sets the virtual number of items that the control contains.

The dwFlags parameter is intended only for list view controls that use the LVS_OWNERDATA and LVS_REPORT or LVS_LIST styles.


LVM_SETITEMPOSITION

LVM_SETITEMPOSITION
    wParam = (LPARAM) (int) i;
    lParam = MAKELPARAM((int) x, (int) y);

Moves an item to a specified position in a list view control (must be in icon or small icon view). You can send this message explicitly or by using the ListView_SetItemPosition macro.

  • Returns TRUE if successful, or FALSE otherwise.
i
Index of the list view item.
x and y
New position of the item's upper-left corner, in view coordinates.

If the list view control has the LVS_AUTOARRANGE style, the items in the list view control are arranged after the position of the item is set.


LVM_SETITEMPOSITION32

LVM_SETITEMPOSITION32
    wParam = (WPARAM) (int) iItem;
    lParam = (LPARAM) (LPPOINT) lpptNewPos;

Moves an item to a specified position in a list view control (must be in icon or small icon view). This message differs from the LVM_SETITEMPOSITION message in that it uses 32-bit coordinates. You can send this message explicitly or by using the ListView_SetItemPosition32 macro.

  • No return value.
iItem
Index of the list view item for which to set the position.
lpptNewPos
Address of a POINT structure that contains the new position of the item, in list view coordinates.


LVM_SETITEMSTATE

LVM_SETITEMSTATE
    wParam = (WPARAM) (int) i;
    lParam = (LPARAM) (LPLVITEM) pitem;

Changes the state of an item in a list view control. You can send this message explicitly or by using the ListView_SetItemState macro.

  • If you send this message explicitly, it returns TRUE if successful or FALSE otherwise.
i
Index of the list view item.
If this parameter is -1, then the state change is applied to all items.
pitem
Address of an LVITEM 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.

An item's state value includes a set of bit flags that indicate the item's state. The state value can also include image list indexes that indicate the item's state image and overlay image.


LVM_SETITEMTEXT

LVM_SETITEMTEXT
    wParam = (WPARAM) (int) i;
    lParam = (LPARAM) (LPLVITEM) pitem;

Changes the text of a list view item or subitem. You can send this message explicitly or by using the ListView_SetItemText macro.

  • If you send this message explicitly, it returns TRUE if successful or FALSE otherwise.
i
Index of the list view item.
pitem
Address of an LVITEM 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 address of a null-terminated string containing the new text; it can also be NULL.

The pszText member can also be LPSTR_TEXTCALLBACK to indicate a callback item for which the parent window stores the text. In this case, the list view control sends the parent an LVN_GETDISPINFO notification message when it needs the text.


LVM_SETSELECTIONMARK

LVM_SETSELECTIONMARK
    wParam = 0;
    lParam = (LPARAM)(INT) iIndex;

Sets the selection mark in a list view control. You can send this message explicitly or use the ListView_SetSelectionMark macro.

  • Returns the previous selection mark, or -1 if there is no previous selection mark.
iIndex
Zero-based index of the new selection mark.

The selection mark is the item index from which a multiple selection starts. This message does not affect the selection state of the item.

Version 4.71

See also LVM_GETSELECTIONMARK


LVM_SETTEXTBKCOLOR

LVM_SETTEXTBKCOLOR
    wParam = 0;
    lParam = (LPARAM) (COLORREF) clrText;

Sets the background color of text in a list view control. You can send this message explicitly or by using the ListView_SetTextBkColor macro.

  • Returns TRUE if successful, or FALSE otherwise.
clrText
New text color.


LVM_SETTEXTCOLOR

LVM_SETTEXTCOLOR
    wParam = 0;
    lParam = (LPARAM) (COLORREF) clrText;

Sets the text color of a list view control. You can send this message explicitly or by use the ListView_SetTextColor macro.

  • Returns TRUE if successful, or FALSE otherwise.
clrText
New text color.


LVM_SETTOOLTIPS

LVM_SETTOOLTIPS
    wParam = 0;
    lParam = (LPARAM)(HWND)hwndToolTip;

Sets the tooltip control that the list view control will use to display tooltips. You can send this message explicitly or use the ListView_SetToolTips macro.

  • Returns the handle to the previous tooltip control.
hwndToolTip
Handle to the tooltip control to be set.

See also LVM_GETTOOLTIPS


LVM_SETUNICODEFORMAT

LVM_SETUNICODEFORMAT
    wParam = (WPARAM)(BOOL)fUnicode;
    lParam = 0;

Sets the UNICODE character format flag for the control. This message allows you to change the character set used by the control at run time rather than having to re-create the control. You can send this message explicitly or use the ListView_SetUnicodeFormat macro.

  • Returns the previous UNICODE format flag for the control.
fUnicode
Determines the character set that is used by the control. If this value is nonzero, the control will use UNICODE characters. If this value is zero, the control will use ANSI characters.

See also LVM_GETUNICODEFORMAT


LVM_SETWORKAREAS

LVM_SETWORKAREAS
    wParam = (WPARAM)(INT) nWorkAreas;
    lParam = (LPARAM)(LPRECT) lprc;

Sets the working areas within a list view control. You can send this message explicitly or use the ListView_SetWorkAreas macro.

  • The return value for this message is not used.
nWorkAreas
The number of structures in the array at lprc. The maximum number of working areas allowed is defined by the LV_MAX_WORKAREAS value.
lprc
Address of an array of RECT structures that contain the new working areas of the list view control. Values in these structures are in client coordinates. If this parameter is NULL, the working area will be set to the client area of the control. nWorkAreas specifies the number of structures in this array.

Version 4.71


LVM_SORTITEMS

LVM_SORTITEMS
    wParam = (WPARAM) (LPARAM) lParamSort;
    lParam = (LPARAM) (PFNLVCOMPARE) pfnCompare;

Uses an application-defined comparison function to sort the items of a list view control. The index of each item changes to reflect the new sequence. You can send this message explicitly or by using the ListView_SortItems macro.

  • Returns TRUE if successful, or FALSE otherwise.
lParamSort
Application-defined value that is passed to the comparison function.
pfnCompare
Address of 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.

The comparison function has the following form:

int CALLBACK CompareFunc(LPARAM lParam1, LPARAM lParam2,
    LPARAM lParamSort);

The lParam1 parameter is the 32-bit value associated with the first item being compared, and the lParam2 parameter is the value associated with the second item. These are the values that were specified in the lParam member of the items' LVITEM structure when they were inserted into the list. The lParamSort parameter is the same value passed to the LVM_SORTITEMS message.

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.


LVM_SUBITEMHITTEST

LVM_SUBITEMHITTEST
    wParam = 0;
    lParam = (LPARAM)(LVHITTESTINFO FAR *)pInfo;

Determines which list view item or subitem is at a given position. You can send this message explicitly or by using the ListView_SubItemHitTest macro.

  • Returns the index of the item or subitem tested, if any, or -1 otherwise. If an item or subitem is at the given coordinates, the fields of the LVHITTESTINFO structure will be filled with the applicable hit information.
pInfo
Address of an LVHITTESTINFO structure. The POINT structure within LVHITTESTINFO should be set to the client coordinates to be hit-tested.

Version 4.70


LVM_UPDATE

LVM_UPDATE
    wParam = (WPARAM) iItem;
    lParam = 0;

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.

  • Returns TRUE if successful, or FALSE otherwise.
iItem
Index of the item to update.


List View Control Macros

This section contains information about the macros used with list view control messages.

ListView_ApproximateViewRect

ListView_Arrange

ListView_CreateDragImage

ListView_DeleteAllItems

ListView_DeleteColumn

ListView_DeleteItem

ListView_EditLabel

ListView_EnsureVisible

ListView_FindItem

ListView_GetBkColor

ListView_GetBkImage

ListView_GetCallbackMask

ListView_GetCheckState

ListView_GetColumn

ListView_GetColumnOrderArray

ListView_GetColumnWidth

ListView_GetCountPerPage

ListView_GetEditControl

ListView_GetExtendedListViewStyle

ListView_GetHeader

ListView_GetHotCursor

ListView_GetHotItem

ListView_GetHoverTime

ListView_GetImageList

ListView_GetISearchString

ListView_GetItem

ListView_GetItemCount

ListView_GetItemPosition

ListView_GetItemRect

ListView_GetItemSpacing

ListView_GetItemState

ListView_GetItemText

ListView_GetNextItem

ListView_GetNumberOfWorkAreas

ListView_GetOrigin

ListView_GetSelectedCount

ListView_GetSelectionMark

ListView_GetStringWidth

ListView_GetSubItemRect

ListView_GetTextBkColor

ListView_GetTextColor

ListView_GetToolTips

ListView_GetTopIndex

ListView_GetUnicodeFormat

ListView_GetViewRect

ListView_GetWorkAreas

ListView_HitTest

ListView_InsertColumn

ListView_InsertItem

ListView_RedrawItems

ListView_Scroll

ListView_SetBkColor

ListView_SetBkImage

ListView_SetCallbackMask

ListView_SetColumn

ListView_SetColumnOrderArray

ListView_SetColumnWidth

ListView_SetExtendedListViewStyle

ListView_SetExtendedListViewStyleEx

ListView_SetHotCursor

ListView_SetHotItem

ListView_SetHoverTime

ListView_SetIconSpacing

ListView_SetImageList

ListView_SetItem

ListView_SetItemCount

ListView_SetItemCountEx

ListView_SetItemPosition

ListView_SetItemPosition32

ListView_SetItemState

ListView_SetItemText

ListView_SetSelectionMark

ListView_SetTextBkColor

ListView_SetTextColor

ListView_SetToolTips

ListView_SetUnicodeFormat

ListView_SetWorkAreas

ListView_SortItems

ListView_SubItemHitTest

ListView_Update


ListView_ApproximateViewRect

DWORD ListView_ApproximateViewRect(
    hwndLV,
    cx,
    cy,
    iCount
);

Calculates the approximate width and height required to display a given number of items. You can use this macro or send the LVM_APPROXIMATEVIEWRECT message explicitly.

  • Returns a DWORD value that holds the approximate width and height needed to display the items, in pixels.
hwndLV
Handle to the list view control.
cx and cy
The proposed dimensions of the control, in pixels. Either parameter can be -1 to allow the message to use the current width or height value.
iCount
Number of items to be displayed in the control. If this parameter is -1, the message uses the total number of items in the control.

Version 4.70


ListView_Arrange

BOOL ListView_Arrange(
    HWND hwnd,
    UINT code
);

Arranges items in icon view. You can use this macro or send the LVM_ARRANGE message explicitly.

  • Returns TRUE if successful, or FALSE otherwise.
hwnd
Handle to the list view control.
code
Alignment. This can be one of the following values:
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.


ListView_CreateDragImage

HIMAGELIST ListView_CreateDragImage(
    HWND hwnd,
    int iItem,
    LPPOINT lpptUpLeft
);

Creates a drag image list for the specified item. You can use this macro or send the LVM_CREATEDRAGIMAGE message explicitly.

  • Returns the handle to the drag image list if successful, or NULL otherwise.
hwnd
Handle to the list view control.
iItem
Index of the item.
lpptUpLeft
Address of a POINT structure that receives the initial location of the upper-left corner of the image, in view coordinates.


ListView_DeleteAllItems

BOOL ListView_DeleteAllItems(
    HWND hwnd
);

Removes all items from a list view control. You can use this macro or send the LVM_DELETEALLITEMS message explicitly.

  • Returns TRUE if successful, or FALSE otherwise.
hwnd
Handle to the list view control.

When a list view control receives the LVM_DELETEALLITEMS message, it sends the LVN_DELETEALLITEMS notification message to its parent window.


ListView_DeleteColumn

BOOL ListView_DeleteColumn(
    HWND hwnd,
    int iCol
);

Removes a column from a list view control. You can use this macro or send the LVM_DELETECOLUMN message explicitly.

  • Returns TRUE if successful, or FALSE otherwise.
hwnd
Handle to the list view control.
iCol
Index of the column to delete.


ListView_DeleteItem

BOOL ListView_DeleteItem(
    HWND hwnd,
    int iItem
);

Removes an item from a list view control. You can use this macro or send the LVM_DELETEITEM message explicitly.

  • Returns TRUE if successful, or FALSE otherwise.
hwnd
Handle to the list view control.
iItem
Index of the list view item to delete.


ListView_EditLabel

HWND ListView_EditLabel(
    HWND hwnd,
    int iItem
);

Begins in-place editing of the specified list view item's text. The message implicitly selects and focuses the specified item. You can use this macro or send the LVM_EDITLABEL message explicitly.

  • Returns the handle to the edit control that is used to edit the item text if successful, or NULL otherwise.
hwnd
Handle to the list view control.
iItem
Index of the list view item. To cancel editing, set iItem to -1.

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


ListView_EnsureVisible

BOOL ListView_EnsureVisible(
    HWND hwnd,
    int i,
    BOOL fPartialOK
);

Ensures that a list view item is either entirely or partially visible, scrolling the list view control if necessary. You can use this macro or send the LVM_ENSUREVISIBLE message explicitly.

  • Returns TRUE if successful, or FALSE otherwise.
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.


ListView_FindItem

int ListView_FindItem(
    HWND hwnd,
    int iStart,
    const LPLVFINDINFO plvfi
);

Searches for a list view item with the specified characteristics. You can use this macro or send the LVM_FINDITEM message explicitly.

  • Returns the index of the item if successful, or -1 otherwise.
hwnd
Handle to the list view control.
iStart
Index of the item after which to begin the search, or -1 to start from the beginning.
plvfi
Address of an LVFINDINFO structure that contains information about what to search for.


ListView_GetBkColor

COLORREF ListView_GetBkColor(
    HWND hwnd
);

Retrieves the background color of a list view control. You can use this macro or send the LVM_GETBKCOLOR message explicitly.

  • Returns the background color of the list view control.
hwnd
Handle to the list view control.


ListView_GetBkImage

BOOL ListView_GetBkImage(
    HWND hwndLV,
    LPLVBKIMAGE plvbki
);

Retrieves the background image in a list view control. You can use this macro or send the LVM_GETBKIMAGE message explicitly.

  • Returns nonzero if successful, or zero otherwise.
hwndLV
Handle to the list view control.
plvbki
Address of a LVBKIMAGE structure that will receive the background image information.

Version 4.71

See also ListView_SetBkImage


ListView_GetCallbackMask

UINT ListView_GetCallbackMask(
    HWND hwnd
);

Retrieves the callback mask for a list view control. You can use this macro or send the LVM_GETCALLBACKMASK message explicitly.

  • Returns the callback mask.
hwnd
Handle to the list view control.

See also LVM_SETCALLBACKMASK


ListView_GetCheckState

BOOL ListView_GetCheckState(
    HWND hwndLV,
    UINT iIndex
);

Determines if an item in a list view control is selected. This should be used only for list view controls that have the LVS_EX_CHECKBOXES style.

  • Returns nonzero if the given item is selected, or zero otherwise. If this macro is applied to a list view control that does not have check boxes enabled, the return value is not reliable.
hwndLV
Handle to a list view control.
iIndex
Index of the item for which to retrieve the check state.

Version 4.70


ListView_GetColumn

BOOL ListView_GetColumn(
    HWND hwnd,
    int iCol,
    LPLVCOLUMN pcol
);

Retrieves the attributes of a list view control's column. You can use this macro or send the LVM_GETCOLUMN message explicitly.

  • Returns TRUE if successful, or FALSE otherwise.
hwnd
Handle to the list view control.
iCol
Index of the column.
pcol
Address of an LVCOLUMN 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 address of the buffer that receives the item text, and the cchTextMax member must specify the size of the buffer.


ListView_GetColumnOrderArray

BOOL ListView_GetColumnOrderArray(
    HWND hwndLV,
    int iCount,
    int *lpiArray
);

Retrieves the current left-to-right order of columns in a list view control. You can use this macro or send the LVM_GETCOLUMNORDERARRAY message explicitly.

  • If successful, returns nonzero and the buffer at lpiArray receives the column index of each column in the control in the order they appear from left to right. Otherwise, the return value is zero.
hwndLV
Handle to a list view control.
iCount
Number of columns in the list view control.
lpiArray
Address of an array of integers that will receive the index values of the columns in the list view control. The array must be large enough to hold iCount elements.

Version 4.70


ListView_GetColumnWidth

int ListView_GetColumnWidth(
    HWND hwnd,
    int iCol
);

Retrieves the width of a column in report or list view. You can use this macro or send the LVM_GETCOLUMNWIDTH message explicitly.

  • Returns the column width if successful, or zero otherwise. If this macro is used on a list view control with the LVS_REPORT style and the specified column doesn't exist, the return value is undefined.
hwnd
Handle to the list view control.
iCol
Index of the column. This parameter is ignored in list view.


ListView_GetCountPerPage

int ListView_GetCountPerPage(
    HWND hwnd
);

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 use this macro or send the LVM_GETCOUNTPERPAGE message explicitly.

  • 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.
hwnd
Handle to the list view control.


ListView_GetEditControl

HWND ListView_GetEditControl(
    HWND hwnd
);

Retrieves the handle to the edit control being used to edit a list view item's text. You can use this macro or send the LVM_GETEDITCONTROL message explicitly.

  • Returns the handle to the edit control if successful, or NULL otherwise.
hwnd
Handle to the list view control.

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.


ListView_GetExtendedListViewStyle

DWORD ListView_GetExtendedListViewStyle(
    HWND hwndLV
);

Retrieves the extended styles that are currently in use for a given list view control. You can use this macro or send the LVM_GETEXTENDEDLISTVIEWSTYLE message explicitly.

  • Returns a DWORD value that represents the styles currently in use for a given list view control. This can be a combination of extended styles.
hwndLV
Handle to a list view control.

Version 4.70


ListView_GetHeader

HWND ListView_GetHeader(
    HWND hwndLV
);

Retrieves the handle to the header control used by a list view control. You can use this macro or send the LVM_GETHEADER message explicitly.

  • Returns the handle to the header control.
hwndLV
Handle to a list view control.

Version 4.70


ListView_GetHotCursor

HCURSOR ListView_GetHotCursor(
    HWND hwndLV
);

Retrieves the HCURSOR used when the pointer is over an item while hot tracking is enabled. You can use this macro or send the LVM_GETHOTCURSOR message explicitly.

  • Returns an HCURSOR value that is the handle to the cursor that the list view control uses when hot tracking is enabled.
hwndLV
Handle to a list view control.

A list view control uses hot tracking and hover selection when the LVS_EX_TRACKSELECT style is set.

Version 4.70


ListView_GetHotItem

INT ListView_GetHotItem(
    HWND hwndLV
);

Retrieves the index of the hot item. You can use this macro or send the LVM_GETHOTITEM message explicitly.

  • Returns the index of the item that is currently hot.
hwndLV
Handle to a list view control.

Version 4.70


ListView_GetHoverTime

DWORD ListView_GetHoverTime(
   HWND hwndLV
);

Retrieves the amount of time that the mouse cursor must hover over an item before it is selected. You can use this macro or send the LVM_GETHOVERTIME message explicitly.

  • Returns the amount of time, in milliseconds, that the mouse cursor must hover over an item before it is selected. If the return value is (DWORD)-1, then the hover time is the default hover time.
hwndLV
Handle to a list view control.

The hover time only affects list view controls that have the LVS_EX_TRACKSELECT, LVS_EX_ONECLICKACTIVATE, or LVS_EX_TWOCLICKACTIVATE extended list view style.

Version 4.71


ListView_GetImageList

HIMAGELIST ListView_GetImageList(
    HWND hwnd,
    int iImageList
);

Retrieves the handle to an image list used for drawing list view items. You can use this macro or send the LVM_GETIMAGELIST message explicitly.

  • Returns the handle to the specified image list if successful, or NULL otherwise.
hwnd
Handle to the list view control.
iImageList
Image list to retrieve. This parameter can be one of the following values:
LVSIL_NORMAL | Image list with large icons.
LVSIL_SMALL | Image list with small icons.
LVSIL_STATE | Image list with state images.


ListView_GetISearchString

BOOL ListView_GetISearchString(
    HWND hwnd,
    LPSTR lpsz
);

Retrieves the incremental search string of a list view control. You can use this macro or send the LVM_GETISEARCHSTRING message explicitly.

  • Returns the number of characters in the incremental search string, or zero if the list view control is not in incremental search mode.
hwnd
Handle to the list view control.
lpsz
Address of a buffer that receives the incremental search string.

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 time-out period is associated with each character that the user types. If the time-out period elapses before the user types another character, the incremental search string is reset.


ListView_GetItem

BOOL ListView_GetItem(
    HWND hwnd,
    LPLVITEM pitem
);

Retrieves some or all of a list view item's attributes. You can use this macro or send the LVM_GETITEM message explicitly.

  • Returns TRUE if successful, or FALSE otherwise.
hwnd
Handle to the list view control.
pitem
Address of an LVITEM structure that specifies the information to retrieve and receives information about the list view item.

When the LVM_GETITEM 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 LVITEM structure.

If the mask member specifies the LVIF_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.

If the mask member specifies the LVIF_STATE value, the stateMask member must specify the item state bits to retrieve. On output, the state member contains the values of the specified state bits.


ListView_GetItemCount

int ListView_GetItemCount(
    HWND hwnd
);

Retrieves the number of items in a list view control. You can use this macro or send the LVM_GETITEMCOUNT message explicitly.

  • Returns the number of items.
hwnd
Handle to the list view control.


ListView_GetItemPosition

BOOL ListView_GetItemPosition(
    HWND hwnd,
    int i,
    POINT FAR *ppt
);

Retrieves the position of a list view item. You can use this macro or explicitly send the LVM_GETITEMPOSITION message.

  • Returns TRUE if successful, or FALSE otherwise.
hwnd
Handle to the list view control.
i
Index of the list view item.
ppt
Address of a POINT structure that receives the position of the item's upper-left corner, in view coordinates.


ListView_GetItemRect

BOOL ListView_GetItemRect(
    HWND hwnd,
    int i,
    RECT FAR *prc,
    int code
);

Retrieves the bounding rectangle for all or part of an item in the current view. You can use this macro or send the LVM_GETITEMRECT message explicitly.

  • Returns TRUE if successful, or FALSE otherwise.
hwnd
Handle to the list view control.
i
Index of the list view item.
prc
Address of a RECT structure that receives the bounding rectangle. When the LVM_GETITEMRECT 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:
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.


ListView_GetItemSpacing

DWORD ListView_GetItemSpacing(
    HWND hwnd,
    BOOL fSmall
);

Determines the spacing between items in a list view control. You can use this macro or send the LVM_GETITEMSPACING message explicitly.

  • Returns the amount of spacing between items.
hwnd
Handle to the list view control.
fSmall
View for which to retrieve the item spacing. This parameter is TRUE for small icon view, or FALSE for icon view.


ListView_GetItemState

UINT WINAPI ListView_GetItemState(
    HWND hwnd,
    int i,
    UINT mask
);

Retrieves the state of a list view item. You can use this macro or send the LVM_GETITEMSTATE message explicitly.

  • Returns the current state for the specified item. The only valid bits in the return value are those that correspond to the bits set in the mask parameter.
hwnd
Handle to the list view control.
i
Index of the list view item.
mask
State information to retrieve. This parameter can be a combination 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 also on the system colors used for selection.
LVIS_OVERLAYMASK | Use this mask to retrieve the item's overlay image index.
LVIS_STATEIMAGEMASK | Use this mask to retrieve the item's state image index.

An item's state information includes a set of bit flags as well as image list indexes that indicate the item's state image and overlay image.

See also ListView_SetItemState


ListView_GetItemText

void WINAPI ListView_GetItemText(
    HWND hwnd,
    int iItem,
    int iSubItem,
    LPSTR pszText,
    int cchTextMax
);

Retrieves the text of a list view item or subitem. You can use this macro or send the LVM_GETITEMTEXT message explicitly.

  • The ListView_GetItemText macro does not return a value. If you send the LVM_GETITEMTEXT message explicitly, it returns the length of the retrieved string.
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
Address of the buffer that receives the item or subitem text.
cchTextMax
Size of the buffer, in bytes.

See also LVITEM


ListView_GetNextItem

int ListView_GetNextItem(
    HWND hwnd,
    int iStart,
    UINT flags
);

Searches for a list view item that has the specified properties and bears the specified relationship to a specified item. You can use this macro or send the LVM_GETNEXTITEM message explicitly.

  • Returns the index of the next item if successful, or -1 otherwise.
hwnd
Handle to the list view control.
iStart
Index of the item with which to begin the search, 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. For a list of possible values, see the description of the flags parameter in the LVM_GETNEXTITEM message. If an item does not have all of the specified state flags set, the search continues with the next item.


ListView_GetNumberOfWorkAreas

BOOL ListView_GetNumberOfWorkAreas(
    HWND hwndLV,
    LPUINT lpuWorkAreas
);

Retrieves the number of working areas in a list view control. You can use this macro or send the LVM_GETNUMBEROFWORKAREAS message explicitly.

  • The return value for this macro is not used.
hwndLV
Handle to the list view control.
lpuWorkAreas
Address of a UINT value that receives the number of working areas in the list view control. If zero is placed in this variable, then no working areas are currently set. This value cannot be NULL.

Version 4.71


ListView_GetOrigin

BOOL ListView_GetOrigin(
    HWND hwnd,
    LPPOINT lpptOrg
);

Retrieves the current view origin for a list view control. You can use this macro or send the LVM_GETORIGIN message explicitly.

  • Returns TRUE if successful, or FALSE if the current view is list or report view.
hwnd
Handle to the list view control.
lpptOrg
Address of a POINT structure that receives the view origin.


ListView_GetSelectedCount

UINT ListView_GetSelectedCount(
    HWND hwnd
);

Determines the number of selected items in a list view control. You can use this macro or send the LVM_GETSELECTEDCOUNT message explicitly.

  • Returns the number of selected items.
hwnd
Handle to the list view control.


ListView_GetSelectionMark

INT ListView_GetSelectionMark(
    HWND hwndLV
);

Retrieves the selection mark from a list view control. You can use this macro or explicitly send the LVM_GETSELECTIONMARK message.

  • Returns the zero-based selection mark, or -1 if there is no selection mark.
hwndLV
Handle to a list view control.

The selection mark is the item index from which a multiple selection starts.

Version 4.71

See also ListView_SetSelectionMark


ListView_GetStringWidth

int ListView_GetStringWidth(
    HWND hwnd,
    LPCSTR psz
);

Determines the width of a specified string using the specified list view control's current font. You can use this macro or send the LVM_GETSTRINGWIDTH message explicitly.

  • Returns the string width if successful, or zero otherwise.
hwnd
Handle to the list view control.
psz
Address of a null-terminated string.

The ListView_GetStringWidth macro returns the exact width, in pixels, of the specified string. If you use the returned string width as the column width in a call to the ListView_SetColumnWidth macro, the string will be truncated. To get the column width that can contain the string without truncating it, you must add padding to the returned string width.


ListView_GetSubItemRect

BOOL ListView_GetSubItemRect(
    HWND hwndLV,
    int iItem,
    int iSubItem,
    int code,
    LPRECT lpRect
);

Retrieves information about the rectangle that surrounds a subitem in a list view control. You can use this macro (recommended) or send the LVM_GETSUBITEMRECT message explicitly. This macro is intended to be used only on list view controls that use the LVS_REPORT style.

  • Returns nonzero if successful, or zero otherwise.
hwndLV
Handle to a list view control.
iItem
Index of the subitem's parent item.
iSubItem
The one-based index of the subitem.
code
Portion of the list view subitem for which to retrieve the bounding rectangle information. This value can be one of the following:
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 entire item, including the icon and label. This is identical to LVIR_BOUNDS.
lpRect
Address of a RECT structure that receives the subitem bounding rectangle information.

Version 4.70


ListView_GetTextBkColor

COLORREF ListView_GetTextBkColor(
    HWND hwnd
);

Retrieves the text background color of a list view control. You can use this macro or send the LVM_GETTEXTBKCOLOR message explicitly.

  • Returns the background color of the text.
hwnd
Handle to the list view control.


ListView_GetTextColor

COLORREF ListView_GetTextColor(
    HWND hwnd
);

Retrieves the text color of a list view control. You can use this macro or send the LVM_GETTEXTCOLOR message explicitly.

  • Returns the text color.
hwnd
Handle to the list view control.


ListView_GetToolTips

HWND ListView_GetToolTips(
    HWND hwnd
);

Retrieves the tooltip control that the list view control uses to display tooltips. You can use this macro or send the LVM_GETTOOLTIPS message explicitly.

  • Returns the handle to the tooltip control.
hwnd
Handle to the list view control.

See also ListView_SetToolTips


ListView_GetTopIndex

int ListView_GetTopIndex(
    HWND hwnd
);

Retrieves the index of the topmost visible item when in list or report view. You can use this macro or send the LVM_GETTOPINDEX message explicitly.

  • Returns the index of the item if successful, or zero if the list view control is in icon or small icon view.
hwnd
Handle to the list view control.


ListView_GetUnicodeFormat

BOOL ListView_GetUnicodeFormat(
    HWND hwnd
);

Retrieves the UNICODE character format flag for the control. You can use this macro or send the LVM_GETUNICODEFORMAT message explicitly.

  • Returns the UNICODE format flag for the control. If this value is nonzero, the control is using UNICODE characters. If this value is zero, the control is using ANSI characters.
hwnd
Handle to the control.

See also ListView_SetUnicodeFormat


ListView_GetViewRect

BOOL ListView_GetViewRect(
    HWND hwnd,
    RECT FAR *prc
);

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 use this macro or send the LVM_GETVIEWRECT message explicitly.

  • Returns TRUE if successful, or FALSE otherwise.
hwnd
Handle to the list view control.
prc
Address of a RECT structure that receives the bounding rectangle. All coordinates are relative to the visible area of the list view control.


ListView_GetWorkAreas

void ListView_GetWorkAreas(
    HWND hwndLV,
    INT nWorkAreas,
    LPRECT lprc
);

Retrieves the working areas from a list view control. You can use this macro, or send the LVM_GETWORKAREAS message explicitly.

hwndLV
Handle to the list view control.
nWorkAreas
The number of RECT structures in the array at lprc.
lprc
Address of an array of RECT structures that receive the working areas of the list view control. Values in these structures are in client coordinates. nWorkAreas specifies the number of structures in this array.

Version 4.71


ListView_HitTest

int ListView_HitTest(
    HWND hwnd,
    LPLVHITTESTINFO pinfo
);

Determines which list view item, if any, is at a specified position. You can use this macro or send the LVM_HITTEST message explicitly.

  • Returns the index of the item at the specified position, if any, or -1 otherwise.
hwnd
Handle to the list view control.
pinfo
Address of an LVHITTESTINFO structure that contains the position to hit test and receives information about the results of the hit test.


ListView_InsertColumn

int ListView_InsertColumn(
    HWND hwnd,
    int iCol,
    const LPLVCOLUMN pcol
);

Inserts a new column in a list view control. You can use this macro or send the LVM_INSERTCOLUMN message explicitly.

  • Returns the index of the new column if successful, or -1 otherwise.
hwnd
Handle to the list view control.
iCol
Index of the new column.
pcol
Address of an LVCOLUMN structure that contains the attributes of the new column.


ListView_InsertItem

int ListView_InsertItem(
    HWND hwnd,
    const LPLVITEM pitem
);

Inserts a new item in a list view control. You can use this macro or send the LVM_INSERTITEM message explicitly.

  • Returns the index of the new item if successful, or -1 otherwise.
hwnd
Handle to the list view control.
pitem
Address of an LVITEM structure that specifies the attributes of the list view item. The iItem member specifies the index of the new item.
You cannot use ListView_InsertItem or LVM_INSERTITEM to insert subitems; the iSubItem member of the LVITEM structure must be zero.

If a list view control has either the LVS_SORTASCENDING or LVS_SORTDESCENDING window style, an LVM_INSERTITEM message will fail if you try to insert an item that has LPSTR_TEXTCALLBACK as the pszText member of its LVITEM structure.


ListView_RedrawItems

BOOL ListView_RedrawItems(
    HWND hwnd,
    int iFirst,
    int iLast
);

Forces a list view control to redraw a range of items. You can use this macro or send the LVM_REDRAWITEMS message explicitly.

  • Returns TRUE if successful, or FALSE otherwise.
hwnd
Handle to the list view control.
iFirst
Index of the first item to redraw.
iLast
Index of the last item to redraw.

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.


ListView_Scroll

BOOL ListView_Scroll(
    HWND hwnd,
    int dx,
    int dy
);

Scrolls the content of a list view control. You can use this macro or send the LVM_SCROLL message explicitly.

  • Returns TRUE if successful, or FALSE otherwise.
hwnd
Handle to the list view control.
dx
Integer value that specifies the amount of horizontal scrolling in pixels. If the list view control is in list view, this value specifies the number of columns to scroll.
dy
Integer value that specifies the amount of vertical scrolling in pixels.

When the list view control is in report view, the control can only be scrolled vertically in whole line increments. Therefore, the dy parameter will be rounded to the nearest number of pixels that form a whole line increment. For example, if the height of a line is 16 pixels and 8 is passed for dy, the list will be scrolled by 16 pixels (1 line). If 7 is passed for dy, the list will be scrolled 0 pixels (0 lines).


ListView_SetBkColor

BOOL ListView_SetBkColor(
    HWND hwnd,
    COLORREF clrBk
);

Sets the background color of a list view control. You can use this macro or send the LVM_SETBKCOLOR message explicitly.

  • Returns TRUE if successful, or FALSE otherwise.
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.


ListView_SetBkImage

BOOL ListView_SetBkImage(
    HWND hwndLV,
    LPLVBKIMAGE plvbki;
);

Sets the background image in a list view control. You can use this macro or send the LVM_SETBKIMAGE message explicitly.

  • Returns nonzero if successful, or zero otherwise.
hwndLV
Handle to the list view control.
plvbki
Address of an LVBKIMAGE structure that contains the new background image information.

Because the list view control uses OLE COM to manipulate the background images, the calling application must call CoInitialize or OleInitialize before using this macro. It is best to call one of these functions when the application is initialized, and call either CoUnitialize or OleUnitialize when the application is terminating.

Version 4.71

See also ListView_GetBkImage


ListView_SetCallbackMask

BOOL ListView_SetCallbackMask(
    WND hwnd,
    UINT mask
);

Changes the callback mask for a list view control. You can use this macro or send the LVM_SETCALLBACKMASK message explicitly.

  • Returns TRUE if successful, or FALSE otherwise.
hwnd
Handle to the list view control.
mask
Value of the callback mask. The bits of the mask indicate the item states or images for which the application stores the current state data. This value can be any combination of the following constants:
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.
LVIS_SELECTED | The item is selected.
LVIS_OVERLAYMASK | The application stores the image list index of the current overlay image for each item.
LVIS_STATEIMAGEMASK | The application stores the image list index of the current state image for each item.

The callback mask of a list view control is a set of bit flags that specify the item states for which the application, rather than the control, stores the current data. The callback mask applies to all of the control's items, unlike the callback item designation, which applies to a specific item. The callback mask is zero by default, meaning that the list view control stores all item state information. After creating a list view control and initializing its items, you can use the ListView_SetCallbackMask macro or LVM_SETCALLBACKMASK message to change the callback mask. To get the current callback mask, send the LVM_GETCALLBACKMASK message.

For more information about overlay images and state images, see List View Image Lists.

For more information on list view callbacks, see Callback Items and the Callback Mask

See also LVN_GETDISPINFO


ListView_SetColumn

BOOL ListView_SetColumn(
    HWND hwnd,
    int iCol,
    LPLVCOLUMN pcol
);

Sets the attributes of a list view column. You can use this macro or send the LVM_SETCOLUMN message explicitly.

  • Returns TRUE if successful, or FALSE otherwise.
hwnd
Handle to the list view control.
iCol
Index of the column.
pcol
Address of an LVCOLUMN 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 address of a null-terminated string and the cchTextMax member is ignored.


ListView_SetColumnOrderArray

BOOL ListView_SetColumnOrderArray(
    HWND hwndLV,
    int iCount,
    int *lpiArray
);

Sets the left-to-right order of columns in a list view control. You can use this macro or send the LVM_SETCOLUMNORDERARRAY message explicitly.

hwndLV
Handle to a list view control.
iCount
Number of columns in the list view control.
lpiArray
Address of an array specifying the order in which columns should be displayed, from left to right. For example, if the contents of the array are {2,0,1}, the control displays column 2, column 0, and column 1, from left to right.

Version 4.70


ListView_SetColumnWidth

BOOL ListView_SetColumnWidth(
    HWND hwnd,
    int iCol,
    int cx
);

Changes the width of a column in report or list view. You can use this macro or send the LVM_SETCOLUMNWIDTH message explicitly.

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:
LVSCW_AUTOSIZE | Automatically sizes the column.
LVSCW_AUTOSIZE_USEHEADER | Automatically sizes the column to fit the header text.

Note that ListView_SetColumnWidth converts the cx parameter to a 16-bit value.


ListView_SetExtendedListViewStyle

void ListView_SetExtendedListViewStyle(
    HWND hwndLV,
    DWORD dwExStyle
);

Sets extended styles for list view controls. You can use this macro or send the LVM_SETEXTENDEDLISTVIEWSTYLE message explicitly.

hwndLV
Handle to the list view control that will receive the style change.
dwExStyle
Value specifying the extended list view control style. This parameter can be a combination of extended styles.

For backward compatibility reasons, the ListView_SetExtendedListViewStyle macro has not been updated to use dwExMask. To use the dwExMask value, use the ListView_SetExtendedListViewStyleEx macro.

Version 4.70


ListView_SetExtendedListViewStyleEx

void ListView_SetExtendedListViewStyleEx(
    HWND hwndLV,
    DWORD dwExMask,
    DWORD dwExStyle
);

Sets extended styles for list view controls using the style mask. You can use this macro or send the LVM_SETEXTENDEDLISTVIEWSTYLE message explicitly.

hwndLV
Handle to the list view control that will receive the style change.
dwExMask
DWORD value that indicates which styles in dwExStyle are to be affected. This parameter can be a combination of extended styles. Only the extended styles in dwExMask will be changed. All other styles will be maintained as they are. If this parameter is zero, then all of the styles in dwExStyle will be affected.
dwExStyle
Value specifying the extended list view control style. This parameter can be a combination of extended styles.

Version 4.71


ListView_SetHotCursor

HCURSOR ListView_SetHotCursor(
    HWND    hwndLV,
    HCURSOR hCursor
);

Sets the HCURSOR that the list view control uses when the pointer is over an item while hot tracking is enabled. You can use this macro or send the LVM_SETHOTCURSOR message explicitly.

  • Returns an HCURSOR value that is the cursor that was previously used when the pointer was over an item.
hwndLV
Handle to a list view control.
hCursor
Handle to the cursor to be set.

A list view control uses hot tracking and hover selection when the LVS_EX_TRACKSELECT style is set.

Version 4.70


ListView_SetHotItem

INT ListView_SetHotItem(
    HWND hwndLV,
    INT  iIndex
);

Sets the hot item in a list view control. You can use this macro or send the LVM_SETHOTITEM message explicitly.

  • Returns the index of the item that was previously hot.
hwndLV
Handle to a list view control.
iIndex
Zero-based index of the item to be set as the hot item.

Version 4.70


ListView_SetHoverTime

ListView_SetHoverTime(
    HWND hwndLV,
    DWORD dwHoverTime
);

Sets the amount of time that the mouse cursor must hover over an item before it is selected. You can use this macro or send the LVM_SETHOVERTIME message explicitly.

  • Returns the previous hover time.
hwndLV
Handle to a list view control.
dwHoverTime
The new amount of time, in milliseconds, that the mouse cursor must hover over an item before it is selected. If this value is (DWORD)-1, then the hover time is set to the default hover time.

The hover time only affects list view controls that have the LVS_EX_TRACKSELECT, LVS_EX_ONECLICKACTIVATE, or LVS_EX_TWOCLICKACTIVATE extended list view style.

Version 4.71


ListView_SetIconSpacing

DWORD ListView_SetIconSpacing(
    HWND hwndLV,
    int cx,
    int cy
);

Sets the spacing between icons in list view controls set to the LVS_ICON style. You can use this macro or send the LVM_SETICONSPACING message explicitly.

  • Returns a DWORD value that contains the previous cx in the low word and the previous cy in the high word.
hwndLV
Handle to a list view control.
cx
Distance, in pixels, to set between icons on the x-axis.
cy
Distance, in pixels, to set between icons on the y-axis.

The cx and cy parameters are relative to the upper-left corner of an icon bitmap. Therefore, to set spacing between icons that do not overlap, the cx or cy values must include the size of the icon, plus the amount of empty space desired between icons. Values that do not include the width of the icon will result in overlaps.

Version 4.70


ListView_SetImageList

HIMAGELIST ListView_SetImageList(
    HWND hwnd,
    HIMAGELIST himl,
    int iImageList
);

Assigns an image list to a list view control. You can use this macro or send the LVM_SETIMAGELIST message explicitly.

  • Returns the handle to the image list previously associated with the control if successful, or NULL otherwise.
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:
LVSIL_NORMAL | Image list with large icons.
LVSIL_SMALL | Image list with small icons.
LVSIL_STATE | Image list with state images.


ListView_SetItem

BOOL ListView_SetItem(
    HWND hwnd,
    const LPLVITEM pitem
);

Sets some or all of a list view item's attributes. You can also use ListView_SetItem to set the text of a subitem. You can use this macro or send the LVM_SETITEM message explicitly.

  • Returns TRUE if successful, or FALSE otherwise.
hwnd
Handle to the list view control.
pitem
Address of an LVITEM 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 address of 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.

To set the attributes of a list view item, set the iItem member of the LVITEM structure to the index of the item, and set the iSubItem member to zero. For an item, you can use the state, pszText, iImage, and lParam members of the LVITEM structure to modify these item parameters.

To set the text of a subitem, set the iItem and iSubItem members to indicate the specific subitem, and use the pszText member to specify the text. Alternatively, you can use the ListView_SetItemText macro to set the text of a subitem. You cannot set the state or lParam members for subitems because subitems do not have these attributes. In version 4.70 and later, you can set the iImage member for subitems. The subitem image will be displayed if the list view control has the LVS_EX_SUBITEMIMAGES extended style. Previous versions will ignore the subitem image.


ListView_SetItemCount

void ListView_SetItemCount(
    HWND hwndLV,
    int cItems
);

Causes the list view control to allocate memory for the specified number of items. You can use this macro or send the LVM_SETITEMCOUNT message explicitly.

hwndLV
Handle to a list view control.
cItems
Number of items for which the list view control should allocate memory.

If the list view control was created without the LVS_OWNERDATA style, this macro causes the control to allocate its internal data structures for the specified number of items. This prevents the control from having to allocate the data structures every time an item is added.

If the list view control was created with the LVS_OWNERDATA style (a virtual list view), the ListView_SetItemCountEx macro should be used.


ListView_SetItemCountEx

void ListView_SetItemCountEx(
    HWND hwndLV,
    int cItems,
    DWORD dwFlags
);

Sets the virtual number of items in a virtual list view control. You can use this macro or send the LVM_SETITEMCOUNT message explicitly.

hwndLV
Handle to a virtual list view control.
cItems
Number of items that the list view control will contain.
dwFlags
Values that specify the behavior of the list view control after resetting the item count. This value can be a combination of the following:
LVSICF_NOINVALIDATEALL | The list view control will not repaint unless affected items are currently in view.
LVSICF_NOSCROLL | The list view control will not change the scroll position when the item count changes.

This macro is intended only for list view controls that use the LVS_OWNERDATA and LVS_REPORT or LVS_LIST styles.

If the list view control was created with the LVS_OWNERDATA style, this macro sets the virtual number of items that the control contains.

If the list view control was created without the LVS_OWNERDATA style, the ListView_SetItemCount macro should be used.

Version 4.70


ListView_SetItemPosition

BOOL ListView_SetItemPosition(
    HWND hwnd,
    int i,
    int x,
    int y
);

Moves an item to a specified position in a list view control (in icon or small icon view). You can use this macro or send the LVM_SETITEMPOSITION message explicitly.

  • Returns TRUE if successful, or FALSE otherwise.
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.

If the list view control has the LVS_AUTOARRANGE style, the list view control is arranged after the position of the item is set.


ListView_SetItemPosition32

void ListView_SetItemPosition32(
    HWND hwnd,
    int iItem,
    int x,
    int y
);

Moves an item to a specified position in a list view control (in icon or small icon view). This macro differs from the ListView_SetItemPosition macro in that it uses 32-bit coordinates. You can use the ListView_SetItemPosition32 macro or send the LVM_SETITEMPOSITION32 message explicitly.

  • No return value.
hwnd
Handle to the list view control.
iItem
Index of the list view item for which to set the position.
x and y
New horizontal and vertical coordinates of the item.

See also POINT


ListView_SetItemState

BOOL WINAPI ListView_SetItemState(
    HWND hwnd,
    int i,
    UINT state,
    UINT mask
);

Changes the state of an item in a list view control. You can use this macro or send the LVM_SETITEMSTATE message explicitly.

  • No return value.
hwnd
Handle to the list view control.
i
Index of the list view item. If this parameter is -1, then the state change is applied to all items.
state
New state bits for the item. The mask parameter indicates the valid bits of the state parameter. The macro ignores bits in the state parameter if the corresponding bit is not set in the mask parameter.

The low-order byte contains a set of bit flags that indicate the item's state. This byte can be a combination 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 also on the system colors used for selection.

Bits 8 through 11 of the state parameter specify the one-based index of an overlay image in the control's image lists. Both the full-sized icon image list and the small icon image list can have overlay images. The overlay image is superimposed over the item's icon image. If these bits are zero, the item has no overlay image. To isolate these bits, use the LVIS_OVERLAYMASK mask. To specify an overlay index, use the INDEXTOOVERLAYMASK macro.

Bits 12 through 15 of the state parameter specify the one-based index of an image in the control's state image list. The state image is displayed next to an item's icon to indicate an application-defined state. If these bits are zero, the item has no state image. To isolate these bits, use the LVIS_STATEIMAGEMASK mask. To specify a state image index, use the INDEXTOSTATEIMAGEMASK macro.

mask
Bits of the state parameter that you want to set or clear. You can use ListView_SetItemState both to set and to clear bits. To set an item's overlay image index, set the LVIS_OVERLAYMASK bits. To set an item's state image index, set the LVIS_STATEIMAGEMASK bits.

An item's state value includes a set of bit flags that indicate the item's state. The state value can also include image list indexes that indicate the item's state image and overlay image.

The mask parameter specifies the state bits you want to modify, and the state parameter specifies the new value for those bits. To set a bit in the item's internal state, set it in both the mask and state parameters. To clear a bit in the item's internal state, set it in the mask parameter and clear it in the state parameter. To leave a bit unchanged in the item's internal state, clear it in the mask parameter.

See also ListView_GetItemState


ListView_SetItemText

VOID WINAPI ListView_SetItemText(
    HWND hwnd,
    int i,
    int iSubItem,
    LPCSTR pszText
);

Changes the text of a list view item or subitem. You can use this macro or send the LVM_SETITEMTEXT message explicitly.

  • No return value.
hwnd
Handle to the list view control.
i
Index of the list view item.
iSubItem
Index of the subitem. To set the item label, set iSubItem to zero.
pszText
Address of a null-terminated string that contains the new text.
This parameter can be LPSTR_TEXTCALLBACK to indicate a callback item for which the parent window stores the text. In this case, the list view control sends the parent an LVN_GETDISPINFO notification message when it needs the text.
This parameter can be NULL.


ListView_SetSelectionMark

INT ListView_SetSelectionMark(
    HWND hwndLV,
    INT  iIndex
);

Sets the selection mark in a list view control. You can use this macro or send the LVM_SETSELECTIONMARK message explicitly.

  • Returns the previous selection mark, or -1 if there is no previous selection mark.
hwndLV
Handle to a list view control.
iIndex
Zero-based index of the list view item to be selected.

The selection mark is the item index from which a multiple selection starts. This macro does not affect the selection state of the item.

Version 4.71

See also ListView_GetSelectionMark


ListView_SetTextBkColor

BOOL ListView_SetTextBkColor(
    HWND hwnd,
    COLORREF clrText
);

Sets the background color of text in a list view control. You can use this macro or send the LVM_SETTEXTBKCOLOR message explicitly.

  • Returns TRUE if successful, or FALSE otherwise.
hwnd
Handle to the list view control.
clrText
New text color.


ListView_SetTextColor

BOOL ListView_SetTextColor(
    HWND hwnd,
    COLORREF clrText
);

Sets the text color of a list view control. You can use this macro or send the LVM_SETTEXTCOLOR message explicitly.

  • Returns TRUE if successful, or FALSE otherwise.
hwnd
Handle to the list view control.
clrText
New text color.


ListView_SetToolTips

HWND ListView_SetToolTips(
    HWND hwnd,
    HWND hwndToolTip
);

Sets the tooltip control that the list view control will use to display tooltips. You can use this macro or send the LVM_SETTOOLTIPS message explicitly.

  • Returns the handle to the previous tooltip control.
hwnd
Handle to the list view control.
hwndToolTip
Handle to the tooltip control to be set.

See also ListView_GetToolTips


ListView_SetUnicodeFormat

BOOL ListView_SetUnicodeFormat(
    HWND hwnd,
    BOOL fUnicode
);

Sets the UNICODE character format flag for the control. This message allows you to change the character set used by the control at run time rather than having to re-create the control. You can use this macro or send the LVM_SETUNICODEFORMAT message explicitly.

  • Returns the previous UNICODE format flag for the control.
hwnd
Handle to the control.
fUnicode
Determines the character set that is used by the control. If this value is nonzero, the control will use UNICODE characters. If this value is zero, the control will use ANSI characters.

See also ListView_GetUnicodeFormat


ListView_SetWorkAreas

void ListView_SetWorkAreas(
    HWND hwndLV,
    INT nWorkAreas,
    LPRECT lprc
);

Sets the working area within a list view control. You can use this macro or send the LVM_SETWORKAREAS message explicitly.

hwndLV
Handle to a list view control.
nWorkAreas
Number of RECT structures in the array at lprc. The maximum number of working areas allowed is defined by the LV_MAX_WORKAREAS value.
lprc
Address of an array of RECT structures that contain the new working areas of the list view control. Values in these structures are in client coordinates. If this parameter is NULL, the working area will be set to the client area of the control. nWorkAreas specifies the number of structures in this array.

Version 4.71


ListView_SortItems

BOOL ListView_SortItems(
    HWND hwnd,
    PFNLVCOMPARE pfnCompare,
    LPARAM lParamSort
);

Uses an application-defined comparison function to sort the items of a list view control. The index of each item changes to reflect the new sequence. You can use this macro or send the LVM_SORTITEMS message explicitly.

  • Returns TRUE if successful, or FALSE otherwise.
hwnd
Handle to the list view control.
pfnCompare
Address of 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.
lParamSort
Application-defined value that is passed to the comparison function.

The comparison function has the following form:

int CALLBACK CompareFunc(LPARAM lParam1, LPARAM lParam2,
    LPARAM lParamSort);

The lParam1 parameter is the 32-bit value associated with the first item being compared; and the lParam2 parameter is the value associated with the second item. These are the values that were specified in the lParam member of the items' LVITEM structure when they were inserted into the list. The lParamSort parameter is the same value passed to the LVM_SORTITEMS message.

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.


ListView_SubItemHitTest

INT ListView_SubItemHitTest(
    HWND hwndLV,
    LPLVHITTESTINFO pInfo
);

Determines which list view item or subitem is located at a given position. You can use this macro or send the LVM_SUBITEMHITTEST message explicitly.

  • Returns the index of the item or subitem tested, if any, or -1 otherwise. If an item or subitem is at the given coordinates, the fields of the LVHITTESTINFO structure will be filled with the applicable hit information.
hwndLV
Handle to the list view control that will be hit-tested.
pInfo
Address of an LVHITTESTINFO structure. The POINT structure within LVHITTESTINFO must be set to the client coordinates to be hit-tested.

Version 4.70


ListView_Update

BOOL ListView_Update(
    HWND hwnd,
    int iItem
);

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 use this macro or send the LVM_UPDATE message explicitly.

  • Returns TRUE if successful, or FALSE otherwise.
hwnd
Handle to the list view control.
iItem
Index of the item to update.


List View Control Notification Messages

This section contains information about the notification messages sent by list view controls.

LVN_BEGINDRAG

LVN_BEGINLABELEDIT

LVN_BEGINRDRAG

LVN_COLUMNCLICK

LVN_DELETEALLITEMS

LVN_DELETEITEM

LVN_ENDLABELEDIT

LVN_GETDISPINFO

LVN_GETINFOTIP

LVN_INSERTITEM

LVN_HOTTRACK

LVN_ITEMACTIVATE

LVN_ITEMCHANGED

LVN_ITEMCHANGING

LVN_KEYDOWN

LVN_MARQUEEBEGIN

LVN_ODCACHEHINT

LVN_ODFINDITEM

LVN_ODSTATECHANGED

LVN_SETDISPINFO

NM_CLICK (list view)

NM_CUSTOMDRAW (list view)

NM_DBLCLK (list view)

NM_HOVER (list view)

NM_KILLFOCUS (list view)

NM_RCLICK (list view)

NM_RDBLCLK (list view)

NM_RELEASEDCAPTURE (list view)

NM_RETURN (list view)

NM_SETFOCUS (list view)


LVN_BEGINDRAG

LVN_BEGINDRAG
    pnmv = (LPNMLISTVIEW) lParam;

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.

  • No return value.
pnmv
Address of an NMLISTVIEW structure. The iItem member identifies the item being dragged, and the other members are zero.


LVN_BEGINLABELEDIT

LVN_BEGINLABELEDIT
    pdi = (LPNMLVDISPINFO) lParam;

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.

  • To allow the user to edit the label, return FALSE.

    To prevent the user from editing the label, return TRUE.

pdi
Address of an NMLVDISPINFO structure. The item member of this structure is an LVITEM structure whose iItem member identifies the item being edited.

When the user begins editing an item label, the parent window of the list view control receives an LVN_BEGINLABELEDIT notification message. When the user cancels or completes the editing, the parent window receives an LVN_ENDLABELEDIT notification message.


LVN_BEGINRDRAG

LVN_BEGINRDRAG
    pnmv = (LPNMLISTVIEW) lParam;

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.

  • No return value.
pnmv
Address of an NMLISTVIEW structure. The iItem member identifies the item being dragged, and the other members are zero.


LVN_COLUMNCLICK

LVN_COLUMNCLICK
    pnmv = (LPNMLISTVIEW) lParam;

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.

  • No return value.
pnmv
Address of an NMLISTVIEW structure. The iItem member is -1, and the iSubItem member identifies the column. All other members are zero.


LVN_DELETEALLITEMS

LVN_DELETEALLITEMS
    pnmv = (LPNMLISTVIEW) lParam;

Notifies a list view control's parent window that all items in the control are about to be deleted. This notification message is sent in the form of a WM_NOTIFY message.

  • To suppress subsequent LVN_DELETEITEM notification messages, return TRUE.

    To receive subsequent LVN_DELETEITEM notification messages, return FALSE.

pnmv
Address of an NMLISTVIEW structure. The iItem member is -1, and the other members are zero.

A list view control sends the LVN_DELETEALLITEMS notification message when it is destroyed or when it receives the LVM_DELETEALLITEMS message. If LVN_DELETEALLITEMS does not return TRUE, the control will also send an LVN_DELETEITEM notification message as each item is deleted.

If the LVN_DELETEALLITEMS message handler is in a dialog procedure, return TRUE from the dialog procedure, and use the SetWindowLong function with DWL_MSGRESULT to set the message return value.


LVN_DELETEITEM

LVN_DELETEITEM
    pnmv = (LPNMLISTVIEW) lParam;

Notifies a list view control's parent window that an item is about to be deleted. This notification message is sent in the form of a WM_NOTIFY message.

  • No return value.
pnmv
Address of an NMLISTVIEW structure. The iItem member identifies the item being deleted. All other members of this structure are zero.


LVN_ENDLABELEDIT

LVN_ENDLABELEDIT
    pdi = (LPNMLVDISPINFO) lParam;

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.

  • If the pszText member of the LVITEM structure is non-NULL, return TRUE to set the item's label to the edited text. Return FALSE to reject the edited text and revert to the original label.

    If the pszText member of the LVITEM structure is NULL, the return value is ignored.

pdi
Address of an NMLVDISPINFO structure. The item member of this structure is an LVITEM structure whose iItem member identifies the item being edited. The pszText member of item 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 LVITEM structure.

If the user cancels editing, the pszText member of the LVITEM structure is NULL; otherwise, pszText is the address of the edited text.

When the user begins editing an item label, the parent window of the list view control receives an LVN_BEGINLABELEDIT notification message. When the user cancels or completes the editing, the parent window receives an LVN_ENDLABELEDIT notification message.


LVN_GETDISPINFO

LVN_GETDISPINFO
    pnmv = (LPNMLVDISPINFO) lParam;

Sent by a list view control to its parent window. It is a request for the parent window to provide information needed to display or sort a list view item. This notification message is sent in the form of a WM_NOTIFY message.

  • No return value.
pnmv
Address of an NMLVDISPINFO structure. On input, the LVITEM structure contained in this structure specifies the type of information required and identifies the item or subitem of interest.
Use the LVITEM structure to return the requested information to the control. If your message handler sets the LVIF_DI_SETITEM flag in the mask member of the LVITEM structure, the list view control stores the requested information and will not ask for it again.

A list view control sends the LVN_GETDISPINFO notification to retrieve item information that is stored by the application rather than the control. The information can be text or icon information for an item. It can also be item state information. See the LVM_SETCALLBACKMASK message for more information on implementing item state on a callback basis.

For more information on list view callbacks, see Callback Items and the Callback Mask.

See also LVN_SETDISPINFO


LVN_GETINFOTIP

LVN_GETINFOTIP
    pGetInfoTip = (LPNMLVGETINFOTIP)lParam;

Sent by a large icon view list view control that has the LVS_EX_INFOTIP extended style. This notification is sent when the list view control is requesting additional text information to be displayed in a tooltip. It is sent in the form of a WM_NOTIFY message.

  • The return value for this notification is not used.
pGetInfoTip
Address of an NMLVGETINFOTIP structure that contains information about this notification.

This notification is only sent by list view controls that have the LVS_ICON style and the LVS_EX_INFOTIP extended style.

Version 4.71


LVN_INSERTITEM

LVN_INSERTITEM
    pnmv = (LPNMLISTVIEW) lParam;

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.

  • No return value.
pnmv
Address of an NMLISTVIEW structure. The iItem member identifies the new item, and the other members are zero.


LVN_HOTTRACK

LVN_HOTTRACK
    lpnmlv = (LPNMLISTVIEW)lParam;

Sent by a list view control when the user moves the mouse over an item. This notification is only sent by list view controls that have the LVS_EX_TRACKSELECT extended list view style. It is sent in the form of a WM_NOTIFY message.

  • Return zero to allow the list view to perform its normal track select processing. If the application returns nonzero, the item will not be selected.
lpnmlv
Address of an NMLISTVIEW structure that contains information about this notification. The iItem, iSubItem, and ptAction members of this structure contain information about the item. The receiving application can modify the iItem member to specify the item that will be selected. If iItem is set to -1, no item will be selected.

Version 4.71


LVN_ITEMACTIVATE

LVN_ITEMACTIVATE
#if (_WIN32_IE >= 0x0400)
    lpnmia = (LPNMITEMACTIVATE)lParam;
#else
    lpnm = (LPNMHDR)lParam;
#endif

Sent by a list view control when the user activates an item. This notification is sent in the form of a WM_NOTIFY message.

  • The application receiving this notification must return zero.
lpnmia
Version 4.71. Address of an NMITEMACTIVATE structure that contains information about this notification.
lpnm
Version 4.70 and earlier. Address of an NMHDR structure that contains information about this notification.

To obtain the items being activated, the receiving application should use the LVM_GETSELECTEDCOUNT message to get the number of items that are selected and then send the LVM_GETNEXTITEM message with LVNI_SELECTED until all of the items have been retrieved.

Version 4.70


LVN_ITEMCHANGED

LVN_ITEMCHANGED
    pnmv = (LPNMLISTVIEW) lParam;

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.

  • No return value.
pnmv
Address of an NMLISTVIEW structure that identifies the item and specifies which of its attributes have changed.


LVN_ITEMCHANGING

LVN_ITEMCHANGING
    pnmv = (LPNMLISTVIEW) lParam;

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.

  • Returns TRUE to prevent the change, or FALSE to allow the change.
pnmv
Address of an NMLISTVIEW structure that identifies the item and specifies which of its attributes are changing.


LVN_KEYDOWN

LVN_KEYDOWN
    pnkd = (LPNMLVKEYDOWN) lParam;

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.

  • No return value.
pnkd
Address of an NMLVKEYDOWN structure.


LVN_MARQUEEBEGIN

LVN_MARQUEEBEGIN
    pnmv = (LPNMLISTVIEW) lParam;

Notifies a list view control's parent window that a bounding box (marquee) selection has begun. This notification message is sent in the form of a WM_NOTIFY message.

Note A bounding box selection is the process of clicking the list view window's client area and dragging to select multiple items simultaneously.

  • To accept the notification message, return zero. To quit the bounding box selection, return nonzero.
pnmv
Address of an NMHDR structure.

Version 4.70


LVN_ODCACHEHINT

LVN_ODCACHEHINT
    pCachehint = (NMLVCACHEHINT *)lParam;

Sent by a virtual list view control when the contents of its display area have changed. For example, a list view control sends this notification when the user scrolls the control's display. The LVN_ODCACHEHINT notification message is sent in the form of a WM_NOTIFY message.

  • The application receiving this notification must return zero.
pCachehint
Address of an NMLVCACHEHINT structure containing information about the range of items to be cached.

Handling this message allows the application to update the item information held in cache so that it is readily available when an LVN_GETDISPINFO notification message is sent.

Note that this message is not always an exact representation of the items that will be requested by LVN_GETDISPINFO. Therefore, if the requested item is not cached while handling LVN_GETDISPINFO, the application must be prepared to supply the requested information from a source outside the cache.

Version 4.70


LVN_ODFINDITEM

LVN_ODFINDITEM
    pFindInfo = (PNMLVFINDITEM) lParam;

Sent by a virtual list view control when it needs the owner to find a particular callback item. For example, the control will send this notification when it receives shortcut keyboard input or when it receives an LVM_FINDITEM message.

  • Return the index of the item found, or -1 if no item is found.
pFindInfo
Address of an NMLVFINDITEM structure that includes information to be used for the search.

Search information is sent in the form of an LVFINDINFO structure, which is a member of the NMLVFINDITEM structure.

Version 4.70


LVN_ODSTATECHANGED

LVN_ODSTATECHANGED
    lpStateChange = (LPNMLVODSTATECHANGE) lParam;

Sent by a list view control when the state of an item or range of items has changed. This notification is sent in the form of a WM_NOTIFY message.

  • The application receiving this notification must return zero.
lpStateChange
Address of an NMLVODSTATECHANGE structure that contains information about the item or items that have changed.

Version 4.70


LVN_SETDISPINFO

LVN_SETDISPINFO
    pnmv = (LPNMLVDISPINFO) lParam;

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.

  • No return value.
pnmv
Address of an NMLVDISPINFO structure that specifies information for the changed item. The item member of this structure is an LVITEM structure that contains information about the item that was changed. The pszText member of item contains a valid value, regardless of whether the LVIF_TEXT flag is set in the mask member of this structure.

See also LVN_GETDISPINFO


NM_CLICK (list view)

NM_CLICK
    lpnmlv = (LPNMLISTVIEW) lParam;

Sent by a list view control when the user clicks an item with the left mouse button. This notification message is sent in the form of a WM_NOTIFY message.

  • The return value for this notification is not used.
lpnmlv
Version 4.71. Address of an NMLISTVIEW structure that contains additional information about this notification message. The iItem, iSubItem, and ptAction members of this structure contain information about the item.

This notification is identical to the standard NM_CLICK notification except that, in version 4.71 and later, the list view supplies an NMLISTVIEW structure instead of an NMHDR structure for the lParam.


NM_CUSTOMDRAW (list view)

NM_CUSTOMDRAW
    lpNMCustomDraw = (LPNMLVCUSTOMDRAW) lParam;

Sent by a list view control to notify its parent windows about drawing operations. This notification is sent in the form of a WM_NOTIFY message.

  • The value your application can return depends on the current drawing stage. The dwDrawStage member of the associated NMCUSTOMDRAW structure holds a value that specifies the drawing stage. You must return one of the following values.

    When dwDrawStage equals CDDS_PREPAINT:
    CDRF_DODEFAULT
    The control will draw itself. It will not send any additional NM_CUSTOMDRAW messages for this paint cycle.
    CDRF_NOTIFYITEMDRAW
    The control will notify the parent of any item-related drawing operations. It will send NM_CUSTOMDRAW notification messages before and after drawing items.
    CDRF_NOTIFYITEMERASE
    The control will notify the parent when an item will be erased. It will send NM_CUSTOMDRAW notification messages before and after erasing items.
    CDRF_NOTIFYPOSTERASE
    The control will notify the parent after erasing an item.
    CDRF_NOTIFYPOSTPAINT
    The control will notify the parent after painting an item.
    CDRF_NOTIFYSUBITEMDRAW
    Version 4.71. The control will notify the parent when a list view subitem is being drawn.

    When dwDrawStage equals CDDS_ITEMPREPAINT:
    CDRF_NEWFONT
    Your application specified a new font for the item; the control will use the new font. For more information on changing fonts, see Changing fonts and colors.
    CDRF_SKIPDEFAULT
    Your application drew the item manually. The control will not draw the item.

lpNMCustomDraw
Address of a NMLVCUSTOMDRAW structure that contains information about the drawing operation. The dwItemSpec member of the nmcd member of this structure contains the identifier of the item being drawn. The lItemlParam member of the nmcd member of this structure contains the lParam of the item being drawn.

Version 4.70

See also Using Custom Draw


NM_DBLCLK (list view)

NM_DBLCLK
    lpnmlv = (LPNMLISTVIEW) lParam;

Sent by a list view control when the user double-clicks an item with the left mouse button. This notification message is sent in the form of a WM_NOTIFY message.

  • The return value for this notification is not used.
lpnmlv
Version 4.71. Address of an NMLISTVIEW structure that contains additional information about this notification message. The iItem, iSubItem, and ptAction members of this structure contain information about the item.

This notification is identical to the standard NM_DBLCLK notification except that, in version 4.71 and later, the list view supplies an NMLISTVIEW structure instead of an NMHDR structure for the lParam.


NM_HOVER (list view)

NM_HOVER
    lpnmh = (LPNMHDR) lParam;

Sent by a list view control when the mouse hovers over an item. This notification message is sent in the form of a WM_NOTIFY message.

  • Return zero to allow the list view to process the hover normally, or nonzero to prevent the hover from being processed.
lpnmh
Address of an NMHDR structure that contains additional information about this notification message.

Version 4.70


NM_KILLFOCUS (list view)

NM_KILLFOCUS
    lpnmh = (LPNMHDR) lParam;

Notifies a list view control's parent window that the control has lost the input focus. NM_KILLFOCUS is sent in the form of a WM_NOTIFY message.

  • The return value for this notification is not used.
lpnmh
Address of an NMHDR structure that contains additional information about this notification message.


NM_RCLICK (list view)

NM_RCLICK
    lpnmlv = (LPNMLISTVIEW) lParam;

Sent by a list view control when the user clicks an item with the right mouse button. This notification message is sent in the form of a WM_NOTIFY message.

  • The return value for this notification is not used.
lpnmlv
Version 4.71. Address of an NMLISTVIEW structure that contains additional information about this notification message. The iItem, iSubItem, and ptAction members of this structure contain information about the item.

This notification is identical to the standard NM_RCLICK notification except that, in version 4.71 and later, the list view supplies a NMLISTVIEW structure instead of an NMHDR structure for the lParam.


NM_RDBLCLK (list view)

NM_RDBLCLK
    lpnmlv = (LPNMLISTVIEW) lParam;

Sent by a list view control when the user double-clicks an item with the right mouse button. This notification message is sent in the form of a WM_NOTIFY message.

  • The return value for this notification is not used.
lpnmlv
Version 4.71. Address of an NMLISTVIEW structure that contains additional information about this notification message. The iItem, iSubItem, and ptAction members of this structure contain information about the item.

This notification is identical to the standard NM_RDBLCLK notification except that, in version 4.71 and later, the list view supplies an NMLISTVIEW structure instead of an NMHDR structure for the lParam.


NM_RELEASEDCAPTURE (list view)

NM_RELEASEDCAPTURE
    lpnmh = (LPNMHDR) lParam;

Notifies a list view control's parent window that the control is releasing mouse capture. This notification is sent in the form of a WM_NOTIFY message.

  • The control ignores the return value from this notification.
lpnmh
Address of an NMHDR structure that contains additional information about this notification message.

Version 4.71.


NM_RETURN (list view)

NM_RETURN
    lpnmh = (LPNMHDR) lParam;

Notifies a list view control's parent window 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.

  • The return value for this notification is not used.
lpnmh
Address of an NMHDR structure that contains additional information about this notification message.


NM_SETFOCUS (list view)

NM_SETFOCUS
    lpnmh = (LPNMHDR) lParam;

Notifies a list view control's parent window that the control has received the input focus. NM_SETFOCUS is sent in the form of a WM_NOTIFY message.

  • The return value for this notification is not used.
lpnmh
Address of an NMHDR structure that contains additional information about this notification message.


List View Control Structures

This section contains information about the structures used with list view controls.

LVBKIMAGE

LVCOLUMN

LVFINDINFO

LVHITTESTINFO

LVITEM

NMITEMACTIVATE

NMLISTVIEW

NMLVCACHEHINT

NMLVCUSTOMDRAW

NMLVDISPINFO

NMLVFINDITEM

NMLVGETINFOTIP

NMLVKEYDOWN

NMLVODSTATECHANGE


LVBKIMAGE

typedef struct tagLVBKIMAGE
{
    ULONG ulFlags;
    HBITMAP hbm;
    LPTSTR pszImage;
    UINT cchImageMax;
    int xOffsetPercent;
    int yOffsetPercent;
} LVBKIMAGE, FAR *LPLVBKIMAGE;

Contains information about the background image of a list view control. This structure is used for both setting and retrieving background image information.

ulFlags
One or more of the following flags. The LVBKIF_SOURCE_MASK value can be used to mask off all but the source flags. The LVBKIF_STYLE_MASK value can be used to mask off all but the style flags.
LVBKIF_SOURCE_NONE | The list view control has no background image.
LVBKIF_SOURCE_HBITMAP | Not currently implemented.
LVBKIF_SOURCE_URL | The pszImage member contains the URL of the background image.
LVBKIF_STYLE_NORMAL | The background image is displayed normally.
LVBKIF_STYLE_TILE | The background image will be tiled to fill the entire background of the control.
hbm
Not currently used.
pszImage
Address of a NULL-terminated string that contains the URL of the background image. This member is only valid if the LVBKIF_SOURCE_URL flag is set in ulFlags. This member must be initialized to point to the buffer that contains or receives the text before sending the message.
cchImageMax
Size of the buffer at the address in pszImage. If information is being sent to the control, this member is ignored.
xOffsetPercent
Percentage of the control's client area that the image should be offset horizontally. For example, at 0 percent, the image will be displayed against the left edge of the control's client area. At 50 percent, the image will be displayed horizontally centered in the control's client area. At 100 percent, the image will be displayed against the right edge of the control's client area. This member is only valid when LVBKIF_STYLE_NORMAL is specified in ulFlags.
yOffsetPercent
Percentage of the control's client area that the image should be offset vertically. For example, at 0 percent, the image will be displayed against the top edge of the control's client area. At 50 percent, the image will be displayed vertically centered in the control's client area. At 100 percent, the image will be displayed against the bottom edge of the control's client area. This member is only valid when LVBKIF_STYLE_NORMAL is specified in ulFlags.

This structure is used with the LVM_GETBKIMAGE and LVM_SETBKIMAGE messages.

Version 4.71


LVCOLUMN

typedef struct _LVCOLUMN {
    UINT mask;
    int fmt;
    int cx;
    LPTSTR pszText;
    int cchTextMax;
    int iSubItem;
#if (_WIN32_IE >= 0x0300)
    int iImage;
    int iOrder;
#endif
} LVCOLUMN, FAR *LPLVCOLUMN;

Contains information about a column in report view. This structure is used both for creating and manipulating columns. This structure supersedes the LV_COLUMN structure.

mask
Variable specifying which members contain valid information. This member can be zero, or one or more of the following values:
LVCF_FMT | The fmt member is valid.
LVCF_IMAGE | Version 4.70. The iImage member is valid.
LVCF_ORDER | Version 4.70. The iOrder 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 heading and the subitem text in the column. This member can be one of the following values:
LVCFMT_BITMAP_ON_RIGHT | Version 4.70. The bitmap appears to the right of text. This does not affect an image from an image list assigned to the header item.
LVCFMT_CENTER | Text is centered.
LVCFMT_COL_HAS_IMAGES | Version 4.70. The header item contains an image in the image list.
LVCFMT_IMAGE | Version 4.70. The item displays an image from an image list.
LVCFMT_LEFT | Text is left-aligned.
LVCFMT_RIGHT | Text is right-aligned.

The leftmost column in a list view control must be left-aligned.

cx
Width of the column, in pixels.
pszText
If column information is being set, this member is the address of a null-terminated string that contains the column heading text. If the structure is receiving information about a column, this member specifies the address of the buffer that receives the column heading text.
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 the column.
iImage
Version 4.70. Zero-based index of an image within the image list. The specified image will appear within the column.
iOrder
Version 4.70. Zero-based column offset. Column offset is in left-to-right order. For example, zero indicates the leftmost column.

This structure is used with the LVM_GETCOLUMN, LVM_SETCOLUMN, LVM_INSERTCOLUMN, and LVM_DELETECOLUMN messages.


LVFINDINFO

typedef struct tagLVFINDINFO
{
    UINT flags;
    LPCTSTR psz;
    LPARAM lParam;
    POINT pt;
    UINT vkDirection;
} LVFINDINFO, FAR* LPFINDINFO;

Contains information used to search for a list view item. This structure is the same as the LV_FINDINFO structure but has been renamed to fit standard naming conventions.

flags
Type of search to perform. This can be one or more of the following values:
LVFI_PARAM | Searches based on the lParam member. The lParam member of the matching item's LVITEM structure must match the lParam member of this structure. If this value is specified, all other values are ignored.
LVFI_PARTIAL | Checks to see 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 to the position specified in the pt member, in the direction specified by the vkDirection member.
psz
Address of 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 LVITEM 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 in the flags member.
vkDirection
Direction to search. This member contains the virtual key code of an arrow key that corresponds to the direction to search. This member is used only if LVFI_NEARESTXY is specified in the flags member.


LVHITTESTINFO

typedef struct _LVHITTESTINFO {
    POINT pt;
    UINT flags;
    int iItem;
    int iSubItem;
 } LVHITTESTINFO, FAR *LPLVHITTESTINFO;

Has been extended to accommodate subitem hit-testing. The LVHITTESTINFO structure contains information about a hit test. It is used in association with the LVM_HITTEST and LVM_SUBITEMHITTEST messages and their related macros. This structure supersedes the LV_HITTESTINFO structure.

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:
LVHT_ABOVE | The position is above the control's client area.
LVHT_BELOW | The position is below the control's client area.
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 could use both LVHT_ABOVE and LVHT_TOLEFT.

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. Or if hit-testing a subitem, this value represents the subitem's parent item.
iSubItem
Version 4.70. Receives the index of the matching subitem. When hit-testing an item, this member will be zero.


LVITEM

typedef struct _LVITEM {
    UINT   mask;
    int    iItem;
    int    iSubItem;
    UINT   state;
    UINT   stateMask;
    LPTSTR  pszText;
    int    cchTextMax;
    int    iImage;
    LPARAM lParam;
#if (_WIN32_IE >= 0x0300)
    int iIndent;
#endif
} LVITEM, FAR *LPLVITEM;

Specifies or receives the attributes of a list view item. This structure has been updated to support a new mask value (LVIF_INDENT) that enables item indenting. This structure supersedes the LV_ITEM structure.

mask
Set of flags that specify which members of this structure contain data to be set or which members are being requested. This can be one or more of the following flags:
LVIF_TEXT | The pszText member is valid or must be filled in.
LVIF_IMAGE | The iImage member is valid or must be filled in.
LVIF_INDENT | The iIndent member is valid or must be filled in.
LVIF_NORECOMPUTE | The control will not generate LVN_GETDISPINFO to retrieve text information if it receives a LVM_GETITEM message. Instead, the pszText member will contain LPSTR_TEXTCALLBACK.
LVIF_PARAM | The lParam member is valid or must be filled in.
LVIF_STATE | The state member is valid or must be filled in.
LVIF_DI_SETITEM | The operating system should store the requested list item information and not ask for it again. This flag is used only with the LVN_GETDISPINFO notification message.
iItem
Zero-based index of the item to which this structure refers.
iSubItem
One-based index of the subitem to which this structure refers, or zero if this structure refers to an item rather than a subitem.
state
Indicates the item's state, state image, and overlay image. The stateMask member indicates the valid bits of this member.

Bits 0 through 7 of this member contain the item state flags. This can be one or more of the item state values.

Bits 8 through 11 of this member specify the one-based overlay image index. Both the full-sized icon image list and the small icon image list can have overlay images. The overlay image is superimposed over the item's icon image. If these bits are zero, the item has no overlay image. To isolate these bits, use the LVIS_OVERLAYMASK mask. To set the overlay image index in this member, you should use the INDEXTOOVERLAYMASK macro. The image list's overlay images are set with the ImageList_SetOverlayImage function.

Bits 12 through 15 of this member specify the state image index. The state image is displayed next to an item's icon to indicate an application-defined state. If these bits are zero, the item has no state image. To isolate these bits, use the LVIS_STATEIMAGEMASK mask. To set the state image index, you should use the INDEXTOSTATEIMAGEMASK macro. The state image index specifies the index of the image in the state image list that should be drawn. The state image list is specified with the LVM_SETIMAGELIST message.

stateMask
Value specifying which bits of the state member will be retrieved or modified. For example, setting this member to LVIS_SELECTED will cause only the item's selection state to be retrieved.

This member allows you to modify one or more item states without having to retrieve all of the item states first. For example, setting this member to LVIS_SELECTED and state to zero will cause the item's selection state to be cleared, but none of the other states will be affected.

To retrieve or modify all of the states, set this member to (UINT)-1.

You can use the macro ListView_SetItemState both to set and to clear bits.

pszText
Address of a null-terminated string containing 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 address of 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. This member is ignored if the structure specifies item attributes.
iImage
Index of the item's icon in the control's image list. This applies to both the large and small image list.

If this member is the I_IMAGECALLBACK value, the parent window is responsible for storing the index. In this case, the list view control sends the parent an LVN_GETDISPINFO notification message to get the index when it needs to display the image.

lParam
32-bit value specific to the item. If you use the LVM_SORTITEMS message, the list view control passes this value to the application-defined comparison function. You can also use the LVM_FINDITEM message to search a list view control for an item with a specified lParam value.
iIndent
Version 4.70. Number of image widths to indent the item. A single indentation equals the width of an item image. Therefore, the value 1 indents the item by the width of one image, the value 2 indents by two images, and so on. Note that this field is supported only for items. Attempting to set subitem indentation will cause the calling function to fail.

The LVITEM structure is used with a number of messages, including LVM_GETITEM, LVM_SETITEM, LVM_INSERTITEM, and LVM_DELETEITEM.


NMITEMACTIVATE

typedef struct tagNMITEMACTIVATE{
    NMHDR   hdr;
    int     iItem;
    int     iSubItem;
    UINT    uNewState;
    UINT    uOldState;
    UINT    uChanged;
    POINT   ptAction;
    LPARAM  lParam;
    UINT    uKeyFlags;
} NMITEMACTIVATE, FAR *LPNMITEMACTIVATE;

Contains information about an LVN_ITEMACTIVATE notification message.

hdr
NMHDR structure that contains information about this notification message.
iItem
Index of the list view item. If the item index is not used for the notification, this member will contain -1.
iSubItem
One-based index of the subitem. If the subitem index is not used for the notification or the notification does not apply to a subitem, this member will contain zero.
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
Set of flags that indicate the 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 LVITEM structure.
ptAction
POINT structure that indicates the location at which the event occurred. This member is undefined for notification messages that do not use it.
lParam
Application-defined 32-bit value of the item. This member is undefined for notification messages that do not use it.
uKeyFlags
Modifier keys that were pressed at the time of the activation. This member contains zero or a combination of the following flags:
LVKF_ALT | The ALT key is pressed.
LVKF_CONTROL | The CTRL key is pressed.
LVKF_SHIFT | The SHIFT key is pressed.

Version 4.71


NMLISTVIEW

typedef struct tagNMLISTVIEW{
    NMHDR   hdr;
    int     iItem;
    int     iSubItem;
    UINT    uNewState;
    UINT    uOldState;
    UINT    uChanged;
    POINT   ptAction;
    LPARAM  lParam;
} NMLISTVIEW, FAR *LPNMLISTVIEW;

Contains information about a list view notification message. This structure is the same as the NM_LISTVIEW structure but has been renamed to fit standard naming conventions.

hdr
NMHDR structure that contains information about this notification message.
iItem
Identifies the list view item, or -1 if not used.
iSubItem
Identifies the 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
Set of flags that indicate the 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 LVITEM structure.
ptAction
POINT structure that indicates the location at which the event occurred. This member is undefined for notification messages that do not use it.
lParam
Application-defined 32-bit value of the item. This member is undefined for notification messages that do not use it.

Version 4.70


NMLVCACHEHINT

typedef struct tagNMLVCACHEHINT {
    NMHDR   hdr;
    int     iFrom;
    int     iTo;
} NMLVCACHEHINT, *PNMLVCACHEHINT;

Contains information used to update the cached item information for use with a virtual list view.

hdr
NMHDR structure that contains information about this notification message.
iFrom
Starting index of the requested range of items. This value is inclusive.
iTo
Ending index of the requested range of items. This value is inclusive.

Version 4.70


NMLVCUSTOMDRAW

typedef struct tagNMLVCUSTOMDRAW {
    NMCUSTOMDRAW nmcd;
    COLORREF clrText;
    COLORREF clrTextBk;
#if (_WIN32_IE >= 0x0400)
    int iSubItem;
#endif
} NMLVCUSTOMDRAW, *LPNMLVCUSTOMDRAW;

Contains information specific to an NM_CUSTOMDRAW notification message sent by a list view control.

nmcd
NMCUSTOMDRAW structure that contains general custom draw information.
clrText
COLORREF value representing the color that will be used to display text foreground in the list view control.
clrTextBk
COLORREF value representing the color that will be used to display text background in the list view control.
iSubItem
Version 4.71. Index of the subitem that is being drawn. If the main item is being drawn, this member will be zero.

Version 4.70


NMLVDISPINFO

typedef struct tagLVDISPINFO {
    NMHDR hdr;
    LVITEM item;
} NMLVDISPINFO, FAR *LPNMLVDISPINFO;

Contains information about an LVN_GETDISPINFO or LVN_SETDISPINFO notification message. This structure is the same as the LV_DISPINFO structure but has been renamed to fit standard naming conventions.

hdr
NMHDR structure that contains information about this notification message.
item
LVITEM 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:
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. For list view controls with the LVS_REPORT style, this flag only applies to the first (subitem 0) column's information. The control will not store information for subitems.


NMLVFINDITEM

typedef struct _NMLVFINDITEM {
    NMHDR hdr;
    int iStart;
    LVFINDINFO lvfi;
} NMLVFINDITEM, *PNMLVFINDITEM;

Contains information the owner needs to find items requested by a virtual list view control. This structure is used with the LVN_ODFINDITEM notification message.

hdr
NMHDR structure that contains information on this notification message.
iStart
Index of the item at which the search will start.
lvfi
LVFINDINFO structure that contains information necessary to perform a search.

Version 4.70


NMLVGETINFOTIP

typedef struct tagNMLVGETINFOTIP{
    NMHDR hdr;
    DWORD dwFlags;
    LPTSTR pszText;
    int cchTextMax;
    int iItem;
    int iSubItem;
    LPARAM lParam;
} NMLVGETINFOTIP, *LPNMLVGETINFOTIP;

Contains and receives list view item information needed to display a tooltip for an item. This structure is used with the LVN_GETINFOTIP notification message.

hdr
NMHDR structure that contains information on this notification message.
dwFlags
Either zero or LVGIT_UNFOLDED.
pszText
Address of a string buffer that receives any additional text information. If dwFlags is zero, this member will contain the existing item text. In this case, you should append any additional text onto the end of this string. The size of this buffer is specified by the ccTextMax structure.
cchTextMax
Size, in characters, of the buffer pointed to by pszText. Although you should never assume that this buffer will be of any particular size, the INFOTIPSIZE value can be used for design purposes.
iItem
Zero-based index of the item to which this structure refers.
iSubItem
One-based index of the subitem to which this structure refers. If this member is zero, the structure is referring to the item and not a subitem. This member is not currently used and will always be zero.
lParam
Application-defined value associated with the item. This member is not currently used and will always be zero.

Version 4.71


NMLVKEYDOWN

typedef struct tagLVKEYDOWN {
    NMHDR hdr;
    WORD  wVKey;
    UINT  flags;
} NMLVKEYDOWN, FAR *LPNMLVKEYDOWN;

Contains information used in processing the LVN_KEYDOWN notification message. This structure is the same as the LV_KEYDOWN structure but has been renamed to fit standard naming conventions.

hdr
NMHDR structure that contains additional information about the notification message.
wVKey
Virtual key code.
flags
This member must always be zero.


NMLVODSTATECHANGE

typedef struct tagNMLVODSTATECHANGE {
    NMHDR hdr;
    int   iFrom;
    int   iTo;
    UINT  uNewState;
    UINT  uOldState;
} NMLVODSTATECHANGE, FAR *LPNMLVODSTATECHANGE;

Structure that contains information for use in processing the LVN_ODSTATECHANGED notification message.

hdr
NMHDR structure that contains additional information about the notification message.
iFrom
Zero-based index of the first item in the range of items.
iTo
Zero-based index of the last item in the range of items.
uNewState and uOldState
Values indicating the new and old states for the item or items. These members can be any valid combination of the list view item states.

Version 4.70


Month Calendar Controls

A month calendar control implements a calendar-like user interface. This provides the user with a very intuitive and recognizable method of entering or selecting a date. The control also provides the application with the means to obtain and set the date information in the control using existing data types.

About Month Calendar Controls

Using Month Calendar Controls

Month Calendar Control Reference

About Month Calendar Controls

A month calendar control provides a simple and intuitive way for a user to select a date from a familiar interface. The following illustration shows a month calendar control in a dialog box.

Month calendar control in a dialog box.

An application creates a month calendar control by calling the CreateWindowEx function, specifying MONTHCAL_CLASS as the window class. The class is registered when the month calendar class is loaded from the common controls dynamic-link library (DLL). Register this class by calling the InitCommonControlsEx function, specifying the ICC_DATE_CLASSES bit flag in the accompanying INITCOMMONCONTROLSEX structure.

Note The month calendar control is implemented in version 4.70 and later of Comctl32.dll.

The Month Calendar Control User Interface

The month calendar control user interface allows the user to select a date from the displayed days or change the control's display in various ways.

  • Scrolling the control's display.

    By default, when a user clicks the arrow buttons in the top left or top right of the month calendar control, it updates its display to show the previous or next month. If the month calendar control is displaying more than one month at a time, the display changes by the number of months currently in view. That is, if the month calendar displays January, February, and March and the user clicks the top right arrow button, the control updates its display to show April, May, and June. The user can also perform the same action by clicking the partial months displayed before the first month and after the last month.

    An application can change the number of months by which the control updates its display by using the MCM_SETMONTHDELTA message or the corresponding macro, MonthCal_SetMonthDelta.

  • Selecting a nonadjacent month.

    When a user clicks the name of a displayed month, a pop-up menu appears that lists all months within the year. The user can select a month on the list. If the user's selection is not visible, the month calendar control scrolls its display to show the chosen month.

  • Selecting a different year.

    If the user clicks the year displayed next to a month name, an up-down control appears in place of the year. The user can change the year with this control. The month calendar control updates its display for the selected year when the up-down control loses focus.

  • Selecting the current day.

    If a month calendar control is not using the MCS_NOTODAY style, the user can return to the current day by clicking the "today" text at the bottom of the control. If the current day is not visible, the control updates its display to show it.

Day States

Month calendar controls that use the MCS_DAYSTATE style support day states. The control uses day state information to determine how it draws specific days within the control. Day state information is expressed as a 32-bit data type, MONTHDAYSTATE. Each bit in a MONTHDAYSTATE bit field (1 through 31) represents the state of a day in a month. If a bit is on, the corresponding day will be displayed in bold; otherwise it will be displayed with no emphasis.

An application can explicitly set day state information by sending the MCM_SETDAYSTATE message or by using the corresponding macro, MonthCal_SetDayState. Additionally, month calendar controls that use the MCS_DAYSTATE style send MCN_GETDAYSTATE notification messages to request day state information. For more information on supporting day states, see Processing the MCN_GETDAYSTATE Notification Message and Preparing the MONTHDAYSTATE Array.

Month Calendar Control Styles

Month calendar controls have several styles that determine their appearance and behavior. When you create the control using CreateWindowEx, include the desired styles in the dwStyle parameter.

After creating the control, you can change all of the styles except for MCS_DAYSTATE and MCS_MULTISELECT. To change these styles, you will need to destroy the existing control and create a new one that has the desired styles. To retrieve or change any other window styles, use the GetWindowLong and SetWindowLong functions.

Month calendar controls that use the MCS_MULTISELECT style allow the user to select a range of days. By default, the control allows the user to select seven contiguous days. Your application can change the control's default behavior by using the MCM_SETMAXSELCOUNT message or the accompanying macro, MonthCal_SetMaxSelCount.

When a month calendar control uses the MCS_WEEKNUMBERS style, it displays week numbers at the left side of each month. If the MCS_NOTODAY style is applied, the control no longer circles the current day.

The MCS_DAYSTATE style is helpful when you want the control to highlight specific dates by displaying them in bold. For more information, see Day States.

Month Calendar Control Notification Messages

A month calendar control sends notification messages when it receives user input or must request day state information (MCS_DAYSTATE style only). The control's parent receives these notifications as WM_NOTIFY messages.

The following notification messages are used with month calendar controls.
Notification | Description
MCN_GETDAYSTATE | Requests information about which days should be displayed in bold. For more information, see Preparing the MONTHDAYSTATE Array.
MCN_SELCHANGE | Notifies the parent that the selected date or range of dates has changed. The control sends this notification when the user explicitly changes the selection within the current month or when the selection is implicitly changed in response to next/previous month navigation.
MCN_SELECT | Notifies the parent that the user has explicitly selected a date.

Times in the Month Calendar Control

Because the month calendar control cannot be used to select a time, the time related fields of the SYSTEMTIME structure need to be handled differently. When the control is created, it will insert the current time into its "today" date and time.

When a time is later set programmatically, the control will either copy the time fields as they are or validate them first and then, if invalid, store the current default times. Following is a list of the messages that set a date and a description of how the time fields are treated by the message.

MCM_SETCURSEL | The control will copy the time fields as they are, without validation or modification.
MCM_SETRANGE | The time fields of the structures passed in will be validated. If they are valid, the time fields will be copied without modification. If they are invalid, the control will copy the time fields from the "today" date and time.
MCM_SETSELRANGE | The time fields of the structures passed in will be validated. If they are valid, the time fields will be copied without modification. If they are invalid, the control will retain the time fields from the current selection ranges.
MCM_SETTODAY | The control will copy the time fields as they are, without validation or modification.

When a date is retrieved from the control, the time fields will be copied from the stored times without modification. Handling of the time fields by the control is provided as a convenience to the programmer. The control does not examine or modify the time fields as a result of any operation other than those listed above.

Using Month Calendar Controls

This section provides information and sample code for implementing month calendar controls.

Creating a Month Calendar Control

To create a month calendar control, use the CreateWindowEx function, specifying MONTHCAL_CLASS as the window class. You must first register the window class by calling the InitCommonControlsEx function, specifying the ICC_DATE_CLASSES bit in the accompanying INITCOMMONCONTROLSEX structure.

The following example demonstrates how to create a month calendar control in an existing modeless dialog box. Note that the size values passed to CreateWindowEx are all zeros. Because the minimum required size depends on the font the control uses, the DoNotify example function uses the MonthCal_GetMinReqRect macro to request size information and then resizes the control by calling SetWindowPos.

//   CreateMonthCal -- Creates a month calendar control in a dialog box.
//                   Returns the handle to the month calendar control
//                   if successful, or NULL otherwise.
//
//    hwndOwner   -- Handle to the owner of the dialog box.
//    g_hinst     -- Global handle to the program instance.
//
/////
HWND WINAPI CreateMonthCal(HWND hwndOwner)
{
   HWND hwnd;
   RECT rc;
   INITCOMMONCONTROLSEX icex;

   // Load the window class.
   icex.dwSize = sizeof(icex);
   icex.dwICC  = ICC_DATE_CLASSES;
   InitCommonControlsEx(&icex);

   // Create a modeless dialog box to hold the control.
   g_hwndDlg = CreateDialog(g_hinst,
                     MAKEINTRESOURCE(IDD_DIALOG1),
                     hwndOwner,
                     DlgProc);

   // Create the month calendar.
   hwnd = CreateWindowEx(0,
                     MONTHCAL_CLASS,
                     "",
                     WS_BORDER | WS_CHILD | WS_VISIBLE | MCS_DAYSTATE,
                     0,0,0,0, // resize it later
                     g_hwndDlg,
                     NULL,
                     g_hinst,
                     NULL);

   // Get the size required to show an entire month.
   MonthCal_GetMinReqRect(hwnd, &rc);

// Arbitrary values
#define LEFT 35
#define TOP  40

   // Resize the control now that the size values have been obtained.
   SetWindowPos(hwnd, NULL, TOP, LEFT,
                LEFT + rc.right, TOP + rc.bottom,
                SWP_NOZORDER);

   // Set colors for aesthetics.
   MonthCal_SetColor(hwnd, MCSC_BACKGROUND, RGB(175,175,175));
   MonthCal_SetColor(hwnd, MCSC_MONTHBK, RGB(248,245,225));

   return(hwnd);
}

Processing the MCN_GETDAYSTATE Notification Message

Month calendar controls send the MCN_GETDAYSTATE notification message to request information about how the days within the visible months should be displayed. The following application-defined function, DoNotify, processes MCN_GETDAYSTATE by filling an array of MONTHDAYSTATE values to highlight the 15th day of each month.

DoNotify extracts the number of MONTHDAYSTATE values needed from the cDayState member of the NMDAYSTATE structure that lParam points to. It then loops to set the 15th bit in each element of the array, using the application-defined BOLDDAY macro.

BOOL WINAPI DoNotify(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
#define BOLDDAY(ds,iDay) if(iDay>0 && iDay<32)\
                            (ds)|=(0x00000001<<(iDay-1))

#define lpnmDS ((NMDAYSTATE *)lParam)
#define MAX_MONTHS 12

   MONTHDAYSTATE mds[MAX_MONTHS];
   INT i, iMax;
   LPNMHDR hdr = (LPNMHDR)lParam;

   switch(hdr->code){
      case MCN_GETDAYSTATE:
         iMax=lpnmDS->cDayState;

         for(i=0;i<iMax;i++){
            mds[i] = (MONTHDAYSTATE)0;
            BOLDDAY(mds[i],15);
         }
         lpnmDS->prgDayState = mds;
         break;
   }
   return FALSE;
}

Preparing the MONTHDAYSTATE Array

Both the MCM_SETDAYSTATE message and MCN_GETDAYSTATE notification message require an array of MONTHDAYSTATE values to determine how dates will be displayed. Each month that the control displays must have a corresponding element within the array.

To support these messages, your application must properly prepare the array. The following is a simple macro that sets a bit in a MONTHDAYSTATE value for a given day within that month.

#define BOLDDAY(ds,iDay) if(iDay>0 && iDay<32)\
                            (ds)|=(0x00000001<<(iDay-1))

Using this macro, an application could simply loop through an array of important dates, setting bits within the corresponding array elements. This approach is not the most efficient, of course, but works well for many purposes. As long as your application sets MONTHDAYSTATE bits appropriately, it does not matter how those bits were set.


Month Calendar Control Reference

This section contains information about the following programming elements used with month calendar controls.

Month calendar control styles

Month calendar day numbers

Messages
MCM_GETCOLOR
MCM_GETCURSEL
MCM_GETFIRSTDAYOFWEEK
MCM_GETMAXSELCOUNT
MCM_GETMAXTODAYWIDTH
MCM_GETMINREQRECT
MCM_GETMONTHDELTA
MCM_GETMONTHRANGE
MCM_GETRANGE
MCM_GETSELRANGE
MCM_GETTODAY
MCM_GETUNICODEFORMAT
MCM_HITTEST
MCM_SETCOLOR
MCM_SETCURSEL
MCM_SETDAYSTATE
MCM_SETFIRSTDAYOFWEEK
MCM_SETMAXSELCOUNT
MCM_SETMONTHDELTA
MCM_SETRANGE
MCM_SETSELRANGE
MCM_SETTODAY
MCM_SETUNICODEFORMAT

Utility Macros
MonthCal_GetColor
MonthCal_GetCurSel
MonthCal_GetFirstDayOfWeek
MonthCal_GetMaxSelCount
MonthCal_GetMaxTodayWidth
MonthCal_GetMinReqRect
MonthCal_GetMonthDelta
MonthCal_GetMonthRange
MonthCal_GetRange
MonthCal_GetSelRange
MonthCal_GetToday
MonthCal_GetUnicodeFormat
MonthCal_HitTest
MonthCal_SetColor
MonthCal_SetCurSel
MonthCal_SetDayState
MonthCal_SetFirstDayOfWeek
MonthCal_SetMaxSelCount
MonthCal_SetMonthDelta
MonthCal_SetRange
MonthCal_SetSelRange
MonthCal_SetToday
MonthCal_SetUnicodeFormat

Notifications
MCN_GETDAYSTATE
MCN_SELCHANGE
MCN_SELECT
NM_RELEASEDCAPTURE (monthcal)

Structures and Data Types
MCHITTESTINFO
MONTHDAYSTATE
NMDAYSTATE
NMSELCHANGE

Month calendar control styles

Month calendar day numbers

Month Calendar Control Messages

Month Calendar Control Macros

Month Calendar Control Notification Messages

Month Calendar Control Structures

Month Calendar Control Data Types


Month calendar control styles

The following are the styles used with month calendar controls.
MCS_DAYSTATE | Version 4.70. The month calendar will send MCN_GETDAYSTATE notifications to request information about which days should be displayed in bold. For more information about supporting this style, see Processing the MCN_GETDAYSTATE Notification Message.
MCS_MULTISELECT | Version 4.70. The month calendar will allow the user to select a range of dates within the control. By default, the maximum range is one week. You can change the maximum range that can be selected by using the MCM_SETMAXSELCOUNT message.
MCS_NOTODAY | Version 4.70. The month calendar control will not display the "today" date at the bottom of the control.
MCS_NOTODAYCIRCLE | Version 4.70. The month calendar control will not circle the "today" date.
MCS_WEEKNUMBERS | Version 4.70. The month calendar control will display week numbers (1-52) to the left of each row of days.


Month calendar day numbers

The following list contains the numeric representations of the days of the week that are used by the month calendar control.
Value | Day of Week
0 | Monday
1 | Tuesday
2 | Wednesday
3 | Thursday
4 | Friday
5 | Saturday
6 | Sunday


Month Calendar Control Messages

This section contains information about the messages used with month calendar controls.

MCM_GETCOLOR

MCM_GETCURSEL

MCM_GETFIRSTDAYOFWEEK

MCM_GETMAXSELCOUNT

MCM_GETMAXTODAYWIDTH

MCM_GETMINREQRECT

MCM_GETMONTHDELTA

MCM_GETMONTHRANGE

MCM_GETRANGE

MCM_GETSELRANGE

MCM_GETTODAY

MCM_GETUNICODEFORMAT

MCM_HITTEST

MCM_SETCOLOR

MCM_SETCURSEL

MCM_SETDAYSTATE

MCM_SETFIRSTDAYOFWEEK

MCM_SETMAXSELCOUNT

MCM_SETMONTHDELTA

MCM_SETRANGE

MCM_SETSELRANGE

MCM_SETTODAY

MCM_SETUNICODEFORMAT


MCM_GETCOLOR

MCM_GETCOLOR
    wParam = (WPARAM)(INT)iColor;
    lParam = 0;

Retrieves the color for a given portion of a month calendar control. You can send this message explicitly or by using the MonthCal_GetColor macro.

  • Returns a COLORREF value that represents the color setting for the specified portion of the month calendar control if successful. Otherwise, this message returns -1.
iColor
INT value specifying which month calendar color to retrieve. This value can be one of the following:
MCSC_BACKGROUND | Retrieve the background color displayed between months.
MCSC_MONTHBK | Retrieve the background color displayed within the month.
MCSC_TEXT | Retrieve the color used to display text within a month.
MCSC_TITLEBK | Retrieve the background color displayed in the calendar's title.
MCSC_TITLETEXT | Retrieve the color used to display text within the calendar's title.
MCSC_TRAILINGTEXT | Retrieve the color used to display header day and trailing day text. Header and trailing days are the days from the previous and following months that appear on the current month calendar.

Version 4.70


MCM_GETCURSEL

MCM_GETCURSEL
    wParam = 0;
    lParam = (LPARAM) (LPSYSTEMTIME) lpSysTime;

Retrieves the currently selected date. You can send this message explicitly or by using the MonthCal_GetCurSel macro.

  • Returns nonzero if successful, or zero otherwise. This message will always fail when applied to month calendar controls set to the MCS_MULTISELECT style.
lpSysTime
Address of a SYSTEMTIME structure that will receive the currently selected date information. This parameter must be a valid address and cannot be NULL.

Version 4.70

See also Times in the Month Calendar Control


MCM_GETFIRSTDAYOFWEEK

MCM_GETFIRSTDAYOFWEEK
    wParam = 0;
    lParam = 0;

Retrieves the first day of the week for a month calendar control. You can send this message explicitly or by using the MonthCal_GetFirstDayOfWeek macro.

  • Returns a DWORD value that contains two values. The high word is a BOOL value that is nonzero if the first day of the week is set to something other than LOCALE_IFIRSTDAYOFWEEK, or zero otherwise. The low word is an INT value that represents the first day of the week. This will be one of the day numbers.

Version 4.70


MCM_GETMAXSELCOUNT

MCM_GETMAXSELCOUNT
    wParam = 0;
    lParam = 0;

Retrieves the maximum date range that can be selected in a month calendar control. You can send this message explicitly or by using the MonthCal_GetMaxSelCount macro.

  • Returns an INT value that represents the total number of days that can be selected for the control.

You can change the maximum date range that can be selected by using the MCM_SETMAXSELCOUNT message.

Version 4.70


MCM_GETMAXTODAYWIDTH

MCM_GETMAXTODAYWIDTH
    wParam = 0;
    lParam = 0;

Retrieves the maximum width of the "today" string in a month calendar control. This includes the label text and the date text. You can send this message explicitly or by using the MonthCal_GetMaxTodayWidth macro.

  • Returns the width of the "today" string, in pixels.

Version 4.70


MCM_GETMINREQRECT

MCM_GETMINREQRECT
    wParam = 0;
    lParam = (LPARAM) (LPRECT) lpRectInfo;

Retrieves the minimum size required to display a full month in a month calendar control. Size information is presented in the form of a RECT structure. You can send this message explicitly or by using the MonthCal_GetMinReqRect macro.

  • Returns nonzero and lpRectInfo receives the applicable bounding information if successful. Otherwise, the message returns zero.
lpRectInfo
Address of a RECT structure that will receive bounding rectangle information. This parameter must be a valid address and cannot be NULL.

The top and left members of lpRectInfo will always be zero. The right and bottom members represent the minimum cx and cy required for the control.

The minimum required window size for a month calendar control depends on the currently selected font.

Version 4.70


MCM_GETMONTHDELTA

MCM_GETMONTHDELTA
    wParam = 0;
    lParam = 0;

Retrieves the scroll rate for a month calendar control. The scroll rate is the number of months that the control moves its display when the user clicks a scroll button. You can send this message explicitly or by using the MonthCal_GetMonthDelta macro.

  • If the month delta was previously set using the MCM_SETMONTHDELTA message, returns an INT value that represents the month calendar's current scroll rate. If the month delta was not previously set using the MCM_SETMONTHDELTA message, or the month delta was reset to the default, returns an INT value that represents the current number of months visible.

Version 4.70


MCM_GETMONTHRANGE

MCM_GETMONTHRANGE
    wParam = (WPARAM)(DWORD) dwFlag;
    lParam = (LPARAM)(LPSYSTEMTIME) lprgSysTimeArray;

Retrieves date information (using SYSTEMTIME structures) that represents the high and low limits of a month calendar control's display. You can send this message explicitly or by using the MonthCal_GetMonthRange macro.

  • Returns an INT value that represents the range, in months, spanned by the two limits returned at lprgSysTimeArray.
dwFlag
Value specifying the scope of the range limits to be retrieved. This value must be one of the following:
GMR_DAYSTATE | Include preceding and trailing months of visible range that are only partially displayed.
GMR_VISIBLE | Include only those months that are entirely displayed.
lprgSysTimeArray
Address of a two-element array of SYSTEMTIME structures that will receive the lower and upper limits of the scope specified by dwFlag. The lower and upper limits are placed in lprgSysTimeArray[0] and lprgSysTimeArray[1], respectively. This parameter must be a valid address and cannot be NULL.

Version 4.70

See also Times in the Month Calendar Control


MCM_GETRANGE

MCM_GETRANGE
    wParam = 0;
    lParam = (LPARAM)(LPSYSTEMTIME) lprgSysTimeArray;

Retrieves the minimum and maximum allowable dates set for a month calendar control. You can send this message explicitly or by using the MonthCal_GetRange macro.

  • Returns a DWORD that can be zero (no limits are set) or a combination of the following values that specify limit information:
    GDTR_MAX | A maximum limit is set for the control; lprgSysTimeArray[0] is valid and contains the applicable date information.
    GDTR_MIN | A minimum limit is set for the control; lprgSysTimeArray[1] is valid and contains the applicable date information.
lprgSysTimeArray
Address of a two-element array of SYSTEMTIME structures that will receive the date limit information. The minimum limit is set in lprgSysTimeArray[0], and lprgSysTimeArray[1] receives the maximum limit. If either element is set to all zeros, then no corresponding limit is set for the month calendar control. This parameter must be a valid address and cannot be NULL.

Version 4.70

See also Times in the Month Calendar Control


MCM_GETSELRANGE

MCM_GETSELRANGE
    wParam = 0;
    lParam = (LPARAM)(LPSYSTEMTIME) lprgSysTimeArray;

Retrieves date information that represents the upper and lower limits of the date range currently selected by the user. You can send this message explicitly or by using the MonthCal_GetSelRange macro.

  • Returns nonzero if successful, or zero otherwise. MCM_GETSELRANGE will fail if applied to a month calendar control that does not use the MCS_MULTISELECT style.
lprgSysTimeArray
Address of a two-element array of SYSTEMTIME structures that will receive the lower and upper limits of the user's selection. The lower and upper limits are placed in lprgSysTimeArray[0] and lprgSysTimeArray[1], respectively. This parameter must be a valid address and cannot be NULL.

Version 4.70

See also Times in the Month Calendar Control


MCM_GETTODAY

MCM_GETTODAY
    wParam = 0;
    lParam = (LPARAM)(LPSYSTEMTIME) lpToday;

Retrieves the date information for the date specified as "today" for a month calendar control. You can send this message explicitly or by using the MonthCal_GetToday macro.

  • Returns nonzero if successful, or zero otherwise.
lpToday
Address of a SYSTEMTIME structure that will receive the date information. This parameter must be a valid address and cannot be NULL.

Version 4.70

See also Times in the Month Calendar Control


MCM_GETUNICODEFORMAT

MCM_GETUNICODEFORMAT
    wParam = 0;
    lParam = 0;

Retrieves the UNICODE character format flag for the control. You can send this message explicitly or use the MonthCal_GetUnicodeFormat macro.

  • Returns the UNICODE format flag for the control. If this value is nonzero, the control is using UNICODE characters. If this value is zero, the control is using ANSI characters.

See also MCM_SETUNICODEFORMAT


MCM_HITTEST

MCM_HITTEST
    wParam = 0;
    lParam = (LPARAM)(PMCHITTESTINFO) pMCHitTest;

Determines which portion of a month calendar control is at a given point on the screen. You can send this message explicitly or by using the MonthCal_HitTest macro.

  • Sets values in members of the MCHITTESTINFO structure at pMCHitTest and returns a DWORD value that contains one or more of the following:
    MCHT_CALENDAR | The given point was within the calendar.
    MCHT_CALENDARBK | The given point was in the calendar's background.
    MCHT_CALENDARDATE | The given point was on a particular date within the calendar. The SYSTEMTIME structure at lpMCHitTest->st is set to the date at the given point.
    MCHT_CALENDARDATENEXT | The given point was over a date from the next month (partially displayed at the end of the currently displayed month). If the user clicks here, the month calendar will scroll its display to the next month or set of months.
    MCHT_CALENDARDATEPREV | The given point was over a date from the previous month (partially displayed at the end of the currently displayed month). If the user clicks here, the month calendar will scroll its display to the previous month or set of months.
    MCHT_CALENDARDAY | The given point was over a day abbreviation ("Fri", for example). The SYSTEMTIME structure at lpMCHitTest->st is set to the corresponding date in the top row.
    MCHT_CALENDARWEEKNUM | The given point was over a week number (MCS_WEEKNUMBERS style only). The SYSTEMTIME structure at lpMCHitTest->st is set to the corresponding date in the leftmost column.
    MCHT_NEXT | The given point is in an area that will cause the month calendar to scroll its display to the next month or set of months. This flag is used to modify other hit test flags.
    MCHT_NOWHERE | The given point was not on the month calendar control, or it was in an inactive portion of the control.
    MCHT_PREV | The given point is in an area that will cause the month calendar to scroll its display to the previous month or set of months. This flag is used to modify other hit test flags.
    MCHT_TITLE | The given point was over a month's title.
    MCHT_TITLEBK | The given point was over the background of a month's title.
    MCHT_TITLEBTNNEXT | The given point was over the button at the top right corner of the control. If the user clicks here, the month calendar will scroll its display to the next month or set of months.
    MCHT_TITLEBTNPREV | The given point was over the button at the top left corner of the control. If the user clicks here, the month calendar will scroll its display to the previous month or set of months.
    MCHT_TITLEMONTH | The given point was in a month's title bar, over a month name.
    MCHT_TITLEYEAR | The given point was in a month's title bar, over the year value.
    MCHT_TODAYLINK | The given point was on the "today" link at the bottom of the month calendar control.

    The uHit member of the MCHITTESTINFO structure at pMCHitTest will equal the return value.

pMCHitTest
Address of an MCHITTESTINFO structure. Upon sending the message, the cbSize member must be set to the size of the MCHITTESTINFO structure, and pt must be set to the point you want to hit test.

Version 4.70


MCM_SETCOLOR

MCM_SETCOLOR
    wParam = (WPARAM)(INT) iColor;
    lParam = (LPARAM)(COLORREF) clr;

Sets the color for a given portion of a month calendar control. You can send this message explicitly or by using the MonthCal_SetColor macro.

  • Returns a COLORREF value that represents the previous color setting for the specified portion of the month calendar control if successful. Otherwise, the return is -1.
iColor
INT value specifying which month calendar color to set. This value can be one of the following:
MCSC_BACKGROUND | Retrieve the background color displayed between months.
MCSC_MONTHBK | Retrieve the background color displayed within the month.
MCSC_TEXT | Retrieve the color used to display text within a month.
MCSC_TITLEBK | Retrieve the background color displayed in the calendar's title.
MCSC_TITLETEXT | Retrieve the color used to display text within the calendar's title.
MCSC_TRAILINGTEXT | Retrieve the color used to display header day and trailing day text. Header and trailing days are the days from the previous and following months that appear on the current month calendar.
clr
COLORREF value that represents the color that will be set for the specified area of the month calendar.

Version 4.70


MCM_SETCURSEL

MCM_SETCURSEL
    wParam = 0;
    lParam = (LPARAM)(LPSYSTEMTIME) lpSysTime;

Sets the currently selected date for a month calendar control. If the specified date is not in view, the control updates the display to bring it into view. You can send this message explicitly or by using the MonthCal_SetCurSel macro.

  • Returns nonzero if successful, or zero otherwise. This message will fail if applied to a month calendar control that uses the MCS_MULTISELECT style.
lpSysTime
Address of a SYSTEMTIME structure that contains the date to be set as the current selection.

Version 4.70

See also Times in the Month Calendar Control


MCM_SETDAYSTATE

MCM_SETDAYSTATE
    wParam = (WPARAM) iMonths;
    lParam = (LPARAM)(LPMONTHDAYSTATE) lpDayStateArray;

Sets the day states for all months that are currently visible within a month calendar control. You can send this message explicitly or by using the MonthCal_SetDayState macro.

  • Returns nonzero if successful, or zero otherwise.
iMonths
Value indicating how many elements are in the array that lpDayStateArray points to.
lpDayStateArray
Address of an array of MONTHDAYSTATE values that define how the month calendar control will draw each day in its display.

The array at lpDayStateArray must contain as many elements as the value returned by the following macro:

MonthCal_GetMonthRange(hwndMC, GMR_DAYSTATE, NULL);

Keep in mind that the array at lpDayStateArray must contain MONTHDAYSTATE values that correspond with all months currently in the control's display, in chronological order. This includes the two months only partially displayed before the first month and after the last month. For more information about preparing your array, see Preparing the MONTHDAYSTATE Array.

Version 4.70


MCM_SETFIRSTDAYOFWEEK

MCM_SETFIRSTDAYOFWEEK
    wParam = 0;
    lParam = (LPARAM)(INT) iDay;

Sets the first day of the week for a month calendar control. You can send this message explicitly or by using the MonthCal_SetFirstDayOfWeek macro.

  • Returns a DWORD value that contains two values. The high word is a BOOL value that is nonzero if the previous first day of the week did not equal LOCALE_IFIRSTDAYOFWEEK, or zero otherwise. The low word is an INT value that represents the previous first day of the week.
iDay
INT value representing which day is to be set as the first day of the week. This value must be one of the day numbers.

If the first day of the week is set to anything other than the default (LOCALE_IFIRSTDAYOFWEEK), the control will not automatically update first-day-of-the-week changes based on locale changes.

Version 4.70


MCM_SETMAXSELCOUNT

MCM_SETMAXSELCOUNT
    wParam = (WPARAM)(INT) iMax;
    lParam = 0;

Sets the maximum number of days that can be selected in a month calendar control. You can send this message explicitly or by using the MonthCal_SetMaxSelCount macro.

  • Returns nonzero if successful, or zero otherwise. This message will fail if applied to a month calendar control that does not use the MCS_MULTISELECT style.
iMax
INT value that will be set to represent the maximum number of days that can be selected.

Version 4.70


MCM_SETMONTHDELTA

MCM_SETMONTHDELTA
    wParam = (WPARAM)(INT) iDelta;
    lParam = 0;

Sets the scroll rate for a month calendar control. The scroll rate is the number of months that the control moves its display when the user clicks a scroll button. You can send this message explicitly or by using the MonthCal_SetMonthDelta macro.

  • Returns an INT value that represents the previous scroll rate. If the scroll rate was not previously set, the return value is zero.
iDelta
Value representing the number of months to be set as the control's scroll rate. If this value is zero, the month delta is reset to the default, which is the number of months displayed in the control.

Version 4.70


MCM_SETRANGE

MCM_SETRANGE
    wParam = (WPARAM)(SHORT) fWhichLimit;
    lParam = (LPARAM)(LPSYSTEMTIME) lprgSysTimeArray;

Sets the minimum and maximum allowable dates for a month calendar control. You can send this message explicitly or by using the MonthCal_SetRange macro.

  • Returns nonzero if successful, or zero otherwise.
fWhichLimit
Flag values that specify which date limits are being set. This value must be one or both of the following:
GDTR_MAX | The maximum allowable date is being set. The SYSTEMTIME structure at lprgSysTimeArray[1] must contain date information.
GDTR_MIN | The minimum allowable date is being set. The SYSTEMTIME structure at lprgSysTimeArray[0] must contain date information.
lprgSysTimeArray
Address of a two-element array of SYSTEMTIME structures that contain the date limits. The maximum limit must be in lpSysTimeArray[1] if GDTR_MAX is specified, and lpSysTimeArray[0] must contain the minimum limit if GDTR_MIN is specified.

Version 4.70

See also Times in the Month Calendar Control


MCM_SETSELRANGE

MCM_SETSELRANGE
    wParam = 0;
    lParam = (LPARAM)(LPSYSTEMTIME) lprgSysTimeArray;

Sets the selection for a month calendar control to a given date range. You can send this message explicitly or by using the MonthCal_SetSelRange macro.

  • Returns nonzero if successful, or zero otherwise. This message will fail if applied to a month calendar control that does not use the MCS_MULTISELECT style.
lprgSysTimeArray
Address of a two-element array of SYSTEMTIME structures that contain date information representing the selection limits. The first selected date must be specified in lpSysTimeArray[0], and the last selected date must be specified in lpSysTimeArray[1].

Version 4.70

See also Times in the Month Calendar Control


MCM_SETTODAY

MCM_SETTODAY
    wParam = 0;
    lParam = (LPARAM)(LPSYSTEMTIME) lpSysTime;

Sets the "today" selection for a month calendar control. You can send this message explicitly or by using the MonthCal_SetToday macro.

  • The return value for this message is not used.
lpSysTime
Address of a SYSTEMTIME structure that contains the date to be set as the "today" selection for the control. If this parameter is set to NULL, the control returns to the default setting.

If the "today" selection is set to any date other than the default, the following conditions apply:

  • The control will not automatically update the "today" selection when the time passes midnight for the current day.
  • The control will not automatically update its display based on locale changes.

Version 4.70

See also Times in the Month Calendar Control


MCM_SETUNICODEFORMAT

MCM_SETUNICODEFORMAT
    wParam = (WPARAM)(BOOL)fUnicode;
    lParam = 0;

Sets the UNICODE character format flag for the control. This message allows you to change the character set used by the control at run time rather than having to re-create the control. You can send this message explicitly or use the MonthCal_SetUnicodeFormat macro.

  • Returns the previous UNICODE format flag for the control.
fUnicode
Determines the character set that is used by the control. If this value is nonzero, the control will use UNICODE characters. If this value is zero, the control will use ANSI characters.

See also MCM_GETUNICODEFORMAT


Month Calendar Control Macros

This section contains information about the macros used with month calendar controls.

MonthCal_GetColor

MonthCal_GetCurSel

MonthCal_GetFirstDayOfWeek

MonthCal_GetMaxSelCount

MonthCal_GetMaxTodayWidth

MonthCal_GetMinReqRect

MonthCal_GetMonthDelta

MonthCal_GetMonthRange

MonthCal_GetRange

MonthCal_GetSelRange

MonthCal_GetToday

MonthCal_GetUnicodeFormat

MonthCal_HitTest

MonthCal_SetColor

MonthCal_SetCurSel

MonthCal_SetDayState

MonthCal_SetFirstDayOfWeek

MonthCal_SetMaxSelCount

MonthCal_SetMonthDelta

MonthCal_SetRange

MonthCal_SetSelRange

MonthCal_SetToday

MonthCal_SetUnicodeFormat


MonthCal_GetColor

COLORREF MonthCal_GetColor(
    HWND hwndMC,
    INT iColor
);

Retrieves the color for a given portion of a month calendar control. You can use this macro or send the MCM_GETCOLOR message explicitly.

  • Returns a COLORREF value that represents the color setting for the specified portion of the month calendar control if successful. Otherwise, the return is -1.
hwndMC
Handle to a month calendar control.
iColor
INT value specifying which month calendar color to retrieve. This value can be one of the following:
MCSC_BACKGROUND | Retrieve the background color displayed between months.
MCSC_MONTHBK | Retrieve the background color displayed within the month.
MCSC_TEXT | Retrieve the color used to display text within a month.
MCSC_TITLEBK | Retrieve the background color displayed in the calendar's title.
MCSC_TITLETEXT | Retrieve the color used to display text within the calendar's title.
MCSC_TRAILINGTEXT | Retrieve the color used to display header day and trailing day text. Header and trailing days are the days from the previous and following months that appear on the current month calendar.

Version 4.70


MonthCal_GetCurSel

BOOL MonthCal_GetCurSel(
    HWND hwndMC,
    LPSYSTEMTIME lpSysTime
);

Retrieves the currently selected date. You can use this macro or send the MCM_GETCURSEL message explicitly.

  • Returns nonzero if successful, or zero otherwise. This macro will always fail when applied to month calendar controls that are set to the MCS_MULTISELECT style.
hwndMC
Handle to a month calendar control.
lpSysTime
Address of a SYSTEMTIME structure that will receive the currently selected date information. This parameter must be a valid address and cannot be NULL.

Version 4.70


MonthCal_GetFirstDayOfWeek

DWORD MonthCal_GetFirstDayOfWeek(
    HWND hwndMC
);

Retrieves the first day of the week for a month calendar control. You can use this macro or send the MCM_GETFIRSTDAYOFWEEK message explicitly.

  • Returns a DWORD value that contains two values. The high word is a BOOL value that is nonzero if the first day of the week is set to something other than LOCALE_IFIRSTDAYOFWEEK, or zero otherwise. The low word is an INT value that represents the first day of the week. This will be one of the day numbers.
hwndMC
Handle to a month calendar control.

Version 4.70


MonthCal_GetMaxSelCount

DWORD MonthCal_GetMaxSelCount(
    HWND hwndMC
);

Retrieves the maximum date range that can be selected in a month calendar control. You can use this macro or send the MCM_GETMAXSELCOUNT message explicitly.

  • Returns an INT value that represents the total number of days that can be selected for the control.
hwndMC
Handle to a month calendar control.

You can change the maximum date range that can be selected by using the MCM_SETMAXSELCOUNT message.

Version 4.70


MonthCal_GetMaxTodayWidth

DWORD MonthCal_GetMaxTodayWidth(
    HWND hwndMC
);

Retrieves the maximum width of the "today" string in a month calendar control. This includes the label text and the date text. You can use this macro or send the MCM_GETMAXTODAYWIDTH message explicitly.

  • Returns the width of the "today" string, in pixels.
hwndMC
Handle to a month calendar control.

Version 4.70


MonthCal_GetMinReqRect

BOOL MonthCal_GetMinReqRect(
    HWND hwndMC,
    LPRECT lpRectInfo
);

Retrieves the minimum size required to display a full month in a month calendar control. Size information is presented in the form of a RECT structure. You can use this macro or send the MCM_GETMINREQRECT message explicitly.

  • Returns nonzero and lpRectInfo receives the applicable bounding information if successful. Otherwise, the return is zero.
hwndMC
Handle to a month calendar control.
lpRectInfo
Address of a RECT structure that will receive bounding rectangle information. This parameter must be a valid address and cannot be NULL.

The top and left members of lpRectInfo will always be zero. The right and bottom members represent the minimum cx and cy required for the control.

The minimum required window size for a month calendar control depends on the currently selected font.

Version 4.70


MonthCal_GetMonthDelta

INT MonthCal_GetMonthDelta(
    HWND hwndMC
);

Retrieves the scroll rate for a month calendar control. The scroll rate is the number of months that the control moves its display when the user clicks a scroll button. You can use this macro or send the MCM_GETMONTHDELTA message explicitly.

  • If the month delta was previously set using the MonthCal_SetMonthDelta macro, returns an INT value that represents the month calendar's current scroll rate. If the month delta was not previously set using the MonthCal_SetMonthDelta macro, or the month delta was reset to the default, returns an INT value that represents the current number of months visible.
hwndMC
Handle to a month calendar control.

Version 4.70


MonthCal_GetMonthRange

DWORD MonthCal_GetMonthRange(
    HWND hwndMC,
    DWORD dwFlag,
    LPSYSTEMTIME lprgSysTimeArray
);

Retrieves date information (using SYSTEMTIME structures) that represents the high and low limits of a month calendar control's display. You can use this macro or send the MCM_GETMONTHRANGE message explicitly.

  • Returns an INT value that represents the range, in months, spanned by the two limits returned at lprgSysTimeArray.
hwndMC
Handle to a month calendar control.
dwFlag
Value specifying the scope of the range limits to be retrieved. This value must be one of the following:
GMR_DAYSTATE | Include preceding and trailing months of visible range that are only partially displayed.
GMR_VISIBLE | Include only those months that are entirely displayed.
lprgSysTimeArray
Address of a two-element array of SYSTEMTIME structures that will receive the lower and upper limits of the scope specified by dwFlag. The lower and upper limits are placed in lprgSysTimeArray[0] and lprgSysTimeArray[1], respectively. The time members of these structures will not be modified. This parameter must be a valid address and cannot be NULL.

Version 4.70


MonthCal_GetRange

DWORD MonthCal_GetRange(
    HWND hwndMC,
    LPSYSTEMTIME lprgSysTimeArray
);

Retrieves the minimum and maximum allowable dates set for a month calendar control. You can use this macro or send the MCM_GETRANGE message explicitly.

  • Returns a DWORD value that can be zero (no limits are set) or a combination of the following values that specify limit information:
    GDTR_MAX | There is a maximum limit set for the control; lprgSysTimeArray[0] is valid and contains the applicable date information.
    GDTR_MIN | There is a minimum limit set for the control; lprgSysTimeArray[1] is valid and contains the applicable date information.
hwndMC
Handle to a month calendar control.
lprgSysTimeArray
Address of a two-element array of SYSTEMTIME structures that will receive the date limit information. The minimum limit is set in lprgSysTimeArray[0], and lprgSysTimeArray[1] receives the maximum limit. If either element is set to all zeros, then no corresponding limit is set for the month calendar control. The time members of these structures will not be modified. This parameter must be a valid address and cannot be NULL.

Version 4.70


MonthCal_GetSelRange

BOOL MonthCal_GetSelRange(
    HWND hwndMC,
    LPSYSTEMTIME lprgSysTimeArray
);

Retrieves date information that represents the upper and lower limits of the date range currently selected by the user. You can use this macro or send the MCM_GETSELRANGE message explicitly.

  • Returns nonzero if successful, or zero otherwise. MonthCal_GetSelRange will fail if applied to a month calendar control that does not use the MCS_MULTISELECT style.
hwndMC
Handle to a month calendar control.
lprgSysTimeArray
Address of a two-element array of SYSTEMTIME structures that will receive the lower and upper limits of the user's selection. The lower and upper limits are placed in lprgSysTimeArray[0] and lprgSysTimeArray[1], respectively. The time members of these structures will not be modified. This parameter must be a valid address and cannot be NULL.

Version 4.70


MonthCal_GetToday

BOOL MonthCal_GetToday(
    HWND hwndMC,
    LPSYSTEMTIME lpToday
);

Retrieves the date information for the date specified as "today" for a month calendar control. You can use this macro or send the MCM_GETTODAY message explicitly.

  • Returns nonzero if successful, or zero otherwise.
hwndMC
Handle to a month calendar control.
lpToday
Address of a SYSTEMTIME structure that will receive the date information. The time members of this structure will not be modified. This parameter must be a valid address and cannot be NULL.

Version 4.70


MonthCal_GetUnicodeFormat

BOOL MonthCal_GetUnicodeFormat(
    HWND hwnd
);

Retrieves the UNICODE character format flag for the control. You can use this macro or send the MCM_GETUNICODEFORMAT message explicitly.

  • Returns the UNICODE format flag for the control. If this value is nonzero, the control is using UNICODE characters. If this value is zero, the control is using ANSI characters.
hwnd
Handle to the control.

See also MonthCal_SetUnicodeFormat


MonthCal_HitTest

DWORD MonthCal_HitTest(
    HWND hwndMC,
    PMCHITTESTINFO pMCHitTest
);

Determines which portion of a month calendar control is at a given point on the screen. You can use this macro or send the MCM_HITTEST message explicitly.

  • Sets values in members of the MCHITTESTINFO structure at pMCHitTest and returns a DWORD value that contains a set of hit test result flags. See the return value description of MCM_HITTEST for a list of the hit test result flags.

    The uHit member of the MCHITTESTINFO structure at pMCHitTest will equal the return value.

hwndMC
Handle to a month calendar control.
pMCHitTest
Address of an MCHITTESTINFO structure. Upon calling the macro, the cbSize member must be set to the size of the MCHITTESTINFO structure, and pt must be set to the point you want to hit test.

Version 4.70


MonthCal_SetColor

COLORREF MonthCal_SetColor(
    HWND hwndMC,
    INT iColor,
    COLORREF clr
);

Sets the color for a given portion of a month calendar control. You can use this macro or send the MCM_SETCOLOR message explicitly.

  • Returns a COLORREF value that represents the previous color setting for the specified portion of the month calendar control if successful. Otherwise, the return is -1.
hwndMC
Handle to a month calendar control.
iColor
INT value specifying which month calendar color to set. This value can be one of the following:
MCSC_BACKGROUND | Retrieve the background color displayed between months.
MCSC_MONTHBK | Retrieve the background color displayed within the month.
MCSC_TEXT | Retrieve the color used to display text within a month.
MCSC_TITLEBK | Retrieve the background color displayed in the calendar's title.
MCSC_TITLETEXT | Retrieve the color used to display text within the calendar's title.
MCSC_TRAILINGTEXT | Retrieve the color used to display header day and trailing day text. Header and trailing days are the days from the previous and following months that appear on the current month calendar.
clr
COLORREF value that represents the color that will be set for the specified area of the month calendar.

Version 4.70


MonthCal_SetCurSel

BOOL MonthCal_SetCurSel(
    HWND hwndMC,
    LPSYSTEMTIME lpSysTime
);

Sets the currently selected date for a month calendar control. If the specified date is not in view, the control updates the display to bring it into view. You can use this macro or send the MCM_SETCURSEL message explicitly.

  • Returns nonzero if successful, or zero otherwise. This macro will fail if applied to a month calendar control that uses the MCS_MULTISELECT style.
hwndMC
Handle to a month calendar control.
lpSysTime
Address of a SYSTEMTIME structure that contains the date to be set as the current selection. The time members of this structure are ignored.

Version 4.70


MonthCal_SetDayState

BOOL MonthCal_SetDayState(
    HWND hwndMC,
    INT iMonths,
    LPMONTHDAYSTATE lpDayStateArray
);

Sets the day states for all months that are currently visible within a month calendar control. You can use this macro or send the MCM_SETDAYSTATE message explicitly.

  • Returns nonzero if successful, or zero otherwise.
hwndMC
Handle to a month calendar control.
iMonths
INT value indicating how many elements are in the array that lpDayStateArray points to.
lpDayStateArray
Address of an array of MONTHDAYSTATE values that define how the month calendar control will draw each day in its display.

The array at lpDayStateArray must contain as many elements as the value returned by the following macro:

MonthCal_GetMonthRange(hwndMC, GMR_DAYSTATE, NULL);

The preceding macro returns the total number of months that are in complete or partial view within the month calendar's display.

Keep in mind that the array at lpDayStateArray must contain MONTHDAYSTATE values that correspond with all months currently in the control's display, in chronological order. This includes the two months only partially displayed before the first month and after the last month. For more information about preparing your array, see Preparing the MONTHDAYSTATE Array.

Version 4.70


MonthCal_SetFirstDayOfWeek

DWORD MonthCal_SetFirstDayOfWeek(
    HWND hwndMC,
    INT iDay
);

Sets the first day of the week for a month calendar control. You can use this macro or send the MCM_SETFIRSTDAYOFWEEK message explicitly.

  • Returns a DWORD value that contains two values. The high word is a BOOL value that is nonzero if the previous first day of the week did not equal LOCALE_IFIRSTDAYOFWEEK, or zero otherwise. The low word is an INT value that represents the previous first day of the week.
hwndMC
Handle to a month calendar control.
iDay
INT value representing which day is to be set as the first day of the week. This value must be one of the day numbers.

If the first day of the week is set to anything other than the default (LOCALE_IFIRSTDAYOFWEEK), the control will not automatically update first-day-of-the-week changes based on locale changes.

Version 4.70


MonthCal_SetMaxSelCount

BOOL MonthCal_SetMaxSelCount(
    HWND hwndMC,
    UINT iMax
);

Sets the maximum number of days that can be selected in a month calendar control. You can use this macro or send the MCM_SETMAXSELCOUNT message explicitly.

  • Returns nonzero if successful, or zero otherwise. This macro will fail if applied to a month calendar control that does not use the MCS_MULTISELECT style.
hwndMC
Handle to a month calendar control.
iMax
INT value that will be set to represent the maximum number of days that can be selected.

Version 4.70


MonthCal_SetMonthDelta

INT MonthCal_SetMonthDelta(
    HWND hwndMC,
    INT iDelta
);

Sets the scroll rate for a month calendar control. The scroll rate is the number of months that the control moves its display when the user clicks a scroll button. You can use this macro or send the MCM_SETMONTHDELTA message explicitly.

  • Returns an INT value that represents the previous scroll rate. If the scroll rate was not previously set, the return value is zero.
hwndMC
Handle to a month calendar control.
iDelta
Value representing the number of months to be set as the control's scroll rate. If this value is zero, the month delta is reset to the default, which is the number of months displayed in the control.

Version 4.70


MonthCal_SetRange

BOOL MonthCal_SetRange(
    HWND hwndMC,
    DWORD fWhichLimit,
    LPSYSTEMTIME lprgSysTimeArray
);

Sets the minimum and maximum allowable dates for a month calendar control. You can use this macro or send the MCM_SETRANGE message explicitly.

  • Returns nonzero if successful, or zero otherwise.
hwndMC
Handle to a month calendar control.
fWhichLimit
Flag values that specify which date limits are being set. This value must be one or both of the following:
GDTR_MAX | The maximum allowable date is being set. The SYSTEMTIME structure at lprgSysTimeArray[1] must contain date information.
GDTR_MIN | The minimum allowable date is being set. The SYSTEMTIME structure at lprgSysTimeArray[0] must contain date information.
lprgSysTimeArray
Address of a two-element array of SYSTEMTIME structures that contain the date limits. The maximum limit must be in lpSysTimeArray[1] if GDTR_MAX is specified, and lpSysTimeArray[0] must contain the minimum limit if GDTR_MIN is specified.

Version 4.70


MonthCal_SetSelRange

BOOL MonthCal_SetSelRange(
    HWND hwndMC,
    LPSYSTEMTIME lprgSysTimeArray
);

Sets the selection for a month calendar control to a given date range. You can use this macro or send the MCM_SETSELRANGE message explicitly.

  • Returns nonzero if successful, or zero otherwise. This macro will fail if applied to a month calendar control that does not use the MCS_MULTISELECT style.
hwndMC
Handle to a month calendar control.
lprgSysTimeArray
Address of a two-element array of SYSTEMTIME structures that contain date information representing the selection limits. The first selected date must be specified in lpSysTimeArray[0], and the last selected date must be specified in lpSysTimeArray[1]. The time members of these structures are ignored.

Version 4.70


MonthCal_SetToday

void MonthCal_SetToday(
    HWND hwndMC,
    LPSYSTEMTIME lpSysTime
);

Sets the "today" selection for a month calendar control. You can use this macro or send the MCM_SETTODAY message explicitly.

hwndMC
Handle to a month calendar control.
lpSysTime
Address of a SYSTEMTIME structure that contains the date to be set as the "today" selection for the control. If this parameter is set to NULL, the control returns to the default setting. The time members of this structure are ignored.

If the "today" selection is set to any date other than the default, the following conditions apply:

  • The control will not automatically update the "today" selection when the time passes midnight for the current day.
  • The control will not automatically update its display based on locale changes.

Version 4.70


MonthCal_SetUnicodeFormat

BOOL MonthCal_SetUnicodeFormat(
    HWND hwnd,
    BOOL fUnicode
);

Sets the UNICODE character format flag for the control. This message allows you to change the character set used by the control at run time rather than having to re-create the control. You can use this macro or send the MCM_SETUNICODEFORMAT message explicitly.

  • Returns the previous UNICODE format flag for the control.
hwnd
Handle to the control.
fUnicode
Determines the character set that is used by the control. If this value is nonzero, the control will use UNICODE characters. If this value is zero, the control will use ANSI characters.

See also MonthCal_GetUnicodeFormat


Month Calendar Control Notification Messages

This section contains information about the notification messages used with month calendar controls.

MCN_GETDAYSTATE

MCN_SELCHANGE

MCN_SELECT

NM_RELEASEDCAPTURE (monthcal)


MCN_GETDAYSTATE

MCN_GETDAYSTATE
    lpNMDayState = (LPNMDAYSTATE) lParam;

Sent by a month calendar control to request information about how individual days should be displayed. This notification message is sent only by month calendar controls that use the MCS_DAYSTATE style, and it is sent in the form of a WM_NOTIFY message.

lpNMDayState
Address of an NMDAYSTATE structure. The structure contains information about the time frame for which the control needs information, and it receives the address of an array that provides this data.

Handling this notification message allows your application to customize its display by specifying that certain days be displayed in bold. For more information about processing this message, see Processing the MCN_GETDAYSTATE Notification Message.

Version 4.70


MCN_SELCHANGE

MCN_SELCHANGE
    lpNMSelChange = (LPNMSELCHANGE) lParam;

Sent by a month calendar control when the currently selected date or range of dates changes. This notification message is sent in the form of a WM_NOTIFY message.

For example, the control sends MCN_SELCHANGE when the user explicitly changes his or her selection within the current month or when the selection is implicitly changed in response to next/previous month navigation.

lpNMSelChange
Address of an NMSELCHANGE structure that contains information about the currently selected date range.

This notification message is similar to MCN_SELECT, but it is sent in response to any selection change. MCN_SELECT is sent only for an explicit date selection.

Version 4.70


MCN_SELECT

MCN_SELECT
    lpNMSelChange = (LPNMSELCHANGE) lParam;

Sent by a month calendar control when the user makes an explicit date selection within a month calendar control. This notification is sent in the form of a WM_NOTIFY message.

lpNMSelChange
Address of an NMSELCHANGE structure that contains information about the currently selected date range.

This notification message is similar to MCN_SELCHANGE, but it is sent only in response to a user's explicit date selections. MCN_SELCHANGE applies to any selection change.

Version 4.70


NM_RELEASEDCAPTURE (monthcal)

NM_RELEASEDCAPTURE
    lpnmh = (LPNMHDR) lParam;

Notifies a monthcal control's parent window that the control is releasing mouse capture. This notification is sent in the form of a WM_NOTIFY message.

  • The control ignores the return value from this notification.
lpnmh
Address of an NMHDR structure that contains additional information about this notification message.

Version 4.71.


Month Calendar Control Structures

This section contains information about the structures used with month calendar controls.

MCHITTESTINFO

NMDAYSTATE

NMSELCHANGE


MCHITTESTINFO

typedef struct {
    UINT       cbSize;
    POINT      pt;
    UINT       uHit;   // An output member
    SYSTEMTIME st;     // An output member
} MCHITTESTINFO, *PMCHITTESTINFO;

Carries information specific to hit-testing points for a month calendar control. This structure is used with the MCM_HITTEST message and the corresponding MonthCal_HitTest macro.

cbSize
Size of this structure, in bytes.
pt
POINT structure that contains information about the point to be hit-tested.
uHit
Output member that receives a bit flag representing the result of the hit-test operation. This value will be one of the following:
MCHT_CALENDARBK | The given point was in the calendar's background.
MCHT_CALENDARDATE | The given point was on a particular date within the calendar. The SYSTEMTIME structure at lpMCHitTest->st is set to the date at the given point.
MCHT_CALENDARDATENEXT | The given point was over a date from the next month (partially displayed at the end of the currently displayed month). If the user clicks here, the month calendar will scroll its display to the next month or set of months.
MCHT_CALENDARDATEPREV | The given point was over a date from the previous month (partially displayed at the end of the currently displayed month). If the user clicks here, the month calendar will scroll its display to the previous month or set of months.
MCHT_CALENDARDAY | The given point was over a day abbreviation ("Fri", for example). The SYSTEMTIME structure at lpMCHitTest->st is set to the corresponding date in the top row.
MCHT_CALENDARWEEKNUM | The given point was over a week number (MCS_WEEKNUMBERS style only). The SYSTEMTIME structure at lpMCHitTest->st is set to the corresponding date in the leftmost column.
MCHT_NOWHERE | The given point was not on the month calendar control, or it was in an inactive portion of the control.
MCHT_TITLEBK | The given point was over the background of a month's title.
MCHT_TITLEBTNNEXT | The given point was over the button at the top right corner of the control. If the user clicks here, the month calendar will scroll its display to the next month or set of months.
MCHT_TITLEBTNPREV | The given point was over the button at the top left corner of the control. If the user clicks here, the month calendar will scroll its display to the previous month or set of months.
MCHT_TITLEMONTH | The given point was in a month's title bar, over a month name.
MCHT_TITLEYEAR | The given point was in a month's title bar, over the year value.
st
SYSTEMTIME structure that receives date and time information specific to the location that was hit-tested.

Version 4.70


NMDAYSTATE

typedef struct tagNMDAYSTATE {
    NMHDR           nmhdr;
    SYSTEMTIME      stStart;
    int             cDayState;
    LPMONTHDAYSTATE prgDayState;
} NMDAYSTATE, FAR * LPNMDAYSTATE;

Carries information required to process the MCN_GETDAYSTATE notification message. All members of this structure are for input, except prgDayState, which the receiving application must set when processing MCN_GETDAYSTATE.

nmhdr
NMHDR structure that contains information about this notification message.
stStart
SYSTEMTIME structure that contains the starting date.
cDayState
INT value specifying the total number of elements that must be in the array at prgDayState.
prgDayState
Address of an array of MONTHDAYSTATE values. This must be set to point to an array that contains as many elements as specified in cDayState. The first element in the array corresponds to the date in stStart.

Version 4.70


NMSELCHANGE

typedef struct tagNMSELCHANGE{
    NMHDR           nmhdr;
    SYSTEMTIME      stSelStart;
    SYSTEMTIME      stSelEnd;
} NMSELCHANGE, FAR * LPNMSELCHANGE;

Carries information required to process the MCN_SELCHANGE notification message.

nmhdr
NMHDR structure that contains information about this notification message.
stSelStart
SYSTEMTIME structure that contains the date for the first day in the user's selection range.
stSelEnd
SYSTEMTIME structure that contains the date for the last day in the user's selection range.

Version 4.70


Month Calendar Control Data Types

This section contains information about the data types used with month calendar controls.

MONTHDAYSTATE


MONTHDAYSTATE

This is a new data type that is defined in Commctrl.h as follows:

typedef DWORD MONTHDAYSTATE, FAR * LPMONTHDAYSTATE;

The MONTHDAYSTATE type is a bit field, where each bit (1 through 31) represents the state of a day in a month. If a bit is on, the corresponding day will be displayed in bold; otherwise it will be displayed with no emphasis.

This data type is used with the MCM_SETDAYSTATE message and the corresponding macro, MonthCal_SetDayState. When MONTHDAYSTATE values are used in reference to months shorter than 31 days, only the needed bits will be accessed.

Version 4.70.


Pager Controls

A pager control is a window container that is used with a window that does not have enough display area to show all of its content. The pager control allows the user to scroll to the area of the window that is not currently in view.

About Pager Controls

Using Pager Controls

Pager Control Reference

About Pager Controls

Microsoft® Internet Explorer Version 4.0 introduces the pager control. This control is useful in situations where a window does not have enough area to display a child window. For example, if your application has a toolbar that is not wide enough to show all of its items, you can assign the toolbar to a pager control and users will be able to scroll to the left or right to access all of the items. You can also create pager controls that scroll vertically.

A window assigned to the pager control is referred to as the contained window.

The following illustration shows a toolbar contained inside of a pager control. The pager control is displayed in red to show what areas of the control are visible.

Note The pager control is implemented in version 4.71 and later of Comctl32.dll.

Using Pager Controls

This section describes how to implement the pager control in your application.

Initializing the Pager Control

To use the pager control, you must call InitCommonControlsEx with the ICC_PAGESCROLLER_CLASS flag set in the dwICC member of the INITCOMMONCONTROLSEX structure.

Creating the Pager Control

Use the CreateWindow or the CreateWindowEx API to create a pager control. The class name for the control is WC_PAGESCROLLER, which is defined in Commctrl.h. The PGS_HORZ style is used to create a horizontal pager, and the PGS_VERT style is used to create a vertical pager. Because this is a child control, the WS_CHILD style should also be used.

Once the pager control is created, you will most likely want to assign a contained window to it. If the contained window is a child window, you should make the child window a child of the pager control so that the size and position will be calculated correctly. You then assign the window to the pager control with the PGM_SETCHILD message. Be aware that this message does not actually change the parent window of the contained window; it simply assigns the contained window. If the contained window is one of the common controls, it must have the CCS_NORESIZE style to prevent the control from attempting to resize itself to the pager control's size.

Processing Pager Control Notifications

At a minimum, it is necessary to process the PGN_CALCSIZE notification. If you don't process this notification and enter a value for the width or height, the scroll arrows in the pager control will not be displayed. This is because the pager control uses the width or height supplied in the PGN_CALCSIZE notification to determine the "ideal" size of the contained window.

The following example demonstrates how to process the PGN_CALCSIZE notification case. In this example, the contained window is a toolbar control that contains an unknown number of buttons at an unknown size. The example shows how to use the TB_GETMAXSIZE message to determine the size of all of the items in the toolbar. The example then places the width of all of the items into the iWidth member of the NMPGCALCSIZE structure passed to the notification.

case PGN_CALCSIZE:
  {
  LPNMPGCALCSIZE   pCalcSize = (LPNMPGCALCSIZE)lParam;

  switch(pCalcSize->dwFlag)
     {
     case PGF_CALCWIDTH:
        {
        SIZE  size;

        //Get the optimum width of the toolbar.
        SendMessage(hwndToolbar, TB_GETMAXSIZE, 0, (LPARAM)&size);
        pCalcSize->iWidth = size.cx;
        }
        break;

     }

  }
  return 0;

Processing the PGN_SCROLL notification is optional. Process this notification if you need to know when a scroll action occurs, need to track the scroll position, or wish to change the scroll delta. To cancel the scroll, simply place zero in the iScroll member of the NMPGSCROLL structure passed to the notification.

The following example shows how to modify the scroll delta.

case PGN_SCROLL:
  {
  LPNMPGSCROLL   pScroll = (LPNMPGSCROLL)lParam;

  switch(pScroll->iDir)
     {
     case PGF_SCROLLLEFT:
     case PGF_SCROLLRIGHT:
     case PGF_SCROLLUP:
     case PGF_SCROLLDOWN:
        pScroll->iScroll = 20;
        break;
     }
  }
  return 0;


Pager Control Reference

This section contains information about the following API elements used with pager controls.

Pager Control Styles

Messages
PGM_FORWARDMOUSE
PGM_GETBKCOLOR
PGM_GETBORDER
PGM_GETBUTTONSIZE
PGM_GETBUTTONSTATE
PGM_GETDROPTARGET
PGM_GETPOS
PGM_RECALCSIZE
PGM_SETBKCOLOR
PGM_SETBORDER
PGM_SETBUTTONSIZE
PGM_SETCHILD
PGM_SETPOS

Utility Macros
Pager_ForwardMouse
Pager_GetBkColor
Pager_GetBorder
Pager_GetButtonSize
Pager_GetButtonState
Pager_GetDropTarget
Pager_GetPos
Pager_RecalcSize
Pager_SetBkColor
Pager_SetBorder
Pager_SetButtonSize
Pager_SetChild
Pager_SetPos

Notifications
NM_RELEASEDCAPTURE (pager)
PGN_CALCSIZE
PGN_SCROLL

Structures
NMPGCALCSIZE
NMPGSCROLL


Pager Control Styles

The following window styles are used when creating pager controls.
PGS_AUTOSCROLL | The pager control will scroll when the user hovers the mouse over one of the scroll buttons.
PGS_DRAGNDROP | The contained window can be a drag-and-drop target. The pager control will automatically scroll if an item is dragged from outside the pager over one of the scroll buttons.
PGS_HORZ | Creates a pager control that can be scrolled horizontally. This style and the PGS_VERT style are mutually exclusive and cannot be combined.
PGS_VERT | Creates a pager control that can be scrolled vertically. This is the default direction if no direction style is specified. This style and the PGS_HORZ style are mutually exclusive and cannot be combined.


Pager Control Messages

This section contains information about the messages used with pager controls.

PGM_FORWARDMOUSE

PGM_GETBKCOLOR

PGM_GETBORDER

PGM_GETBUTTONSIZE

PGM_GETBUTTONSTATE

PGM_GETDROPTARGET

PGM_GETPOS

PGM_RECALCSIZE

PGM_SETBKCOLOR

PGM_SETBORDER

PGM_SETBUTTONSIZE

PGM_SETCHILD

PGM_SETPOS


PGM_FORWARDMOUSE

PGM_FORWARDMOUSE
    wParam = (WPARAM)(BOOL)bForward;
    lParam = 0;

Enables or disables mouse forwarding for the pager control. When mouse forwarding is enabled, the pager control forwards WM_MOUSEMOVE messages to the contained window. You can send this message explicitly or use the Pager_ForwardMouse macro.

  • The return value is not used.
bForward
BOOL value that determines if mouse forwarding is enabled or disabled. If this value is nonzero, mouse forwarding is enabled. If this value is zero, mouse forwarding is disabled.

Version 4.71


PGM_GETBKCOLOR

PGM_GETBKCOLOR
    wParam = 0;
    lParam = 0;

Retrieves the current background color for the pager control. You can send this message explicitly or use the Pager_GetBkColor macro.

  • Returns a COLORREF value that contains the current background color.

By default, the pager control will use the system button face color as the background color. This is the same color that can be retrieved by calling GetSysColor with COLOR_BTNFACE.

Version 4.71


PGM_GETBORDER

PGM_GETBORDER
    wParam = 0;
    lParam = 0;

Retrieves the current border size for the pager control. You can send this message explicitly or use the Pager_GetBorder macro.

  • Returns an INT value that contains the current border size, in pixels.

Version 4.71

See also PGM_SETBORDER


PGM_GETBUTTONSIZE

PGM_GETBUTTONSIZE
    wParam = 0;
    lParam = 0;

Retrieves the current button size for the pager control. You can send this message explicitly or use the Pager_GetButtonSize macro.

  • Returns an INT value that contains the current button size, in pixels.

Version 4.71

See also PGM_SETBUTTONSIZE


PGM_GETBUTTONSTATE

PGM_GETBUTTONSTATE
    wParam = 0;
    lParam = (LPARAM)(int)iButton;

Retrieves the state of the specified button in a pager control. You can send this message explicitly or use the Pager_GetButtonState macro.

  • Returns the state of the button specified in iButton. This will be one of the following values:
    PGF_INVISIBLE | The button is not visible.
    PGF_NORMAL | The button is in normal state.
    PGF_GRAYED | The button is in grayed state.
    PGF_DEPRESSED | The button is in pressed state.
    PGF_HOT | The button is in hot state.
iButton
Indicates which button to retrieve the state for. This can be one of the following values:
PGB_TOPORLEFT | Indicates the top button in a PGS_VERT pager control or the left button in a PGS_HORZ pager control.
PGB_BOTTOMORRIGHT | Indicates the bottom button in a PGS_VERT pager control or the right button in a PGS_HORZ pager control.

Version 4.71


PGM_GETDROPTARGET

PGM_GETDROPTARGET
    wParam = 0;
    lParam = (IDropTarget**)ppDropTarget;

Retrieves a pager control's IDropTarget interface pointer. You can send this message explicitly or use the Pager_GetDropTarget macro.

  • The return value for this message is not used.
ppDropTarget
Address of an IDropTarget pointer that receives the interface pointer. It is the caller's responsibility to call Release on this pointer when it is no longer needed.


PGM_GETPOS

PGM_GETPOS
    wParam = 0;
    lParam = 0;

Retrieves the current scroll position of the pager control. You can send this message explicitly or use the Pager_GetPos macro.

  • Returns an INT value that contains the current scroll position, in pixels.

Version 4.71


PGM_RECALCSIZE

PGM_RECALCSIZE
    wParam = 0;
    lParam = 0;

Forces the pager control to recalculate the size of the contained window. Sending this message will result in a PGN_CALCSIZE notification being sent. You can send this message explicitly or use the Pager_RecalcSize macro.

  • The return value is not used.

Version 4.71


PGM_SETBKCOLOR

PGM_SETBKCOLOR
    wParam = 0;
    lParam = (LPARAM)(COLORREF)clrBk;

Sets the current background color for the pager control. You can send this message explicitly or use the Pager_SetBkColor macro.

  • Returns a COLORREF value that contains the previous background color.
clrBk
COLORREF value that contains the new background color of the pager control.

By default, the pager control will use the system button face color as the background color. This is the same color that can be retrieved by calling GetSysColor with COLOR_BTNFACE.

Version 4.71


PGM_SETBORDER

PGM_SETBORDER
    wParam = 0;
    lParam = (LPARAM)(int)iBorder;

Sets the current border size for the pager control. You can send this message explicitly or use the Pager_SetBorder macro.

  • Returns an INT value that contains the previous border size, in pixels.
iBorder
INT value that contains the new size of the border, in pixels.

Version 4.71


PGM_SETBUTTONSIZE

PGM_SETBUTTONSIZE
    wParam = 0;
    lParam = (LPARAM)(int)iButtonSize;

Sets the current button size for the pager control. You can send this message explicitly or use the Pager_SetButtonSize macro.

  • Returns an INT value that contains the previous button size, in pixels.
iButtonSize
INT value that contains the new button size, in pixels.

If the pager control has the PGS_HORZ style, the button size determines the width of the pager buttons. If the pager control has the PGS_VERT style, the button size determines the height of the pager buttons. By default, the pager control sets its button size to three-fourths of the width of the scroll bar.

Version 4.71

See also PGM_GETBUTTONSIZE


PGM_SETCHILD

PGM_SETCHILD
    wParam = 0;
    lParam = (LPARAM)(HWND)hwndChild;

Sets the contained window for the pager control. This message will not change the parent of the contained window; it only assigns a window handle to the pager control for scrolling. In most cases, the contained window will be a child window. If this is the case, the contained window should be a child of the pager control. You can send this message explicitly or use the Pager_SetChild macro.

  • The return value is not used.
hwndChild
Handle to the window to be contained.

Version 4.71


PGM_SETPOS

PGM_SETPOS
    wParam = 0;
    lParam = (LPARAM)(int)iPos;

Sets the current scroll position for the pager control. You can send this message explicitly or use the Pager_SetPos macro.

  • The return value is not used.
iPos
INT value that contains the new scroll position, in pixels.

Version 4.71


Pager Control Utility Macros

This section contains information about the utility macros used with pager controls.

Pager_ForwardMouse

Pager_GetBkColor

Pager_GetBorder

Pager_GetButtonSize

Pager_GetButtonState

Pager_GetDropTarget

Pager_GetPos

Pager_RecalcSize

Pager_SetBkColor

Pager_SetBorder

Pager_SetButtonSize

Pager_SetChild

Pager_SetPos


Pager_ForwardMouse

VOID Pager_ForwardMouse(
    HWND hwndPager,
    BOOL bForward
);

Enables or disables mouse forwarding for the pager control. When mouse forwarding is enabled, the pager control forwards WM_MOUSEMOVE messages to the contained window. You can use this macro or send the PGM_FORWARDMOUSE message explicitly.

  • The return value is not used.
hwndPager
Handle to the pager control.
bForward
BOOL value that determines if mouse forwarding is enabled or disabled. If this value is nonzero, mouse forwarding is enabled. If this value is zero, mouse forwarding is disabled.

Version 4.71


Pager_GetBkColor

COLORREF Pager_GetBkColor(
    HWND hwndPager
);

Retrieves the current background color for the pager control. You can use this macro or send the PGM_GETBKCOLOR message explicitly.

  • Returns a COLORREF value that contains the current background color.
hwndPager
Handle to the pager control.

By default, the pager control will use the system button face color as the background color. This is the same color that can be retrieved by calling GetSysColor with COLOR_BTNFACE.

Version 4.71


Pager_GetBorder

int Pager_GetBorder(
    HWND hwndPager
);

Retrieves the current border size for the pager control. You can use this macro or send the PGM_GETBORDER message explicitly.

  • Returns an INT value that contains the current border size, in pixels.
hwndPager
Handle to the pager control.

Version 4.71


Pager_GetButtonSize

int Pager_GetButtonSize(
    HWND hwndPager
);

Retrieves the current button size for the pager control. You can use this macro or send the PGM_GETBUTTONSIZE message explicitly.

  • Returns an INT value that contains the current button size, in pixels.
hwndPager
Handle to the pager control.

Version 4.71

See also Pager_SetButtonSize


Pager_GetButtonState

DWORD Pager_GetButtonState(
    HWND hwndPager;
    int iButton
);

Retrieves the state of the specified button in a pager control. You can use this macro or send the PGM_GETBUTTONSTATE message explicitly.

  • Returns the state of the button specified in iButton. See the return value description in PGM_GETBUTTONSTATE for a list of possible values.
hwndPager
Handle to the pager control.
iButton
Indicates which button to retrieve the state for. See the description for iButton in PGM_GETBUTTONSTATE for a list of possible values.

Version 4.71


Pager_GetDropTarget

void Pager_GetDropTarget(
    HWND hwndPager,
    IDropTarget **ppDropTarget
);

Retrieves a pager control's IDropTarget interface pointer. You can use this macro or send the PGM_GETDROPTARGET message explicitly.

hwndPager
Handle to the pager control.
ppDropTarget
Address of an IDropTarget pointer that receives the interface pointer. It is the caller's responsibility to call Release on this pointer when it is no longer needed.


Pager_GetPos

COLORREF Pager_GetPos(
    HWND hwndPager
);

Retrieves the current scroll position of the pager control. You can use this macro or send the PGM_GETPOS message explicitly.

  • Returns an INT value that contains the current scroll position, in pixels.
hwndPager
Handle to the pager control.

Version 4.71


Pager_RecalcSize

COLORREF Pager_RecalcSize(
    HWND hwndPager
);

Forces the pager control to recalculate the size of the contained window. Using this macro will result in a PGN_CALCSIZE notification being sent. You can use this macro or send the PGM_RECALCSIZE message explicitly.

  • The return value is not used.
hwndPager
Handle to the pager control.

Version 4.71


Pager_SetBkColor

COLORREF Pager_SetBkColor(
    HWND hwndPager,
    COLORREF clrBk
);

Sets the current background color for the pager control. You can use this macro or send the PGM_SETBKCOLOR message explicitly.

  • Returns a COLORREF value that contains the previous background color.
hwndPager
Handle to the pager control.
clrBk
COLORREF value that contains the new background color of the pager control.

By default, the pager control will use the system button face color as the background color. This is the same color that can be retrieved by calling GetSysColor with COLOR_BTNFACE.

Version 4.71


Pager_SetBorder

INT Pager_SetBorder(
    HWND hwndPager,
    int iBorder
);

Sets the current border size for the pager control. You can use this macro or send the PGM_SETBORDER message explicitly.

  • Returns an INT value that contains the previous border size, in pixels.
hwndPager
Handle to the pager control.
iBorder
INT value that contains the new size of the border, in pixels.

Version 4.71


Pager_SetButtonSize

int Pager_SetButtonSize(
    HWND hwndPager,
    Int iButtonSize
);

Sets the current button size for the pager control. You can use this macro or send the PGM_SETBUTTONSIZE message explicitly.

  • Returns an INT value that contains the previous button size, in pixels.
hwndPager
Handle to the pager control.
iButtonSize
INT value that contains the new button size, in pixels.

If the pager control has the PGS_HORZ style, the button size determines the width of the pager buttons. If the pager control has the PGS_VERT style, the button size determines the height of the pager buttons. By default, the pager control sets its button size to three-fourths of the width of the scroll bar.

Version 4.71

See also Pager_GetButtonSize


Pager_SetChild

COLORREF Pager_SetChild(
    HWND hwndPager,
    HWND hwndChild
);

Sets the contained window for the pager control. This macro will not change the parent of the contained window; it only assigns a window handle to the pager control for scrolling. In most cases, the contained window will be a child window. If this is the case, the contained window should be a child of the pager control. You can use this macro or send the PGM_SETCHILD message explicitly.

  • The return value is not used.
hwndPager
Handle to the pager control.
hwndChild
Handle to the window to be contained.

Version 4.71


Pager_SetPos

INT Pager_SetPos(
    HWND hwndPager,
    int iPos
);

Sets the scroll position for the pager control. You can use this macro or send the PGM_SETPOS message explicitly.

  • The return value is not used.
hwndPager
Handle to the pager control.
iPos
INT value that contains the new scroll position, in pixels.

Version 4.71


Pager Control Notifications

This section contains information about the notification messages sent by pager controls.

NM_RELEASEDCAPTURE (pager)

PGN_CALCSIZE

PGN_SCROLL


NM_RELEASEDCAPTURE (pager)

NM_RELEASEDCAPTURE
    lpnmh = (LPNMHDR) lParam;

Notifies a pager control's parent window that the control has released the mouse capture. NM_RELEASEDCAPTURE is sent in the form of a WM_NOTIFY message.

  • The return value is ignored by the pager control.
lpnmh
Address of an NMHDR structure that contains additional information about this notification message.


PGN_CALCSIZE

PGN_CALCSIZE
    lpnmcs = (LPNMPGCALCSIZE) lParam;

Notification sent by a pager control to obtain the scrollable dimensions of the contained window. These dimensions are used by the pager control to determine the scrollable size of the contained window. This notification is sent in the form of a WM_NOTIFY message.

  • The return value is ignored.
lpnmcs
Address of an NMPGCALCSIZE structure that contains and receives information about the notification. The dwFlag member of this structure indicates which dimension is being calculated. Depending on the value of dwFlags, you should place the desired dimension in the iWidth or iHeight member of this structure.

Version 4.71


PGN_SCROLL

PGN_SCROLL
    lpnms = (LPNMPGSCROLL) lParam;

Notification sent by a pager control prior to the contained window being scrolled. This notification is sent in the form of a WM_NOTIFY message.

  • The return value is ignored.
lpnms
Address of an NMPGSCROLL structure that contains and receives information about the notification. The iDir member of this structure indicates the direction of the scroll. The iXpos and iYpos members contain the horizontal and vertical position of the contained window prior to the scroll. The iScroll member contains the default scroll delta amount. You can modify this member to a different scroll amount if desired.

Version 4.71


Pager Control Structures

This section contains information about the structures used with pager controls.

NMPGCALCSIZE

NMPGSCROLL


NMPGCALCSIZE

typedef struct {
    NMHDR   hdr;
    DWORD   dwFlag;
    int     iWidth;
    int     iHeight;
}NMPGCALCSIZE, *LPNMPGCALCSIZE;

Contains and receives information that the pager control uses to calculate the scrollable area of the contained window. It is used with the PGN_CALCSIZE notification.

hdr
NMHDR structure that contains information about the notification message.
dwFlag
Value that indicates which dimension is being requested. This will be one of the following values:
PGF_CALCHEIGHT | The height of the scrollable area is being requested. The height must be placed in the iHeight member before returning from the notification.
PGF_CALCWIDTH | The width of the scrollable area is being requested. The width must be placed in the iWidth member before returning from the notification.
iWidth
Receives the desired width of the scrollable area, in pixels.
iHeight
Receives the desired height of the scrollable area, in pixels.

Version 4.71


NMPGSCROLL

typedef struct {
    NMHDR hdr;
    BOOL fwKeys;
    RECT rcParent;
    int  iDir;
    int  iXpos;
    int  iYpos;
    int  iScroll;
}NMPGSCROLL, *LPNMPGSCROLL;

Contains and receives information that the pager control uses when scrolling the contained window. It is used with the PGN_SCROLL notification.

hdr
NMHDR structure that contains information about the notification message.
fwKeys
Modifier keys that are down when the scroll occurs. This can be one or more of the following values:
0 | None of the modifier keys are down.
PGK_SHIFT | The SHIFT key is down.
PGK_CONTROL | The CONTROL key is down.
PGK_MENU | The ALT key is down.
rcParent
Contains the client rectangle of the pager control.
iDir
Value that indicates in which direction the scroll is occurring. This will be one of the following values:
PGF_SCROLLDOWN | The contained window is being scrolled down.
PGF_SCROLLLEFT | The contained window is being scrolled to the left.
PGF_SCROLLRIGHT | The contained window is being scrolled to the right.
PGF_SCROLLUP | The contained window is being scrolled up.
iXpos
Contains the horizontal scroll position of the contained window, in pixels, before the scroll action.
iYpos
Contains the vertical scroll position of the contained window, in pixels, before the scroll action.
iScroll
On entry, contains the default scroll delta in pixels. This member can be modified to contain a different scroll delta amount if desired. This value is always positive, regardless of the scroll direction.

Version 4.71


Progress Bar Control

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 with the system highlight color as an operation progresses. The following illustration shows a progress bar positioned along the bottom of a window.

Progress bar positioned along the bottom of a window.

Using Progress Bars

Progress Bar Control Updates in Internet Explorer

Progress Bar Control Reference

Using 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's 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 as well as 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 messages handled by the window procedure for the PROGRESS_CLASS 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 to the font that the progress bar is currently using to draw text.
WM_PAINT | Draws the progress bar. If the wParam parameter is non-NULL, the control assumes that the value is an HDC and paints using that device context.
WM_SETFONT | Saves the handle to the new font and returns the handle to the previous font.

Progress Bar Example

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 Control Updates in Internet Explorer

Progress bar controls in Microsoft® Internet Explorer support the following new features.

New Progress Bar Control Styles
Progress bar controls can now display progress information vertically, using the PBS_VERTICAL style. Also, a smooth progress mode is supported using the PBS_SMOOTH style. Using the PBS_SMOOTH style causes the control to display a contiguous progress bar instead of a segmented bar.
Extended Range Values
Progress bar controls now support 32-bit range values. To set range values in excess of 65,535, use the PBM_SETRANGE32 message. To retrieve 32-bit range values, use the PBM_GETRANGE message. The progress bar high limit, low limit, and position parameters are signed integers. To make full use of the 32-bit range, set the range to -0x7FFFFFFF to 0x7FFFFFFF and treat the position as a signed integer.
Programmable Colors
An application can now control the colors used in a progress bar control with the PBM_SETBARCOLOR and PBM_SETBKCOLOR messages.


Progress Bar Control Reference

This section contains information about the following programming elements used with progress bar controls.

Progress Bar Control Styles

Messages
PBM_DELTAPOS
PBM_GETPOS
PBM_GETRANGE
PBM_SETBARCOLOR
PBM_SETBKCOLOR
PBM_SETPOS
PBM_SETRANGE
PBM_SETRANGE32
PBM_SETSTEP
PBM_STEPIT

Structures
PBRANGE


Progress Bar Control Styles

Progress bar controls now support control styles. You can set progress bar styles in the same way as other common controls ( CreateWindowEx, GetWindowLong, SetWindowLong). The following are the supported styles:
PBS_SMOOTH | Version 4.70. The progress bar displays progress status in a smooth scrolling bar instead of the default segmented bar.
PBS_VERTICAL | Version 4.70. The progress bar displays progress status vertically, from bottom to top.


Progress Bar Control Messages

This section includes information about the messages used with progress bar controls.

PBM_DELTAPOS

PBM_GETPOS

PBM_GETRANGE

PBM_SETBARCOLOR

PBM_SETBKCOLOR

PBM_SETPOS

PBM_SETRANGE

PBM_SETRANGE32

PBM_SETSTEP

PBM_STEPIT


PBM_DELTAPOS

PBM_DELTAPOS
    wParam = (WPARAM) nIncrement
    lParam = 0;

Advances the current position of a progress bar by a specified increment and redraws the bar to reflect the new position.

  • Returns the previous position.
nIncrement
Amount to advance the position.


PBM_GETPOS

PBM_GETPOS
    wParam = 0;
    lParam = 0;

Retrieves the current position of the progress bar.

  • Returns a UINT value that represents the current position of the progress bar.

Version 4.70


PBM_GETRANGE

PBM_GETRANGE
    wParam = (WPARAM)(BOOL) fWhichLimit;
    lParam = (LPARAM)(PPBRANGE) ppBRange;

Retrieves information about the current high and low limits of a given progress bar control.

  • Returns an INT that represents the limit value specified by fWhichLimit. If lParam is not NULL, lParam must point to a PBRANGE structure that is to be filled with both limit values.
fWhichLimit
Flag value specifying which limit value is to be used as the message's return value. This parameter can be one of the following values:
TRUE | Return the low limit.
FALSE | Return the high limit.
ppBRange
Address of a PBRANGE structure that is to be filled with the high and low limits of the progress bar control. If this parameter is set to NULL, the control will return only the limit specified by fWhichLimit.

Version 4.70


PBM_SETBARCOLOR

PBM_SETBARCOLOR
    wParam = 0;
    lParam = (LPARAM)(COLORREF)clrBar;

Sets the color of the progress indicator bar in the progress bar control.

  • Returns the previous progress indicator bar color, or CLR_DEFAULT if the progress indicator bar color is the default color.
clrBar
COLORREF value that specifies the new progress indicator bar color. Specify the CLR_DEFAULT value to cause the progress bar to use its default progress indicator bar color.

Version 4.71


PBM_SETBKCOLOR

PBM_SETBKCOLOR
    wParam = 0;
    lParam = (LPARAM)(COLORREF)clrBk;

Sets the background color in the progress bar.

  • Returns the previous background color, or CLR_DEFAULT if the background color is the default color.
clrBk
COLORREF value that specifies the new background color. Specify the CLR_DEFAULT value to cause the progress bar to use its default background color.

Version 4.71


PBM_SETPOS

PBM_SETPOS
    wParam = (WPARAM) nNewPos;
    lParam = 0;

Sets the current position for a progress bar and redraws the bar to reflect the new position.

  • Returns the previous position.
nNewPos
Signed integer that becomes the new position.


PBM_SETRANGE

PBM_SETRANGE
    wParam = 0;
    lParam = MAKELPARAM(nMinRange, nMaxRange);

Sets the minimum and maximum values for a progress bar and redraws the bar to reflect the new range.

  • 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.
nMinRange
Minimum range value. By default, the minimum value is zero.
nMaxRange
Maximum range value. By default, the maximum value is 100.


PBM_SETRANGE32

PBM_SETRANGE32
    wParam = (WPARAM)(int) iLowLim;
    lParam = (LPARAM)(int) iHighLim;

Sets the range of a progress bar control to a 32-bit value.

  • Returns a DWORD value that holds the previous 16-bit low limit in its low word and the previous 16-bit high limit in its high word. If the previous ranges were 32-bit values, the return value consists of the low words of both 32-bit limits.
iLowLim
A signed integer that represents the low limit to be set for the progress bar control.
iHighLim
A signed integer that represents the high limit to be set for the progress bar control.

To retrieve the entire high and low 32-bit values, use the PBM_GETRANGE message.

Version 4.70


PBM_SETSTEP

PBM_SETSTEP
    wParam = (WPARAM) nStepInc;
    lParam = 0;

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.

  • Returns the previous step increment.
nStepInc
New step increment.


PBM_STEPIT

PBM_STEPIT
    wParam = 0;
    lParam = 0;

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.

  • Returns the previous position.

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.


Progress Bar Control Structures

This section contains information about the structure used with progress bar controls.

PBRANGE


PBRANGE

typedef struct {
    int iLow;
    int iHigh;
} PBRANGE, *PPBRANGE;

Contains information about the high and low limits of a progress bar control. This structure is used with the PBM_GETRANGE message.

iLow
Low limit for the progress bar control. This is a signed integer.
iHigh
High limit for the progress bar control. This is a signed integer.

Version 4.70


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.

About Property Sheets

Using Property Sheets

Property Sheet Updates in Internet Explorer

Property Sheet Reference

About Property Sheets

This document assumes that you have a thorough understanding of dialog box templates and dialog box procedures. If you don't, you should read the "Dialog Boxes" chapter in the Platform SDK before continuing with this overview chapter.

To implement property sheets in your application, include the Prsht.h header file in your project. Prsht.h contains all of the identifiers used with 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 used 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 clicks 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 clicks the OK, Cancel, Apply Now, or Help button. The notifications are sent in the form of WM_NOTIFY messages. The lParam parameter is the address of an NMHDR structure that includes the window handle to the property sheet dialog box.

Some notification messages require a page to return either TRUE or FALSE in response to the WM_NOTIFY message. To do this, the page 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 it 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 to 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.

The minimum size for a property sheet page is 212 dialog units horizontally and 114 dialog units vertically. If a page dialog is smaller than this, the page will be enlarged until it meets the minimum size. The Prsht.h header file contains three sets of recommended sizes for property sheet pages. PROP_SM_CXDLG and PROP_SM_CYDLG define the recommended dimensions for a small property sheet page. PROP_MED_CXDLG and PROP_MED_CYDLG define the recommended dimensions for a medium-sized property sheet page. PROP_LG_CXDLG and PROP_LG_CYDLG define the recommended dimensions for a large property sheet page. Prsht.h also contains recommended dimensions for property sheet wizard pages. See Wizard Property Sheets for an explanation of these dimensions. Using these recommended sizes will help ensure visual consistency between your application and other Microsoft® Windows® applications.

Use the following values to set the sizes of the elements in your property sheet pages:

PROP_SM_CXDLG | Width, in dialog units, of a small property sheet page.
PROP_SM_CYDLG | Height, in dialog units, of a small property sheet page.
PROP_MED_CXDLG | Width, in dialog units, of a medium-sized property sheet page.
PROP_MED_CYDLG | Height, in dialog units, of a medium-sized property sheet page.
PROP_LG_CXDLG | Width, in dialog units, of a large property sheet page.
PROP_LG_CYDLG | Height, in dialog units, of a large property sheet 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 to 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 the address of an array of HPROPSHEETPAGE handles. When PropertySheet creates the property sheet, it includes the pages identified in the array. The pages appear in the property sheet in the same order that they are contained in the array.

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 is the address of 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. You 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 clicks 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 clicking the OK button causes the property sheet to be destroyed after the changes are applied.

When the user clicks 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 selection 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 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 clicks the Apply Now or Cancel button, the page should reinitialize its controls and then send the PSM_UNCHANGED message to again disable 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 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 PSN_RESET notification message to all pages when the user clicks 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, PSWIZB_FINISH, and PSWIZB_DISABLEDFINISH 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.

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 Windows 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 clicks the Back, Next, or Finish button.

When the user clicks the Back or Next button, the property sheet 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 to 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 by name.

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

This section contains examples that demonstrate how to create a property sheet and process 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 to 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 to the property sheet dialog box, the handle to 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 Updates in Internet Explorer

Property sheets in Microsoft® Internet Explorer support the following new features.

New Notification
The PSN_GETOBJECT notification has been added to allow a page to be an OLE drop target.
Updated Structures
The PROPSHEETHEADER and PROPSHEETPAGE structures have been updated to support new features. See the references for these structures for more information.


Property Sheet Reference

This section contains information about the following programming elements used with property sheets.

Functions
AddPropSheetPageProc
CreatePropertySheetPage
DestroyPropertySheetPage
ExtensionPropSheetPageProc
PropertySheet
PropSheetPageProc
PropSheetProc

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

Utility Macros
PropSheet_AddPage
PropSheet_Apply
PropSheet_CancelToClose
PropSheet_Changed
PropSheet_GetCurrentPageHwnd
PropSheet_GetTabControl
PropSheet_IsDialogMessage
PropSheet_PressButton
PropSheet_QuerySiblings
PropSheet_RebootSystem
PropSheet_RemovePage
PropSheet_RestartWindows
PropSheet_SetCurSel
PropSheet_SetCurSelByID
PropSheet_SetFinishText
PropSheet_SetTitle
PropSheet_SetWizButtons
PropSheet_UnChanged

Notifications
PSN_APPLY
PSN_GETOBJECT
PSN_HELP
PSN_KILLACTIVE
PSN_QUERYCANCEL
PSN_RESET
PSN_SETACTIVE
PSN_WIZBACK
PSN_WIZFINISH
PSN_WIZNEXT

Structures
PROPSHEETHEADER
PROPSHEETPAGE
PSHNOTIFY


Property Sheet Functions

This section contains information about the functions used with property sheets.

AddPropSheetPageProc

CreatePropertySheetPage

DestroyPropertySheetPage

ExtensionPropSheetPageProc

PropertySheet

PropSheetPageProc

PropSheetProc


AddPropSheetPageProc

BOOL CALLBACK AddPropSheetPageProc(
    HPROPSHEETPAGE hpage,
    LPARAM lParam
);

Specifies an application-defined callback function that a property sheet extension uses to add a page to a property sheet.

  • Returns TRUE if successful, or FALSE otherwise.
hpage
Handle to a property sheet page.
lParam
Application-defined 32-bit value.


CreatePropertySheetPage

HPROPSHEETPAGE CreatePropertySheetPage(
    LPCPROPSHEETPAGE lppsp
);

Creates a new page for a property sheet.

  • Returns the handle to the new property sheet if successful, or NULL otherwise.
lppsp
Address of a PROPSHEETPAGE structure that defines a page to be included in a property sheet.

An application uses the PropertySheet function to create a property sheet that includes the new page, or it uses the PSM_ADDPAGE message to add the new page to an existing property sheet.

Windows 95: The system can support a maximum of 16,364 window handles.


DestroyPropertySheetPage

BOOL DestroyPropertySheetPage(
    HPROPSHEETPAGE hPSPage
);

Destroys a property sheet page. An application must call this function for pages that have not been passed to the PropertySheet function.

  • Returns nonzero if successful, or zero otherwise.
hPSPage
Handle to the property sheet page to delete.


ExtensionPropSheetPageProc

BOOL CALLBACK ExtensionPropSheetPageProc(
    LPVOID lpv,
    LPFNADDPROPSHEETPAGE lpfnAddPropSheetPageProc,
    LPARAM lParam
);

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

  • Returns nonzero if successful, or zero otherwise.
lpv
Address of an application-defined value that describes an item for which a property sheet page is to be created. This parameter can be NULL.
lpfnAddPropSheetPageProc
Address of 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.


PropertySheet

int PropertySheet(
    LPCPROPSHEETHEADER lppsph
);

Creates a property sheet and adds the pages defined in the specified property sheet header structure.

  • 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 to the property sheet dialog.

    The following return values have a special 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.

    To get extended error information, call GetLastError.

lppsph
Address of a PROPSHEETHEADER structure that defines the frame and pages of a property sheet.

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 to 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 clicks the OK or Cancel button, PSM_GETCURRENTPAGEHWND returns NULL, and you can then use the DestroyWindow function to destroy the dialog.


PropSheetPageProc

UINT CALLBACK PropSheetPageProc(
    HWND hwnd,
    UINT uMsg,
    LPPROPSHEETPAGE ppsp
);

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.

  • The return value depends on the value of uMsg.
hwnd
Reserved; must be NULL.
uMsg
Action flag. This parameter can be one of the following values:
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
Address of a PROPSHEETPAGE structure that defines the page being created or destroyed.

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.


PropSheetProc

int CALLBACK PropSheetProc(
    HWND hwndDlg,
    UINT uMsg,
    LPARAM lParam
);

An application-defined callback function that the system calls when the property sheet is being created and initialized.

  • Returns zero.
hwndDlg
Handle to the property sheet dialog box.
uMsg
Message being received. This parameter is one of the following values:
PSCB_INITIALIZED | Indicates that the property sheet is being initialized. The lParam value is zero for this message.
PSCB_PRECREATE | Indicates that the property sheet is about to be created. The hwndDlg parameter is NULL, and the lParam parameter is the address of a dialog template in memory. This template is in the form of a DLGTEMPLATE structure followed by one or more DLGITEMTEMPLATE structures.
lParam
Additional information about the message. The meaning of this value depends on the uMsg parameter.

To enable a PropSheetProc callback function, use the PROPSHEETHEADER structure when you call the PropertySheet function to create the property sheet. Use the pfnCallback member to specify an address of the callback function, and set the PSP_USECALLBACK flag in the dwFlags member.

PropSheetProc is a placeholder for the application-defined function name. The PFNPROPSHEETCALLBACK type is the address of a PropSheetProc callback function.


Property Sheet Messages

This section contains information about the messages used with property sheets.

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


PSM_ADDPAGE

PSM_ADDPAGE
    wParam = 0;
    lParam = (LPARAM) (HPROPSHEETPAGE) hpage;

Adds a new page to the end of an existing property sheet. You can send this message explicitly or by using the PropSheet_AddPage macro.

  • No return value.
hpage
Handle to the page to add. The page must have been created by a previous call to the CreatePropertySheetPage function.

The new page should be no larger than the largest page currently in the property sheet because the property sheet is not resized to fit the new page.


PSM_APPLY

PSM_APPLY
    wParam = 0;
    lParam = 0;

Simulates the selection 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. You can send the PSM_APPLY message explicitly or by using the PropSheet_Apply macro.

  • Returns TRUE if all pages successfully applied the changes, or FALSE otherwise.


PSM_CANCELTOCLOSE

PSM_CANCELTOCLOSE
    wParam = 0;
    lParam = 0;

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. You can send this message explicitly or by using the PropSheet_CancelToClose macro.

  • No return value.


PSM_CHANGED

PSM_CHANGED
    wParam = (WPARAM) (HWND) hwndPage;
    lParam = 0;

Informs a property sheet that information in a page has changed. The property sheet enables the Apply Now button. You can send this message explicitly or by using the PropSheet_Changed macro.

  • No return value.
hwndPage
Handle to the page that has changed.


PSM_GETCURRENTPAGEHWND

PSM_GETCURRENTPAGEHWND
    wParam = 0;
    lParam = 0;

Retrieves a handle to the window of the current page of a property sheet. You can send this message explicitly or by using the PropSheet_GetCurrentPageHwnd macro.

  • Returns a handle to the window of the current property sheet page.

Use the PSM_GETCURRENTPAGEHWND message with modeless property sheets to determine when to destroy the dialog box. When the user clicks the OK or Cancel button, PSM_GETCURRENTPAGEHWND returns NULL, and you can then use the DestroyWindow function to destroy the dialog box.

See also PropertySheet


PSM_GETTABCONTROL

PSM_GETTABCONTROL
    wParam = 0;
    lParam = 0;

Retrieves the handle to the tab control of a property sheet. You can send this message explicitly or by using the PropSheet_GetTabControl macro.

  • Returns the handle to the tab control.


PSM_ISDIALOGMESSAGE

PSM_ISDIALOGMESSAGE
    wParam = 0;
    lParam = (LPARAM)pMsg;

Passes a message to a property sheet dialog box and indicates whether the dialog box processed the message. You can send this message explicitly or by using the PropSheet_IsDialogMessage macro.

  • Returns TRUE if the message has been processed, or FALSE if the message has not been processed.
pMsg
Address of an MSG structure that contains the message to be checked.

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 PropertySheet


PSM_PRESSBUTTON

PSM_PRESSBUTTON
    wParam = (WPARAM) (int) iButton;
    lParam = 0;

Simulates the selection of a property sheet button. You can send this message explicitly or by using the PropSheet_PressButton macro.

  • No return value.
iButton
Index of the button to select. This parameter can be one of the following values:
PSBTN_APPLYNOW | Selects the Apply Now button.
PSBTN_BACK | Selects the Back button.
PSBTN_CANCEL | Selects the Cancel button.
PSBTN_FINISH | Selects the Finish button.
PSBTN_HELP | Selects the Help button.
PSBTN_NEXT | Selects the Next button.
PSBTN_OK | Selects the OK button.


PSM_QUERYSIBLINGS

PSM_QUERYSIBLINGS
    wParam = (WPARAM) param1;
    lParam = (LPARAM) param2;

Sent to a property sheet, which then forwards the message to each of its pages. If a page returns a nonzero value, the property sheet does not send the message to subsequent pages. You can send this message explicitly or by using the PropSheet_QuerySiblings macro.

  • Returns the nonzero value from a page in the property sheet, or zero if no page returns a nonzero value.
param1
First application-defined parameter.
param2
Second application-defined parameter.


PSM_REBOOTSYSTEM

PSM_REBOOTSYSTEM
    wParam = 0;
    lParam = 0;

Indicates 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. You can send the PSM_REBOOTSYSTEM message explicitly or by using the PropSheet_RebootSystem macro.

  • No return value.

This message causes the PropertySheet function to return the ID_PSREBOOTSYSTEM value, but only if the user clicks 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.


PSM_REMOVEPAGE

PSM_REMOVEPAGE
    wParam = (WPARAM) (int) index;
    lParam = (LPARAM) (HPROPSHEETPAGE) hpage);

Removes a page from a property sheet. You can send this message explicitly or by using the PropSheet_RemovePage macro.

  • No return value.
index and hpage
Zero-based index of the page and the handle to the page to remove, respectively. An application can specify the index or the handle, or both. If both are specified, hpage takes precedence.


PSM_RESTARTWINDOWS

PSM_RESTARTWINDOWS
    wParam = 0;
    lParam = 0;

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. You can send the PSM_RESTARTWINDOWS message explicitly or by using the PropSheet_RestartWindows macro.

  • No return value.

This message causes the PropertySheet function to return the ID_PSRESTARTWINDOWS value, but only if the user clicks 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.


PSM_SETCURSEL

PSM_SETCURSEL
    wParam = (WPARAM) (int) index;
    lParam = (LPARAM) (HPROPSHEETPAGE) hpage;

Activates the specified page in a property sheet. You can send this message explicitly or by using the PropSheet_SetCurSel macro.

  • Returns TRUE if successful, or FALSE otherwise.
index and hpage
The zero-based index of the page and the handle to the page to activate, respectively. An application can specify the index or the handle, or both. If both are specified, hpage takes precedence.

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.


PSM_SETCURSELID

PSM_SETCURSELID
    wParam = 0;
    lParam = (LPARAM) (int) id;

Activates the given page in a property sheet based on the resource identifier of the page. You can send this message explicitly or by using the PropSheet_SetCurSelByID macro.

  • Returns TRUE if successful, or FALSE otherwise.
id
Resource identifier of the page to activate.

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.


PSM_SETFINISHTEXT

PSM_SETFINISHTEXT
    wParam = 0;
    lParam = (LPARAM) (LPSTR) lpszText;

Sets the text of the Finish button in a wizard property sheet, shows and enables the button, and hides the Next and Back buttons. You can send this message explicitly or by using the PropSheet_SetFinishText macro.

  • No return value.
lpszText
Address of the new text for the Finish button.

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.


PSM_SETTITLE

PSM_SETTITLE
    wParam = (WPARAM) (DWORD) dwStyle
    lParam = (LPARAM) (LPCSTR) lpszText;

Sets the title of a property sheet. You can send this message explicitly or by using the PropSheet_SetTitle macro.

  • No return value.
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
Address of 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.


PSM_SETWIZBUTTONS

PSM_SETWIZBUTTONS
    wParam = 0;
    lParam = (LPARAM) (DWORD) dwFlags;

Enables or disables the Back, Next, and Finish buttons in a wizard property sheet. You can send or post this message explicitly to a wizard property sheet, or you can use the PropSheet_SetWizButtons macro to post the message.

  • No return value.
dwFlags
Buttons to display and enable. A wizard property sheet displays the Back button and either the Next or Finish button. This parameter can include the PSWIZB_BACK flag, which enables the Back button, and one of the following flags:
PSWIZB_NEXT | Enables the Next button.
PSWIZB_FINISH | Displays an enabled Finish button in place of the Next button.
PSWIZB_DISABLEDFINISH | Displays a disabled Finish button in place of the Next button.

If you send the PSM_SETWIZBUTTONS message during your handling of the PSN_SETACTIVE notification message, use the PostMessage function rather than the SendMessage function. Otherwise, the system will not update the buttons properly. At any other time, you can use SendMessage to send PSM_SETWIZBUTTONS.


PSM_UNCHANGED

PSM_UNCHANGED
    wParam = (WPARAM) (HWND) hwndPage;
    lParam = 0;

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. You can send this message explicitly or by using the PropSheet_UnChanged macro.

  • No return value.
hwndPage
Handle to the page that has reverted to the previously saved state.


Property Sheet Macros

This section contains information about the macros used with property sheets.

PropSheet_AddPage

PropSheet_Apply

PropSheet_CancelToClose

PropSheet_Changed

PropSheet_GetCurrentPageHwnd

PropSheet_GetTabControl

PropSheet_IsDialogMessage

PropSheet_PressButton

PropSheet_QuerySiblings

PropSheet_RebootSystem

PropSheet_RemovePage

PropSheet_RestartWindows

PropSheet_SetCurSel

PropSheet_SetCurSelByID

PropSheet_SetFinishText

PropSheet_SetTitle

PropSheet_SetWizButtons

PropSheet_UnChanged


PropSheet_AddPage

BOOL PropSheet_AddPage(
    HWND hPropSheetDlg,
    HPROPSHEETPAGE hpage
);

Adds a new page to the end of an existing property sheet. You can use this macro or send the PSM_ADDPAGE message explicitly.

  • No return value.
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.

The new page should be no larger than the largest page currently in the property sheet because the property sheet is not resized to fit the new page.


PropSheet_Apply

BOOL PropSheet_Apply(
    HWND hPropSheetDlg
);

Simulates the selection 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. You can use this macro or send the PSM_APPLY message explicitly.

  • Returns TRUE if all pages successfully applied the changes, or FALSE otherwise.
hPropSheetDlg
Handle to the property sheet.


PropSheet_CancelToClose

VOID PropSheet_CancelToClose(
    HWND hPropSheetDlg
);

Disables the Cancel button and changes the text of the OK button to "Close." An application sends the PSM_CANCELTOCLOSE message after applying a change that cannot be canceled. You can use this macro or send the PSM_CANCELTOCLOSE message explicitly.

  • No return value.
hPropSheetDlg
Handle to the property sheet.


PropSheet_Changed

BOOL PropSheet_Changed(
    HWND hPropSheetDlg,
    HWND hwndPage
);

Informs a property sheet that information in a page has changed. The property sheet enables the Apply Now button. You can use this macro or send the PSM_CHANGED message explicitly.

  • No return value.
hPropSheetDlg
Handle to the property sheet.
hwndPage
Handle to the page that has changed.


PropSheet_GetCurrentPageHwnd

HWND PropSheet_GetCurrentPageHwnd(
    HWND hDlg
);

Retrieves a handle to the window of the current page of a property sheet. You can use this macro or send the PSM_GETCURRENTPAGEHWND message explicitly.

  • Returns a handle to the window of the current property sheet page.
hDlg
Handle to the property sheet.

Use the PropSheet_GetCurrentPageHwnd macro with modeless property sheets to determine when to destroy the dialog box. When the user clicks the OK or Cancel button, PropSheet_GetCurrentPageHwnd returns NULL, and you can then use the DestroyWindow function to destroy the dialog box.

See also PropertySheet


PropSheet_GetTabControl

HWND PropSheet_GetTabControl(
    HWND hPropSheetDlg
);

Retrieves the handle to the tab control of a property sheet. You can use this macro or send the PSM_GETTABCONTROL message explicitly.

  • Returns the handle to the tab control.
hPropSheetDlg
Handle to the property sheet.


PropSheet_IsDialogMessage

BOOL PropSheet_IsDialogMessage(
    HWND hDlg,
    LPMSG pMsg
);

Passes a message to a property sheet dialog box and indicates whether the dialog box processed the message. You can use this macro or send the PSM_ISDIALOGMESSAGE message explicitly.

  • Returns TRUE if the macro has been processed, or FALSE if the macro has not been processed.
hDlg
Handle to the property sheet.
pMsg
Address of an MSG structure that contains the message to be checked.

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 PSM_ISDIALOGMESSAGE message was processed, it must not be passed to the TranslateMessage or DispatchMessage function.

See also PropertySheet


PropSheet_PressButton

BOOL PropSheet_PressButton(
    HWND hPropSheetDlg,
    int iButton
);

Simulates the selection of a property sheet button. You can use this macro or send the PSM_PRESSBUTTON message explicitly.

  • No return value.
hPropSheetDlg
Handle to the property sheet.
iButton
Index of the button to select. This parameter can be one of the following values:
PSBTN_APPLYNOW | Selects the Apply Now button.
PSBTN_BACK | Selects the Back button.
PSBTN_CANCEL | Selects the Cancel button.
PSBTN_FINISH | Selects the Finish button.
PSBTN_HELP | Selects the Help button.
PSBTN_NEXT | Selects the Next button.
PSBTN_OK | Selects the OK button.


PropSheet_QuerySiblings

int PropSheet_QuerySiblings(
    HWND hPropSheetDlg,
    WPARAM param1,
    LPARAM param2
);

Causes a property sheet to send the PSM_QUERYSIBLINGS message to each of its pages. If a page returns a nonzero value, the property sheet does not send the message to subsequent pages. You can use this macro or send the PSM_QUERYSIBLINGS message explicitly.

  • Returns the nonzero value from a page in the property sheet, or zero if no page returns a nonzero value.
hPropSheetDlg
Handle to the property sheet.
param1
First application-defined parameter.
param2
Second application-defined parameter.


PropSheet_RebootSystem

VOID PropSheet_RebootSystem(
    HWND hPropSheetDlg
);

Indicates the system needs to be restarted for the changes to take effect. You can use this macro or send the PSM_REBOOTSYSTEM message explicitly. An application should send the PSM_REBOOTSYSTEM message only in response to the PSN_APPLY or PSN_KILLACTIVE notification message.

  • No return value.
hPropSheetDlg
Handle to the property sheet.

This macro causes the PropertySheet function to return the ID_PSREBOOTSYSTEM value, but only if the user clicks 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 macro supersedes all PropSheet_RebootSystem macros that precede or follow it.

See also PSM_RESTARTWINDOWS


PropSheet_RemovePage

VOID PropSheet_RemovePage(
    HWND hPropSheetDlg,
    int index,
    HPROPSHEETPAGE hpage
);

Removes a page from a property sheet. You can use this macro or send the PSM_REMOVEPAGE message explicitly.

  • No return value.
hPropSheetDlg
Handle to the property sheet.
index and hpage
Zero-based index of the page and the handle to the page to remove, respectively. An application can specify the index or the handle, or both. If both are specified, hpage takes precedence.


PropSheet_RestartWindows

VOID PropSheet_RestartWindows(
    HWND hPropSheetDlg
);

Sends a PSM_RESTARTWINDOWS message indicating that Windows needs to be restarted for changes to take effect. You can use this macro or send the PSM_RESTARTWINDOWS message explicitly. An application should send the PSM_RESTARTWINDOWS message only in response to the PSN_APPLY or PSN_KILLACTIVE notification message.

  • No return value.
hPropSheetDlg
Handle to the property sheet.

The PSM_RESTARTWINDOWS message causes the PropertySheet function to return the ID_PSRESTARTWINDOWS value, but only if the user clicks 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.


PropSheet_SetCurSel

BOOL PropSheet_SetCurSel(
    HWND hPropSheetDlg,
    HPROPSHEETPAGE hpage,
    int index
);

Activates the specified page in a property sheet. You can use this macro or send the PSM_SETCURSEL message explicitly.

  • Returns TRUE if successful, or FALSE otherwise.
hPropSheetDlg
Handle to the property sheet.
index and hpage
Zero-based index of the page and the handle to the page to activate, respectively. An application can specify the index or the handle, or both. If both are specified, hpage takes precedence.

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.


PropSheet_SetCurSelByID

BOOL PropSheet_SetCurSelByID(
    HWND hPropSheetDlg,
    int id
);

Activates the specified page in a property sheet based on the resource identifier of the page. You can use this macro or send the PSM_SETCURSELID message explicitly.

  • Returns TRUE if successful, or FALSE otherwise.
hPropSheetDlg
Handle to the property sheet.
id
Resource identifier of the page to activate.

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.


PropSheet_SetFinishText

VOID PropSheet_SetFinishText(
    HWND hPropSheetDlg,
    LPTSTR lpszText
);

Sets the text of the Finish button in a wizard property sheet, shows and enables the button, and hides the Next and Back buttons. You can use this macro or send the PSM_SETFINISHTEXT message explicitly.

  • No return value.
hPropSheetDlg
Handle to the property sheet.
lpszText
Address of the new text for the Finish button.

This macro causes the DM_SETDEFID message to be sent to the property sheet dialog box. The wParam parameter specifies the identifier of the Finish button.


PropSheet_SetTitle

VOID PropSheet_SetTitle(
    HWND hPropSheetDlg,
    DWORD dwStyle,
    LPTSTR lpszText
);

Sets the title of a property sheet. You can use this macro or send the PSM_SETTITLE message explicitly.

  • No return value.
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
Address of 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.


PropSheet_SetWizButtons

VOID PropSheet_SetWizButtons(
    HWND  hPropSheetDlg,
    DWORD dwFlags
);

Posts the PSM_SETWIZBUTTONS message to a wizard property sheet. The PSM_SETWIZBUTTONS message enables or disables the Back, Next, and Finish buttons in a wizard property sheet. You can use this macro or use the PSM_SETWIZBUTTONS message explicitly.

  • No return value.
hPropSheetDlg
Handle to the property sheet.
dwFlags
Buttons to display and enable. A wizard property sheet displays the Back button and either the Next or Finish button. This parameter can include the PSWIZB_BACK flag, which enables the Back button, and one of the following flags:
PSWIZB_NEXT | Enables the Next button.
PSWIZB_FINISH | Displays an enabled Finish button in place of the Next button.
PSWIZB_DISABLEDFINISH | Displays a disabled Finish button in place of the Next button.


PropSheet_UnChanged

VOID PropSheet_UnChanged(hPropSheetDlg, hwndPage)
    HWND hPropSheetDlg,
    HWND hwndPage
);

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. You can use this macro or send the PSM_UNCHANGED message explicitly.

  • No return value.
hPropSheetDlg
Handle to the property sheet.
hwndPage
Handle to the page that has reverted to the previously saved state.


Property Sheet Notification Messages

This section contains information about the notification messages used with property sheets.

PSN_APPLY

PSN_GETOBJECT

PSN_HELP

PSN_KILLACTIVE

PSN_QUERYCANCEL

PSN_RESET

PSN_SETACTIVE

PSN_WIZBACK

PSN_WIZFINISH

PSN_WIZNEXT


PSN_APPLY

PSN_APPLY
    lppsn = (LPPSHNOTIFY) lParam;

Indicates that the user clicked 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.

  • 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.
lppsn
Address of a PSHNOTIFY structure that contains information about the notification. The lParam member of this structure does not contain any information. The hwndFrom member of the hdr member of this structure contains the handle to the property sheet.

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


PSN_GETOBJECT

PSN_GETOBJECT
    lpnmon = (LPNMOBJECTNOTIFY) lParam;

Sent by a property sheet to request a drop target object when the cursor passes over one of the tab control's buttons.

  • The application processing this notification must return zero.
lpnmon
Address of an NMOBJECTNOTIFY structure that, on entry, contains information about the notification. If this notification is processed, you must insert object information into this structure.

To provide an object, an application must set values in some members of the NMOBJECTNOTIFY structure at lpnmon. The pObject member must be set to a valid object pointer, and the hResult member must be set to a success flag. To comply with COM standards, always increment the object's reference count when providing an object pointer.

If an application does not provide an object, it must set pObject to NULL and hResult to a failure flag.

Version 4.71


PSN_HELP

PSN_HELP
    lppsn = (LPPSHNOTIFY) lParam;

Notifies a page that the user has clicked the Help button. This notification message is sent in the form of a WM_NOTIFY message.

  • No return value.
lppsn
Address of a PSHNOTIFY structure that contains information about the notification. The lParam member of this structure does not contain any information. The hwndFrom member of the hdr member of this structure contains the handle to the property sheet.

An application should display Help information for the page.


PSN_KILLACTIVE

PSN_KILLACTIVE
    lppsn = (LPPSHNOTIFY) lParam;

Notifies a page that it is about to lose activation either because another page is being activated or the user has clicked the OK button. This notification message is sent in the form of a WM_NOTIFY message.

  • Returns TRUE to prevent the page from losing the activation, or FALSE to allow it.
lppsn
Address of a PSHNOTIFY structure that contains information about the notification. The lParam member of this structure does not contain any information. The hwndFrom member of the hdr member of this structure contains the handle to the property sheet.

An application should validate the information 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.


PSN_QUERYCANCEL

PSN_QUERYCANCEL
    lppsn = (LPPSHNOTIFY) lParam;

Indicates the user clicked the Cancel button. This notification message is sent in the form of a WM_NOTIFY message.

  • Returns TRUE to prevent the cancel operation, or FALSE to allow it.
lppsn
Address of a PSHNOTIFY structure that contains information about the notification. The lParam member of this structure does not contain any information. The hwndFrom member of the hdr member of this structure contains the handle to the property sheet.

A property sheet page can use this notification message to ask the user to verify the cancel operation.

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.


PSN_RESET

PSN_RESET
    lppsn = (LPPSHNOTIFY) lParam;

Notifies a page that the user has clicked the Cancel button and the property sheet is about to be destroyed. All changes made since the user last clicked the Apply Now button are canceled. This notification message is sent in the form of a WM_NOTIFY message.

  • No return value.
lppsn
Address of a PSHNOTIFY structure that contains information about the notification. If this notification is in response to the Close button being pressed, the lParam member of this structure will contain a non-zero value. If this notification is in response to the Cancel button being pressed, the lParam member of this structure will contain zero. The hwndFrom member of the hdr member of this structure contains the handle to the property sheet.

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.


PSN_SETACTIVE

PSN_SETACTIVE
    lppsn = (LPPSHNOTIFY) lParam;

Notifies a page that it is about to be activated. This notification message is sent in the form of a WM_NOTIFY message.

  • Returns zero to accept the activation, or -1 to activate the next or the previous page (depending on whether the user clicked the Next or Back button). To set the activation to a particular page, return the resource identifier of the page.
lppsn
Address of a PSHNOTIFY structure that contains information about the notification. The lParam member of this structure does not contain any information. The hwndFrom member of the hdr member of this structure contains the handle to the property sheet.

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


PSN_WIZBACK

PSN_WIZBACK
    lppsn = (LPPSHNOTIFY) lParam;

Notifies a page that the user has clicked the Back button in a wizard property sheet. This notification message is sent in the form of a WM_NOTIFY message.

  • Returns -1 to prevent the property sheet from advancing to the previous page or zero otherwise.
lppsn
Address of a PSHNOTIFY structure that contains information about the notification. The lParam member of this structure does not contain any information. The hwndFrom member of the hdr member of this structure contains the handle to the property sheet.

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.


PSN_WIZFINISH

PSN_WIZFINISH
    lppsn = (LPPSHNOTIFY) lParam;

Notifies a page that the user has clicked the Finish button in a wizard property sheet. This notification message is sent in the form of a WM_NOTIFY message.

  • Returns a nonzero value to prevent the property sheet from being destroyed or zero otherwise.
lppsn
Address of a PSHNOTIFY structure that contains information about the notification. The lParam member of this structure does not contain any information. The hwndFrom member of the hdr member of this structure contains the handle to the property sheet.

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.


PSN_WIZNEXT

PSN_WIZNEXT
    lppsn = (LPPSHNOTIFY) lParam;

Notifies a page that the user has clicked the Next button in a wizard property sheet. This notification message is sent in the form of a WM_NOTIFY message.

  • Returns -1 to prevent the property sheet from advancing to the next page or zero otherwise.
lppsn
Address of a PSHNOTIFY structure that contains information about the notification. The lParam member of this structure does not contain any information. The hwndFrom member of the hdr member of this structure contains the handle to the property sheet.

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.


Property Sheet Structures

This section contains information about the structures used with property sheets.

PROPSHEETHEADER

PROPSHEETPAGE

PSHNOTIFY


PROPSHEETHEADER

typedef struct _PROPSHEETHEADER {
    DWORD dwSize;
    DWORD dwFlags;
    HWND  hwndParent;
    HINSTANCE hInstance;
    union {
        HICON hIcon;
        LPCTSTR pszIcon;
        };
    LPCSTR pszCaption;
    UINT nPages;
    union {
        UINT nStartPage;
        LPCTSTR pStartPage;
        };
    union {
        LPCPROPSHEETPAGE ppsp;
        HPROPSHEETPAGE FAR *phpage;
        };
    PFNPROPSHEETCALLBACK pfnCallback;

#if (_WIN32_IE >= 0x0400)
    union {
        HBITMAP hbmWatermark;
        LPCTSTR pszbmWatermark;
        };
    HPALETTE hplWatermark;
    union {
        HBITMAP hbmHeader;
        LPCSTR pszbmHeader;
        };
#endif
} PROPSHEETHEADER, FAR *LPPROPSHEETHEADER;

Defines the frame and pages of a property sheet.

dwSize
Size, in bytes, of this structure.
dwFlags
Flags that indicate which options to use when creating the property sheet page. This member can be a combination of the following values:
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 set 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_HEADER | Version 4.71. Indicates that a header bitmap will be used. If this value does not include PSH_USEHBMHEADER, the header bitmap is obtained from pszbmHeader. If this value includes PSH_USEHBMHEADER, the header bitmap is obtained from hbmHeader. This flag is ignored if PSH_WIZARD97 is not included.
PSH_MODELESS | Causes the PropertySheet function to create the property sheet as a modeless dialog instead of as a modal dialog. When this flag is set, PropertySheet returns immediately after the dialog is created, and the return value from PropertySheet is the window handle to the property sheet dialog.
PSH_NOAPPLYNOW | Removes the Apply Now button.
PSH_PROPSHEETPAGE | Uses ppsp and ignores phpage when creating the pages for the property sheet.
PSH_PROPTITLE | Displays the string "Properties for", followed by the string specified by pszCaption, in the title bar of the property sheet.
PSH_RTLREADING | Displays the title of the property sheet dialog using right-to-left reading order on Hebrew or Arabic systems.
PSH_STRETCHWATERMARK | Version 4.71. Stretches the bitmap to fit the background of the property sheet instead of tiling the watermark and/or header bitmap. This flag is ignored if PSH_WIZARD97 and PSH_WATERMARK or PSH_HEADER are not included.
PSH_USECALLBACK | Calls the function specified by pfnCallback when initializing the property sheet defined by this structure.
PSH_USEHBMHEADER | Version 4.71. Obtains the header bitmap from hbmHeader instead of pszbmHeader. This flag is ignored if PSH_WIZARD97 and PSH_HEADER are not included.
PSH_USEHBMWATERMARK | Version 4.71. Obtains the watermark bitmap from hbmWatermark instead of pszbmWatermark. This flag is ignored if PSH_WIZARD97 and PSH_WATERMARK are not included.
PSH_USEHICON | Uses hIcon as the small icon in the title bar of the property sheet dialog box.
PSH_USEHPLWATERMARK | Version 4.71. Obtains the HPALETTE for drawing the watermark bitmap and/or header bitmap from hplWatermark instead of using the default palette. This flag is ignored if PSH_WIZARD97 and PSH_WATERMARK or PSH_HEADER are not included.
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_USEPAGELANG | Version 4.71. The language for the property sheet will be taken from the first page's resource.
PSH_USEPSTARTPAGE | Uses pStartPage and ignores nStartPage when displaying the initial page of the property sheet.
PSH_WATERMARK | Version 4.71. Specifies that a watermark bitmap will be used. If this value does not include PSH_USEHBMWATERMARK, the watermark bitmap is obtained from pszbmWatermark. If this value includes PSH_USEHBMWATERMARK, the header bitmap is obtained from hbmWatermark. This flag is ignored if PSH_WIZARD97 is not included.
PSH_WIZARD | Creates a wizard property sheet.
PSH_WIZARD97 | Creates a wizard property sheet that allows a header and/or watermark bitmap to be displayed in the background. This and all Wizard 97-associated flags are not currently implemented.
PSH_WIZARDCONTEXTHELP | Adds a system menu to the wizard property sheet. This flag is ignored if PSH_WIZARD or PSH_WIZARD97 is not included.
PSH_WIZARDHASFINISH | Always displays the Finish button on the wizard. This flag is ignored if PSH_WIZARD or PSH_WIZARD97 is not included.
hwndParent
Handle to the property sheet's owner window.
hInstance
Handle to 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 to the icon to use as the small icon in the title bar of the property sheet dialog box. If dwFlags does not include PSH_USEHICON, 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 address of the string that specifies the name of the icon resource. If dwFlags does not include PSH_USEICONID, 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 address of a string that specifies the title. If dwFlags includes PSH_PROPTITLE, the string "Properties for" is inserted at the beginning of the title.
nPages
Number of elements in the 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 address of a string that specifies the name.
ppsp
Address of an array of PROPSHEETPAGE structures that define the pages in the property sheet. If dwFlags does not include PSH_PROPSHEETPAGE, this member is ignored.
phpage
Address of an array of handles to the property sheet pages. Each handle must have been created by a previous call to the CreatePropertySheetPage function. If dwFlags includes PSH_PROPSHEETPAGE, this member is ignored.
pfnCallback
Address of 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 PSH_USECALLBACK, this member is ignored.
hbmWatermark
Version 4.71. Handle to the watermark bitmap. If dwFlags does not include PSH_USEHBMWATERMARK, this member is ignored.
pszbmWatermark
Version 4.71. Bitmap resource to use as the watermark. This member can specify either the identifier of the bitmap resource or the address of the string that specifies the name of the bitmap resource. If dwFlags includes PSH_USEHBMWATERMARK, this member is ignored.
hplWatermark
Version 4.71. HPALETTE used for drawing the watermark bitmap and/or header bitmap. If dwFlags does not include PSH_USEHPLWATERMARK, this member is ignored.
hbmHeader
Version 4.71. Handle to the header bitmap. If dwFlags does not include PSH_USEHBMHEADER, this member is ignored.
pszbmHeader
Version 4.71. Bitmap resource to use as the header. This member can specify either the identifier of the bitmap resource or the address of the string that specifies the name of the bitmap resource. If dwFlags includes PSH_USEHBMHEADER, this member is ignored.


PROPSHEETPAGE

typedef struct _PROPSHEETPAGE {
    DWORD dwSize;
    DWORD dwFlags;
    HINSTANCE hInstance;
    union {
        LPCSTR pszTemplate;
        LPCDLGTEMPLATE pResource;
        };
    union {
        HICON hIcon;
        LPCSTR pszIcon;
        };
    LPCSTR pszTitle;
    DLGPROC pfnDlgProc;
    LPARAM lParam;
    LPFNPSPCALLBACK pfnCallback;
    UINT FAR * pcRefParent;

#if (_WIN32_IE >= 0x0400)
    LPCTSTR pszHeaderTitle;
    LPCTSTR pszHeaderSubTitle;
#endif
} PROPSHEETPAGE, FAR *LPPROPSHEETPAGE;

This structure defines a page in a property sheet.

dwSize
Size, in bytes, of this structure.
dwFlags
Flags that indicate which options to use when creating the property sheet page. This member can be a combination of the following values:
PSP_DEFAULT | Uses the default meaning for all structure members.
PSP_DLGINDIRECT | Creates the page from the dialog box template in memory pointed to by pResource. The PropertySheet function assumes that the template is in memory that can be written; a read-only template will cause an exception in some versions of Windows.
PSP_HASHELP | Enables the property sheet Help button when this page is active.
PSP_HIDEHEADER | Version 4.71. Causes the wizard property sheet to hide the header area when this page is selected.
PSP_PREMATURE | Causes the page to be created when the property sheet is created. If this flag is not specified, the page will not be created until it is selected the first time.
PSP_RTLREADING | When this page is active, displays the text of pszTitle using right-to-left reading order on Hebrew or Arabic systems.
PSP_USECALLBACK | Calls the function specified by pfnCallback when creating or destroying the property sheet page defined by this structure.
PSP_USEHEADERSUBTITLE | Version 4.71. Displays the text in pszHeaderSubTitle as the subtitle of the header area. This flag is ignored if PSP_HIDEHEADER is included or the dwFlags member of the PROPSHEETHEADER structure does not contain the PSH_WIZARD97 flag.
PSP_USEHEADERTITLE | Version 4.71. Displays the text in pszHeaderTitle as the title of the header area. This flag is ignored if PSP_HIDEHEADER is included or the dwFlags member of the PROPSHEETHEADER structure does not contain the PSH_WIZARD97 flag.
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.
hInstance
Handle to 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.
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 PSP_DLGINDIRECT, this member is ignored.
pResource
Address of a dialog box template in memory. The PropertySheet function assumes that the template is in memory that can be written; a read-only template will cause an exception in some versions of Windows. If dwFlags does not include PSP_DLGINDIRECT, this member is ignored.
hIcon
Handle to the icon to use as the icon in the tab of the page. If dwFlags does not include PSP_USEHICON, this member is ignored.
pszIcon
Icon resource to use as the icon in the tab of the page. This member can specify either the identifier of the icon resource or the address of the string that specifies the name of the icon resource. If dwFlags does not include PSP_USEICONID, 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 address of a string that specifies the title. If dwFlags does not include PSP_USETITLE, this member is ignored.
pfnDlgProc
Address of the dialog box procedure for the page. Because the pages are created as modeless dialogs, the dialog box procedure must not call the EndDialog function.
lParam
Application-defined data.
pfnCallback
Address of 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 PSP_USECALLBACK, this member is ignored.
pcRefParent
Address of the reference count value. If dwFlags does not include PSP_USEREFPARENT, this member is ignored.
pszHeaderTitle
Version 4.71. Title of the header area. This member is ignored if any of the following are true:
  • The dwFlags member of this structure contains PSP_HIDEHEADER.
  • The dwFlags member of this structure does not contain PSP_USEHEADERTITLE.
  • The dwFlags member of the PROPSHEETHEADER structure does not contain PSH_WIZARD97.
pszHeaderSubTitle
Version 4.71. Subtitle of the header area. This member is ignored if any of the following are true:
  • The dwFlags member of this structure contains PSP_HIDEHEADER.
  • The dwFlags member of this structure does not contain PSP_USEHEADERSUBTITLE.
  • The dwFlags member of the PROPSHEETHEADER structure does not contain PSH_WIZARD97.


PSHNOTIFY

typedef struct _PSHNOTIFY {
    NMHDR hdr;
    LPARAM lParam;
} PSHNOTIFY, FAR *LPPSHNOTIFY;

Contains information for the property sheet notification messages.

hdr
Address of an NMHDR structure that contains additional informaiton about the notification.
lParam
Additional information about this notification. See the description of the particular notification message to determine what, if any, information is contained in this member.


Rebar Controls

Rebar controls act as containers for child windows. An application assigns child windows, which are often other controls, to a rebar control band. Rebar controls contain one or more bands, and each band can have any combination of a gripper bar, a bitmap, a text label, and a child window. However, bands cannot contain more than one child window.

About Rebar Controls

Using Rebar Controls

Rebar Control Reference

About Rebar Controls

A rebar control displays the child window over a specified background bitmap. As you dynamically reposition a rebar control band, the rebar control manages the size and position of the child window assigned to that band.

The following illustration shows a rebar control that has two bands. One contains a combo box, and the other contains a transparent toolbar control.

Rebar control with bands containing a combo box and a transparent toolbar control.

Note The rebar control is implemented in version 4.70 and later of Comctl32.dll.

Rebar Bands and Child Windows

An application defines a rebar band's traits by using the RB_INSERTBAND and RB_SETBANDINFO messages. These messages accept the address of a REBARBANDINFO structure as the lParam parameter. The REBARBANDINFO structure members define the traits of a given band. To set a band's traits, set the cbSize member to indicate the size of the structure, in bytes. Then set the fMask member to indicate which structure members your application is filling.

To assign a child window to a band, include the RBBIM_CHILD flag in the fMask member of the REBARBANDINFO structure, and then set the hwndChild member to the child window's handle. Applications can set the minimum allowable width and height of a child window in the cxMinChild and cyMinChild members.

When a rebar control is destroyed, it destroys any child windows assigned to the bands within it. To prevent the control from destroying child windows assigned to its bands, remove the bands by sending the RB_DELETEBAND message, and then reset the parent to another window with the SetParent function before destroying the rebar control.

The Rebar Control User Interface

All rebar control bands can be resized, except those that use the RBBS_FIXEDSIZE style. To resize or change the order of bands within the control, click and drag a band's gripper bar. The rebar control automatically resizes and repositions child windows assigned to its bands. Additionally, you can toggle the size of a band by clicking on the band text, if there is any.

The Rebar Control's Image List

If an application is using an image list with a rebar control, it must send the RB_SETBARINFO message before adding bands to the control. This message accepts the address of a REBARINFO structure as the lParam parameter. Before sending the message, prepare the REBARINFO structure by setting the cbSize member to the size of the structure, in bytes. Then, if the rebar control is going to display images on the bands, set the fMask member to the RBIM_IMAGELIST flag and assign an image list handle to the himl member. If the rebar will not use band images, set fMask to zero.

Rebar Control Message Forwarding

A rebar control forwards all WM_NOTIFY window messages to its parent window. Additionally, a rebar control forwards any messages sent to it from windows assigned to its bands, like WM_CHARTOITEM, WM_COMMAND, and others.

Custom Draw Support

Rebar controls support custom draw functionality. For more information, see About Custom Draw.

Using Rebar Controls

This section gives sample code that demonstrates how to implement a rebar control.

Creating a Rebar Control

An application creates a rebar control by calling the CreateWindowEx function, specifying REBARCLASSNAME as the window class. The application must first register the window class by calling the InitCommonControlsEx function, while specifying the ICC_COOL_CLASSES bit in the accompanying INITCOMMONCONTROLSEX structure.

The following sample creates a rebar control with two bands—one that contains a combo box and another that contains a toolbar. The sample includes the RBS_VARHEIGHT style to allow the control to use variable band height. After creating the rebar control, CreateRebar creates the child windows with calls to two application-defined functions, CreateComboBox and CreateToolbar. Before adding each band, CreateRebar initializes the cbSize member of the REBARBANDINFO structure, as required by the RB_INSERTBAND message. Then it sets the value of the structure's fMask member to reflect which members contain valid data. CreateRebar sets the cyMinChild member for each band to allow for the height of the control within it. The cxMinChild member is zero to allow the user to completely hide the control within a given band.

HWND WINAPI CreateRebar(HWND hwndOwner)
{
   REBARINFO     rbi;
   REBARBANDINFO rbBand;
   RECT          rc;
   HWND   hwndCB, hwndTB, hwndRB;
   DWORD  dwBtnSize;
   INITCOMMONCONTROLSEX icex;

   icex.dwSize = sizeof(INITCOMMONCONTROLSEX);
   icex.dwICC   = ICC_COOL_CLASSES|ICC_BAR_CLASSES;
   InitCommonControlsEx(&icex);

   hwndRB = CreateWindowEx(WS_EX_TOOLWINDOW,
                           REBARCLASSNAME,
                           NULL,
                           WS_CHILD|WS_VISIBLE|WS_CLIPSIBLINGS|
                           WS_CLIPCHILDREN|RBS_VARHEIGHT|CCS_NODIVIDER,
                           0,0,0,0,
                           hwndOwner,
                           NULL,
                           g_hinst,
                           NULL);
   if(!hwndRB)
      return NULL;

   // Initialize and send the REBARINFO structure.
   rbi.cbSize = sizeof(REBARINFO);  // Required when using this struct.
   rbi.fMask  = 0;
   rbi.himl   = (HIMAGELIST)NULL;
   if(!SendMessage(hwndRB, RB_SETBARINFO, 0, (LPARAM)&rbi))
      return NULL;

   // Initialize structure members that both bands will share.
   rbBand.cbSize = sizeof(REBARBANDINFO);  // Required
   rbBand.fMask  = RBBIM_COLORS | RBBIM_TEXT | RBBIM_BACKGROUND |
                   RBBIM_STYLE | RBBIM_CHILD  | RBBIM_CHILDSIZE |
                   RBBIM_SIZE;
   rbBand.fStyle = RBBS_CHILDEDGE | RBBS_FIXEDBMP;
   rbBand.hbmBack= LoadBitmap(g_hinst, MAKEINTRESOURCE(IDB_BACKGRND));

   // Create the combo box control to be added.
   hwndCB = CreateComboBox(hwndRB);

   // Set values unique to the band with the combo box.
   GetWindowRect(hwndCB, &rc);
   rbBand.lpText     = "Combo Box";
   rbBand.hwndChild  = hwndCB;
   rbBand.cxMinChild = 0;
   rbBand.cyMinChild = rc.bottom - rc.top;
   rbBand.cx         = 200;

   // Add the band that has the combo box.
   SendMessage(hwndRB, RB_INSERTBAND, (WPARAM)-1, (LPARAM)&rbBand);

   // Create the toolbar control to be added.
   hwndTB = CreateToolbar(hwndOwner, dwStyle);

   // Get the height of the toolbar.
   dwBtnSize = SendMessage(hwndTB, TB_GETBUTTONSIZE, 0,0);

   // Set values unique to the band with the toolbar.
   rbBand.lpText     = "Tool Bar";
   rbBand.hwndChild  = hwndTB;
   rbBand.cxMinChild = 0;
   rbBand.cyMinChild = HIWORD(dwBtnSize);
   rbBand.cx         = 250;

   // Add the band that has the toolbar.
   SendMessage(hwndRB, RB_INSERTBAND, (WPARAM)-1, (LPARAM)&rbBand);

   return (hwndRB);
}


Rebar Control Reference

This section contains information about the following new or updated API elements used with rebar controls.

Rebar Control Styles

Messages
RB_BEGINDRAG
RB_DELETEBAND
RB_DRAGMOVE
RB_ENDDRAG
RB_GETBANDBORDERS
RB_GETBANDCOUNT
RB_GETBANDINFO
RB_GETBARHEIGHT
RB_GETBARINFO
RB_GETBKCOLOR
RB_GETCOLORSCHEME
RB_GETDROPTARGET
RB_GETPALETTE
RB_GETRECT
RB_GETROWCOUNT
RB_GETROWHEIGHT
RB_GETTEXTCOLOR
RB_GETTOOLTIPS
RB_GETUNICODEFORMAT
RB_HITTEST
RB_IDTOINDEX
RB_INSERTBAND
RB_MAXIMIZEBAND
RB_MINIMIZEBAND
RB_MOVEBAND
RB_SETBANDINFO
RB_SETBARINFO
RB_SETBKCOLOR
RB_SETCOLORSCHEME
RB_SETPALETTE
RB_SETPARENT
RB_SETTEXTCOLOR
RB_SETTOOLTIPS
RB_SETUNICODEFORMAT
RB_SHOWBAND
RB_SIZETORECT

Notifications
NM_CUSTOMDRAW (rebar)
NM_NCHITTEST (rebar)
NM_RELEASEDCAPTURE (rebar)
RBN_AUTOSIZE
RBN_BEGINDRAG
RBN_CHILDSIZE
RBN_DELETEDBAND
RBN_DELETINGBAND
RBN_ENDDRAG
RBN_GETOBJECT
RBN_HEIGHTCHANGE
RBN_LAYOUTCHANGED

Structures
NMRBAUTOSIZE
NMREBAR
NMREBARCHILDSIZE
RBHITTESTINFO
REBARBANDINFO
REBARINFO


Rebar Control Styles

Rebar controls support a variety of control styles in addition to standard window styles.
RBS_AUTOSIZE | Version 4.71. The rebar control will automatically change the layout of the bands when the size or position of the control changes. An RBN_AUTOSIZE notification will be sent when this occurs.
RBS_BANDBORDERS | Version 4.70. The rebar control displays narrow lines to separate adjacent bands.
RBS_DBLCLKTOGGLE | Version 4.71. The rebar band will toggle its maximized or minimized state when the user double-clicks on the band. Without this style, the maximized or minimized state is toggled when the user single-clicks on the band.
RBS_FIXEDORDER | Version 4.70. The rebar control always displays bands in the same order. You can move bands to different rows, but the band order is static.
RBS_REGISTERDROP | Version 4.71. The rebar control generates RBN_GETOBJECT notification messages when an object is dragged over a band in the control. To receive the RBN_GETOBJECT notifications, initialize OLE with a call to OleInitialize or CoInitialize.
RBS_TOOLTIPS | Version 4.70. Not yet supported.
RBS_VARHEIGHT | Version 4.70. The rebar control displays bands at the minimum required height, when possible. Without this style, the rebar control displays all bands at the same height, using the height of the tallest visible band to determine the height of other bands.
RBS_VERTICALGRIPPER | Version 4.71. The size grip will be displayed vertically instead of horizontally in a vertical rebar control. This style is ignored for rebar controls that do not have the CCS_VERT style.


Rebar Control Messages

This section contains information about the messages used with rebar controls.

RB_BEGINDRAG

RB_DELETEBAND

RB_DRAGMOVE

RB_ENDDRAG

RB_GETBANDBORDERS

RB_GETBANDCOUNT

RB_GETBANDINFO

RB_GETBARHEIGHT

RB_GETBARINFO

RB_GETBKCOLOR

RB_GETDROPTARGET

RB_GETCOLORSCHEME

RB_GETPALETTE

RB_GETRECT

RB_GETROWCOUNT

RB_GETROWHEIGHT

RB_GETTEXTCOLOR

RB_GETTOOLTIPS

RB_GETUNICODEFORMAT

RB_HITTEST

RB_IDTOINDEX

RB_INSERTBAND

RB_MAXIMIZEBAND

RB_MINIMIZEBAND

RB_MOVEBAND

RB_SETBANDINFO

RB_SETBARINFO

RB_SETBKCOLOR

RB_SETCOLORSCHEME

RB_SETPALETTE

RB_SETPARENT

RB_SETTEXTCOLOR

RB_SETTOOLTIPS

RB_SETUNICODEFORMAT

RB_SHOWBAND

RB_SIZETORECT


RB_BEGINDRAG

RB_BEGINDRAG
    wParam = (WPARAM)(UINT) uBand;
    lParam = (LPARAM)(DWORD)dwPos;

Puts the rebar control in drag-and-drop mode. This message does not cause a RBN_BEGINDRAG notification to be sent.

  • The return value for this message is not used.
uBand
Zero-based index of the band that the drag-and-drop operation will affect.
dwPos
DWORD value that contains the starting mouse coordinates. The horizontal coordinate is contained in the LOWORD and the vertical coordinate is contained in the HIWORD. If you pass (DWORD)-1, the rebar control will use the position of the mouse the last time the control's thread called GetMessage or PeekMessage.

The RB_BEGINDRAG, RB_DRAGMOVE, and RB_ENDDRAG messages allow you to implement an IDropTarget::DragEnter, send the RB_DRAGMOVE message in response to RB_ENDDRAG message in response to IDropTarget::DragLeave.

Version 4.71


RB_DELETEBAND

RB_DELETEBAND
    wParam = (WPARAM)(UINT) uBand;
    lParam = 0;

Deletes a band from a rebar control.

  • Returns nonzero if successful, or zero otherwise.
uBand
Zero-based index of the band to be deleted.

Version 4.70


RB_DRAGMOVE

RB_DRAGMOVE
    wParam = 0;
    lParam = (LPARAM)(DWORD)dwPos;

Updates the drag position in the rebar control after a previous RB_BEGINDRAG message.

  • The return value for this message is not used.
dwPos
DWORD value that contains the new mouse coordinates. The horizontal coordinate is contained in the LOWORD and the vertical coordinate is contained in the HIWORD. If you pass (DWORD)-1, the rebar control will use the position of the mouse the last time the control's thread called GetMessage or PeekMessage.

Version 4.71

See also RB_ENDDRAG


RB_ENDDRAG

RB_ENDDRAG
    wParam = 0;
    lParam = 0;

Terminates the rebar control's drag-and-drop operation. This message does not cause an RBN_ENDDRAG notification to be sent.

  • The return value for this message is not used.

Version 4.71

See also RB_BEGINDRAG, RB_DRAGMOVE


RB_GETBANDBORDERS

RB_GETBANDBORDERS
    wParam = (WPARAM)(UINT) uBand;
    lParam = (LPARAM)(LPRECT) lprc;

Retrieves the borders of a band. The result of this message can be used to calculate the usable area in a band.

  • The return value is not used.
uBand
Zero-based index of the band for which the borders will be retrieved.
lprc
Address of a RECT structure that will receive the band borders. If the rebar control has the RBS_BANDBORDERS style, each member of this structure will receive the number of pixels, on the corresponding side of the band, that constitute the border. If the rebar control does not have the RBS_BANDBORDERS style, only the left member of this structure receives valid information.

Version 4.71


RB_GETBANDCOUNT

RB_GETBANDCOUNT
    wParam = 0;
    lParam = 0;

Retrieves the count of bands currently in the rebar control.

  • Returns a UINT value that represents the number of bands assigned to the control.

Version 4.70


RB_GETBANDINFO

RB_GETBANDINFO
    wParam = (WPARAM)(UINT) uBand;
    lParam = (LPARAM)(LPREBARBANDINFO) lprbbi;

Retrieves information about a specified band in a rebar control.

  • Returns nonzero if successful, or zero otherwise.
uBand
Zero-based index of the band for which the information will be retrieved.
lprbbi
Address of a REBARBANDINFO structure that will receive the requested band information. Before sending this message, you must set the cbSize member of this structure to the size of the REBARBANDINFO structure and set the fMask parameter to the items you want to retrieve. Additionally, you must set the cch member of the REBARBANDINFO structure to the size of the lpText buffer when RBBIM_TEXT is specified.

Version 4.70

See also RB_SETBANDINFO


RB_GETBARHEIGHT

RB_GETBARHEIGHT
    wParam = 0;
    lParam = 0;

Retrieves the height of the rebar control.

  • Returns a UINT value that represents the height, in pixels, of the control.

Version 4.71


RB_GETBARINFO

RB_GETBARINFO
    wParam = 0;
    lParam = (LPARAM)(LPREBARINFO) lprbi;

Retrieves information about the rebar control and the image list it uses.

  • Returns nonzero if successful, or zero otherwise.
lprbi
Address of a REBARINFO structure that will receive the rebar control information. You must set the cbSize member of this structure to sizeof(REBARINFO) before sending this message.

Version 4.70


RB_GETBKCOLOR

RB_GETBKCOLOR
    wParam = 0;
    lParam = 0;

Retrieves a rebar control's default background color.

  • Returns a COLORREF value that represent the current default background color.

Version 4.71

See also RB_SETBKCOLOR


RB_GETDROPTARGET

RB_GETDROPTARGET
    wParam = 0;
    lParam = (IDropTarget**)ppDropTarget;

Retrieves a rebar control's IDropTarget interface pointer.

  • The return value for this message is not used.
ppDropTarget
Address of an IDropTarget pointer that receives the interface pointer.
It is the caller's responsibility to call Release on this pointer when it is no longer needed.

Version 4.71


RB_GETCOLORSCHEME

RB_GETCOLORSCHEME
    wParam = 0;
    lParam = (LPARAM)(LPCOLORSCHEME) lpcs;

Retrieves the color scheme information from the rebar control.

  • Returns nonzero if successful, or zero otherwise.
lpcs
Address of a COLORSCHEME structure that will receive the color scheme information. You must set the dwSize member of this structure to sizeof(COLORSCHEME) before sending this message.

Version 4.71

See also RB_SETCOLORSCHEME


RB_GETPALETTE

RB_GETPALETTE
    wParam = 0;
    lParam = 0;

Retrieves the rebar control's current palette.

  • Returns an HPALETTE that specifies the rebar control's current palette.

Version 4.71

See also RB_SETPALETTE


RB_GETRECT

RB_GETRECT
    wParam = (WPARAM)(INT) iBand;
    lParam = (LPARAM)(LPRECT) lprc;

Retrieves the bounding rectangle for a given band in a rebar control.

  • Returns nonzero if successful, or zero otherwise.
iBand
Zero-based index of a band in the rebar control.
lprc
Address of a RECT structure that will receive the bounds of the rebar band.

Version 4.71


RB_GETROWCOUNT

RB_GETROWCOUNT
    wParam = 0;
    lParam = 0;

Retrieves the number of rows of bands in a rebar control.

  • Returns a UINT value that represents the number of band rows in the control.

Version 4.70


RB_GETROWHEIGHT

RB_GETROWHEIGHT
    wParam = (WPARAM)(UINT) uRow;
    lParam = 0;

Retrieves the height of a specified row in a rebar control.

  • Returns a UINT value that represents the row height, in pixels.
uRow
Zero-based index of a band. The height of the row that contains the specified band will be retrieved.

To retrieve the number of rows in a rebar control, use the RB_GETROWCOUNT message.

Version 4.70


RB_GETTEXTCOLOR

RB_GETTEXTCOLOR
    wParam = 0;
    lParam = 0;

Retrieves a rebar control's default text color.

  • Returns a COLORREF value that represent the current default text color.

Version 4.71

See also RB_SETTEXTCOLOR


RB_GETTOOLTIPS

RB_GETTOOLTIPS
    wParam = 0;
    lParam = 0;

Retrieves the handle to any tooltip control associated with the rebar control.

  • Returns an HWND value that is the handle to the tooltip control associated with the rebar control, or zero if no tooltip control is associated with the rebar control.

Version 4.71


RB_GETUNICODEFORMAT

RB_GETUNICODEFORMAT
    wParam = 0;
    lParam = 0;

Retrieves the UNICODE character format flag for the control.

  • Returns the UNICODE format flag for the control. If this value is nonzero, the control is using UNICODE characters. If this value is zero, the control is using ANSI characters.

See also RB_SETUNICODEFORMAT


RB_HITTEST

RB_HITTEST
    wParam = 0;
    lParam = (LPARAM)(LPRBHITTESTINFO) lprbht;

Determines which portion of a rebar band is at a given point on the screen, if a rebar band exists at that point.

  • Returns the zero-based index of the band at the given point, or -1 if no rebar band was at the point.
lprbht
Address of an RBHITTESTINFO structure. Before sending the message, the pt member of this structure must be initialized to the point that will be hit tested, in client coordinates.

Version 4.71


RB_IDTOINDEX

RB_IDTOINDEX
    wParam = (WPARAM)(UINT) uBandID;
    lParam = 0;

Converts a band identifier to a band index in a rebar control.

  • Returns the zero-based band index if successful, or -1 otherwise. If duplicate band identifiers exist, the first one is returned.
uBandID
The application-defined identifier of the band in question. This is the value that was passed in the wID member of the REBARBANDINFO structure when the band was inserted.

Version 4.71


RB_INSERTBAND

RB_INSERTBAND
    wParam = (WPARAM)(UINT) uIndex;
    lParam = (LPARAM)(LPREBARBANDINFO) lprbbi;

Inserts a new band in a rebar control.

  • Returns nonzero if successful, or zero otherwise.
uIndex
Zero-based index of the location where the band will be inserted. If you set this parameter to -1, the control will add the new band at the last location.
lprbbi
Address of a REBARBANDINFO structure that defines the band to be inserted. You must set the cbSize member of this structure to sizeof(REBARBANDINFO) before sending this message.

Version 4.70


RB_MAXIMIZEBAND

RB_MAXIMIZEBAND
    wParam = (WPARAM)(UINT) uBand;
    lParam = (LPARAM)(BOOL) fIdeal;

Resizes a band in a rebar control to either its ideal or largest size.

  • The return value is not used.
uBand
Zero-based index of the band to be maximized.
fIdeal
Indicates if the ideal width of the band should be used when the band is maximized. If this value is nonzero, the ideal width will be used. If this value is zero, the band will be made as large as possible.

Version 4.71


RB_MINIMIZEBAND

RB_MINIMIZEBAND
    wParam = (WPARAM)(UINT) uBand;
    lParam = 0;

Resizes a band in a rebar control to its smallest size.

  • The return value is not used.
uBand
Zero-based index of the band to be minimized.

Version 4.71


RB_MOVEBAND

RB_MOVEBAND
    wParam = (WPARAM)(UINT) iFrom;
    lParam = (LPARAM)(UINT) iTo;

Moves a band from one index to another.

  • Returns nonzero if successful, or zero otherwise.
iFrom
Zero-based index of the band to be moved.
iTo
Zero-based index of the new band position.

This message will most likely change the index of other bands in the rebar control. If a band is moved from index 6 to index 0, all of the bands in between will have their index incremented by one.

iTo must never be greater than the number of bands minus one. The number of bands can be obtained with the RB_GETBANDCOUNT message.

Version 4.71


RB_SETBANDINFO

RB_SETBANDINFO
    wParam = (WPARAM)(UINT) uBand;
    lParam = (LPARAM)(LPREBARBANDINFO) lprbbi;

Sets characteristics of an existing band in a rebar control.

  • Returns nonzero if successful, or zero otherwise.
uBand
Zero-based index of the band to receive the new settings.
lprbbi
Address of a REBARBANDINFO structure that defines the band to be modified and the new settings. Before sending this message, you must set the cbSize member of this structure to the sizeof(REBARBANDINFO) structure. Additionally, you must set the cch member of the REBARBANDINFO structure to the size of the lpText buffer when RBBIM_TEXT is specified.

Version 4.70


RB_SETBARINFO

RB_SETBARINFO
    wParam = 0;
    lParam = (LPARAM)(LPREBARINFO) lprbi;

Sets the characteristics of a rebar control.

  • Returns nonzero if successful, or zero otherwise.
lprbi
Address of a REBARINFO structure that contains the information to be set. You must set the cbSize member of this structure to sizeof(REBARINFO) before sending this message.

Version 4.70


RB_SETBKCOLOR

RB_SETBKCOLOR
    wParam = 0;
    lParam = (LPARAM)(COLORREF)clrBk;

Sets a rebar control's default background color.

  • Returns a COLORREF value that represents the previous default background color.
clrBk
COLORREF value that represents the new default background color.

The rebar control's default background color is used to draw the background in a rebar control and all bands that are added after this message has been sent. The default background color for a particular band can be overridden when a band is added or modified by setting the RBBIM_COLORS flag in fMask and setting clrBack in the REBARBANDINFO structure.

Version 4.71

See also RB_GETBKCOLOR


RB_SETCOLORSCHEME

RB_SETCOLORSCHEME
    wParam = 0;
    lParam = (LPARAM)(LPCOLORSCHEME) lpcs;

Sets the color scheme information for the rebar control.

  • The return value for this message is not used.
lpcs
Address of a COLORSCHEME structure that contains the color scheme information.

The rebar control uses the color scheme information when drawing the 3-D elements in the control and bands.

Version 4.71

See also RB_GETCOLORSCHEME


RB_SETPALETTE

RB_SETPALETTE
    wParam = 0;
    lParam = (LPARAM)(HPALETTE) hpal;

Sets the rebar control's current palette.

  • Returns an HPALETTE that specifies the rebar control's previous palette.
hpal
An HPALETTE that specifies the new palette that the rebar control will use.

It is the responsibility of the application sending this message to delete the HPALETTE passed in this message (see DeleteObject). The rebar control will not delete an HPALETTE set with this message.

Version 4.71

See also RB_GETPALETTE


RB_SETPARENT

RB_SETPARENT
    wParam = (WPARAM)(HWND) hwndParent;
    lParam = 0;

Sets a rebar control's parent window.

  • Returns the handle to the previous parent window, or NULL if there is no previous parent.
hwndParent
Handle to the parent window to be set.

The rebar control sends notification messages to the window you specify with this message. This message does not actually change the parent of the rebar control.

Version 4.70


RB_SETTEXTCOLOR

RB_SETTEXTCOLOR
    wParam = 0;
    lParam = (LPARAM)(COLORREF)clrText;

Sets a rebar control's default text color.

  • Returns a COLORREF value that represents the previous default text color.
clrText
COLORREF value that represents the new default text color.

The rebar control's default text color is used to draw the text in a rebar control and all bands that are added after this message has been sent. The default text color for a particular band can be overridden when a band is added or modified by setting the RBBIM_COLORS flag in fMask and setting clrBack in the REBARBANDINFO structure.

Version 4.71

See also RB_GETTEXTCOLOR


RB_SETTOOLTIPS

RB_SETTOOLTIPS
    wParam = (WPARAM)(HWND) hwndToolTip;
    lParam = 0;

Associates a tooltip control with the rebar control.

  • The return value for this message is not used.
hwndToolTip
Handle to the tooltip control to be set.

Version 4.71


RB_SETUNICODEFORMAT

RB_SETUNICODEFORMAT
    wParam = (WPARAM)(BOOL)fUnicode;
    lParam = 0;

Sets the UNICODE character format flag for the control. This message allows you to change the character set used by the control at run time rather than having to re-create the control.

  • Returns the previous UNICODE format flag for the control.
fUnicode
Determines the character set that is used by the control. If this value is nonzero, the control will use UNICODE characters. If this value is zero, the control will use ANSI characters.

See also RB_GETUNICODEFORMAT


RB_SHOWBAND

RB_SHOWBAND
    wParam = (WPARAM)(INT) iBand;
    lParam = (LPARAM)(BOOL) fShow;

Shows or hides a given band in a rebar control.

  • Returns nonzero if successful, or zero otherwise.
iBand
Zero-based index of a band in the rebar control.
fShow
Boolean value that indicates if the band should be shown or hidden. If this value is nonzero, the band will be shown. Otherwise, the band will be hidden.

Version 4.71


RB_SIZETORECT

RB_SIZETORECT
    wParam = 0;
    lParam = (LPARAM)(LPRECT) prc;

Attempts to find the best layout of the bands for the given rectangle.

  • Returns nonzero if a layout change occurred, or zero otherwise.
prc
Address of a RECT structure that specifies the rectangle to which the rebar control should be sized.

The rebar bands will be arranged and wrapped as necessary to fit the rectangle.
Bands that have the RBBS_VARIABLEHEIGHT style will be resized as evenly as possible to fit the rectangle.
The height of a horizontal rebar or the width of a vertical rebar may change, depending on the new layout.

Version 4.71


Rebar Control Notification Messages

This section contains information about the rebar control notification messages.

NM_CUSTOMDRAW (rebar)

NM_NCHITTEST (rebar)

NM_RELEASEDCAPTURE (rebar)

RBN_AUTOSIZE

RBN_BEGINDRAG

RBN_CHILDSIZE

RBN_DELETEDBAND

RBN_DELETINGBAND

RBN_ENDDRAG

RBN_GETOBJECT

RBN_HEIGHTCHANGE

RBN_LAYOUTCHANGED


NM_CUSTOMDRAW (rebar)

NM_CUSTOMDRAW
    lpNMCustomDraw = (LPNMCUSTOMDRAW) lParam;

Sent by the rebar control to notify its parent window about drawing operations. This notification is sent in the form of a WM_NOTIFY message.

  • The value your application can return depends on the current drawing stage. The dwDrawStage member of the associated NMCUSTOMDRAW structure holds a value that specifies the drawing stage. You must return one of the following values.

    When dwDrawStage equals CDDS_PREPAINT:
    CDRF_DODEFAULT
    The control will draw itself. It will not send any additional NM_CUSTOMDRAW messages for this paint cycle.
    CDRF_NOTIFYITEMDRAW
    The control will notify the parent of any item-related drawing operations. It will send NM_CUSTOMDRAW notification messages before and after drawing items.
    CDRF_NOTIFYITEMERASE
    The control will notify the parent when an item will be erased. It will send NM_CUSTOMDRAW notification messages before and after erasing items.
    CDRF_NOTIFYPOSTERASE
    The control will notify the parent after erasing an item.
    CDRF_NOTIFYPOSTPAINT
    The control will notify the parent after painting an item.
    CDRF_NOTIFYSUBITEMDRAW
    Version 4.71. The control will notify the parent when a list view subitem is being drawn.

    When dwDrawStage equals CDDS_ITEMPREPAINT:
    CDRF_NEWFONT
    Your application specified a new font for the item; the control will use the new font. For more information on changing fonts, see Changing fonts and colors.
    CDRF_SKIPDEFAULT
    Your application drew the item manually. The control will not draw the item.

lpNMCustomDraw
Address of an NMCUSTOMDRAW structure that contains information about the drawing operation. The dwItemSpec member of this structure contains the identifier of the band being drawn. The lItemlParam member of this structure contains the lParam of the band being drawn.

Version 4.70

See also Using Custom Draw


NM_NCHITTEST (rebar)

NM_NCHITTEST
    lpnmmouse = (LPNMMOUSE) lParam;

Sent by a rebar control when the control receives a WM_NCHITTEST message. This notification message is sent in the form of a WM_NOTIFY message.

  • Return zero to allow the rebar to perform default processing of the hit test message, or return one of the HT* values documented under WM_NCHITTEST to override the default hit test processing.
lpnmmouse
Address of an NMMOUSE structure that contains information about the notification. The dwItemSpec member contains the band index over which the hit test message occurred, and the pt member contains the mouse coordinates of the hit test message.

Version 4.71


NM_RELEASEDCAPTURE (rebar)

NM_RELEASEDCAPTURE
    lpnmh = (LPNMHDR) lParam;

Notifies a rebar control's parent window that the control is releasing mouse capture. This notification is sent in the form of a WM_NOTIFY message.

  • The control ignores the return value from this notification.
lpnmh
Address of an NMHDR structure that contains additional information about this notification message.

Version 4.71.


RBN_AUTOSIZE

RBN_AUTOSIZE
    lpnmas = (LPNMRBAUTOSIZE) lParam;

Sent by a rebar control created with the RBS_AUTOSIZE style when the rebar automatically resizes itself. This notification message is sent in the form of a WM_NOTIFY message.

  • The return value for this notification is not used.
lpnmas
Address of an NMRBAUTOSIZE structure that contains information about the resize operation.

Version 4.71


RBN_BEGINDRAG

RBN_BEGINDRAG
    lpnmrb = (LPNMREBAR)lParam;

Sent by a rebar control when the user begins dragging a band. This notification message is sent in the form of a WM_NOTIFY message.

  • Return zero to allow the rebar to continue the drag operation, or nonzero to abort the drag operation.
lpnmrb
Address of an NMREBAR structure that contains information about the notification.

Version 4.71


RBN_CHILDSIZE

RBN_CHILDSIZE
    lprbcs = (LPNMREBARCHILDSIZE)lParam;

Sent by a rebar control when a band's child window is resized. This notification message is sent in the form of a WM_NOTIFY message.

  • The return value for this notification is not used.
lprbcs
Address of an NMREBARCHILDSIZE structure that contains information about the notification.

Version 4.71


RBN_DELETEDBAND

RBN_DELETEDBAND
    lpnmrb = (LPNMREBAR)lParam;

Sent by a rebar control after a band has been deleted. This notification message is sent in the form of a WM_NOTIFY message.

  • The return value for this notification is not used.
lpnmrb
Address of an NMREBAR structure that contains information about the notification.

Version 4.71


RBN_DELETINGBAND

RBN_DELETINGBAND
    lpnmrb = (LPNMREBAR)lParam;

Sent by a rebar control when a band is about to be deleted. This notification message is sent in the form of a WM_NOTIFY message.

  • The return value for this notification is not used.
lpnmrb
Address of an NMREBAR structure that contains information about the notification.

Version 4.71


RBN_ENDDRAG

RBN_ENDDRAG
    lpnmrb = (LPNMREBAR)lParam;

Sent by a rebar control when the user stops dragging a band. This notification message is sent in the form of a WM_NOTIFY message.

  • The return value for this notification is not used.
lpnmrb
Address of an NMREBAR structure that contains information about the notification.

Version 4.71


RBN_GETOBJECT

RBN_GETOBJECT
    lpnmon = (LPNMOBJECTNOTIFY) lParam;

Sent by a rebar control created with the RBS_REGISTERDROP style when an object is dragged over a band in the control. This notification message is sent in the form of a WM_NOTIFY message.

  • The return value for this notification must be zero.
lpnmon
Address of an NMOBJECTNOTIFY structure that contains information about the band that the object is dragged over and also receives the data provided by the receiving application in response to this message.

To receive the RBN_GETOBJECT notification, initialize OLE with a call to OleInitialize or CoInitialize.

Version 4.71


RBN_HEIGHTCHANGE

RBN_HEIGHTCHANGE
    lpnmhdr = (LPNMHDR) lParam;

Sent by a rebar control when its height has changed. This notification message is sent in the form of a WM_NOTIFY message.

  • The return value for this notification is not used.
lpnmhdr
Address of an NMHDR structure that contains additional information about this notification message.

Rebar controls that use the CCS_VERT style send this notification message when their width changes.

Version 4.70


RBN_LAYOUTCHANGED

RBN_LAYOUTCHANGED
    lpnmhdr = (LPNMHDR) lParam;

Sent by a rebar control when the user changes the layout of the control's bands. This notification message is sent in the form of a WM_NOTIFY message.

  • The return value for this notification is not used.
lpnmhdr
Address of an NMHDR structure that contains additional information about this notification message.

Version 4.71


Rebar Control Structures

This section contains information about the structures used with rebar controls.

NMRBAUTOSIZE

NMREBAR

NMREBARCHILDSIZE

RBHITTESTINFO

REBARBANDINFO

REBARINFO


NMRBAUTOSIZE

typedef struct tagNMRBAUTOSIZE {
    NMHDR hdr;
    BOOL fChanged;
    RECT rcTarget;
    RECT rcActual;
} NMRBAUTOSIZE, *LPNMRBAUTOSIZE;

Contains information used in handling the RBN_AUTOSIZE notification messages.

hdr
NMHDR structure that contains additional information about the notification message.
fChanged
Member that indicates if the size or layout of the rebar control has changed (nonzero if a change occurred or zero otherwise).
rcTarget
RECT structure that contains the rectangle to which the rebar control tried to size itself.
rcActual
RECT structure that contains the rectangle to which the rebar control actually sized itself.

Version 4.71


NMREBAR

typedef struct tagNMREBAR {
    NMHDR hdr;
    DWORD dwMask;
    UINT uBand;
    UINT fStyle;
    UINT wID;
    LPARAM lParam;
} NMREBAR, *LPNMREBAR;

Contains information used in handling various rebar notification messages.

hdr
NMHDR structure that contains additional information about the notification message.
dwMask
Set of flags that define which members of this structure contain valid information. This can be one or more of the following values:
RBNM_ID | The wID member contains valid information.
RBNM_LPARAM | The lParam member contains valid information.
RBNM_STYLE | The fStyle member contains valid information.
uBand
Zero-based index of the band affected by the notification. This will be -1 if no band is affected.
fStyle
The style of the band. This is one or more of the RBBS_ styles detailed in the fStyle member of the REBARBANDINFO structure. This member is only valid if dwMask contains RBNM_STYLE.
wID
Application-defined identifier of the band. This member is only valid if dwMask contains RBNM_ID.
lParam
Application-defined 32-bit value associated with the band. This member is only valid if dwMask contains RBNM_LPARAM.

Version 4.71


NMREBARCHILDSIZE

typedef struct tagNMREBARCHILDSIZE{
    NMHDR hdr;
    UINT uBand;
    UINT wID;
    RECT rcChild;
    RECT rcBand;
} NMREBARCHILDSIZE, *LPNMREBARCHILDSIZE;

Contains information used in handling the RBN_CHILDSIZE notification message.

hdr
NMHDR structure that contains additional information about the notification message.
uBand
Zero-based index of the band affected by the notification. This will be -1 if no band is affected.
wID
Application-defined identifier of the band.
rcChild
RECT structure that contains the new size of the child window. This member can be changed during the notification to modify the child window's position and size.
rcBand
RECT structure that contains the new size of the band.

Version 4.71


RBHITTESTINFO

typedef struct _RB_HITTESTINFO {
    POINT pt;
    UINT  flags;
    int   iBand;
} RBHITTESTINFO, FAR *LPRBHITTESTINFO;

Contains information specific to a hit test operation. This structure is used with the RB_HITTEST message.

pt
POINT structure that describes the point to be hit tested, in client coordinates.
flags
Member that receives a flag value indicating the rebar band's component located at the point described by pt. This member will be one of the following:
RBHT_CAPTION | The point was in the rebar band's caption.
RBHT_CLIENT | The point was in the rebar band's client area.
RBHT_GRABBER | The point was in the rebar band's gripper.
RBHT_NOWHERE | The point was not in a rebar band.
iBand
Member that receives the rebar band's index at the point described by pt. This value will be the zero-based index of the band, or -1 if no band was at the hit-tested point.

Version 4.71


REBARBANDINFO

typedef struct tagREBARBANDINFO{
    UINT        cbSize;
    UINT        fMask;
    UINT        fStyle;
    COLORREF    clrFore;
    COLORREF    clrBack;
    LPTSTR      lpText;
    UINT        cch;
    int         iImage;
    HWND        hwndChild;
    UINT        cxMinChild;
    UINT        cyMinChild;
    UINT        cx;
    HBITMAP     hbmBack;
    UINT        wID;
#if (_WIN32_IE >= 0x0400)
    UINT        cyChild;
    UINT        cyMaxChild;
    UINT        cyIntegral;
    UINT        cxIdeal;
    LPARAM      lParam;
    UINT        cxHeader;
#endif
 } REBARBANDINFO, FAR *LPREBARBANDINFO;

Contains information that defines a band in a rebar control.

cbSize
Size of this structure, in bytes. Your application must fill this member before sending any messages that use the address of this structure as a parameter.
fMask
Flags that indicate which members of this structure are valid or must be filled. This value can be a combination of the following:
RBBIM_BACKGROUND | The hbmBack member is valid or must be filled.
RBBIM_CHILD | The hwndChild member is valid or must be filled.
RBBIM_CHILDSIZE | The cxMinChild, cyMinChild, cyChild, cyMaxChild, and cyIntegral members are valid or must be filled.
RBBIM_COLORS | The clrFore and clrBack members are valid or must be filled.
RBBIM_HEADERSIZE | Version 4.71. The cxHeader member is valid or must be filled.
RBBIM_IDEALSIZE | Version 4.71. The cxIdeal member is valid or must be filled.
RBBIM_ID | The wID member is valid or must be filled.
RBBIM_IMAGE | The iImage member is valid or must be filled.
RBBIM_LPARAM | Version 4.71. The lParam member is valid or must be filled.
RBBIM_SIZE | The cx member is valid or must be filled.
RBBIM_STYLE | The fStyle member is valid or must be filled.
RBBIM_TEXT | The lpText member is valid or must be filled.
fStyle
Flags that specify the band style. This value can be a combination of the following:
RBBS_BREAK | The band is on a new line.
RBBS_CHILDEDGE | The band has an edge at the top and bottom of the child window.
RBBS_FIXEDBMP | The background bitmap does not move when the band is resized.
RBBS_FIXEDSIZE | The band can't be sized. With this style, the sizing grip is not displayed on the band.
RBBS_GRIPPERALWAYS | Version 4.71. The band will always have sizing grip, even if it is the only band in the rebar.
RBBS_HIDDEN | The band will not be visible.
RBBS_NOGRIPPER | Version 4.71. The band will never have sizing grip, even if there is more than one band in the rebar.
RBBS_NOVERT | The band won't be displayed when the rebar control uses the CCS_VERT style.
RBBS_VARIABLEHEIGHT | Version 4.71. The band can be resized by the rebar control. cyIntegral and cyMaxChild affect how the rebar will resize the band.
clrFore and clrBack
Band foreground and background colors. If hbmBack specifies a background bitmap, these members are ignored. By default, the band will use the background color of the rebar control set with the RB_SETBKCOLOR message. If a background color is specified here, then this background color will be used instead.
lpText
Address of a buffer that contains the display text for the band. If band information is being requested from the control and RBBIM_TEXT is specified in fMask, this member must be initialized to the address of the buffer that will receive the text.
cch
Size of the buffer at lpText, in bytes. If information is not being requested from the control, this member is ignored.
iImage
Zero-based index of any image that should be displayed in the band. The image list is set using the RB_SETBARINFO message.
hwndChild
Handle to the child window contained in the band, if any.
cxMinChild
Minimum width of the child window, in pixels. The band can't be sized smaller than this value.
cyMinChild
Minimum height of the child window, in pixels. The band can't be sized smaller than this value.
cx
Length of the band, in pixels.
hbmBack
Handle to a bitmap that is used as the background for this band.
wID
UINT value that the control uses to identify this band for custom draw notification messages. This value may be used for additional purposes in the future.
cyChild
Version 4.71. Initial height of the band, in pixels. This member is ignored unless the RBBS_VARIABLEHEIGHT style is specified.
cyMaxChild
Version 4.71. Maximum height of the band, in pixels. This member is ignored unless the RBBS_VARIABLEHEIGHT style is specified.
cyIntegral
Version 4.71. Specifies the step value by which the band can grow or shrink, in pixels. If the band is resized, it will be resized in steps specified by this value. This member is ignored unless the RBBS_VARIABLEHEIGHT style is specified.
cxIdeal
Version 4.71. Specifies the ideal width of the band, in pixels. If the band is maximized to the ideal width (see RB_MAXIMIZEBAND), the rebar control will attempt to make the band this width.
lParam
Version 4.71. A 32-bit application-defined value.
cxHeader
Version 4.71. Specifies the size of the band's header, in pixels. The band header is the area between the edge of the band and the edge of the child window. This is the area where band text and images are displayed, if they are specified. If this value is specified, it will override the normal header dimensions that the control calculates for the band.

The cxMinChild, cyMinChild, and cx members provide information on dimensions relative to the orientation of the control. That is, for a horizontal rebar control, cxMinChild and cx are horizontal measurements and cyMinChild is a vertical measurement. However, if the control uses the CCS_VERT style, cxMinChild and cx are vertical measurements and cyMinChild is a horizontal measurement.

Version 4.70


REBARINFO

typedef struct tagREBARINFO{
    UINT        cbSize;
    UINT        fMask;
    HIMAGELIST  himl;
} REBARINFO, FAR *LPREBARINFO;

Contains information that describes rebar control characteristics.

cbSize
Size of this structure, in bytes. Your application must fill this member before sending any messages that use the address of this structure as a parameter.
fMask
Flag values that describe characteristics of the rebar control. Currently, rebar controls support only one value:
RBIM_IMAGELIST The himl member is valid or must be filled.
himl
Handle to an image list. The rebar control will use the specified image list to obtain images.

Version 4.70


Status Bars

A status bar is a horizontal window at the bottom of a parent window in which an application can display various kinds of status information. The status bar 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. The status bar is the bar at the bottom of the window that contains Help text and coordinate information.

Status bar in the Microsoft® Windows® Paint application.

Using Status Bars

Status Bar Updates in Internet Explorer

Status Bar Reference

Using Status Bars

You can create a status bar 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 bar, you can divide it into parts, set the text for each part, and control the appearance of the window by using status bar messages.

Types and Styles

The default position of a status bar 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 bar.

Note Combining the CCS_TOP and SBARS_SIZEGRIP styles is not recommended because the resulting sizing grip is not functional.

Size and Height

The window procedure for the status bar 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 bar's device context and on the width of the window's borders.

The window procedure automatically adjusts the size of the status bar 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 bar.

An application can set the minimum height of a status bar'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 bar. For more information, see Owner-Drawn Status Bars later in this chapter.

You retrieve the widths of the borders of a status bar by sending the window an SB_GETBORDERS message. The message includes the address of a three-element array that receives the widths.

Multiple-Part Status Bars

A status bar can have many different parts, each displaying a different line of text. You divide a status bar into parts by sending the window an SB_SETPARTS message, specifying the number of parts to create and the address of 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 bar 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 bar, as well as the coordinate of the right edge of each part, by sending the window an SB_GETPARTS message.

Status Bar Text Operations

You set the text of any part of a status bar by sending the SB_SETTEXT message, specifying the zero-based index of a part, an address of 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 Owner-Drawn Status Bars section below.

By default, text is left-aligned within the specified part of a status bar. 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 bar, use the SB_GETTEXTLENGTH and SB_GETTEXT messages.

If your application uses a status bar 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 bar much like a static text control.

To display a line of status without creating a status bar, use the DrawStatusText function. The function uses the same techniques to draw the status as the window procedure for the status bar, 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 Bars

You can define individual parts of a status bar 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 or draw text using a different font.

To define a window part as owner-drawn, send the SB_SETTEXT message to the status bar, 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, an address of a string, and so on.

When a status bar 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 bar, and the lParam parameter is the address of a DRAWITEMSTRUCT structure. The parent window uses the information in the structure to draw the part. For an owner-drawn part of a status bar, DRAWITEMSTRUCT contains the following information.
Member | Description
CtlType | Undefined; do not use.
CtlID | Child window identifier of the status bar.
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 bar.
hDC | Handle to the device context of the status bar.
rcItem | Coordinates of the window part to be drawn. The coordinates are relative to the upper left corner of the status bar.
itemData | Application-defined 32-bit value specified in the lParam parameter of the SB_SETTEXT message.

Simple Mode Status Bars

You put a status bar in "simple mode" by sending it an SB_SIMPLE message. A simple mode status bar 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 bar is useful for displaying Help text for menu items while the user is scrolling through the menu.

The string that a status bar displays while in simple mode is maintained separately from the strings that it displays while in nonsimple mode. This means you can put the window in simple mode, set its text, and switch back to nonsimple mode without the nonsimple mode text being changed.

When setting the text of a simple mode status bar, you can specify any drawing technique except SBT_OWNERDRAW. A simple mode status bar does not support owner drawing.

Default Status Bar Message Processing

This section describes the messages handled by the window procedure for the predefined STATUSCLASSNAME class.
Message | Default processing
WM_CREATE | Initializes the status bar.
WM_DESTROY | Frees resources allocated for the status bar.
WM_GETFONT | Returns the handle to the current font with which the status bar draws its text.
WM_GETTEXT | Copies the text from the first part of a status bar 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 bar 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 bar passes this message to the DefWindowProc function.
WM_PAINT | Paints the invalid region of the status bar. If the wParam parameter is non-NULL, the control assumes that the value is an HDC and paints using that device context.
WM_SETFONT | Selects the font handle into the device context for the status bar.
WM_SETTEXT | Copies the specified text into the first part of a status bar, using the default drawing operation (specified as zero). It returns TRUE if successful, or FALSE otherwise.
WM_SIZE | Resizes the status bar based on the current width of the parent window's client area and the height of the current font of the status bar.

Status Bar Example

The following example demonstrates how to create a status bar that has a sizing grip and divide the window into four equal parts based on the width of the parent window's client area.

    // DoCreateStatusBar - creates a status bar and divides it into
    //     the specified number of parts.
    // Returns the handle to the status bar.
    // hwndParent - parent window for the status bar.
    // nStatusID - child window identifier.
    // hinst - handle to the application instance.
    // nParts - number of parts into which to divide the status bar.
    HWND DoCreateStatusBar(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 bar.
    hwndStatus = CreateWindowEx(
        0,                       // no extended styles
        STATUSCLASSNAME,         // name of status bar 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 bar 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 Bar Updates in Internet Explorer

Status bar controls in Microsoft® Internet Explorer support the following new features.

Icon Support
Icons can now be displayed in a status bar. The SB_SETICON message is used to set the icon.
Tooltip Support
The status bar now supports tooltips. To enable tooltips, the SBT_TOOLTIPS style must be set when the status bar is created. The SB_SETTIPTEXT and SB_GETTIPTEXT messages are used to set and get the tooltip text, respectively. The tooltip for a part will only be displayed if the part has an icon and no text or if all of the text cannot be displayed inside the part. Tooltips are not supported in simple mode.
Enhanced Simple Mode Support
The SB_ISSIMPLE message has been added to determine if a status bar is in simple mode. The SBN_SIMPLEMODECHANGE notification has been added to inform the owner that the simple mode has changed.
Background Color Support
The SB_SETBKCOLOR message has been added to allow the background color of a status bar to be modified.


Status Bar Reference

This section contains information about the programming elements used with status bar controls.

Status Bar Styles

Functions
CreateStatusWindow
DrawStatusText
MenuHelp

Messages
SB_GETBORDERS
SB_GETICON
SB_GETPARTS
SB_GETRECT
SB_GETTEXT
SB_GETTEXTLENGTH
SB_GETTIPTEXT
SB_GETUNICODEFORMAT
SB_ISSIMPLE
SB_SETBKCOLOR
SB_SETICON
SB_SETMINHEIGHT
SB_SETPARTS
SB_SETTEXT
SB_SETTIPTEXT
SB_SETUNICODEFORMAT
SB_SIMPLE

Notifications
NM_CLICK (status bar)
NM_DBLCLK (status bar)
NM_RCLICK (status bar)
NM_RDBLCLK (status bar)
SBN_SIMPLEMODECHANGE


Status Bar Styles

Status bar controls support the following style in addition to standard window styles.
SBARS_SIZEGRIP The status bar control will include a sizing grip at the right end of the status bar. 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.


Status Bar Functions

This section contains information about the functions used with status bar controls.

CreateStatusWindow

DrawStatusText

MenuHelp


CreateStatusWindow

HWND CreateStatusWindow(
    LONG style,
    LPCTSTR lpszText,
    HWND hwndParent,
    UINT wID
);

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.

  • Returns the handle for the status window if successful, or NULL otherwise. To get extended error information, call GetLastError.
style
Window styles for the status window. This parameter must include the WS_CHILD style and should also include the WS_VISIBLE style.
lpszText
Address of 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.

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.


DrawStatusText

void DrawStatusText(
    HDC hdc,
    LPRECT lprc,
    LPCTSTR pszText,
    UINT uFlags
);

Draws the specified text in the style of a status window with borders.

  • This function does not return a value.
hdc
Handle to the display context for the window.
lprc
Address of 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 the edges of the specified rectangle.
pszText
Address of 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:
SBT_NOBORDERS | Prevents borders from being drawn around the specified text.
SBT_POPOUT | Draws highlighted borders that make the text stand out.
SBT_RTLREADING | Displays text using right-to-left reading order on Hebrew or Arabic systems.


MenuHelp

void MenuHelp(
    UINT uMsg,
    WPARAM wParam,
    LPARAM lParam,
    HMENU hMainMenu,
    HINSTANCE hInst,
    HWND hwndStatus,
    LPUINT lpwIDs
);

Processes WM_MENUSELECT and WM_COMMAND messages and displays Help text about the current menu in the specified status window.

  • This function does not return a value.
uMsg
Message being processed. This can be either WM_MENUSELECT or WM_COMMAND.
wParam
wParam of the message specified in uMsg.
lParam
lParam of the message specified in uMsg.
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
Address of 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.


Status Bar Messages

This section contains information about the messages used with status bar controls.

SB_GETBORDERS

SB_GETICON

SB_GETPARTS

SB_GETRECT

SB_GETTEXT

SB_GETTEXTLENGTH

SB_GETTIPTEXT

SB_GETUNICODEFORMAT

SB_ISSIMPLE

SB_SETBKCOLOR

SB_SETICON

SB_SETMINHEIGHT

SB_SETPARTS

SB_SETTEXT

SB_SETTIPTEXT

SB_SETUNICODEFORMAT

SB_SIMPLE


SB_GETBORDERS

SB_GETBORDERS
    wParam = 0;
    lParam = (LPARAM) (LPINT) aBorders;

Retrieves the current widths of the horizontal and vertical borders of a status window.

  • Returns TRUE if successful, or FALSE otherwise.
aBorders
Address of 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.

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_GETICON

Retrieves the icon for a part in a status bar.

Syntax

SB_GETICON
    wParam = (WPARAM)(INT)iPart;
    lParam = 0;

Parameters

iPart
Zero-based index of the part that contains the icon to be retrieved. If this parameter is -1, the status bar is assumed to be a Simple Mode status bar.

Return Values

Returns the handle to the icon if successful, or NULL otherwise.

Remarks

Version 4.71


SB_GETPARTS

SB_GETPARTS
    wParam = (WPARAM) nParts;
    lParam = (LPARAM) (LPINT) aRightCoord;

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.

  • Returns the number of parts in the window if successful, or zero otherwise.
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
Address of 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.


SB_GETRECT

SB_GETRECT
    wParam = (WPARAM) iPart;
    lParam = (LPARAM) (LPRECT) lprc;

Retrieves the bounding rectangle of a part in a status window.

  • Returns TRUE if successful, or FALSE otherwise.
iPart
Zero-based index of the part whose bounding rectangle is to be retrieved.
lprc
Address of a RECT structure that receives the bounding rectangle.


SB_GETTEXT

SB_GETTEXT
    wParam = (WPARAM) iPart;
    lParam = (LPARAM) (LPSTR) szText;

Retrieves the text from the specified part of a status window.

  • 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 the following values:
    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 the window.
    SBT_RTLREADING | Displays text using right-to-left reading order on Hebrew or Arabic systems.
iPart
Zero-based index of the part from which to retrieve text.
szText
Address of the buffer that receives the text. This parameter is a null-terminated string.

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

SB_GETTEXTLENGTH
    wParam = (WPARAM) iPart;
    lParam = 0;

Retrieves the length, in characters, of the text from the specified part of a status window.

  • 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 the following values:
    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 | Displays text using right-to-left reading order on Hebrew or Arabic systems.
iPart
Zero-based index of the part from which to retrieve text.


SB_GETTIPTEXT

SB_GETTIPTEXT
    wParam = MAKEWPARAM(iPart, nSize);
    lParam = (LPARAM)(LPCTSTR)lpszTooltip;

Retrieves the tooltip text for a part in a status bar. The status bar must have been created with the SBT_TOOLTIPS style to enable tooltips.

  • The return value is not used.
iPart
Zero-based index of the part that will receive the tooltip text.
nSize
Size of the buffer at lpszTooltip, in characters.
lpszTooltip
Address of a character buffer that receives the tooltip text.

Version 4.71

See also Status Bar Updates in Internet Explorer


SB_GETUNICODEFORMAT

SB_GETUNICODEFORMAT
    wParam = 0;
    lParam = 0;

Retrieves the UNICODE character format flag for the control.

  • Returns the UNICODE format flag for the control. If this value is nonzero, the control is using UNICODE characters. If this value is zero, the control is using ANSI characters.

See also SB_SETUNICODEFORMAT


SB_ISSIMPLE

SB_ISSIMPLE
    wParam = 0;
    lParam = 0;

Checks a status bar control to determine if it is in simple mode.

  • Returns nonzero if the status bar control is in simple mode, or zero otherwise.

Version 4.70


SB_SETBKCOLOR

SB_SETBKCOLOR
    wParam = 0;
    lParam = (LPARAM)(COLORREF)clrBk;

Sets the background color in a status bar.

  • Returns the previous background color, or CLR_DEFAULT if the background color is the default color.
clrBk
COLORREF value that specifies the new background color. Specify the CLR_DEFAULT value to cause the status bar to use its default background color.

Version 4.71


SB_SETICON

SB_SETICON
    wParam = (WPARAM)(INT)iPart;
    lParam = (LPARAM)(HICON)hIcon;

Sets the icon for a part in a status bar.

  • Returns nonzero if successful, or zero otherwise.
iPart
Zero-based index of the part that will receive the icon. If this parameter is -1, the status bar is assumed to be a simple status bar.
hIcon
Handle to the icon to be set. If this value is NULL, the icon is removed from the part.

The status bar will not destroy the icon. It is the calling application's responsibility to keep track of and destroy any icons.

Version 4.71


SB_SETMINHEIGHT

SB_SETMINHEIGHT
    wParam = (WPARAM) minHeight;
    lParam = 0;

Sets the minimum height of a status window's drawing area.

  • No return value.
minHeight
Minimum height, in pixels, of the window.

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.


SB_SETPARTS

SB_SETPARTS
    wParam = (WPARAM) nParts;
    lParam = (LPARAM) (LPINT) aWidths;

Sets the number of parts in a status window and the coordinate of the right edge of each part.

  • Returns TRUE if successful, or FALSE otherwise.
nParts
Number of parts to set (cannot be greater than 255).
aWidths
Address of 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.


SB_SETTEXT

SB_SETTEXT
    wParam = (WPARAM) iPart | uType;
    lParam = (LPARAM) (LPSTR) szText;

Sets the text in the specified part of a status window.

  • Returns TRUE if successful, or FALSE otherwise.
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:
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 | Displays text using right-to-left reading order on Hebrew or Arabic systems.
szText
Address of 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. The text for each part is limited to 127 characters.

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.


SB_SETTIPTEXT

SB_SETTIPTEXT
    wParam = (WPARAM)(INT)iPart;
    lParam = (LPARAM)(LPCTSTR)lpszTooltip;

Sets the tooltip text for a part in a status bar. The status bar must have been created with the SBT_TOOLTIPS style to enable tooltips.

  • The return value is not used.
iPart
Zero-based index of the part that will receive the tooltip text.
lpszTooltip
Address of a character buffer that contains the new tooltip text.

Version 4.71

See also Status Bar Updates in Internet Explorer


SB_SETUNICODEFORMAT

SB_SETUNICODEFORMAT
    wParam = (WPARAM)(BOOL)fUnicode;
    lParam = 0;

Sets the UNICODE character format flag for the control. This message allows you to change the character set used by the control at run time rather than having to re-create the control.

  • Returns the previous UNICODE format flag for the control.
fUnicode
Determines the character set that is used by the control. If this value is nonzero, the control will use UNICODE characters. If this value is zero, the control will use ANSI characters.

See also SB_GETUNICODEFORMAT


SB_SIMPLE

SB_SIMPLE
    wParam = (WPARAM) (BOOL) fSimple;
    lParam = 0;

Specifies whether a status window displays simple text or displays all window parts set by a previous SB_SETPARTS message.

  • Returns FALSE if an error occurs.
fSimple
Display type flag. If this parameter is TRUE, the window displays simple text. If it is FALSE, it displays multiple parts.

If the status window is being changed from nonsimple to simple, or vice versa, the window is immediately redrawn.


Status Bar Notifications

This section contains information about the notification messages used with status bar controls.

NM_CLICK (status bar)

NM_DBLCLK (status bar)

NM_RCLICK (status bar)

NM_RDBLCLK (status bar)

SBN_SIMPLEMODECHANGE


NM_CLICK (status bar)

NM_CLICK
    lpnmh = (LPNMHDR) lParam;

Notifies a status bar control's parent window that the user has clicked the left mouse button within the control. NM_CLICK is sent in the form of a WM_NOTIFY message.

  • The return value is ignored by the status bar.
lpnmh
Address of an NMHDR structure that contains additional information about this notification message.


NM_DBLCLK (status bar)

NM_DBLCLK
    lpnmh = (LPNMHDR) lParam;

Notifies a status bar control's parent window 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.

  • The return value is ignored by the status bar.
lpnmh
Address of an NMHDR structure that contains additional information about this notification message.


NM_RCLICK (status bar)

Notifies a status bar control's parent window that the user has clicked the right mouse button within the control. This notification is sent in the form of a WM_NOTIFY message.

Syntax

NM_RCLICK
    lpnmh = (LPNMHDR) lParam;

Parameters

lpnmh
Address of an NMHDR structure that contains additional information about this notification message.

Return Value

The return value is ignored by the status bar.

Remarks

Version 4.72


NM_RDBLCLK (status bar)

NM_RDBLCLK
    lpnmh = (LPNMHDR) lParam;

Notifies a status bar control's parent window 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.

  • The return value is ignored by the status bar.
lpnmh
Address of an NMHDR structure that contains additional information about this notification message.


SBN_SIMPLEMODECHANGE

SBN_SIMPLEMODECHANGE
    lpnmh = (NMHDR*) lParam;

Sent by a status bar control when the simple mode changes due to a SB_SIMPLE message. This notification is sent in the form of a WM_NOTIFY message.

  • The return value is ignored by the status bar.
lpnmh
Address of an NMHDR structure that contains information about the notification.

Version 4.71


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 certain type of information or a group of controls that the application displays when the user selects the corresponding tab.

About Tab Controls

Using Tab Controls

Tab Control Updates in Internet Explorer

Tab Control Reference

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 that you can use instead of sending the message explicitly. You cannot 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 certain characteristics to tab controls by specifying tab control styles when the control is created. 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. You can cause a tab control to display multiple rows of tabs, if necessary, by specifying the TCS_MULTILINE style. With this style, 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, placing 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, see Owner-Drawn Tabs.

You can specify that a tab control will create a tooltip control by using the TCS_TOOLTIPS style. For more information about this, see Tab Control Tooltips.

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 TCITEM 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 TCITEM 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 TCITEM structure. If you use more than 4 bytes of application-defined data, you need to define your own structure and use it instead of TCITEM. 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 TCITEMHEADER structure, and the remaining members must specify application-defined data. TCITEMHEADER is identical to TCITEM, except it does not have the lParam member. The difference between the size of your structure and the size of TCITEMHEADER 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 in 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 as before.

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 to 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 TCITEM structure. However, if you change the amount of application-defined data per tab, itemData contains the address of 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.

Tab Control Tooltips

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 destroys the tooltip control when it is destroyed. 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 to a tab control's current tooltip control by using the TCM_GETTOOLTIPS message. If you create your own tooltip control, 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 in other sections of this documentation.
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 tooltip 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 to 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 tooltip 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 tooltip 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 tooltip 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 the tab (or sends a WM_DRAWITEM message to the parent window) and then draws a border around the tab. If the wParam parameter is non-NULL, the control assumes that the value is an HDC and paints using that device context.

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 demonstrates how to use a tab control to switch between multiple pages of text in an application's main window. The second example demonstrates how to use a tab control to switch between multiple pages of controls in a dialog box.

Creating a Tab Control

The example in this section demonstrates how to create a tab control and display 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 to 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 to 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 to the tab control.
    // hwndParent - parent window (the application's main window).

    HWND WINAPI DoCreateTabControl(HWND hwndParent)
    {
    RECT rcClient;
    HWND hwndTab;
    TCITEM 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 to 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 to 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 demonstrates how to create 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 has the WS_CHILD style. When a tab is selected, a modeless dialog box is created for the incoming page and the dialog box for the outgoing page is destroyed.

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;
    TCITEM 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.
    InitCommonControls();
    pHdr->hwndTab = CreateWindow(
        WC_TABCONTROL, "",
        WS_CHILD | WS_CLIPSIBLINGS | WS_VISIBLE,
        0, 0, 100, 100,
        hwndDlg, NULL, g_hinst, NULL
        );
    if (pHdr->hwndTab == NULL) {
        // handle error
    }

    // 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 accommodate 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 the address of 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 to 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 Updates in Internet Explorer

Tab controls in Microsoft® Internet Explorer support the following new features.

Item States
Tab control items now support an item state to support the TCM_DESELECTALL message. Additionally, the TCITEM structure supports item state values. See Tab Control Item States for more information.
Extended Styles
Tab controls now support extended styles that allow the controls to have enhanced capabilities. See Tab Control Extended Styles for more information.
Structures Renamed
All structures used with tab controls have been renamed to conform to current naming conventions, while maintaining backward compatibility. For example, the TC_ITEM structure is now named TCITEM.


Tab Control Reference

This section contains information about the programming elements used with tab controls.

Tab Control Styles

Tab Control Extended Styles

Tab Control Item States

Messages
TCM_ADJUSTRECT
TCM_DELETEALLITEMS
TCM_DELETEITEM
TCM_DESELECTALL
TCM_GETCURFOCUS
TCM_GETCURSEL
TCM_GETEXTENDEDSTYLE
TCM_GETIMAGELIST
TCM_GETITEM
TCM_GETITEMCOUNT
TCM_GETITEMRECT
TCM_GETROWCOUNT
TCM_GETTOOLTIPS
TCM_GETUNICODEFORMAT
TCM_HIGHLIGHTITEM
TCM_HITTEST
TCM_INSERTITEM
TCM_REMOVEIMAGE
TCM_SETCURFOCUS
TCM_SETCURSEL
TCM_SETEXTENDEDSTYLE
TCM_SETIMAGELIST
TCM_SETITEM
TCM_SETITEMEXTRA
TCM_SETITEMSIZE
TCM_SETMINTABWIDTH
TCM_SETPADDING
TCM_SETTOOLTIPS
TCM_SETUNICODEFORMAT

Utility Macros
TabCtrl_AdjustRect
TabCtrl_DeleteAllItems
TabCtrl_DeleteItem
TabCtrl_DeselectAll
TabCtrl_GetCurFocus
TabCtrl_GetCurSel
TabCtrl_GetExtendedStyle
TabCtrl_GetImageList
TabCtrl_GetItem
TabCtrl_GetItemCount
TabCtrl_GetItemRect
TabCtrl_GetRowCount
TabCtrl_GetToolTips
TabCtrl_GetUnicodeFormat
TabCtrl_HighlightItem
TabCtrl_HitTest
TabCtrl_InsertItem
TabCtrl_RemoveImage
TabCtrl_SetCurFocus
TabCtrl_SetCurSel
TabCtrl_SetExtendedStyle
TabCtrl_SetImageList
TabCtrl_SetItem
TabCtrl_SetItemExtra
TabCtrl_SetItemSize
TabCtrl_SetMinTabWidth
TabCtrl_SetPadding
TabCtrl_SetToolTips
TabCtrl_SetUnicodeFormat

Notifications
NM_CLICK (tab)
NM_RCLICK (tab)
NM_RELEASEDCAPTURE (tab)
TCN_GETOBJECT
TCN_KEYDOWN
TCN_SELCHANGE
TCN_SELCHANGING

Structures
NMTCKEYDOWN
TC_HITTESTINFO
TC_ITEM
TC_ITEMHEADER
TC_KEYDOWN
TCHITTESTINFO
TCITEM
TCITEMHEADER


Tab Control Styles

Current tab control styles are supported, and the following styles have been added.
Value | Description
TCS_BOTTOM | Version 4.70. Tabs appear at the bottom of the control. This value equals TCS_RIGHT.
TCS_BUTTONS | Tabs appear as buttons, and no border is drawn around the display area.
TCS_FIXEDWIDTH | All tabs are the same width. This style cannot be combined with the TCS_RIGHTJUSTIFY style.
TCS_FLATBUTTONS | Version 4.71. Selected tabs appear as being indented into the background while other tabs appear as being on the same plane as the background. This style only affects tab controls with the TCS_BUTTONS style.
TCS_FOCUSNEVER | The tab control never receives the input focus.
TCS_FOCUSONBUTTONDOWN | Tabs receive the input focus when clicked.
TCS_FORCEICONLEFT | Icons are aligned with the left edge of each fixed-width tab. This style can only be used with the TCS_FIXEDWIDTH style.
TCS_FORCELABELLEFT Labels are aligned with the left edge of each fixed-width tab; that is, the label is displayed immediately to the right of the icon instead of being centered.

This style can only be used with the TCS_FIXEDWIDTH style, and it implies the TCS_FORCEICONLEFT style.

TCS_HOTTRACK | Version 4.70. Items under the pointer are automatically highlighted.
TCS_MULTILINE | Multiple rows of tabs are displayed, if necessary, so all tabs are visible at once.
TCS_MULTISELECT | Version 4.70. Multiple tabs can be selected by holding down CTRL when clicking. This style must be used with the TCS_BUTTONS style.
TCS_OWNERDRAWFIXED | The parent window is responsible for drawing tabs.
TCS_RAGGEDRIGHT | Rows of tabs will not be stretched to fill the entire width of the control. This style is the default.
TCS_RIGHT | Version 4.70. Tabs appear vertically on the right side of controls that use the TCS_VERTICAL style. This value equals TCS_BOTTOM.
TCS_RIGHTJUSTIFY The width of each tab is increased, 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_SCROLLOPPOSITE | Version 4.70. Unneeded tabs scroll to the opposite side of the control when a tab is selected.
TCS_SINGLELINE | Only one row of tabs is displayed. The user can scroll to see more tabs, if necessary. This style is the default.
TCS_TABS | Tabs appear as tabs, and a border is drawn around the display area. This style is the default.
TCS_TOOLTIPS | The tab control has a tooltip control associated with it.
TCS_VERTICAL | Version 4.70. Tabs appear at the left side of the control, with tab text displayed vertically. This style is valid only when used with the TCS_MULTILINE style. To make tabs appear on the right side of the control, also use the TCS_RIGHT style.


Tab Control Extended Styles

The tab control now supports extended styles. These styles are manipulated using the TCM_GETEXTENDEDSTYLE and TCM_SETEXTENDEDSTYLE messages and should not be confused with extended window styles which are passed to CreateWindowEx.
Value | Description
TCS_EX_FLATSEPARATORS | Version 4.71. The tab control will draw separators between the tab items. This extended style only affects tab controls that have the TCS_BUTTONS and TCS_FLATBUTTONS styles. By default, creating the tab control with the TCS_FLATBUTTONS style sets this extended style. If you do not require separators, you should remove this extended style after creating the control.
TCS_EX_REGISTERDROP | Version 4.71. The tab control generates TCN_GETOBJECT notification messages to request a drop target object when an object is dragged over the tab items in the control. The application must call CoInitialize or OleInitialize before setting this style.


Tab Control Item States

Tab control items now support an item state to support the TCM_DESELECTALL message. Additionally, the TCITEM structure supports item state values.
Value | Description
TCIS_BUTTONPRESSED | Version 4.70. The tab control item is selected.
TCIS_HIGHLIGHTED | Version 4.71. The tab control item is highlighted, and the tab and text are drawn using the current highlight color. When using high-color, this will be a true interpolation, not a dithered color.


Tab Control Messages

This section contains information about the messages used with tab controls.

TCM_ADJUSTRECT

TCM_DELETEALLITEMS

TCM_DELETEITEM

TCM_DESELECTALL

TCM_GETCURFOCUS

TCM_GETCURSEL

TCM_GETEXTENDEDSTYLE

TCM_GETIMAGELIST

TCM_GETITEM

TCM_GETITEMCOUNT

TCM_GETITEMRECT

TCM_GETROWCOUNT

TCM_GETTOOLTIPS

TCM_GETUNICODEFORMAT

TCM_HIGHLIGHTITEM

TCM_HITTEST

TCM_INSERTITEM

TCM_REMOVEIMAGE

TCM_SETCURFOCUS

TCM_SETCURSEL

TCM_SETEXTENDEDSTYLE

TCM_SETIMAGELIST

TCM_SETITEM

TCM_SETITEMEXTRA

TCM_SETITEMSIZE

TCM_SETMINTABWIDTH

TCM_SETPADDING

TCM_SETTOOLTIPS

TCM_SETUNICODEFORMAT


TCM_ADJUSTRECT

TCM_ADJUSTRECT
    wParam = (WPARAM) (BOOL) fLarger;
    lParam = (LPARAM) (LPRECT) prc;

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.

  • No return value.
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
Address of a RECT structure that specifies the given rectangle and receives the calculated rectangle.


TCM_DELETEALLITEMS

TCM_DELETEALLITEMS
    wParam = 0;
    lParam = 0;

Removes all items from a tab control. You can send this message explicitly or by using the TabCtrl_DeleteAllItems macro.

  • Returns TRUE if successful, or FALSE otherwise.


TCM_DELETEITEM

TCM_DELETEITEM
    wParam = (WPARAM) (int) iItem;
    lParam = 0;

Removes an item from a tab control. You can send this message explicitly or by using the TabCtrl_DeleteItem macro.

  • Returns TRUE if successful, or FALSE otherwise.
iItem
Index of the item to delete.


TCM_DESELECTALL

TCM_DESELECTALL
    wParam = (WPARAM) (DWORD) fExcludeFocus;
    lParam = 0;

Resets items in a tab control, clearing any that were set to the TCIS_BUTTONPRESSED state. You can send this message explicitly or by using the TabCtrl_DeselectAll macro.

  • The return value for this message is not used.
fExcludeFocus
Flag that specifies the scope of the item deselection. If this parameter is set to FALSE, all tab items will be reset. If it is set to TRUE, then all tab items except for the one currently selected will be reset.

Version 4.70


TCM_GETCURFOCUS

TCM_GETCURFOCUS
    wParam = 0;
    lParam = 0;

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.

  • Returns the index of the tab item that has the focus.

The item that has the focus may be different than the selected item.


TCM_GETCURSEL

TCM_GETCURSEL
    wParam = 0;
    lParam = 0;

Determines the currently selected tab in a tab control. You can send this message explicitly or by using the TabCtrl_GetCurSel macro.

  • Returns the index of the selected tab if successful, or -1 if no tab is selected.


TCM_GETEXTENDEDSTYLE

TCM_GETEXTENDEDSTYLE
    wParam = 0;
    lParam = 0;

Retrieves the extended styles that are currently in use for the tab control. You can send this message explicitly or by using the TabCtrl_GetExtendedStyle macro.

  • Returns a DWORD value that represents the extended styles currently in use for the tab control. This value is a combination of tab control extended styles.

Version 4.71


TCM_GETIMAGELIST

TCM_GETIMAGELIST
    wParam = 0;
    lParam = 0;

Retrieves the image list associated with a tab control. You can send this message explicitly or by using the TabCtrl_GetImageList macro.

  • Returns the handle to the image list if successful, or NULL otherwise.


TCM_GETITEM

TCM_GETITEM
    wParam = (WPARAM) (int) iItem;
    lParam = (LPARAM) (LPTCITEM) pitem;

Retrieves information about a tab in a tab control. You can send this message explicitly or by using the TabCtrl_GetItem macro.

  • Returns TRUE if successful, or FALSE otherwise.
iItem
Index of the tab.
pitem
Address of a TCITEM 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.


TCM_GETITEMCOUNT

TCM_GETITEMCOUNT
    wParam = 0;
    lParam = 0;

Retrieves the number of tabs in the tab control. You can send this message explicitly or by using the TabCtrl_GetItemCount macro.

  • Returns the number of items if successful, or zero otherwise.


TCM_GETITEMRECT

TCM_GETITEMRECT
    wParam = (WPARAM) (int) iItem;
    lParam = (LPARAM) (RECT FAR *) prc;

Retrieves the bounding rectangle for a tab in a tab control. You can send this message explicitly or by using the TabCtrl_GetItemRect macro.

  • Returns TRUE if successful, or FALSE otherwise.
iItem
Index of the tab.
prc
Address of a RECT structure that receives the bounding rectangle of the tab, in viewport coordinates.


TCM_GETROWCOUNT

TCM_GETROWCOUNT
    wParam = 0;
    lParam = 0;

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.

  • Returns the number of rows of tabs.

Only tab controls that have the TCS_MULTILINE style can have multiple rows of tabs.


TCM_GETTOOLTIPS

TCM_GETTOOLTIPS
    wParam = 0;
    lParam = 0;

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.

  • Returns the handle to the tooltip control if successful, or NULL otherwise.

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.


TCM_GETUNICODEFORMAT

TCM_GETUNICODEFORMAT
    wParam = 0;
    lParam = 0;

Retrieves the UNICODE character format flag for the control. You can send this message explicitly or use the TabCtrl_GetUnicodeFormat macro.

  • Returns the UNICODE format flag for the control. If this value is nonzero, the control is using UNICODE characters. If this value is zero, the control is using ANSI characters.

See also TCM_SETUNICODEFORMAT


TCM_HIGHLIGHTITEM

TCM_HIGHLIGHTITEM
    wParam = (WPARAM) idItem;
    lParam = (LPARAM) MAKELONG(fHighlight,0);

Sets the highlight state of a tab item. You can send this message explicitly or by using the TabCtrl_HighlightItem macro.

  • Returns nonzero if successful, or zero otherwise.
idItem
Zero-based index of a tab control item.
fHighlight
Value specifying the highlight state to be set. If this value is TRUE, the tab is highlighted; if FALSE, the tab is set to its default state.

Version 4.71


TCM_HITTEST

TCM_HITTEST
    wParam = 0;
    lParam = (LPARAM) (LPTCHITTESTINFO) pinfo;

Determines which tab, if any, is at a specified screen position. You can send this message explicitly or by using the TabCtrl_HitTest macro.

  • Returns the index of the tab, or -1 if no tab is at the specified position.
pinfo
Address of a TCHITTESTINFO structure that specifies the screen position to test.


TCM_INSERTITEM

TCM_INSERTITEM
    wParam = (WPARAM) (int) iItem;
    lParam = (LPARAM) (const LPTCITEM) pitem;

Inserts a new tab in a tab control. You can send this message explicitly or by using the TabCtrl_InsertItem macro.

  • Returns the index of the new tab if successful, or -1 otherwise.
iItem
Index of the new tab.
pitem
Address of a TCITEM structure that specifies the attributes of the tab. The dwState and dwStateMask members of this structure are ignored by this message.


TCM_REMOVEIMAGE

TCM_REMOVEIMAGE
    wParam = (WPARAM) (int) iImage;
    lParam = 0;

Removes an image from a tab control's image list. You can send this message explicitly or by using the TabCtrl_RemoveImage macro.

  • No return value.
iImage
Index of the image to remove.

The tab control updates each tab's image index, so each tab remains associated with the same image as before. If a tab is using the image being removed, the tab will be set to have no image.


TCM_SETCURFOCUS

TCM_SETCURFOCUS
    wParam = (WPARAM) (int) iItem;
    lParam = 0;

Sets the focus to a specified tab in a tab control. You can send this message explicitly or by using the TabCtrl_SetCurFocus macro.

  • No return value.
iItem
Index of the tab that gets the focus.

If the tab control has the TCS_BUTTONS style (button mode), the tab with the focus may be different from the selected tab. For example, when a tab is selected, the user can press the arrow keys to set the focus to a different tab without changing the selected tab. In button mode, TCM_SETCURFOCUS sets the input focus to the button associated with the specified tab, but it does not change the selected tab.

If the tab control does not have the TCS_BUTTONS style, changing the focus also changes the selected tab. In this case, the tab control sends the TCN_SELCHANGING and TCN_SELCHANGE notification messages to its parent window.

See also TCM_GETCURFOCUS


TCM_SETCURSEL

TCM_SETCURSEL
    wParam = (WPARAM) (int) iItem;
    lParam = 0;

Selects a tab in a tab control. You can send this message explicitly or by using the TabCtrl_SetCurSel macro.

  • Returns the index of the previously selected tab if successful, or -1 otherwise.
iItem
Index of the tab to select.

A tab control does not send a TCN_SELCHANGING or TCN_SELCHANGE notification message when a tab is selected using this message.


TCM_SETEXTENDEDSTYLE

TCM_SETEXTENDEDSTYLE
    wParam = (WPARAM)dwExMask;
    lParam = (LPARAM)dwExStyle;

Sets the extended styles that the tab control will use. You can send this message explicitly or by using the TabCtrl_SetExtendedStyle macro.

  • Returns a DWORD value that contains the previous tab control extended styles.
dwExMask
A DWORD value that indicates which styles in dwExStyle are to be affected. Only the extended styles in dwExMask will be changed. All other styles will be maintained as they are. If this parameter is zero, then all of the styles in dwExStyle will be affected.
dwExStyle
Value specifying the extended tab control styles. This value is a combination of tab control extended styles.

The dwExMask parameter allows you to modify one or more extended styles without having to retrieve the existing styles first. For example, if you pass TCS_EX_FLATSEPARATORS for dwExMask and 0 for dwExStyle, the TCS_EX_FLATSEPARATORS style will be cleared, but all other styles will remain the same.

For backward compatibility reasons, the TabCtrl_SetExtendedStyle macro has not been updated to use dwExMask.

Version 4.71


TCM_SETIMAGELIST

TCM_SETIMAGELIST
    wParam = 0;
    lParam = (LPARAM) (HIMAGELIST) himl;

Assigns an image list to a tab control. You can send this message explicitly or by using the TabCtrl_SetImageList macro.

  • Returns the handle to the previous image list, or NULL if there is no previous image list.
himl
Handle to the image list to assign to the tab control.


TCM_SETITEM

TCM_SETITEM
    wParam = (WPARAM) (int) iItem;
    lParam = (LPARAM) (LPTCITEM) pitem;

Sets some or all of a tab's attributes. You can send this message explicitly or by using the TabCtrl_SetItem macro.

  • Returns TRUE if successful, or FALSE otherwise.
iItem
Index of the item.
pitem
Address of a TCITEM 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.


TCM_SETITEMEXTRA

TCM_SETITEMEXTRA
    wParam = (WPARAM) (int) cb;
    lParam = 0;

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.

  • Returns TRUE if successful, or FALSE otherwise.
cb
Number of extra bytes.

By default, the number of extra bytes is four. An application that changes the number of extra bytes cannot use the TCITEM structure to retrieve and set the application-defined data for a tab. Instead, you must define a new structure that consists of the TCITEMHEADER 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.


TCM_SETITEMSIZE

TCM_SETITEMSIZE
    wParam = 0;
    lParam = MAKELPARAM(cx, cy);

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.

  • 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.
cx and cy
New width and height, in pixels.


TCM_SETMINTABWIDTH

TCM_SETMINTABWIDTH
    wParam = 0;
    lParam = (LPARAM) (INT) cx;

Sets the minimum width of items in a tab control. You can send this message explicitly or by using the TabCtrl_SetMinTabWidth macro.

  • Returns an INT value that represents the previous minimum tab width.
cx
Minimum width to be set for a tab control item. If this parameter is set to -1, the control will use the default tab width.

Version 4.70


TCM_SETPADDING

TCM_SETPADDING
    wParam = 0;
    lParam = MAKELPARAM(cx, cy);

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.

  • No return value.
cx and cy
Amount of horizontal and vertical padding, in pixels.


TCM_SETTOOLTIPS

TCM_SETTOOLTIPS
    wParam = (WPARAM) (HWND) hwndTT;
    lParam = 0;

Assigns a tooltip control to a tab control. You can send this message explicitly or by using the TabCtrl_SetToolTips macro.

  • No return value.
hwndTT
Handle to the tooltip control.

You can get the tooltip control associated with a tab control by using the TCM_GETTOOLTIPS message.


TCM_SETUNICODEFORMAT

TCM_SETUNICODEFORMAT
    wParam = (WPARAM)(BOOL)fUnicode;
    lParam = 0;

Sets the UNICODE character format flag for the control. This message allows you to change the character set used by the control at run time rather than having to re-create the control. You can send this message explicitly or use the TabCtrl_SetUnicodeFormat macro.

  • Returns the previous UNICODE format flag for the control.
fUnicode
Determines the character set that is used by the control. If this value is nonzero, the control will use UNICODE characters. If this value is zero, the control will use ANSI characters.

See also TCM_GETUNICODEFORMAT


Tab Control Macros

This section contains information about the utility macros used with tab controls.

TabCtrl_AdjustRect

TabCtrl_DeleteAllItems

TabCtrl_DeleteItem

TabCtrl_DeselectAll

TabCtrl_GetCurFocus

TabCtrl_GetCurSel

TabCtrl_GetExtendedStyle

TabCtrl_GetImageList

TabCtrl_GetItem

TabCtrl_GetItemCount

TabCtrl_GetItemRect

TabCtrl_GetRowCount

TabCtrl_GetToolTips

TabCtrl_GetUnicodeFormat

TabCtrl_HighlightItem

TabCtrl_HitTest

TabCtrl_InsertItem

TabCtrl_RemoveImage

TabCtrl_SetCurFocus

TabCtrl_SetCurSel

TabCtrl_SetExtendedStyle

TabCtrl_SetImageList

TabCtrl_SetItem

TabCtrl_SetItemExtra

TabCtrl_SetItemSize

TabCtrl_SetMinTabWidth

TabCtrl_SetPadding

TabCtrl_SetToolTips

TabCtrl_SetUnicodeFormat


TabCtrl_AdjustRect

VOID TabCtrl_AdjustRect(
    HWND hwnd,
    BOOL fLarger,
    RECT FAR *prc
);

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 use this macro or send the TCM_ADJUSTRECT message explicitly.

  • No return value.
hwnd
Handle to the tab control.
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
Address of a RECT structure that specifies the given rectangle and receives the calculated rectangle.


TabCtrl_DeleteAllItems

BOOL TabCtrl_DeleteAllItems(
    HWND hwnd
);

Removes all items from a tab control. You can use this macro or send the TCM_DELETEALLITEMS message explicitly.

  • Returns TRUE if successful, or FALSE otherwise.
hwnd
Handle to the tab control.


TabCtrl_DeleteItem

BOOL TabCtrl_DeleteItem(
    HWND hwnd,
    int iItem
);

Removes an item from a tab control. You can use this macro or send the TCM_DELETEITEM message explicitly.

  • Returns TRUE if successful, or FALSE otherwise.
hwnd
Handle to the tab control.
iItem
Index of the item to delete.


TabCtrl_DeselectAll

void TabCtrl_DeselectAll(
    HWND hwndTab,
    UINT fExcludeFocus
);

Resets items in a tab control, clearing any that were set to the TCIS_BUTTONPRESSED state. You can use this macro or send the TCM_DESELECTALL message explicitly.

  • The return value is not used.
hwndTab
Handle to the tab control.
fExcludeFocus
Flag value that specifies the scope of the item deselection. If this parameter is set to FALSE, all tab items will be reset. If it is set to TRUE, all but the currently selected tab item will be reset.

Version 4.70


TabCtrl_GetCurFocus

int TabCtrl_GetCurFocus(
    HWND hwnd
);

Returns the index of the item that has the focus in a tab control. You can use this macro or send the TCM_GETCURFOCUS message explicitly.

  • Returns the index of the tab item that has the focus.
hwnd
Handle to the tab control.

The item that has the focus may be different than the selected item.


TabCtrl_GetCurSel

int TabCtrl_GetCurSel(
    HWND hwnd
);

Determines the currently selected tab in a tab control. You can use this macro or send the TCM_GETCURSEL message explicitly.

  • Returns the index of the selected tab if successful, or -1 if no tab is selected.
hwnd
Handle to the tab control.


TabCtrl_GetExtendedStyle

DWORD TabCtrl_GetExtendedStyle(
    HWND hwndTab
);

Retrieves the extended styles that are currently in use for the tab control. You can use this macro or send the TCM_GETEXTENDEDSTYLE message explicitly.

  • Returns a DWORD value that represents the extended styles currently in use for the tab control. This value is a combination of tab control extended styles.
hwndTab
Handle to the tab control.

Version 4.71


TabCtrl_GetImageList

HIMAGELIST TabCtrl_GetImageList(
    HWND hwnd
);

Retrieves the image list associated with a tab control. You can use this macro or send the TCM_GETIMAGELIST message explicitly.

  • Returns the handle to the image list if successful, or NULL otherwise.


TabCtrl_GetItem

BOOL TabCtrl_GetItem(
    HWND hwnd,
    int iItem,
    LPTCITEM pitem
);

Retrieves information about a tab in a tab control. You can use this macro or send the TCM_GETITEM message explicitly.

  • Returns TRUE if successful, or FALSE otherwise.
hwnd
Handle to the tab control.
iItem
Index of the tab.
pitem
Address of a TCITEM 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.


TabCtrl_GetItemCount

int TabCtrl_GetItemCount(
    HWND hwnd
);

Retrieves the number of tabs in the tab control. You can use this macro or send the TCM_GETITEMCOUNT message explicitly.

  • Returns the number of items if successful, or zero otherwise.
hwnd
Handle to the tab control.


TabCtrl_GetItemRect

BOOL TabCtrl_GetItemRect(
    HWND hwnd,
    int iItem,
    RECT FAR *prc
);

Retrieves the bounding rectangle for a tab in a tab control. You can use this macro or send the TCM_GETITEMRECT message explicitly.

  • Returns TRUE if successful, or FALSE otherwise.
hwnd
Handle to the tab control.
iItem
Index of the tab.
prc
Address of a RECT structure that receives the bounding rectangle of the tab, in viewport coordinates.


TabCtrl_GetRowCount

int TabCtrl_GetRowCount(
    HWND hwnd
);

Retrieves the current number of rows of tabs in a tab control. You can use this macro or send the TCM_GETROWCOUNT message explicitly.

  • Returns the number of rows of tabs.
hwnd
Handle to the tab control.

Only tab controls that have the TCS_MULTILINE style can have multiple rows of tabs.


TabCtrl_GetToolTips

int TabCtrl_GetToolTips(
    HWND hwnd
);

Retrieves the handle to the tooltip control associated with a tab control. You can use this macro or send the TCM_GETTOOLTIPS message explicitly.

  • Returns the handle to the tooltip control if successful, or NULL otherwise.
hwnd
Handle to the tab control.

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.


TabCtrl_GetUnicodeFormat

BOOL TabCtrl_GetUnicodeFormat(
    HWND hwnd
);

Retrieves the UNICODE character format flag for the control. You can use this macro or send the TCM_GETUNICODEFORMAT message explicitly.

  • Returns the UNICODE format flag for the control. If this value is nonzero, the control is using UNICODE characters. If this value is zero, the control is using ANSI characters.
hwnd
Handle to the control.

See also TabCtrl_SetUnicodeFormat


TabCtrl_HighlightItem

BOOL TabCtrl_HighlightItem(
    HWND hwndTab,
    INT idItem,
    WORD fHighlight
);

Sets the highlight state of a tab item. You can use this macro or send the TCM_HIGHLIGHTITEM message explicitly.

  • Returns nonzero if successful, or zero otherwise.
hwndTab
Handle to the tab control.
idItem
Zero-based index of a tab control item.
fHighlight
Value specifying the highlight state to be set. If this value is nonzero, the tab is highlighted. If this value is zero, the tab is set to its default state.

Version 4.71


TabCtrl_HitTest

int TabCtrl_HitTest(
    HWND hwnd,
    LPTCHITTESTINFO pinfo
);

Determines which tab, if any, is at a specified screen position. You can use this macro or send the TCM_HITTEST message explicitly.

  • Returns the index of the tab, or -1 if no tab is at the specified position.
hwnd
Handle to the tab control.
pinfo
Address of a TCHITTESTINFO structure that specifies the screen position to test.


TabCtrl_InsertItem

int TabCtrl_InsertItem(
    HWND hwnd,
    int iItem,
    const LPTCITEM pitem
);

Inserts a new tab in a tab control. You can use this macro or send the TCM_INSERTITEM message explicitly.

  • Returns the index of the new tab if successful, or -1 otherwise.
hwnd
Handle to the tab control.
iItem
Index of the new tab.
pitem
Address of a TCITEM structure that specifies the attributes of the tab. The dwState and dwStateMask members of this structure are ignored by this message.


TabCtrl_RemoveImage

void TabCtrl_RemoveImage(
    HWND hwnd,
    int iImage
);

Removes an image from a tab control's image list. You can use this macro or send the TCM_REMOVEIMAGE message explicitly.

  • No return value.
hwnd
Handle to the tab control.
iImage
Index of the image to remove.

The tab control updates each tab's image index, so each tab remains associated with the same image as before. If a tab is using the image being removed, the tab will be set to have no image.


TabCtrl_SetCurFocus

VOID TabCtrl_SetCurFocus(
    HWND hwnd,
    int  iItem
);

Sets the focus to a specified tab in a tab control. You can use this macro or send the TCM_SETCURFOCUS message explicitly.

  • No return value.
hwnd
Handle to the tab control.
iItem
Zero-based index of the tab that gets the focus.

If the tab control has the TCS_BUTTONS style (button mode), the tab with the focus may be different from the selected tab. For example, when a tab is selected, the user can press the arrow keys to set the focus to a different tab without changing the selected tab. In button mode, the TabCtrl_SetCurFocus macro sets the input focus to the button associated with the specified tab, but it does not change the selected tab.

If the tab control does not have the TCS_BUTTONS style, changing the focus also changes the selected tab. In this case, the tab control sends the TCN_SELCHANGING and TCN_SELCHANGE notification messages to its parent window.

See also TabCtrl_GetCurFocus, TCM_GETCURFOCUS


TabCtrl_SetCurSel

int TabCtrl_SetCurSel(
    HWND hwnd,
    int iItem
);

Selects a tab in a tab control. You can use this macro or send the TCM_SETCURSEL message explicitly.

  • Returns the index of the previously selected tab if successful, or -1 otherwise.
hwnd
Handle to the tab control.
iItem
Index of the tab to select.

A tab control does not send a TCN_SELCHANGING or TCN_SELCHANGE notification message when a tab is selected using the TCM_SETCURSEL message.


TabCtrl_SetExtendedStyle

DWORD TabCtrl_SetExtendedStyle(
    HWND hwndTab,
    DWORD dwExStyle
);

Sets the extended styles that the tab control will use. You can use this macro or send the TCM_SETEXTENDEDSTYLE message explicitly.

  • Returns a DWORD value that contains the previous tab control extended styles.
hwndTab
Handle to the tab control.
dwExStyle
Value that contains the new tab control extended styles. This value is a combination of tab control extended styles.

Version 4.71


TabCtrl_SetImageList

BOOL TabCtrl_SetImageList(
    HWND hwnd,
    HIMAGELIST himl
);

Assigns an image list to a tab control. You can use this macro or send the TCM_SETIMAGELIST message explicitly.

  • Returns the handle to the previous image list, or NULL if there is no previous image list.
hwnd
Handle to the tab control.
himl
Handle to the image list to assign to the tab control.


TabCtrl_SetItem

BOOL TabCtrl_SetItem(
    HWND hwnd,
    int iItem,
    LPTCITEM pitem
);

Sets some or all of a tab's attributes. You can use this macro or send the TCM_SETITEM message explicitly.

  • Returns TRUE if successful, or FALSE otherwise.
hwnd
Handle to the tab control.
iItem
Index of the item.
pitem
Address of a TCITEM 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.


TabCtrl_SetItemExtra

BOOL TabCtrl_SetItemExtra(
    HWND hwnd,
    int cb
);

Sets the number of bytes per tab reserved for application-defined data in a tab control. You can use this macro or send the TCM_SETITEMEXTRA message explicitly.

  • Returns TRUE if successful, or FALSE otherwise.
hwnd
Handle to the tab control.
cb
Number of extra bytes.

By default, the number of extra bytes is four. An application that changes the number of extra bytes cannot use the TCITEM structure to retrieve and set the application-defined data for a tab. Instead, you must define a new structure that consists of the TCITEMHEADER 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.


TabCtrl_SetItemSize

DWORD TabCtrl_SetItemSize(
    HWND hwnd,
    int cx,
    int cy
);

Sets the width and height of tabs in a fixed-width or owner-drawn tab control. You can use this macro or send the TCM_SETITEMSIZE message explicitly.

  • 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.
hwnd
Handle to the tab control.
cx and cy
New width and height, in pixels.


TabCtrl_SetMinTabWidth

int TabCtrl_SetMinTabWidth(
    HWND hwndTab,
    INT cx
);

Sets the minimum width of items in a tab control. You can use this macro or send the TCM_SETMINTABWIDTH message explicitly.

  • Returns an INT value that represents the previous minimum tab width.
hwndTab
Handle to the tab control.
cx
Minimum width to be set for a tab control item. If this parameter is set to -1, the control will use the default tab width.

Version 4.70


TabCtrl_SetPadding

void TabCtrl_SetPadding(
    HWND hwnd,
    int cx,
    int cy
);

Sets the amount of space (padding) around each tab's icon and label in a tab control. You can use this macro or send the TCM_SETPADDING message explicitly.

  • No return value.
hwnd
Handle to the tab control.
cx and cy
Amount of horizontal and vertical padding, in pixels.


TabCtrl_SetToolTips

void TabCtrl_SetToolTips(
    HWND hwndTab,
    HWND hwndTT
);

Assigns a tooltip control to a tab control. You can use this macro or send the TCM_SETTOOLTIPS message explicitly.

  • No return value.
hwndTab
Handle to the tab control.
hwndTT
Handle to the tooltip control.

You can get the tooltip control associated with a tab control by using the TCM_GETTOOLTIPS message.


TabCtrl_SetUnicodeFormat

BOOL TabCtrl_SetUnicodeFormat(
    HWND hwnd,
    BOOL fUnicode
);

Sets the UNICODE character format flag for the control. This message allows you to change the character set used by the control at run time rather than having to re-create the control. You can use this macro or send the TCM_SETUNICODEFORMAT message explicitly.

  • Returns the previous UNICODE format flag for the control.
hwnd
Handle to the control.
fUnicode
Determines the character set that is used by the control. If this value is nonzero, the control will use UNICODE characters. If this value is zero, the control will use ANSI characters.

See also TabCtrl_GetUnicodeFormat


Tab Control Notification Messages

This section contains information about the notification messages sent by tab controls.

NM_CLICK (tab)

NM_RCLICK (tab)

NM_RELEASEDCAPTURE (tab)

TCN_GETOBJECT

TCN_KEYDOWN

TCN_SELCHANGE

TCN_SELCHANGING


NM_CLICK (tab)

NM_CLICK
    lpnmh = (LPNMHDR) lParam;

Notifies a tab control's parent window that the user has clicked the left mouse button within the control. NM_CLICK is sent in the form of a WM_NOTIFY message.

  • The return value is ignored by the tab control.
lpnmh
Address of an NMHDR structure that contains additional information about this notification message.


NM_RCLICK (tab)

NM_RCLICK
    lpnmh = (LPNMHDR) lParam;

Notifies a tab control's parent window that the user has clicked the right mouse button within the control. NM_RCLICK is sent in the form of a WM_NOTIFY message.

  • The return value is ignored by the tab control.
lpnmh
Address of an NMHDR structure that contains additional information about this notification message.


NM_RELEASEDCAPTURE (tab)

NM_RELEASEDCAPTURE
    lpnmh = (LPNMHDR) lParam;

Notifies a tab control's parent window that the control is releasing mouse capture. This notification is sent in the form of a WM_NOTIFY message.

  • The control ignores the return value from this notification.
lpnmh
Address of an NMHDR structure that contains additional information about this notification message.

Version 4.71.


TCN_GETOBJECT

TCN_GETOBJECT
    lpnmon = (LPNMOBJECTNOTIFY) lParam;

Sent by a tab control when it has the TCS_EX_REGISTERDROP extended style and an object is dragged over a tab item in the control. This notification message is sent in the form of a WM_NOTIFY message.

  • The application processing this notification must return zero.
lpnmon
Address of an NMOBJECTNOTIFY structure that contains information about the tab item the object is dragged over and receives data the application returns in response to this message.

Version 4.71


TCN_KEYDOWN

TCN_KEYDOWN
    pnm = (NMTCKEYDOWN FAR *) lParam;

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.

  • No return value.
pnm
Address of an NMTCKEYDOWN structure.


TCN_SELCHANGE

TCN_SELCHANGE
    lpnmhdr = (LPNMHDR) lParam;

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.

  • No return value.
lpnmhdr
Address of an NMHDR structure. The hwndFrom member is the handle to the tab control. The idFrom member is the child window identifier of the tab control. The code member is TCN_SELCHANGE.

To determine the currently selected tab, use the TabCtrl_GetCurSel macro.

See also TCN_SELCHANGING


TCN_SELCHANGING

TCN_SELCHANGING
    lpnmhdr = (LPNMHDR) lParam;

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.

  • Returns TRUE to prevent the selection from changing, or FALSE to allow the selection to change.
lpnmhdr
Address of an NMHDR structure. The hwndFrom member is the handle to the tab control. The idFrom member is the child window identifier of the tab control. The code member is TCN_SELCHANGING.

To determine the currently selected tab, use the TabCtrl_GetCurSel macro.

See also TCN_SELCHANGE


Tab Control Structures

This section contains information about the structures used with tab controls.

NMTCKEYDOWN

TCHITTESTINFO

TCITEM

TCITEMHEADER


NMTCKEYDOWN

typedef struct tagNMTCKEYDOWN {
    NMHDR hdr;
    WORD wVKey;
    UINT flags;
} NMTCKEYDOWN;

Contains information about a key press in a tab control. It is used with the TCN_KEYDOWN notification message. This structure supersedes the TC_KEYDOWN structure.

hdr
NMHDR structure that contains information about the notification message.
wVKey
Virtual key code.
flags
Value that is identical to the lParam parameter of the WM_KEYDOWN message.


TCHITTESTINFO

typedef struct tagTCHITTESTINFO {
    POINT pt;
    UINT  flags;
} TCHITTESTINFO, FAR * LPTCHITTESTINFO;

Contains information about a hit test. This structure supersedes the TC_HITTESTINFO structure.

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

See also TCM_HITTEST


TCITEM

typedef struct tagTCITEM {
    UINT mask;
#if (_WIN32_IE >= 0x0300)
    DWORD dwState;
    DWORD dwStateMask;
#else
    UINT lpReserved1;
    UINT lpReserved2;
#endif
    LPTSTR pszText;
    int cchTextMax;
    int iImage;
    LPARAM lParam;
} TCITEM, FAR *LPTCITEM;

Specifies or receives the attributes of a tab item. It is used with the TCM_INSERTITEM, TCM_GETITEM, and TCM_SETITEM messages. This structure supersedes the TC_ITEM structure.

mask
Value that specifies which members to retrieve or set. This member can be a combination of the following values:
TCIF_IMAGE | The iImage member is valid.
TCIF_PARAM | The lParam member is valid.
TCIF_RTLREADING | The text of pszText is displayed using right-to-left reading order on Hebrew or Arabic systems.
TCIF_STATE | Version 4.70. The dwState member is valid.
TCIF_TEXT | The pszText member is valid.
dwState
Version 4.70. Specifies the item's current state if information is being retrieved. If item information is being set, this member contains the state value to be set for the item. For a list of valid tab control item states, see Tab Control Item States. This member is ignored in the TCM_INSERTITEM message.
dwStateMask
Version 4.70. Specifies which bits of the dwState member contain valid information. This member is ignored in the TCM_INSERTITEM message.
lpReserved1
Version 4.00. Not used.
lpReserved2
Version 4.00. Not used.
pszText
Address of a null-terminated string that contains the tab text when item information is being set. If item information is being retrieved, 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 in the tab control's image list, or -1 if there is no image for the tab.
lParam
Application-defined data associated with the tab control item. If more or less than 4 bytes of application-defined data exist per tab, an application must define a structure and use it instead of the TCITEM structure. The first member of the application-defined structure must be a TCITEMHEADER structure.


TCITEMHEADER

typedef struct tagTCITEMHEADER{
    UINT   mask;
    UINT   lpReserved1;
    UINT   lpReserved2;
    LPTSTR pszText;
    int    cchTextMax;
    int    iImage;
} TCITEMHEADER, FAR *LPTCITEMHEADER;

Specifies or receives the attributes of a tab. It is used with the TCM_INSERTITEM, TCM_GETITEM, and TCM_SETITEM messages. This structure supersedes the TC_ITEMHEADER structure.

mask
Value that specifies which members to retrieve or set. This member can be a combination of the following values:
TCIF_IMAGE | The iImage member is valid.
TCIF_RTLREADING | The text of pszText is displayed using right-to-left reading order on Hebrew or Arabic systems.
TCIF_TEXT | The pszText member is valid.
lpReserved1
Reserved member. Do not use.
lpReserved2
Reserved member. Do not use.
pszText
Address of a null-terminated string that contains the tab text if item information is being set. If item information is being retrieved, 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.


Toolbar Controls

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

About Toolbar Controls

Using Toolbar Controls

Toolbar Control Updates in Internet Explorer

Toolbar Control Reference

About Toolbar Controls

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.

Window with 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. If you will be retrieving the size of the toolbar, you must send the TB_AUTOSIZE message after all of the items and strings have been inserted into the control to cause the toolbar to recalculate its size based on its content.

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 moves the cursor over a toolbar button and leaves 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 to see 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 to the tooltip by using the TB_GETTOOLTIPS message. An application can replace the tooltip control of a toolbar with another tooltip control by using the TB_SETTOOLTIPS message.

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.

Microsoft® 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 that act like radio buttons by using the TBSTYLE_GROUP or TBSTYLE_CHECKGROUP style. This causes 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 to 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.

When you add a string that is longer than any string currently in the toolbar, the toolbar automatically resets the width of its buttons. 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. 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 that a drag operation has begun. 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.

When 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 an NMTOOLBAR 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. Messages specific to toolbars are discussed in other sections of this documentation, so 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. If the wParam parameter is non-NULL, the control assumes that the value is an HDC and paints using that device context.
WM_SIZE | Recalculates the size and position of the toolbar and redraws it.
WM_SYSCOLORCHANGE | Updates the colors of the buttons and toolbar to match the system colors.
WM_VKEYTOITEM | Forwards this message to the parent window.
WM_WININICHANGE | Reinitializes internal variables that depend on system metric values.

Using Toolbar Controls

This section contains examples that demonstrate how to create a toolbar and process tooltip notification messages.

Creating a Toolbar

The following example shows how to use 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 to the toolbar if successful, or NULL otherwise.
    // hwndParent - handle to 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);

    SendMessage(hwndTB, TB_AUTOSIZE, 0, 0);

    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 Control Updates in Internet Explorer

Toolbar controls in Microsoft® Internet Explorer support the following new features.

Image List Support
Toolbar controls can use up to three different image lists to display buttons in various states:
Normal | Buttons in their default state.
Hot | Buttons that are under the pointer or pressed. Hot items are only supported in toolbar controls that have the TBSTYLE_FLAT style.
Disabled | Buttons that are disabled.

Applications can still use bitmaps for toolbar buttons. Image list support is offered to allow the control to have greater flexibility. An application sets and retrieves toolbar image lists for normal buttons with the TB_SETIMAGELIST and TB_GETIMAGELIST messages, respectively. Similarly, the TB_SETHOTIMAGELIST, TB_GETHOTIMAGELIST, TB_SETDISABLEDIMAGELIST, and TB_GETDISABLEDIMAGELIST messages perform the same actions for hot and disabled button image lists.

Transparent Toolbars
Toolbar controls support a new, transparent look. An application can create a transparent toolbar control by including the TBSTYLE_FLAT style. With the TBSTYLE_FLAT style in place, the control displays buttons while allowing the client area under the toolbar to show through.

Transparent toolbar controls feature hot tracking. That is, when the user moves the pointer over a toolbar button, the button's appearance changes. The control displays a border around the "hot" button and, if a hot image list is set, switches the image under the pointer.

The following illustration shows a transparent toolbar control with four buttons.

Transparent toolbar control with four buttons.

For more information on transparent toolbars, see Creating a Transparent Toolbar Control later in this section.

Drop-Down Toolbar Buttons
Toolbar controls support drop-down style buttons. Drop-down buttons have the TBSTYLE_DROPDOWN style. When the user clicks a drop-down button, the toolbar control sends its parent a TBN_DROPDOWN notification message. If the parent is going to display a drop-down menu, it can display one using the TrackPopupMenuEx function and return zero to the notification message. For more information, see Supporting Drop-Down Toolbar Buttons later in this section.
Insertion Marks
Toolbar controls now support insertion marks. An insertion mark provides a visual indication where an item will be inserted. This is useful for dragging and dropping items into a toolbar. Insertion marks are implemented using the TB_SETINSERTMARK, TB_GETINSERTMARK, and TB_INSERTMARKHITTEST messages.

Creating a Transparent Toolbar Control

To create a transparent toolbar control, use the CreateWindowEx function, specifying TOOLBARCLASSNAME as the window class. You must first register the window class by calling the InitCommonControlsEx function, while specifying the ICC_BAR_CLASSES bit in the accompanying INITCOMMONCONTROLSEX structure.

An application must prepare a toolbar control by sending messages it uses to manage memory and format its display. The CreateTransparentToolbar sample function creates a normal or list style transparent toolbar control. It accepts style bits in the dwStyle parameter that are used to determine which type of toolbar it will create.

To support button text and list style buttons, CreateTransparentToolbar calls the following application-defined functions:

  • BuildStrList
  • WidestBtn

The CreateTransparentToolbar Sample Function

The CreateTransparentToolbar application-defined function creates and initializes a transparent toolbar.

// CreateTransparentToolbar Function
//     Creates a transparent toolbar control based on the owner's
//     window handle and a supplied set of styles that is assumed
//     to be a combination of TBSTYLE_FLAT and TBSTYLE_LIST flags.
//
// Accepts:
//    HWND: The handle to the parent window.
//    DWORD:  Style values that are included in CreateWindowEx.
//
// Returns:
//    HWND to the newly created toolbar. The owner must resize it.

HWND WINAPI CreateTransparentToolbar(HWND hwndOwner, DWORD dwStyle.)
{
   HWND         hwndTB;
   HIMAGELIST   himl, himlHot;
   TBBUTTON     tbArray[MAX_BUTTONS];
   int          i, iListSpace;
   INITCOMMONCONTROLSEX icex;

   LPTSTR lpszStrList,
          pszStrArray[4] = { "Button 1",
                             "Button 2",
                             "Button 3",
                             "Button 4"};

   icex.dwSize = sizeof(INITCOMMONCONTROLSEX);
   icex.dwICC  = ICC_BAR_CLASSES;
   InitCommonControlsEx(&icex);

   // Create the toolbar control.
   hwndTB=CreateWindowEx(WS_EX_TOOLWINDOW,
                         TOOLBARCLASSNAME,
                         NULL,
                         WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN |
                         WS_CLIPSIBLINGS | CCS_NODIVIDER
                         |CCS_NOPARENTALIGN | CCS_NORESIZE | dwStyle,
                         0,0,0,0,  // Make it zero, Let owner resize it.
                         hwndOwner,
                         NULL, g_hinst, NULL);

   // Sets the size of the TBBUTTON structure.
   SendMessage(hwndTB, TB_BUTTONSTRUCTSIZE, sizeof(TBBUTTON), 0);

   // Set the maximum number of text rows and bitmap size.
   SendMessage(hwndTB, TB_SETMAXTEXTROWS, 1, 0L);
   SendMessage(hwndTB, TB_SETBITMAPSIZE,
               0, (LPARAM)MAKELONG(MYICON_CX, MYICON_CY));

   // Create, fill, and assign the image list for default buttons.
   himl = ImageList_Create(MYICON_CX,MYICON_CY,ILC_COLOR8,0,4);
   ImageList_Add(himl,
                 LoadBitmap(g_hinst,MAKEINTRESOURCE(IDB_DEF1)),NULL);
   ImageList_Add(himl,
                 LoadBitmap(g_hinst, MAKEINTRESOURCE(IDB_DEF2)),NULL);
   ImageList_Add(himl,
                 LoadBitmap(g_hinst, MAKEINTRESOURCE(IDB_DEF3)),NULL);
   ImageList_Add(himl,
                 LoadBitmap(g_hinst, MAKEINTRESOURCE(IDB_DEF4)),NULL);

   SendMessage(hwndTB, TB_SETIMAGELIST, 0, (LPARAM)himl);

   // Create, fill, and assign the image list for hot buttons.
   himlHot = ImageList_Create(MYICON_CX,MYICON_CY,ILC_COLOR8,0,4);
   ImageList_Add(himlHot,
                 LoadBitmap(g_hinst, MAKEINTRESOURCE(IDB_HOT1)),NULL);
   ImageList_Add(himlHot,
                 LoadBitmap(g_hinst, MAKEINTRESOURCE(IDB_HOT2)),NULL);
   ImageList_Add(himlHot,
                 LoadBitmap(g_hinst, MAKEINTRESOURCE(IDB_HOT3)),NULL);
   ImageList_Add(himlHot,
                 LoadBitmap(g_hinst, MAKEINTRESOURCE(IDB_HOT4)),NULL);

   SendMessage(hwndTB, TB_SETHOTIMAGELIST, 0, (LPARAM)himlHot);

   // Loop to fill the array of TBBUTTON structures.
   for(i=0;i<MAX_BUTTONS;i++){
      tbArray[i].iBitmap   = i;
      tbArray[i].idCommand = IDM_BUTTONSTART + i;
      tbArray[i].fsState   = TBSTATE_ENABLED;
      tbArray[i].fsStyle   = TBSTYLE_DROPDOWN;//BUTTON;
      tbArray[i].dwData    = 0;
      tbArray[i].iString   = i;
   }

   // Put button text in the correct format for TB_ADDSTRING.
   lpszStrList = BuildStrList(pszStrArray);

   SendMessage(hwndTB, TB_ADDSTRING, 0,(LPARAM)lpszStrList);

   // If this is a list style toolbar, add buffer pixels
   // to make room for button text.
   iBufferPix=(dwStyle & TBSTYLE_LIST)?WidestBtn(pszStrArray, hwndTB):0;

   // Add the buttons, and then set the minimum and maximum button widths.
   SendMessage(hwndTB,
               TB_ADDBUTTONS, (UINT)MAX_BUTTONS, (LPARAM)tbArray);

   SendMessage(hwndTB,
               TB_SETBUTTONWIDTH, 0,
               (LPARAM)MAKELONG(MYICON_CX+iBufferPix,
               MYICON_CX+iBufferPix));

   return (hwndTB);
}

The BuildStrList Sample Function

The BuildStrList application-defined function creates and fills a buffer based on a static array of strings. The calling function uses the resulting buffer with the TB_ADDSTRING message.

// BuildStrList Function
//    Creates a list of null-terminated strings from a passed-in
//    array of strings. See the documentation about TB_ADDSTRING
//    for specific information about this format.
//
// Accepts:
//    LPTSTR *: Address of the array of strings.
//
// Returns:
//    LPTSTR to the newly created list of button text strings.

LPTSTR WINAPI BuildStrList(LPTSTR * ppszStrArray, INT iStrCount)
{
   LPTSTR pScan,
          pszStrList;

   int i;

   pScan = pszStrList = malloc((size_t)37 * sizeof(char));

   for (i=0;i<iStrCount;i++){
      strcpy(pScan,ppszStrArray[i]);
      pScan += strlen(pScan)+1;
   }
   *pScan = '\0';

   return(pszStrList);
}

The WidestBtn Sample Function

The WidestBtn application-defined function calculates the button width necessary to completely display the widest button text string.

// WidestBtn Function
//     Calculates the width, in pixels, of the widest button in the
//     toolbar. Since toolbar controls use the same width for all
//     buttons, the return value is used when sending the
//     TB_SETBUTTONWIDTH message.
//
// Accepts:
//    LPTSTR *: Address of the array of button text strings.
//    HWND: The handle to the parent window.
//
// Returns:
//    An INT value representing the minimum width, in pixels,
//    a button must be to allow room for the button text.

INT WINAPI WidestBtn(LPTSTR *pszStrArray, HWND hwndOwner)
{
// The toolbar reserves pixels for space between buttons,
// text, and so on. This value is added to the return value
// to compensate.
#define EXTRA_PIXELS 8

   INT      i, iStrMax_cx = 0;
   SIZE     sz;
   LOGFONT  lf;
   HFONT    hFont;
   HDC      hdc;

   // Get the font used to display button text, and then select it into
   // a device context to be passed to GetTextExtentPoint32.
   SystemParametersInfo(SPI_GETICONTITLELOGFONT,sizeof(LOGFONT),&lf,0);

   hdc = GetDC(hwnd);
   hFont = CreateFontIndirect(&lf);
   SelectObject(hdc,hFont);

   // Loop to find the widest string.
   for(i=0;i<MAX_BUTTONS;i++){
      GetTextExtentPoint32(hdc, pszStrArray[i],
                           strlen(pszStrArray[i]), &sz);
      if(sz.cx > iStrMax_cx) iStrMax_cx = sz.cx;
   }

   // Release the DC and font.
   ReleaseDC(hwnd, hdc);
   DeleteObject(hFont);

   // Return the sum of the string width, the border, and extra pixels.
   return (iStrMax_cx + GetSystemMetrics(SM_CXBORDER) + EXTRA_PIXELS);}

Supporting Drop-Down Toolbar Buttons

When the user clicks a toolbar button that uses the TBSTYLE_DROPDOWN style, the toolbar control sends its parent a TBN_DROPDOWN notification message. The following DoNotify application-defined function illustrates how an application can support a drop-down button in a toolbar control by responding to this notification message.

If the incoming notification message is TBN_DROPDOWN, DoNotify retrieves the bounding rectangle of the button the user clicked by sending the TB_GETRECT message. When sending the message, DoNotify specifies the command identifier of the drop-down button as the wParam parameter of the SendMessage function. (The button's command identifier was retrieved from the iItem member of the NMTOOLBAR structure that lParam points to.) After DoNotify retrieves the bounding rectangle, it calls MapWindowPoints to convert the rectangle from client coordinates to screen coordinates. It then retrieves the pop-up menu from a menu resource by using the GetSubMenu function and calls the TrackPopupMenuEx function to display the menu. Note that DoNotify positions the menu under the correct button by using the rectangle it retrieved earlier. It also includes the TPM_VERTICAL flag to ensure that the menu is displayed so that it doesn't overlap the button.

BOOL WINAPI DoNotify(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
#define lpnm   ((LPNMHDR)lParam)
#define lpnmTB ((LPNMTOOLBAR)lParam)

   RECT      rc;
   TPMPARAMS tpm;
   HMENU     hPopupMenu = NULL;
   BOOL      bRet = FALSE;

   switch(lpnm->code){
      case TBN_DROPDOWN:
         SendMessage(lpnmTB->hdr.hwndFrom, TB_GETRECT,
                     (WPARAM)lpnmTB->iItem, (LPARAM)&rc);

         MapWindowPoints(lpnmTB->hdr.hwndFrom,
                         HWND_DESKTOP, (LPPOINT)&rc, 2);

         tpm.cbSize = sizeof(TPMPARAMS);
         tpm.rcExclude.top    = rc.top;
         tpm.rcExclude.left   = rc.left;
         tpm.rcExclude.bottom = rc.bottom;
         tpm.rcExclude.right  = rc.right;

         hPopupMenu =
           GetSubMenu( LoadMenu(g_hinst,MAKEINTRESOURCE(IDR_POPUP)),0);

         TrackPopupMenuEx(hPopupMenu,
                          TPM_LEFTALIGN|TPM_LEFTBUTTON|TPM_VERTICAL,
                          rc.left, rc.bottom, g_hwndMain, &tpm);

         return (FALSE);
   }

   return FALSE;
}


Toolbar Control Reference

This section contains information about the following new or updated API elements used with toolbar controls.

Toolbar Control and Button Styles

Toolbar Extended Styles

Toolbar Button States

Toolbar Standard Button Image Index Values

Functions
CreateMappedBitmap
CreateToolbarEx

Messages
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_GETANCHORHIGHLIGHT
TB_GETBITMAP
TB_GETBITMAPFLAGS
TB_GETBUTTON
TB_GETBUTTONINFO
TB_GETBUTTONSIZE
TB_GETBUTTONTEXT
TB_GETCOLORSCHEME
TB_GETDISABLEDIMAGELIST
TB_GETEXTENDEDSTYLE
TB_GETHOTIMAGELIST
TB_GETHOTITEM
TB_GETIMAGELIST
TB_GETINSERTMARK
TB_GETINSERTMARKCOLOR
TB_GETITEMRECT
TB_GETMAXSIZE
TB_GETOBJECT
TB_GETPADDING
TB_GETRECT
TB_GETROWS
TB_GETSTATE
TB_GETSTYLE
TB_GETTEXTROWS
TB_GETTOOLTIPS
TB_GETUNICODEFORMAT
TB_HIDEBUTTON
TB_HITTEST
TB_INDETERMINATE
TB_INSERTBUTTON
TB_INSERTMARKHITTEST
TB_ISBUTTONCHECKED
TB_ISBUTTONENABLED
TB_ISBUTTONHIDDEN
TB_ISBUTTONHIGHLIGHTED
TB_ISBUTTONINDETERMINATE
TB_ISBUTTONPRESSED
TB_LOADIMAGES
TB_MAPACCELERATOR
TB_MARKBUTTON
TB_MOVEBUTTON
TB_PRESSBUTTON
TB_REPLACEBITMAP
TB_SAVERESTORE
TB_SETANCHORHIGHLIGHT
TB_SETBITMAPSIZE
TB_SETBUTTONINFO
TB_SETBUTTONSIZE
TB_SETBUTTONWIDTH
TB_SETCMDID
TB_SETCOLORSCHEME
TB_SETDISABLEDIMAGELIST
TB_SETDRAWTEXTFLAGS
TB_SETEXTENDEDSTYLE
TB_SETHOTIMAGELIST
TB_SETHOTITEM
TB_SETIMAGELIST
TB_SETINDENT
TB_SETINSERTMARK
TB_SETINSERTMARKCOLOR
TB_SETMAXTEXTROWS
TB_SETPADDING
TB_SETPARENT
TB_SETROWS
TB_SETSTATE
TB_SETSTYLE
TB_SETTOOLTIPS
TB_SETUNICODEFORMAT

Notifications
NM_CHAR (toolbar)
NM_CUSTOMDRAW (toolbar)
NM_KEYDOWN (toolbar)
NM_RCLICK (toolbar)
NM_RDBLCLK (toolbar)
NM_RELEASEDCAPTURE (toolbar)
NM_TOOLTIPSCREATED (toolbar)
TBN_BEGINADJUST
TBN_BEGINDRAG
TBN_CUSTHELP
TBN_DELETINGBUTTON
TBN_DRAGOUT
TBN_DROPDOWN
TBN_ENDADJUST
TBN_ENDDRAG
TBN_GETBUTTONINFO
TBN_GETDISPINFO
TBN_GETINFOTIP
TBN_GETOBJECT
TBN_HOTITEMCHANGE
TBN_QUERYDELETE
TBN_QUERYINSERT
TBN_RESET
TBN_TOOLBARCHANGE

Structures
COLORMAP
NMTBCUSTOMDRAW
NMTBDISPINFO
NMTBGETINFOTIP
NMTBHOTITEM
NMTOOLBAR
TBADDBITMAP
TBBUTTON
TBBUTTONINFO
TBINSERTMARK
TBNOTIFY
TBREPLACEBITMAP
TBSAVEPARAMS

Toolbar Control and Button Styles

Toolbar Extended Styles

Toolbar Button States

Toolbar Standard Button Image Index Values

Toolbar Control Functions

Toolbar Control Messages

Toolbar Control Notification Messages

Toolbar Control Structures


Toolbar Control and Button Styles

A toolbar control can have a combination of the following styles:

TBSTYLE_ALTDRAG | Allows users to change a toolbar button's position by dragging it while holding down ALT. If this style is not specified, the user must hold down SHIFT while dragging a button. Note that the CCS_ADJUSTABLE style must be specified to enable toolbar buttons to be dragged.
TBSTYLE_CUSTOMERASE | Version 4.70. Generates NM_CUSTOMDRAW notification messages when it processes WM_ERASEBKGND messages.
TBSTYLE_FLAT | Version 4.70. Creates a flat toolbar. In a flat toolbar, both the toolbar and the buttons are transparent. Button text appears under button bitmaps. To prevent repainting problems, this style should be set before the toolbar control becomes visible.
TBSTYLE_LIST | Version 4.70. Places button text to the right of button bitmaps. To prevent repainting problems, this style should be set before the toolbar control becomes visible.
TBSTYLE_REGISTERDROP | Version 4.71. Generates TBN_GETOBJECT notification messages to request drop target objects when the pointer passes over toolbar buttons.
TBSTYLE_TOOLTIPS | Creates a tooltip control that an application can use to display descriptive text for the buttons in the toolbar.
TBSTYLE_TRANSPARENT | Version 4.71. Creates a transparent toolbar. In a transparent toolbar, the toolbar is transparent but the buttons are not. Button text appears under button bitmaps. To prevent repainting problems, this style should be set before the toolbar control becomes visible.
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 nongroup boundaries.

A button in a toolbar can have a combination of the following styles. Not all styles can be combined.
TBSTYLE_AUTOSIZE | Version 4.71. The button's width will be calculated based on the text of the button, not on the size of the image.
TBSTYLE_BUTTON | Creates a standard push button.
TBSTYLE_CHECK | Creates a button that toggles between the pressed and nonpressed 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_DROPDOWN | Version 4.70. Creates a drop-down list button. Drop-down buttons send the TBN_DROPDOWN notification. If the toolbar has the TBSTYLE_EX_DRAWDDARROWS extended style, drop-down buttons will have a drop-down arrow displayed next to them.
TBSTYLE_GROUP | Creates a button that stays pressed until another button in the group is pressed.
TBSTYLE_NOPREFIX | Version 4.71. The button text will not have an accelerator prefix associated with it.
TBSTYLE_SEP | Creates a separator, providing a small gap between button groups. A button that has this style does not receive user input.


Toolbar Extended Styles

A toolbar can have the following extended style. This style is set with the TB_SETEXTENDEDSTYLE message and retrieved with the TB_GETEXTENDEDSTYLE message.

TBSTYLE_EX_DRAWDDARROWS Version 4.71. Buttons that have the TBSTYLE_DROPDOWN style will be drawn with a drop-down arrow next to the button. If this extended style is not present, the drop-down buttons are drawn as normal buttons. To prevent repainting problems, this style should be set before the toolbar control becomes visible.


Toolbar Button States

A toolbar button can have a combination of the following states:

TBSTATE_CHECKED | The button has the TBSTYLE_CHECK style and is being clicked.
TBSTATE_ELLIPSES | Version 4.70. The button's text is cut off and an ellipsis is displayed.
TBSTATE_ENABLED | The button accepts user input. A button that doesn't have this state is grayed.
TBSTATE_HIDDEN | The button is not visible and cannot receive user input.
TBSTATE_INDETERMINATE | The button is grayed.
TBSTATE_MARKED | Version 4.71. The button is marked. The interpretation of a marked item is dependent upon the application.
TBSTATE_PRESSED | The button is being clicked.
TBSTATE_WRAP | The button is followed by a line break. The button must also have the TBSTATE_ENABLED state.


Toolbar Standard Button Image Index Values

The following values specify index values of images within standard bitmaps. Use these values to specify an image index within a standard image list that was loaded with the TB_LOADIMAGES message.

The following index values correspond to images within standard image lists that the control creates for your convenience. The images depict actions that Windows applications commonly perform.

Index values for IDB_HIST_LARGE_COLOR and IDB_HIST_SMALL_COLOR:
HIST_ADDTOFAVORITES | Add to favorites.
HIST_BACK | Move back.
HIST_FAVORITES | Open favorites folder.
HIST_FORWARD | Move forward.
HIST_VIEWTREE | View tree.
Index values for IDB_STD_LARGE_COLOR and IDB_STD_SMALL_COLOR:
STD_COPY | Copy operation.
STD_CUT | Cut operation.
STD_DELETE | Delete operation.
STD_FILENEW | New file operation.
STD_FILEOPEN | Open file operation.
STD_FILESAVE | Save file operation.
STD_FIND | Find operation.
STD_HELP | Help operation.
STD_PASTE | Paste operation.
STD_PRINT | Print operation.
STD_PRINTPRE | Print preview operation.
STD_PROPERTIES | Properties operation.
STD_REDOW | Redo operation.
STD_REPLACE | Replace operation.
STD_UNDO | Undo operation.
Index values for IDB_VIEW_LARGE_COLOR and IDB_VIEW_SMALL_COLOR:
VIEW_DETAILS | Details view.
VIEW_LARGEICONS | Large icons view.
VIEW_LIST | List view.
VIEW_NETCONNECT | Connect to network drive.
VIEW_NETDISCONNECT | Disconnect from network drive.
VIEW_NEWFOLDER | New folder.
VIEW_PARENTFOLDER | Go to parent folder.
VIEW_SMALLICONS | Small icon view.
VIEW_SORTDATE | Sort by date.
VIEW_SORTNAME | Sort by name.
VIEW_SORTSIZE | Sort by size.
VIEW_SORTTYPE | Sort by type.


Toolbar Control Functions Toolbar Control Functions *
  * Previous Topic: Toolbar Standard Button Image Index Values
  * Next Topic: CreateMappedBitmap

Toolbar Control Functions

This section contains information about the functions used with toolbar controls.

CreateMappedBitmap

CreateToolbarEx


CreateMappedBitmap

HBITMAP CreateMappedBitmap(
    HINSTANCE hInstance,
    int idBitmap,
    UINT wFlags,
    LPCOLORMAP lpColorMap,
    int iNumMaps
);

Creates a bitmap for use in a toolbar.

  • Returns the handle to the bitmap if successful, or NULL otherwise. To get extended error information, call GetLastError.
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:
CMB_MASKED Uses a bitmap as a mask.
lpColorMap
Address of 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.

The function creates a new bitmap using the bitmap data and colors specified by the bitmap resource and the color mapping information.


CreateToolbarEx

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
);

Creates a toolbar window and adds the specified buttons to the toolbar.

  • Returns the window handle to the toolbar if successful, or NULL otherwise. To get extended error information, call GetLastError.
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 Toolbar Control and Button Styles.
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
Address of an array of TBBUTTON structures that contain 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.

Windows 95: The system can support a maximum of 16,364 window handles.


Toolbar Control Messages

This section contains information about the messages used with toolbar controls.

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_GETANCHORHIGHLIGHT

TB_GETBITMAP

TB_GETBITMAPFLAGS

TB_GETBUTTON

TB_GETBUTTONINFO

TB_GETBUTTONSIZE

TB_GETBUTTONTEXT

TB_GETCOLORSCHEME

TB_GETDISABLEDIMAGELIST

TB_GETEXTENDEDSTYLE

TB_GETHOTIMAGELIST

TB_GETHOTITEM

TB_GETIMAGELIST

TB_GETINSERTMARK

TB_GETINSERTMARKCOLOR

TB_GETITEMRECT

TB_GETMAXSIZE

TB_GETOBJECT

TB_GETPADDING

TB_GETRECT

TB_GETROWS

TB_GETSTATE

TB_GETSTYLE

TB_GETTEXTROWS

TB_GETTOOLTIPS

TB_GETUNICODEFORMAT

TB_HIDEBUTTON

TB_HITTEST

TB_INDETERMINATE

TB_INSERTBUTTON

TB_INSERTMARKHITTEST

TB_ISBUTTONCHECKED

TB_ISBUTTONENABLED

TB_ISBUTTONHIDDEN

TB_ISBUTTONHIGHLIGHTED

TB_ISBUTTONINDETERMINATE

TB_ISBUTTONPRESSED

TB_LOADIMAGES

TB_MAPACCELERATOR

TB_MARKBUTTON

TB_MOVEBUTTON

TB_PRESSBUTTON

TB_REPLACEBITMAP

TB_SAVERESTORE

TB_SETANCHORHIGHLIGHT

TB_SETBITMAPSIZE

TB_SETBUTTONINFO

TB_SETBUTTONSIZE

TB_SETBUTTONWIDTH

TB_SETCMDID

TB_SETCOLORSCHEME

TB_SETDISABLEDIMAGELIST

TB_SETDRAWTEXTFLAGS

TB_SETEXTENDEDSTYLE

TB_SETHOTIMAGELIST

TB_SETHOTITEM

TB_SETIMAGELIST

TB_SETINDENT

TB_SETINSERTMARK

TB_SETINSERTMARKCOLOR

TB_SETMAXTEXTROWS

TB_SETPADDING

TB_SETPARENT

TB_SETROWS

TB_SETSTATE

TB_SETSTYLE

TB_SETTOOLTIPS

TB_SETUNICODEFORMAT


TB_ADDBITMAP

TB_ADDBITMAP
    wParam = (WPARAM) nButtons;
    lParam = (LPARAM) (LPTBADDBITMAP) lptbab;

Adds one or more images to the list of button images available for a toolbar.

  • Returns the index of the first new image if successful, or -1 otherwise.
nButtons
Number of button images in the bitmap. If lptbab specifies a system-defined bitmap, this parameter is ignored.
lptbab
Address of 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.

If the toolbar was created using the CreateWindowEx function, you must send the TB_BUTTONSTRUCTSIZE message to the toolbar before sending TB_ADDBITMAP.


TB_ADDBUTTONS

TB_ADDBUTTONS
    wParam = (WPARAM) (UINT) uNumButtons;
    lParam = (LPARAM) (LPTBBUTTON) lpButtons;

Adds one or more buttons to a toolbar.

  • Returns TRUE if successful, or FALSE otherwise.
uNumButtons
Number of buttons to add.
lpButtons
Address of an array of TBBUTTON structures that contain information about the buttons to add. There must be the same number of elements in the array as buttons specified by uNumButtons.

If the toolbar was created using the CreateWindowEx function, you must send the TB_BUTTONSTRUCTSIZE message to the toolbar before sending TB_ADDBUTTONS.


TB_ADDSTRING

TB_ADDSTRING
    wParam = (WPARAM) (HINSTANCE) hinst;
    lParam = (LPARAM) MAKELONG(idString, 0);

Adds a new string to the list of strings available for a toolbar.

  • Returns the index of the first new string if successful, or -1 otherwise.
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.


TB_AUTOSIZE

TB_AUTOSIZE
    wParam = 0;
    lParam = 0;

Causes a toolbar to be resized.

  • No return value.

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

TB_BUTTONCOUNT
    wParam = 0;
    lParam = 0;

Retrieves a count of the buttons currently in the toolbar.

  • Returns the count of the buttons.


TB_BUTTONSTRUCTSIZE

TB_BUTTONSTRUCTSIZE
    wParam = (WPARAM) cb;
    lParam = 0;

Specifies the size of the TBBUTTON structure.

  • No return value.
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.


TB_CHANGEBITMAP

TB_CHANGEBITMAP
    wParam = (WPARAM) idButton;
    lParam = (LPARAM) MAKELPARAM(iBitmap, 0);

Changes the bitmap for a button in a toolbar.

  • Returns TRUE if successful, or FALSE otherwise.
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.


TB_CHECKBUTTON

TB_CHECKBUTTON
    wParam = (WPARAM) idButton;
    lParam = (LPARAM) MAKELONG(fCheck, 0);

Checks or unchecks a given button in a toolbar.

  • Returns TRUE if successful, or FALSE otherwise.
idButton
Command identifier of the button to check.
fCheck
Check flag. If this parameter is TRUE, the check is added. If it is FALSE, the check is removed.

When a button is checked, it is displayed in the pressed state.


TB_COMMANDTOINDEX

TB_COMMANDTOINDEX
    wParam = (WPARAM) idButton;
    lParam = 0;

Retrieves the zero-based index for the button associated with the specified command identifier.

  • Returns the zero-based index for the button.
idButton
Command identifier associated with the button.


TB_CUSTOMIZE

TB_CUSTOMIZE
    wParam = 0;
    lParam = 0;

Displays the Customize Toolbar dialog box.

  • No return value.


TB_DELETEBUTTON

TB_DELETEBUTTON
    wParam = (WPARAM) iButton;
    lParam = 0;

Deletes a button from the toolbar.

  • Returns TRUE if successful, or FALSE otherwise.
iButton
Zero-based index of the button to delete.


TB_ENABLEBUTTON

TB_ENABLEBUTTON
    wParam = (WPARAM) idButton;
    lParam = (LPARAM) MAKELONG(fEnable, 0);

Enables or disables the specified button in a toolbar.

  • Returns TRUE if successful, or FALSE otherwise.
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.

When a button has been enabled, it can be pressed and checked.


TB_GETANCHORHIGHLIGHT

TB_GETANCHORHIGHLIGHT
    wParam = 0;
    lParam = 0;

Retrieves the anchor highlight setting for a toolbar.

  • Returns a Boolean value that indicates if anchor highlighting is set. If this value is nonzero, anchor highlighting is enabled. If this value is zero, it is disabled.

Version 4.71

See also TB_SETANCHORHIGHLIGHT


TB_GETBITMAP

TB_GETBITMAP
    wParam = (WPARAM) idButton;
    lParam = 0;

Retrieves the index of the bitmap associated with a button in a toolbar.

  • Returns the index of the bitmap if successful, or zero otherwise.
idButton
Command identifier of the button whose bitmap index is to be retrieved.


TB_GETBITMAPFLAGS

TB_GETBITMAPFLAGS
    wParam = 0;
    lParam = 0;

Retrieves the flags for the current bitmap.

  • Returns a DWORD value that contains the bitmap flags. If this value is zero, the toolbar is using a small bitmap. If the TBBF_LARGE flag is set, the toolbar is using a large bitmap.


TB_GETBUTTON

TB_GETBUTTON
    wParam = (WPARAM) iButton;
    lParam = (LPARAM) (LPTBBUTTON) lpButton;

Retrieves information about the specified button in a toolbar.

  • Returns TRUE if successful, or FALSE otherwise.
iButton
Zero-based index of the button for which to retrieve information.
lpButton
Address of the TBBUTTON structure that receives the button information.


TB_GETBUTTONINFO

TB_GETBUTTONINFO
    wParam = (WPARAM)(INT) iID;
    lParam = (LPARAM)(LPTBBUTTONINFO) lptbbi;

Retrieves extended information for a button in a toolbar.

  • Returns the zero-based index of the button, or -1 if an error occurs.
iID
Command identifier of the button.
lptbbi
Address of a TBBUTTONINFO structure that receives the button information. The cbSize and dwMask members of this structure must be filled in prior to sending this message.

Version 4.71


TB_GETBUTTONSIZE

TB_GETBUTTONSIZE
    wParam = 0;
    lParam = 0;

Retrieves the current width and height of toolbar buttons, in pixels.

  • Returns a DWORD value that contains the width and height values in the low word and high word, respectively.

Version 4.70.


TB_GETBUTTONTEXT

TB_GETBUTTONTEXT
    wParam = (WPARAM) idButton;
    lParam = (LPARAM) (LPSTR) lpszText;

Retrieves the text of a button in a toolbar.

  • 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.
idButton
Command identifier of the button whose text is to be retrieved.
lpszText
Address of a buffer that receives the button text.


TB_GETCOLORSCHEME

TB_GETCOLORSCHEME
    wParam = 0;
    lParam = (LPARAM)(LPCOLORSCHEME) lpcs;

Retrieves the color scheme information from the toolbar control.

  • Returns nonzero if successful, or zero otherwise.
lpcs
Address of a COLORSCHEME structure that will receive the color scheme information. You must set the cbSize member of this structure to sizeof(COLORSCHEME) before sending this message.

Version 4.71

See also TB_SETCOLORSCHEME


TB_GETDISABLEDIMAGELIST

TB_GETDISABLEDIMAGELIST
    wParam = 0;
    lParam = 0;

Retrieves the image list that a toolbar control uses to display disabled buttons.

  • Returns the handle to the disabled image list, or NULL if no disabled image list is set.

Version 4.70.


TB_GETEXTENDEDSTYLE

TB_GETEXTENDEDSTYLE
    wParam = 0;
    lParam = 0;

Retrieves the extended styles for a toolbar control.

  • Returns a DWORD that represents the styles currently in use for the toolbar control. This value can be a combination of extended styles.

Version 4.71

See also TB_SETEXTENDEDSTYLE


TB_GETHOTIMAGELIST

TB_GETHOTIMAGELIST
    wParam = 0;
    lParam = 0;

Retrieves the image list that a toolbar control uses to display hot buttons. A button is hot when the pointer is above it.

  • Returns the handle to the image list that the control uses to display hot buttons, or NULL if no hot image list is set.

Version 4.70.


TB_GETHOTITEM

TB_GETHOTITEM
    wParam = 0;
    lParam = 0;

Retrieves the index of the hot item in a toolbar.

  • Returns the index of the hot item, or -1 if no hot item is set. Toolbar controls that do not have the TBSTYLE_FLAT style do not have hot items.

Version 4.71


TB_GETIMAGELIST

TB_GETIMAGELIST
    wParam = 0;
    lParam = 0;

Retrieves the image list that a toolbar control uses to display buttons in their default state. A toolbar control uses this image list to display buttons when they are not hot or disabled.

  • Returns the handle to the image list, or NULL if no image list is set.

Version 4.70.


TB_GETINSERTMARK

TB_GETINSERTMARK
    wParam = 0;
    lParam = (LPARAM)(LPTBINSERTMARK)lptbim;

Retrieves the current insertion mark for the toolbar.

  • Always returns TRUE.
lptbim
Address of a TBINSERTMARK structure that receives the insertion mark.

Version 4.71

See also TB_SETINSERTMARK


TB_GETINSERTMARKCOLOR

TB_GETINSERTMARKCOLOR
    wParam = 0;
    lParam = 0;

Retrieves the color used to draw the insertion mark for the toolbar.

  • Returns a COLORREF value that contains the current insertion mark color.

Version 4.71

See also TB_SETINSERTMARKCOLOR


TB_GETITEMRECT

TB_GETITEMRECT
    wParam = (WPARAM) iButton;
    lParam = (LPARAM) (LPRECT) lprc;

Retrieves the bounding rectangle of a button in a toolbar.

  • Returns TRUE if successful, or FALSE otherwise.
iButton
Zero-based index of the button for which to retrieve information.
lprc
Address of a RECT structure that receives the coordinates of the bounding rectangle.

This message does not retrieve the bounding rectangle for buttons whose state is set to the TBSTATE_HIDDEN value.


TB_GETMAXSIZE

TB_GETMAXSIZE
    wParam = 0;
    lParam = (LPARAM)(LPSIZE)lpSize;

Retrieves the total size of all of the visible buttons and separators in the toolbar.

  • Returns nonzero if successful, or zero otherwise.
lpSize
Address of a SIZE structure that receives the size of the items.

Version 4.71


TB_GETOBJECT

TB_GETOBJECT
    wParam = (WPARAM) (REFIID) iid;
    lParam = (LPARAM) (LPVOID*) ppvObject;

Retrieves the IDropTarget for a toolbar control.

  • Returns an HRESULT value indicating success or failure of the operation.
iid
Identifier of the interface being requested. This value must point to IID_IDropTarget.
ppvObject
Address that receives the interface pointer. If an error occurs, a NULL pointer is placed in this address.

The toolbar's IDropTarget is used by the toolbar when objects are dragged over or dropped onto it.

Version 4.71


TB_GETPADDING

TB_GETPADDING
    wParam = 0;
    lParam = 0;

Retrieves the padding for a toolbar control.

  • Returns a DWORD value that contains the horizontal padding in the low word and the vertical padding in the high word, in pixels.

Version 4.71

See also TB_SETPADDING


TB_GETRECT

TB_GETRECT
    wParam = (WPARAM)(INT) iID;
    lParam = (LPARAM)(LPRECT) lprc;

Retrieves the bounding rectangle for a specified toolbar button.

  • Returns nonzero if successful, or zero otherwise.
iID
Button identifier.
lprc
Address of a RECT structure that will receive the bounding rectangle information.

Version 4.70.


TB_GETROWS

TB_GETROWS
    wParam = 0;
    lParam = 0;

Retrieves the number of rows of buttons in a toolbar with the TBSTYLE_WRAPABLE style.

  • Returns the number of rows.


TB_GETSTATE

TB_GETSTATE
    wParam = (WPARAM) idButton;
    lParam = 0;

Retrieves information about the state of the specified button in a toolbar, such as whether it is enabled, pressed, or checked.

  • Returns the button state information if successful, or -1 otherwise. The button state information can be a combination of the values listed in Toolbar Button States.
idButton
Command identifier of the button for which to retrieve information.


TB_GETSTYLE

TB_GETSTYLE
    wParam = 0;
    lParam = 0;

Retrieves the styles currently in use for a toolbar control.

  • Returns a DWORD value that is a combination of toolbar control styles.

Version 4.70.


TB_GETTEXTROWS

TB_GETTEXTROWS
    wParam = 0;
    lParam = 0;

Retrieves the maximum number of text rows that can be displayed on a toolbar button.

  • Returns an INT value representing the maximum number of text rows that the control will display for a button.

Version 4.70.

See also TB_SETMAXTEXTROWS


TB_GETTOOLTIPS

TB_GETTOOLTIPS
    wParam = 0;
    lParam = 0;

Retrieves the handle to the tooltip control, if any, associated with the toolbar.

  • Returns the handle to the tooltip control, or NULL if the toolbar has no associated tooltip.


TB_GETUNICODEFORMAT

TB_GETUNICODEFORMAT
    wParam = 0;
    lParam = 0;

Retrieves the UNICODE character format flag for the control.

  • Returns the UNICODE format flag for the control. If this value is nonzero, the control is using UNICODE characters. If this value is zero, the control is using ANSI characters.

See also TB_SETUNICODEFORMAT


TB_HIDEBUTTON

TB_HIDEBUTTON
    wParam = (WPARAM) idButton;
    lParam = (LPARAM) MAKELONG(fShow, 0);

Hides or shows the specified button in a toolbar.

  • Returns TRUE if successful, or FALSE otherwise.
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.


TB_HITTEST

TB_HITTEST
    wParam = 0;
    lParam = (LPARAM)(LPPOINT)pptHitTest;

Determines where a point lies in a toolbar control.

  • Returns an integer value. If the return value is zero or a positive value, it is the zero-based index of the nonseparator item in which the point lies.

    If the return value is negative, the point does not lie within a button. The absolute value of the return value is the index of a separator item or the nearest nonseparator item.

pptHitTest
Address of a point structure that contains the x-coordinate of the hit test in the x member and the y-coordinate of the hit test in the y member. The coordinates are relative to the toolbar's client area.


TB_INDETERMINATE

TB_INDETERMINATE
    wParam = (WPARAM) idButton;
    lParam = (LPARAM) MAKELONG(fIndeterminate, 0);

Sets or clears the indeterminate state of the specified button in a toolbar.

  • Returns TRUE if successful, or FALSE otherwise.
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.


TB_INSERTBUTTON

TB_INSERTBUTTON
    wParam = (WPARAM) iButton;
    lParam = (LPARAM) (LPTBBUTTON) lpButton;

Inserts a button in a toolbar.

  • Returns TRUE if successful, or FALSE otherwise.
iButton
Zero-based index of a button. The message inserts the new button to the left of this button.
lpButton
Address of a TBBUTTON structure containing information about the button to insert.


TB_INSERTMARKHITTEST

TB_INSERTMARKHITTEST
    wParam = (WPARAM)(LPPOINT)lppt;
    lParam = (LPARAM)(LPTBINSERTMARK)lptbim;

Retrieves the insertion mark information for a point in a toolbar.

  • Returns nonzero if the point is an insertion mark, or zero otherwise.
lppt
Address of a POINT structure that contains the hit test coordinates, relative to the client area of the toolbar.
lptbim
Address of a TBINSERTMARK structure that receives the insertion mark information.

Version 4.71


TB_ISBUTTONCHECKED

TB_ISBUTTONCHECKED
    wParam = (WPARAM) idButton;
    lParam = 0;

Determines whether the specified button in a toolbar is checked.

  • Returns nonzero if the button is checked, or zero otherwise.
idButton
Command identifier of the button.


TB_ISBUTTONENABLED

TB_ISBUTTONENABLED
    wParam = (WPARAM) idButton;
    lParam = 0;

Determines whether the specified button in a toolbar is enabled.

  • Returns nonzero if the button is enabled, or zero otherwise.
idButton
Command identifier of the button.


TB_ISBUTTONHIDDEN

TB_ISBUTTONHIDDEN
    wParam = (WPARAM) idButton;
    lParam = 0;

Determines whether the specified button in a toolbar is hidden.

  • Returns nonzero if the button is hidden, or zero otherwise.
idButton
Command identifier of the button.


TB_ISBUTTONHIGHLIGHTED

TB_ISBUTTONHIGHLIGHTED
    wParam = (WPARAM) idButton;
    lParam = 0;

Checks the highlight state of a toolbar button.

  • Returns nonzero if the button is highlighted, or zero otherwise.
idButton
Command identifier for a toolbar button.

Version 4.71


TB_ISBUTTONINDETERMINATE

TB_ISBUTTONINDETERMINATE
    wParam = (WPARAM) idButton;
    lParam = 0;

Determines whether the specified button in a toolbar is indeterminate.

  • Returns nonzero if the button is indeterminate, or zero otherwise.
idButton
Command identifier of the button.


TB_ISBUTTONPRESSED

TB_ISBUTTONPRESSED
    wParam = (WPARAM) idButton;
    lParam = 0;

Determines whether the specified button in a toolbar is pressed.

  • Returns nonzero if the button is pressed, or zero otherwise.
idButton
Command identifier of the button.


TB_LOADIMAGES

TB_LOADIMAGES
    wParam = (WPARAM)(INT) iBitmapID;
    lParam = (LPARAM)(HINSTANCE) hinst;

Loads bitmaps into a toolbar control's image list.

  • Returns an INT value that represents the count of images in the image list, not including the one just added. Returns zero if the toolbar has no image list or if the existing image list is empty.
iBitmapID
Identifier of a bitmap that contains the images to be loaded. If hinst is HINST_COMMCTRL, this parameter specifies a set of standard toolbar button bitmaps, shown in the following list. Otherwise, this parameter must be the identifier of a bitmap resource that will be added to the image list as a single image.
Bitmap ID | Description
IDB_HIST_LARGE_COLOR | Explorer bitmaps in large size.
IDB_HIST_SMALL_COLOR | Explorer bitmaps in small size.
IDB_STD_LARGE_COLOR | Standard bitmaps in large size.
IDB_STD_SMALL_COLOR | Standard bitmaps in small size.
IDB_VIEW_LARGE_COLOR | View bitmaps in large size.
IDB_VIEW_SMALL_COLOR | View bitmaps in small size.
hinst
Program instance handle to the calling application. This parameter can be HINST_COMMCTRL to load a standard image list.

If your application specifies HINST_COMMCTRL, then you must use the proper image index values when you prepare TBBUTTON structures prior to sending the TB_ADDBUTTONS message. For a list of image index values for these preset bitmaps, see Toolbar Standard Button Image Index Values.

Version 4.70


TB_MAPACCELERATOR

TB_MAPACCELERATOR
    wParam = (WPARAM)(TCHAR) chAccel;
    lParam = (LPARAM)(LPUINT) pIDBtn;

Maps an accelerator character to a toolbar button.

  • Returns nonzero if successful, or zero otherwise.
chAccel
Accelerator character to be mapped. This character is the same character that is underlined in the button's text.
pIDBtn
Address of a UINT that receives the command identifier of the button that corresponds to the accelerator specified in cchAccel.

Version 4.71


TB_MARKBUTTON

TB_MARKBUTTON
    wParam = (WPARAM) idButton;
    lParam = (LPARAM) MAKELONG(fHighlight,0);

Sets the highlight state of a given button in a toolbar control.

  • Returns nonzero if successful, or zero otherwise.
idButton
Command identifier for a toolbar button.
fHighlight
Value that specifies the highlight state to be set. If this value is TRUE, the button is highlighted. If it's FALSE, the button is set to its default state.

Version 4.71


TB_MOVEBUTTON

TB_MOVEBUTTON
    wParam = (WPARAM)(UINT)uOldPos;
    lParam = (LPARAM)(UINT)uNewPos;

Moves a button from one index to another.

  • Returns nonzero if successful, or zero otherwise.
uOldPos
Zero-based index of the button to be moved.
uNewPos
Zero-based index where the button will be moved.

Version 4.71

See also TB_SETANCHORHIGHLIGHT


TB_PRESSBUTTON

TB_PRESSBUTTON
    wParam = (WPARAM) idButton;
    lParam = (LPARAM) MAKELONG(fPress, 0);

Presses or releases the specified button in a toolbar.

  • Returns TRUE if successful, or FALSE otherwise.
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.


TB_REPLACEBITMAP

TB_REPLACEBITMAP
    wParam = 0;
    lParam = (LPARAM) (LPTBREPLACEBITMAP) ptbrb;

Replaces an existing bitmap with a new bitmap.

  • Returns nonzero if successful, or zero otherwise.
ptbrb
Address of a TBREPLACEBITMAP structure that contains the information of the bitmap to be replaced and the new bitmap.


TB_SAVERESTORE

TB_SAVERESTORE
    wParam = (WPARAM) (BOOL) fSave;
    lParam = (LPARAM)  (TBSAVEPARAMS *)ptbsp;

Saves or restores the state of the toolbar.

  • No return value.
fSave
Save or restore flag. If this parameter is TRUE, the information is saved. If it is FALSE, it is restored.
ptbsp
Address of a TBSAVEPARAMS structure that specifies the registry key, subkey, and value name for the toolbar state information.

To save and restore a toolbar's settings using the TB_SAVERESTORE message, the parent window of the toolbar control must implement a handler for the TBN_GETBUTTONINFO notification message. The toolbar uses this notification to retrieve information about the buttons as they are read out of the registry.


TB_SETANCHORHIGHLIGHT

TB_SETANCHORHIGHLIGHT
    wParam = (WPARAM)(BOOL) fAnchor;
    lParam = 0;

Sets the anchor highlight setting for a toolbar.

  • Returns the previous anchor highlight setting. If this value is nonzero, anchor highlighting was enabled. If this value is zero, anchor highlighting was disabled.
fAnchor
Boolean value that specifies if anchor highlighting is enabled or disabled. If this value is nonzero, anchor highlighting will be enabled. If this value is zero, anchor highlighting will be disabled.

Anchor highlighting in a toolbar means that the last highlighted item will remain highlighted until another item is highlighted. This occurs even if the cursor leaves the toolbar control.

Version 4.71


TB_SETBITMAPSIZE

TB_SETBITMAPSIZE
    wParam = 0;
    lParam = (LPARAM) MAKELONG(dxBitmap, dyBitmap)

Sets the size of the bitmapped images to be added to a toolbar.

  • Returns TRUE if successful, or FALSE otherwise.
dxBitmap
Width, in pixels, of the bitmapped images.
dyBitmap
Height, in pixels, of the bitmapped images.

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_SETBUTTONINFO

TB_SETBUTTONINFO
    wParam = (WPARAM)(INT) iID;
    lParam = (LPARAM)(LPTBBUTTONINFO) lptbbi;

Sets the information for an existing button in a toolbar.

  • Returns nonzero if successful, or zero otherwise.
iID
Button identifier.
lptbbi
Address of a TBBUTTONINFO structure that contains the new button information. The cbSize and dwMask members of this structure must be filled in prior to sending this message.

Version 4.71


TB_SETBUTTONSIZE

TB_SETBUTTONSIZE
    wParam = 0;
    lParam = (LPARAM) MAKELONG(dxButton, dyButton)

Sets the size of the buttons to be added to a toolbar.

  • Returns TRUE if successful, or FALSE otherwise.
dxButton
Width, in pixels, of the buttons.
dyButton
Height, in pixels, of the buttons.

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_SETBUTTONWIDTH

TB_SETBUTTONWIDTH
    wParam = 0;
    lParam = (LPARAM)(DWORD) MAKELONG(cxMin,cxMax);

Sets the minimum and maximum button widths in the toolbar control.

  • Returns nonzero if successful, or zero otherwise.
cxMin
Minimum button width, in pixels. Toolbar buttons will never be narrower than this value.
cxMax
Maximum button width, in pixels. If button text is too wide, the control displays it with ellipsis points.

Version 4.70


TB_SETCMDID

TB_SETCMDID
    wParam = (WPARAM) (UINT) index;
    lParam = (WPARAM) (UINT) cmdId;

Sets the command identifier of a toolbar button.

  • Returns TRUE if successful, or FALSE otherwise.
index
Zero-based index of the button whose command identifier is to be set.
cmdId
Command identifier.


TB_SETCOLORSCHEME

TB_SETCOLORSCHEME
    wParam = 0;
    lParam = (LPARAM)(LPCOLORSCHEME) lpcs;

Sets the color scheme information for the toolbar control.

  • The return value for this message is not used.
lpcs
Address of a COLORSCHEME structure that contains the color scheme information.

The toolbar control uses the color scheme information when drawing the 3-D elements in the control.

Version 4.71

See also TB_GETCOLORSCHEME


TB_SETDISABLEDIMAGELIST

TB_SETDISABLEDIMAGELIST
    wParam = 0;
    lParam = (LPARAM)(HIMAGELIST) himlNewDisabled;

Sets the image list that the toolbar control will use to display disabled buttons.

  • Returns the handle to the image list previously used to display disabled buttons, or NULL if no image list was previously set.
himlNewDisabled
Handle to the image list that will be set.

Version 4.70


TB_SETDRAWTEXTFLAGS

TB_SETDRAWTEXTFLAGS
    wParam = (WPARAM)(DWORD) dwMask;
    lParam = (LPARAM)(DWORD) dwDTFlags;

Sets the text drawing flags for the toolbar.

  • Returns the previous text drawing flags.
dwMask
One or more of the DT_ flags, specified in DrawText, that indicate which bits in dwDTFlags will be used when drawing the text.
dwDTFlags
One or more of the DT_ flags, specified in DrawText, that indicate how the button text will be drawn. This value will be passed to the DrawText API when the button text is drawn.

The dwMask parameter allows you to specify which flags will be used when drawing the text, even if these flags are turned off. For example, if you don't want the DT_CENTER flag used when drawing text, you would add the DT_CENTER flag to dwMask and not specify the DT_CENTER flag in dwDTFlags. This prevents the control from passing the DT_CENTER flag to the DrawText API.

Version 4.71


TB_SETEXTENDEDSTYLE

TB_SETEXTENDEDSTYLE
    wParam = 0;
    lParam = (LPARAM)(DWORD)dwExStyle;

Sets the extended styles for a toolbar control.

  • Returns a DWORD that represents the previous extended styles. This value can be a combination of extended styles.
dwExStyle
Value specifying the new extended styles. This parameter can be a combination of extended styles.

Version 4.71

See also TB_GETEXTENDEDSTYLE


TB_SETHOTIMAGELIST

TB_SETHOTIMAGELIST
    wParam = 0;
    lParam = (LPARAM)(HIMAGELIST) himlNewHot;

Sets the image list that the toolbar control will use to display hot buttons. A button is hot when the pointer is above it. Toolbar controls that do not have the TBSTYLE_FLAT style do not have hot items.

  • Returns the handle to the image list previously used to display hot buttons, or NULL if no image list was previously set.
himlNewHot
Handle to the image list that will be set.

Version 4.70.


TB_SETHOTITEM

TB_SETHOTITEM
    wParam = (WPARAM)(INT)iHot;
    lParam = 0;

Sets the hot item in a toolbar. This message is ignored for toolbar controls that do not have the TBSTYLE_FLAT style.

  • Returns the index of the previous hot item, or -1 if there was no hot item.
iHot
Index of the item that will be made hot. If this value is -1, none of the items will be hot.

Version 4.71


TB_SETIMAGELIST

TB_SETIMAGELIST
    wParam = 0;
    lParam = (LPARAM)(HIMAGELIST) himlNew;

Sets the image list that the toolbar will use to display buttons that are in their default state.

  • Returns the handle to the image list previously used to display buttons in their default state, or NULL if no image list was previously set.
himlNew
Handle to the image list that will be set. If this parameter is NULL, no images will be displayed in the buttons.

A toolbar control uses himlNew to display buttons in their default state, which is when they are not hot or disabled.

Version 4.70


TB_SETINDENT

TB_SETINDENT
    wParam = (WPARAM)(INT) iIndent;
    lParam = 0;

Sets the indentation for the first button in a toolbar control.

  • Returns nonzero if successful, or zero otherwise.
iIndent
Value specifying the indentation, in pixels.

Version 4.70


TB_SETINSERTMARK

TB_SETINSERTMARK
    wParam = 0;
    lParam = (LPARAM)(LPTBINSERTMARK)lptbim;

Sets the current insertion mark for the toolbar.

  • The return value for this message is not used.
lptbim
Address of a TBINSERTMARK structure that contains the insertion mark.

Version 4.71

See also TB_GETINSERTMARK


TB_SETINSERTMARKCOLOR

TB_SETINSERTMARKCOLOR
    wParam = 0;
    lParam = (LPARAM)(COLORREF)clrInsertMark;

Sets the color used to draw the insertion mark for the toolbar.

  • Returns a COLORREF value that contains the previous insertion mark color.
clrInsertMark
COLORREF value that contains the new insertion mark color.

Version 4.71

See also TB_GETINSERTMARKCOLOR


TB_SETMAXTEXTROWS

TB_SETMAXTEXTROWS
    wParam = (WPARAM)(INT) iMaxRows;
    lParam = 0;

Sets the maximum number of text rows displayed on a toolbar button.

  • Returns nonzero if successful, or zero otherwise.
iMaxRows
Maximum number of rows of text that can be displayed.

Version 4.70


TB_SETPADDING

TB_SETPADDING
    wParam = 0;
    lParam = MAKELPARAM(cx, cy);

Sets the padding for a toolbar control.

  • Returns a DWORD value that contains the previous horizontal padding in the low word and the previous vertical padding in the high word, in pixels.
cx
The horizontal padding, in pixels.
cy
The vertical padding, in pixels.

The padding values are used to create a blank area between the edge of the button and the button's image and/or text. The horizontal padding value is applied to both the right and left of the button, and the vertical padding value is applied to both the top and bottom of the button. Padding is only applied to buttons that have the TBSTYLE_AUTOSIZE style.

Version 4.71

See also TB_GETPADDING


TB_SETPARENT

TB_SETPARENT
    wParam = (WPARAM) (HWND) hwndParent;
    lParam = 0;

Sets the window to which the toolbar control sends notification messages.

  • The return value is a handle to the previous notification window, or NULL if there is no previous notification window.
hwndParent
Handle to the window to receive notification messages.

The TB_SETPARENT message does not change the parent window that was specified when the control was created. Calling the GetParent function for a toolbar control will return the actual parent window, not the window specified in TB_SETPARENT. To change the control's parent window, call the SetParent function.


TB_SETROWS

TB_SETROWS
    wParam = (WPARAM) MAKEWPARAM(cRows, fLarger);
    lParam = (LPARAM) (LPRECT) lprc;

Sets the number of rows of buttons in a toolbar.

  • No return value.
cRows
Number of rows requested. The minimum number of rows is one, and the maximum number of rows 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
Address of a RECT structure that receives the bounding rectangle of the toolbar after the rows are set.

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.


TB_SETSTATE

TB_SETSTATE
    wParam = (WPARAM) idButton;
    lParam = (LPARAM) MAKELONG(fState, 0);

Sets the state for the specified button in a toolbar.

  • Returns TRUE if successful, or FALSE otherwise.
idButton
Command identifier of the button.
fState
State flags. This parameter can be a combination of the values listed in Toolbar Button States.


TB_SETSTYLE

TB_SETSTYLE
    wParam = 0;
    lParam = (LPARAM)(DWORD) dwStyle;

Sets the style for a toolbar control.

dwStyle
Value specifying the styles to be set for the control. This value can be a combination of toolbar control styles.

Version 4.70


TB_SETTOOLTIPS

TB_SETTOOLTIPS
    wParam = (WPARAM) (HWND) hwndToolTip;
    lParam = 0;

Associates a tooltip control with a toolbar.

  • No return value.
hwndToolTip
Handle to the tooltip control.

Any buttons added to a toolbar before sending the TB_SETTOOLTIPS message will not be registered with the tooltip control.


TB_SETUNICODEFORMAT

TB_SETUNICODEFORMAT
    wParam = (WPARAM)(BOOL)fUnicode;
    lParam = 0;

Sets the UNICODE character format flag for the control. This message allows you to change the character set used by the control at run time rather than having to re-create the control.

  • Returns the previous UNICODE format flag for the control.
fUnicode
Determines the character set that is used by the control. If this value is nonzero, the control will use UNICODE characters. If this value is zero, the control will use ANSI characters.

See also TB_GETUNICODEFORMAT


Toolbar Control Notification Messages

This section contains information about the notification messages sent by toolbar controls.

NM_CHAR (toolbar)

NM_CUSTOMDRAW (toolbar)

NM_KEYDOWN (toolbar)

NM_RCLICK (toolbar)

NM_RDBLCLK (toolbar)

NM_RELEASEDCAPTURE (toolbar)

NM_TOOLTIPSCREATED (toolbar)

TBN_BEGINADJUST

TBN_BEGINDRAG

TBN_CUSTHELP

TBN_DELETINGBUTTON

TBN_DRAGOUT

TBN_DROPDOWN

TBN_ENDADJUST

TBN_ENDDRAG

TBN_GETBUTTONINFO

TBN_GETDISPINFO

TBN_GETINFOTIP

TBN_GETOBJECT

TBN_HOTITEMCHANGE

TBN_QUERYDELETE

TBN_QUERYINSERT

TBN_RESET

TBN_TOOLBARCHANGE


NM_CHAR (toolbar)

NM_CHAR
    lpnmc = (LPNMCHAR) lParam;

Sent by the toolbar when a character key is processed. This notification message is sent in the form of a WM_NOTIFY message.

  • The return value is ignored by the control.
lpnmc
Address of an NMCHAR structure that contains additional information about the character that caused the notification message. The dwItemPrev member of this structure contains the command identifier of the item that is currently hot or -1 if no item is currently hot. The dwItemNext member of this structure contains the command identifier of the item that will become hot or -1 if the key does not match any item's accelerator.

Version 4.71


NM_CUSTOMDRAW (toolbar)

NM_CUSTOMDRAW
    lpNMCustomDraw = (LPNMTBCUSTOMDRAW) lParam;

Sent by the toolbar to notify its parent window about drawing operations. This notification is sent in the form of a WM_NOTIFY message.

  • The value your application can return depends on the current drawing stage. The dwDrawStage member of the associated NMCUSTOMDRAW structure holds a value that specifies the drawing stage. You must return one of the following values.

    When dwDrawStage equals CDDS_PREPAINT:
    CDRF_DODEFAULT
    The control will draw itself. It will not send any additional NM_CUSTOMDRAW messages for this paint cycle.
    CDRF_NOTIFYITEMDRAW
    The control will notify the parent of any item-related drawing operations. It will send NM_CUSTOMDRAW notification messages before and after drawing items.
    CDRF_NOTIFYITEMERASE
    The control will notify the parent when an item will be erased. It will send NM_CUSTOMDRAW notification messages before and after erasing items.
    CDRF_NOTIFYPOSTERASE
    The control will notify the parent after erasing an item.
    CDRF_NOTIFYPOSTPAINT
    The control will notify the parent after painting an item.
    CDRF_NOTIFYSUBITEMDRAW
    Version 4.71. The control will notify the parent when a list view subitem is being drawn.

    When dwDrawStage equals CDDS_ITEMPREPAINT:
    CDRF_NEWFONT
    Your application specified a new font for the item; the control will use the new font. For more information on changing fonts, see Changing fonts and colors.
    CDRF_SKIPDEFAULT
    Your application drew the item manually. The control will not draw the item.
    TBCDRF_NOEDGES
    Version 4.71. Don't draw button edges.
    TBCDRF_HILITEHOTTRACK
    Version 4.71. Use the clrHighlightHotTrack member of the NMTBCUSTOMDRAW structure to drawing the background of hot-tracked items.
    TBCDRF_NOOFFSET
    Version 4.71. Don't offset button when pressed.
    TBCDRF_NOMARK
    Version 4.71. Don't draw default highlight of items that have the TBSTATE_MARKED state.
    TBCDRF_NOETCHEDEFFECT
    Version 4.71. Don't draw etched effect for disabled items.

lpNMCustomDraw
Version 4.70. Address of an NMCUSTOMDRAW structure that contains information about the drawing operation. The dwItemSpec member of this structure contains the command identifier of the item being drawn. The lItemlParam member of this structure contains the dwData value for the item being drawn.

Version 4.71. Address of an NMTBCUSTOMDRAW structure that contains information about the drawing operation. The dwItemSpec member of the nmcd member of this structure contains the command identifier of the item being drawn. The lItemlParam member of the nmcd member of this structure contains the dwData value for the item being drawn.

Version 4.70

See also Using Custom Draw


NM_KEYDOWN (toolbar)

NM_KEYDOWN
    lpnmk = (LPNMKEY) lParam;

Sent by a control when the control has the keyboard focus and the user presses a key. This notification message is sent in the form of a WM_NOTIFY message.

  • Return nonzero to prevent the control from processing the key, or zero otherwise.
lpnmk
Address of an NMKEY structure that contains additional information about the key that caused the notification message.

Currently, only the toolbar control sends this notification.

Version 4.71


NM_RCLICK (toolbar)

NM_RCLICK
    lpnmmouse = (LPNMMOUSE) lParam;

Sent by a toolbar control when the user clicks on the toolbar with the right mouse button. This notification message is sent in the form of a WM_NOTIFY message.

  • Returns FALSE to allow the toolbar control to perform default processing of the event, or TRUE to prevent the control from processing the event.
lpnmmouse
Address of an NMMOUSE structure that contains information about this notification. If the mouse was clicked on a toolbar item, the dwItemSpec member contains the item identifier and the dwItemData member contains the item data. If the mouse was clicked on a separator or white space in the toolbar, the dwItemSpec member will contain -1.

This notification is identical to the standard NM_RCLICK notification except that the toolbar supplies an NMMOUSE structure instead of an NMHDR structure for the lParam.

Version 4.71. Prior versions send a standard NM_RCLICK message.


NM_RDBLCLK (toolbar)

NM_RDBLCLK
    lpnmh = (LPNMHDR) lParam;

Notifies a control's parent window 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.

  • Returns FALSE to allow the toolbar control to perform default processing of the event, or TRUE to prevent the control from processing the event.
lpnmh
Address of an NMHDR structure that contains additional information about this notification message.


NM_RELEASEDCAPTURE (toolbar)

NM_RELEASEDCAPTURE
    lpnmh = (LPNMHDR) lParam;

Notifies a toolbar control's parent window that the control is releasing mouse capture. This notification is sent in the form of a WM_NOTIFY message.

  • The control ignores the return value from this notification.
lpnmh
Address of an NMHDR structure that contains additional information about this notification message.

Version 4.71.


TBN_BEGINADJUST

TBN_BEGINADJUST
    lpnmhdr = (LPNMHDR) lParam;

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.

  • No return value.
lpnmhdr
Address of an NMHDR structure that contains information about the notification message.


TBN_BEGINDRAG

TBN_BEGINDRAG
    lpnmtb = (LPNMTOOLBAR) lParam;

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.

  • No return value.
lpnmtb
Address of an NMTOOLBAR structure. The iItem member contains the command identifier of the button being dragged.


TBN_CUSTHELP

TBN_CUSTHELP
    lpnmhdr = (LPNMHDR) lParam;

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.

  • No return value.
lpnmhdr
Address of an NMHDR structure that contains information about the notification message.


TBN_DELETINGBUTTON

 TBN_DELETINGBUTTON
    lpnmtb = (LPNMTOOLBAR) lParam;

Sent by a toolbar control when a button is about to be deleted.

  • The return value is ignored.
lpnmtb
Address of an NMTOOLBAR structure that contains information about the button being deleted. For this notification message, only the hdr and iItem members of this structure are valid. The iItem member of this structure contains the command identifier of the button being deleted.

Version 4.71


TBN_DRAGOUT

TBN_DRAGOUT
    lpnmtb = (LPNMTOOLBAR) lParam;

Sent by a toolbar control when the user clicks a button and then moves the cursor off the button. This notification message is sent in the form of a WM_NOTIFY message.

  • The return value is ignored.
lpnmtb
Address of an NMTOOLBAR structure that contains information about this notification. For this notification message, only the hdr and iItem members of this structure are valid. The iItem member of this structure contains the command identifier of the button being dragged.

This notification allows an application to implement drag-and-drop functionality for toolbar buttons. When processing this notification, the application will begin the drag-and-drop operation.

Version 4.71


TBN_DROPDOWN

TBN_DROPDOWN
    lpnmtb = (LPNMTOOLBAR) lParam;

Sent by a toolbar control when the user clicks a button that uses the TBSTYLE_DROPDOWN style. This notification message is sent in the form of a WM_NOTIFY message.

  • Returns one of the following values:
    TBDDRET_DEFAULT | The drop-down was handled.
    TBDDRET_NODEFAULT | The drop-down was not handled.
    TBDDRET_TREATPRESSED | The drop-down was handled, but treat the button like a regular button.
lpnmtb
Address of an NMTOOLBAR structure that contains information about this notification. For this notification message, only the hdr and iItem members of this structure are valid.

In version 4.71 and greater, this notification is only sent when the user clicks on the drop-down arrow portion of the button. In previous versions, this notification is sent when the user clicks on any portion of the button.

Version 4.70


TBN_ENDADJUST

TBN_ENDADJUST
    lpnmhdr = (LPNMHDR) lParam;

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.

  • No return value.
lpnmhdr
Address of an NMHDR structure that contains information about the notification message.


TBN_ENDDRAG

TBN_ENDDRAG
    lpnmtb = (LPNMTOOLBAR) lParam;

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.

  • No return value.
lpnmtb
Address of an NMTOOLBAR structure. The iItem member contains the command identifier of the button being dragged.


TBN_GETBUTTONINFO

TBN_GETBUTTONINFO
    lpnmtb = (LPNMTOOLBAR) lParam;

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.

  • Returns TRUE if button information was copied to the specified structure, or FALSE otherwise.
lpnmtb
Address of an NMTOOLBAR structure. The iItem member specifies a zero-based index that provides a count of the buttons the Customize Toolbar 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.

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.


TBN_GETDISPINFO

TBN_GETDISPINFO
    lptbdi = (LPNMTBDISPINFO) lParam;

Retrieves display information for a toolbar item. This notification is sent in the form of a WM_NOTIFY message.

  • The return value is ignored by the control.
lptbdi
Address of an NMTBDISPINFO structure. The idCommand member specifies the item's command identifier, the lParam member contains the item's application-defined data, and the dwMask member specifies what information is being requested.

TBN_GETINFOTIP

TBN_GETINFOTIP
    lptbgit = (LPNMTBGETINFOTIP) lParam;

Retrieves infotip information for a toolbar item. This notification is sent in the form of a WM_NOTIFY message.

  • The return value is ignored by the control.
lptbgit
Address of an NMTBGETINFOTIP structure that contains item information and receives infotip information.

The infotip support in the toolbar allows the toolbar to display tooltips for items that are as large as INFOTIPSIZE characters. If this notification is not processed, the toolbar will use the item's text for the infotip.

Version 4.71


TBN_GETOBJECT

TBN_GETOBJECT
    lpnmon = (LPNMOBJECTNOTIFY) lParam;

Sent by a toolbar control that uses the TBSTYLE_REGISTERDROP style to request a drop target object when the pointer passes over one of its buttons.

  • The application processing this notification must return zero.
lpnmon
Address of an NMOBJECTNOTIFY structure that contains information about the button that the pointer passed over and receives data the application provides in response to this message.

To provide an object, an application must set values in some members of the NMOBJECTNOTIFY structure at lpnmon. The pObject member must be set to a valid object pointer, and the hResult member must be set to a success flag. To comply with Component Object Model (COM) standards, always increment the object's reference count when providing an object pointer.

If an application does not provide an object, it must set pObject to NULL and hResult to a failure flag.

Version 4.71


TBN_HOTITEMCHANGE

TBN_HOTITEMCHANGE
    lpnmhi = (LPNMTBHOTITEM) lParam;

Sent by a toolbar control when the hot (highlighted) item changes. This notification message is sent in the form of a WM_NOTIFY message.

  • Return zero to allow the item to be highlighted, or nonzero to prevent the item from being highlighted.
lpnmhi
Address of an NMTBHOTITEM structure that contains information about this notification.

Version 4.71


TBN_QUERYDELETE

TBN_QUERYDELETE
    lpnmtb = (LPNMTOOLBAR) lParam;

Notifies the toolbar's parent window whether a button may be deleted from a toolbar while the user is customizing the toolbar. This message is sent in the form of a WM_NOTIFY message.

  • Returns TRUE to allow the button to be deleted, or FALSE to prevent the button from being deleted.
lpnmtb
Address of an NMTOOLBAR structure. The iItem member contains the zero-based index of the button to be deleted.


TBN_QUERYINSERT

TBN_QUERYINSERT
    lpnmtb = (LPNMTOOLBAR) lParam;

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.

  • Returns TRUE to allow a button to be inserted in front of the given button, or FALSE to prevent the button from being inserted.
lpnmtb
Address of an NMTOOLBAR structure. The iItem member contains the zero-based index of the button to be inserted.


TBN_RESET

TBN_RESET
    lpnmhdr = (LPNMHDR) lParam;

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.

  • No return value.
lpnmhdr
Address of an NMHDR structure that contains information about the notification message.


TBN_TOOLBARCHANGE

TBN_TOOLBARCHANGE
    lpnmhdr = (LPNMHDR) lParam;

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.

  • No return value.
lpnmhdr
Address of an NMHDR structure that contains information about the notification message.


Toolbar Control Structures

This section contains information about the structures used with toolbar controls.

COLORMAP

NMTBCUSTOMDRAW

NMTBDISPINFO

NMTBGETINFOTIP

NMTBHOTITEM

NMTOOLBAR

TBADDBITMAP

TBBUTTON

TBBUTTONINFO

TBINSERTMARK

TBREPLACEBITMAP

TBSAVEPARAMS


COLORMAP

typedef struct _COLORMAP {
    COLORREF from;
    COLORREF to;
} COLORMAP, FAR* LPCOLORMAP;

Contains information used by the CreateMappedBitmap function to map the colors of the bitmap.

from
Color to map from.
to
Color to map to.


NMTBCUSTOMDRAW

typedef struct _NMTBCUSTOMDRAW {
    NMCUSTOMDRAW nmcd;
    HBRUSH hbrMonoDither;
    HBRUSH hbrLines;
    HPEN hpenLines;
    COLORREF clrText;
    COLORREF clrMark;
    COLORREF clrTextHighlight;
    COLORREF clrBtnFace;
    COLORREF clrBtnHighlight;
    COLORREF clrHighlightHotTrack;
    RECT rcText;
    int nStringBkMode;
    int nHLStringBkMode;
} NMTBCUSTOMDRAW, * LPNMTBCUSTOMDRAW;

Contains information specific to an NM_CUSTOMDRAW notification message sent by a toolbar control.

nmcd
NMCUSTOMDRAW structure that contains general custom draw information. The uItemState member of this structure can be modified so that a toolbar item will be drawn in the specified state without actually changing the item's state.
hbrMonoDither
HBRUSH that the control will use when drawing the background of marked or dithered items. This member is ignored if TBCDRF_NOMARK is returned from the NM_CUSTOMDRAW notification.
hbrLines
HBRUSH that the control will use when drawing lines on the buttons.
hpenLines
HPEN that the control will use when drawing lines on the buttons.
clrText
COLORREF that represents the color that the control will use when drawing text on normal items.
clrMark
COLORREF that represents the background color that the control will use when drawing text on marked items.
clrTextHighlight
COLORREF that represents the color that the control will use when drawing text on highlighted items.
clrBtnFace
COLORREF that represents the face color that the control will use when drawing buttons.
clrBtnHighlight
COLORREF that represents the face color that the control will use when drawing highlighted items. An item is highlighted if it has the TBSTATE_MARKED style and is contained in a toolbar that has the TBSTYLE_FLAT style.
clrHighlightHotTrack
COLORREF that represents the background color that the control will use when drawing text on hot tracked items. This member is ignored if TBCDRF_HILITEHOTTRACK is not returned from the NM_CUSTOMDRAW notification.
rcText
RECT structure that, on entry, contains the rectangle of the item's text. The right and bottom members of this structure can be modified to change the width and height, respectively, of the text rectangle of the item.
nStringBkMode
Background mode that the control will use when drawing the text of a nonhighlighted item. This can be either the TRANSPARENT or OPAQUE value.
nHLStringBkMode
Background mode that the control will use when drawing the text of a highlighted item. This can be either the TRANSPARENT or OPAQUE value.

Version 4.71


NMTBDISPINFO

typedef struct{
    NMHDR  hdr;
    DWORD dwMask;
    int idCommand;
    DWORD lParam;
    int iImage;
    LPTSTR pszText;
    int cchText;
} NMTBDISPINFO, *LPNMTBDISPINFO;

Contains and receives display information for a toolbar item. This structure is used with the TBN_GETDISPINFO notification.

hdr
NMHDR structure that contains additional information about the notification message.
dwMask
Set of flags that indicate which members of this structure are being requested. This can be one or more of the following values:
TBNF_IMAGE | The item's image index is being requested. The image index must be placed in the iImage member.
TBNF_TEXT | Not currently implemented. The item's text is being requested. The text must be copied to the buffer pointed to by the pszText member.

The receiving application can add the TBNF_DI_SETITEM flag to this member, in which case the control will store the display information and not request it again.

idCommand
The command identifier of the item for which display information is being requested. This member is filled in by the control before sending the notification.
lParam
The application-defined 32-bit value associated with the item for which display information is being requested. This member is filled in by the control before sending the notification.
iImage
Receives the image index for the item.
pszText
Address of a character buffer that receives the item's text.
cchText
Size of the buffer, in characters, at pszText.

Version 4.71

NMTBGETINFOTIP

typedef struct tagNMTBGETINFOTIP{
    NMHDR hdr;
    LPTSTR pszText;
    int cchTextMax;
    int iItem;
    LPARAM lParam;
} NMTBGETINFOTIP, *LPNMTBGETINFOTIP;

Contains and receives infotip information for a toolbar item. This structure is used with the TBN_GETINFOTIP notification.

hdr
NMHDR structure that contains additional information about the notification message.
pszText
Address of a character buffer that receives the infotip text.
cchTextMax
Size of the buffer, in characters, at pszText. In most cases, the buffer will be INFOTIPSIZE characters in size, but you should always make sure that your application does not copy more than cchTextMax characters to the buffer at pszText.
iItem
The command identifier of the item for which infotip information is being requested. This member is filled in by the control before sending the notification.
lParam
The application-defined 32-bit value associated with the item for which infotip information is being requested. This member is filled in by the control before sending the notification.

Version 4.71


NMTBHOTITEM

typedef struct tagNMTBHOTITEM {
    NMHDR hdr;
    int idOld;
    int idNew;
    DWORD dwFlags;
} NMTBHOTITEM, FAR* LPNMTBHOTITEM;

Contains information used with the TBN_HOTITEMCHANGE notification.

hdr
NMHDR structure that contains additional information about the notification message.
idOld
Command identifier of the previously highlighted item.
idNew
Command identifier of the item about to be highlighted.
dwFlags
Flags that indicate why the hot item has changed. This can be one or more of the following values:
HICF_ACCELERATOR | The change in the hot item resulted from an accelerator.
HICF_ARROWKEYS | The change in the hot item resulted from an arrow key.
HICF_DUPACCEL | Modifies HICF_ACCELERATOR. If this flag is set, more than one item has the same accelerator character.
HICF_ENTERING | Modifies the other reason flags. If this flag is set, there is no previous hot item and idOld does not contain valid information.
HICF_LEAVING | Modifies the other reason flags. If this flag is set, there is no new hot item and idNew does not contain valid information.
HICF_MOUSE | The change in the hot item resulted from a mouse event.
HICF_OTHER | The change in the hot item resulted from an event that could not be determined. This will most often be due to a change in focus or the TB_SETHOTITEM message.
HICF_RESELECT | The change in the hot item resulted from the user entering the accelerator for an item that was already hot.

Version 4.71


NMTOOLBAR

typedef struct tagNMTOOLBAR {
    NMHDR    hdr;
    int      iItem;
    TBBUTTON tbButton;
    int      cchText;
    LPTSTR   pszText;
} NMTOOLBAR, FAR* LPNMTOOLBAR;

Contains information used to process toolbar notification messages. This structure supersedes the TBNOTIFY structure.

hdr
NMHDR structure that contains additional information about the notification message.
iItem
Command identifier of the button associated with the notification.
tbButton
TBBUTTON structure that contains information about the toolbar button associated with the notification. This member only contains valid information with the TBN_QUERYINSERT and TBN_QUERYDELETE notifications.
cchText
Count of characters in the button text.
pszText
Address of a character buffer that contains the button text.

Version 4.70


TBADDBITMAP

typedef struct {
    HINSTANCE hInst;
    UINT nID;
} TBADDBITMAP, *LPTBADDBITMAP;

Adds a bitmap that contains button images to a toolbar.

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:
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 comments at the end of this reference.
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.

The Windows header files provide the following values to be used as indexes to the standard and view bitmaps.
STD_COPY | Specifies the copy image.
STD_CUT | Specifies the cut image.
STD_DELETE | Specifies the delete image.
STD_FILENEW | Specifies the new file image.
STD_FILEOPEN | Specifies the open file image.
STD_FILESAVE | Specifies the save file image.
STD_FIND | Specifies the find image.
STD_HELP | Specifies the help image.
STD_PASTE | Specifies the paste image.
STD_PRINT | Specifies the print image.
STD_PRINTPRE | Specifies the print preview image.
STD_PROPERTIES | Specifies the properties image.
STD_REDOW | Specifies the redo image.
STD_REPLACE | Specifies the replace image.
STD_UNDO | Specifies the undo image.
VIEW_DETAILS | Specifies the view details image.
VIEW_LARGEICONS | Specifies the view large icons image.
VIEW_LIST | Specifies the view list image.
VIEW_SMALLICONS | Specifies the view small icons image.
VIEW_SORTDATE | Specifies the sort by date image.
VIEW_SORTNAME | Specifies the sort by name image.
VIEW_SORTSIZE | Specifies the sort by size image.
VIEW_SORTTYPE | Specifies the sort by type image.

The TBADDBITMAP structure is used with the TB_ADDBITMAP message.


TBBUTTON

typedef struct _TBBUTTON {
    int iBitmap;
    int idCommand;
    BYTE fsState;
    BYTE fsStyle;
    DWORD dwData;
    int iString;
} TBBUTTON, NEAR* PTBBUTTON, FAR* LPTBBUTTON;

Contains information about a button in a toolbar.

iBitmap
Zero-based index of the button image.
idCommand
Command identifier associated with the button. This identifier is used in a WM_COMMAND message when the button is chosen.
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 the button style values listed in Toolbar Control and Button Styles.
dwData
Application-defined value.
iString
Zero-based index of the button string.


TBBUTTONINFO

typedef struct {
    UINT cbSize;
    DWORD dwMask;
    int idCommand;
    int iImage;
    BYTE fsState;
    BYTE fsStyle;
    WORD cx;
    DWORD lParam;
    LPTSTR pszText;
    int cchText;
} TBBUTTONINFOA, *LPTBBUTTONINFOA;

Contains or receives information for a specific button in a toolbar.

cbSize
Size of the structure, in bytes. This member must be filled in prior to sending the associated message.
dwMask
Set of flags that indicate which members contain valid information. This member must be filled in prior to sending the associated message. This can be one or more of the following values:
TBIF_COMMAND | The idCommand member contains valid information or is being requested.
TBIF_IMAGE | The iImage member contains valid information or is being requested.
TBIF_LPARAM | The lParam member contains valid information or is being requested.
TBIF_SIZE | The cx member contains valid information or is being requested.
TBIF_STATE | The fsState member contains valid information or is being requested.
TBIF_STYLE | The fsStyle member contains valid information or is being requested.
TBIF_TEXT | The pszText member contains valid information or is being requested.
idCommand
Command identifier of the button.
iImage
Image index of the button. If this member is set to I_IMAGECALLBACK, the toolbar will send the TBN_GETDISPINFO notification to retrieve the image index when it is needed.
fsState
State flags of the button. This can be one or more of the toolbar button states.
fsStyle
Style flags of the button. This can be one or more of the toolbar button styles.
cx
Width of the button, in pixels.
lParam
Application-defined 32-bit value associated with the button.
pszText
Address of a character buffer that contains or receives the button text.
cchText
Size of the buffer at pszText. If the button information is being set, this member is ignored.

Version 4.71


TBINSERTMARK

typedef struct {
    int   iButton;
    DWORD dwFlags;
} TBINSERTMARK, * LPTBINSERTMARK;

Contains information on the insertion mark in a toolbar control.

iButton
Zero-based index of the insertion mark. If this member is -1, there is no insertion mark.
dwFlags
Defines where the insertion mark is in relation to iButton. This can be one of the following values:
0 | The insertion mark is to the left of the specified button.
TBIMHT_AFTER | The insertion mark is to the right of the specified button.
TBIMHT_BACKGROUND | The insertion mark is on the background of the toolbar. This flag is only used with the TB_INSERTMARKHITTEST message.


TBREPLACEBITMAP

typedef struct {
    HINSTANCE hInstOld;
    UINT nIDOld;
    HINSTANCE hInstNew;
    UINT nIDNew;
    int nButtons;
} TBREPLACEBITMAP, *LPTBREPLACEBITMAP;

Used with the TB_REPLACEBITMAP message to replace one toolbar bitmap with another.

hInstOld
Module instance handle to the bitmap resource being replaced.
nIDOld
Resource identifier of the bitmap being replaced.
hInstNew
Module instance handle that contains the new bitmap resource.
nIDNew
Resource identifier of the new bitmap.
nButtons
Number of button images contained in the new bitmap.


TBSAVEPARAMS

typedef struct {
    HKEY hkr;
    LPCTSTR pszSubKey;
    LPCTSTR pszValueName;
} TBSAVEPARAMS;

Specifies the location in the registry where the TB_SAVERESTORE message stores and retrieves information about the state of a toolbar.

hkr
Handle to the registry key.
pszSubKey
Subkey name.
pszValueName
Value name.


Tooltip Controls

A tooltip control is a small pop-up window that displays a single line of text that describes the purpose of a tool 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

Using Tooltip Controls

Tooltip Control Update in Internet Explorer

Tooltip Control Reference

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

Activation

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.

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 control the TTM_ADDTOOL message. 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 to 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 to 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 Microsoft® 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 it hasn't, 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 pop-up 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 pop-up 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. This is 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 tooltip 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 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 that the tooltip control will use to draw text.
WM_MOUSEMOVE | Hides the tooltip window.
WM_PAINT | Draws the tooltip window.
WM_SETFONT | Sets the handle of the font that the tooltip control will use to draw text.
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

This section provides examples that demonstrate how to create a tooltip control and use a tooltip control with a dialog box.

Creating a Tooltip Control

The following example demonstrates how to create a tooltip control and add 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 to the application instance.
    // g_hwndTT - handle to the tooltip control.
    // g_hwndDlg - handle to the dialog box.
    // g_hhk - handle to 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 (lstrcmpi(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 Update in Internet Explorer

Tooltip controls in Microsoft® Internet Explorer support a new feature called a tracking tooltip.

Tracking Tooltips

Tooltip controls support tracking tooltips, which are tooltip windows that you can dynamically position on the screen. By rapidly updating the position, the tooltip window appears to move smoothly, or "track." This functionality can be useful if you need tooltip text to follow the position of the pointer as it moves.

To create a tracking tooltip, use the TTM_ADDTOOL message, including the TTF_TRACK flag in the uFlags member of the accompanying TOOLINFO structure.

Your application must manually activate and deactivate a tracking tooltip using the TTM_TRACKACTIVATE message. While your tooltip is active, your application must supply the location at which the tooltip window will appear by using the TTM_TRACKPOSITION message. Tracking tooltip controls do not support the TTF_SUBCLASS style, so all mouse events must be forwarded from the parent to the child using TTM_RELAYEVENT messages.

The TTM_TRACKPOSITION message causes the tooltip control to display the window using one of two placement styles:

  • Next to the corresponding tool in a position the control chooses. The location chosen is relative to the coordinates you provide using this message. In this case, the tooltip window appears to move beside the corresponding tool. This is the default behavior.
  • At the pixel location you specify using this message. In this case, the control does not attempt to change the tooltip window's location from the coordinates you provide. However, you must include the TTF_ABSOLUTE value in the uFlags member of the TOOLINFO structure when creating the tool to prompt this behavior.

For more information and implementation details, see Creating Tracking Tooltips and Supporting Tracking Tooltips.

Creating Tracking Tooltips

The following example demonstrates how to create a tooltip control and assign a tool to it. The example specifies the main window's entire client area as the tool, but you could specify distinct portions of the client area or specify a different window altogether.

The example uses the TTM_ADDTOOL message to add the tool to the tooltip control. Tracking tooltips do not support the TTF_SUBCLASS flag, so the control's owner must manually forward pertinent messages (like WM_MOUSEMOVE) by using TTM_RELAYEVENT.

Additionally, the uFlags member of the TOOLINFO structure used in the example includes the TTF_ABSOLUTE flag. This flag causes the tooltip control to display tooltip text at the exact coordinates the application provides when it sends the TTM_TRACKPOSITION message. Without the TTF_ABSOLUTE flag, the tooltip control will choose a location to display the tooltip text based on the coordinates you provide. This causes tooltip text to appear next to the corresponding tool but not necessarily at the exact coordinates the application provided.

For additional information on using the TTM_TRACKPOSITION message, see Supporting Tracking Tooltips.

HWND WINAPI CreateTT(HWND hwndOwner)
{
    INITCOMMONCONTROLSEX icex;
    HWND        hwndTT;
    TOOLINFO    ti;

    // Load the tooltips class from the DLL.
    icex.dwSize = sizeof(icex);
    icex.dwICC  = ICC_BAR_CLASSES;

    if(!InitCommonControlsEx(&icex))
       return NULL;

    // Create the tooltip control.
    hwndTT = CreateWindow(TOOLTIPS_CLASS, TEXT(""),
                          WS_POPUP,
                          CW_USEDEFAULT, CW_USEDEFAULT,
                          CW_USEDEFAULT, CW_USEDEFAULT,
                          NULL, (HMENU)NULL, g_hinst,
                          NULL);

    // Prep the TOOLINFO structure to be used for a tracking tooltip.
    ti.cbSize = sizeof(TOOLINFO);
    ti.uFlags = TTF_IDISHWND | TTF_TRACK | TTF_ABSOLUTE;
    ti.hwnd   = hwndOwner;
    ti.uId    = (UINT)g_hwndMain;
    ti.hinst  = g_hinst;
    ti.lpszText  = LPSTR_TEXTCALLBACK;
    ti.rect.left = ti.rect.top = ti.rect.bottom = ti.rect.right = 0;

    // Add the tool to the control, displaying an error if needed.
    if(!SendMessage(hwndTT,TTM_ADDTOOL,0,(LPARAM)&ti)){
        MessageBox(hwndOwner,"Couldn't create the tooltip control.","Error",MB_OK);
        return NULL;
    }

    // Activate (display) the tracking tooltip.  Then, set a global
    // flag value to indicate that the tooltip is active, so other
    // functions can check to see if it's visible.
    SendMessage(hwndTT,TTM_TRACKACTIVATE,(WPARAM)TRUE,(LPARAM)&ti);
    g_bIsVisible = TRUE;

    return(hwndTT);
}

Supporting Tracking Tooltips

The following example is a simple window process function that supports tracking tooltips. It requests the current position of the pointer using the GetCursorPos function and then adds 15 pixels to the x- and y-coordinates so the tooltip appears slightly below and to the right of the pointer.

Note that the example relies on the value of a global variable, g_bIsVisible, to determine whether the application should send the TTM_TRACKPOSITION message. For the purpose of this example, g_bIsVisible is a BOOL variable that another function sets to TRUE upon sending the TTM_TRACKACTIVATE message to activate the tooltip. This way, if the tooltip is inactive, the additional overhead to calculate and send a message is not incurred.

LRESULT CALLBACK WndProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    HDC   hdc;
    PAINTSTRUCT ps;
    MSG   mssg;
    POINT pt;

    switch(msg){
        case WM_MOUSEMOVE:
            if(g_bIsVisible){
                mssg.hwnd    = g_hwndMain;
                mssg.message = msg;
                mssg.wParam  = wParam;
                mssg.lParam  = lParam;

                GetCursorPos(&pt);
                mssg.pt.x    = pt.x;
                mssg.pt.y    = pt.y;

#define X_OFFSET 15
#define Y_OFFSET X_OFFSET
                SendMessage(g_hwndTT,
                            TTM_TRACKPOSITION,0,
                            (LPARAM)MAKELPARAM(pt.x+X_OFFSET,
                            pt.y+Y_OFFSET));
            }
            break;

/*
 *
 *  Other standard window messages can be handled here.
 *
 */
    }
    return 0;
}


Tooltip Control Reference

This section contains information about the following programming elements used with tooltip controls.

Tooltip Styles

Messages
TTM_ACTIVATE
TTM_ADDTOOL
TTM_DELTOOL
TTM_ENUMTOOLS
TTM_GETCURRENTTOOL
TTM_GETDELAYTIME
TTM_GETMARGIN
TTM_GETMAXTIPWIDTH
TTM_GETTEXT
TTM_GETTIPBKCOLOR
TTM_GETTIPTEXTCOLOR
TTM_GETTOOLCOUNT
TTM_GETTOOLINFO
TTM_HITTEST
TTM_NEWTOOLRECT
TTM_POP
TTM_RELAYEVENT
TTM_SETDELAYTIME
TTM_SETMARGIN
TTM_SETMAXTIPWIDTH
TTM_SETTIPBKCOLOR
TTM_SETTIPTEXTCOLOR
TTM_SETTOOLINFO
TTM_TRACKACTIVATE
TTM_TRACKPOSITION
TTM_UPDATE
TTM_UPDATETIPTEXT
TTM_WINDOWFROMPOINT

Notifications
NM_CUSTOMDRAW (tooltip)
TTN_GETDISPINFO
TTN_NEEDTEXT
TTN_POP
TTN_SHOW

Structures
NMTTCUSTOMDRAW
NMTTDISPINFO
TOOLINFO
TOOLTIPTEXT
TTHITTESTINFO


Tooltip Styles

Tooltip controls support a variety of control styles in addition to standard window styles. A tooltip control always has the WS_POPUP and WS_EX_TOOLWINDOW window styles, regardless of whether you specify them when creating the control.
TTS_ALWAYSTIP | The tooltip appears when the cursor is on a tool, even if the tooltip control's owner window is inactive. Without this style, the tooltip control appears only when the tool's owner window is active.
TTS_NOPREFIX | Prevents the system from stripping the ampersand (&) character from a string. Without this style, the system automatically strips ampersand characters. This allows an application to use the same string as both a menu item and as text in a tooltip control.


Tooltip Control Messages

This section contains information about the messages used with tooltip controls.

TTM_ACTIVATE

TTM_ADDTOOL

TTM_DELTOOL

TTM_ENUMTOOLS

TTM_GETCURRENTTOOL

TTM_GETDELAYTIME

TTM_GETMARGIN

TTM_GETMAXTIPWIDTH

TTM_GETTEXT

TTM_GETTIPBKCOLOR

TTM_GETTIPTEXTCOLOR

TTM_GETTOOLCOUNT

TTM_GETTOOLINFO

TTM_HITTEST

TTM_NEWTOOLRECT

TTM_POP

TTM_RELAYEVENT

TTM_SETDELAYTIME

TTM_SETMARGIN

TTM_SETMAXTIPWIDTH

TTM_SETTIPBKCOLOR

TTM_SETTIPTEXTCOLOR

TTM_SETTOOLINFO

TTM_TRACKACTIVATE

TTM_TRACKPOSITION

TTM_UPDATE

TTM_UPDATETIPTEXT

TTM_WINDOWFROMPOINT


TTM_ACTIVATE

TTM_ACTIVATE
    wParam = (WPARAM) (BOOL) fActivate;
    lParam = 0;

Activates or deactivates a tooltip control.

  • No return value.
fActivate
Activation flag. If this parameter is TRUE, the tooltip control is activated. If it is FALSE, the tooltip control is deactivated.


TTM_ADDTOOL

TTM_ADDTOOL
    wParam = 0;
    lParam = (LPARAM) (LPTOOLINFO) lpti;

Registers a tool with a tooltip control.

  • Returns TRUE if successful, or FALSE otherwise.
lpti
Address of a TOOLINFO structure containing information that the tooltip control needs to display text for the tool. The cbSize member of this structure must be filled in before sending this message.


TTM_DELTOOL

TTM_DELTOOL
    wParam = 0;
    lParam = (LPARAM) (LPTOOLINFO) lpti;

Removes a tool from a tooltip control.

  • No return value.
lpti
Address of 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.


TTM_ENUMTOOLS

TTM_ENUMTOOLS
    wParam = (WPARAM) (UINT) iTool;
    lParam = (LPARAM) (LPTOOLINFO) lpti;

Retrieves the information that a tooltip control maintains about the current tool—that is, the tool for which the tooltip is currently displaying text.

  • Returns TRUE if any tools are enumerated, or FALSE otherwise.
iTool
Zero-based index of the tool for which to retrieve information.
lpti
Address of a TOOLINFO structure that receives information about the tool. Before sending this message, the cbSize member must specify the size of the structure.


TTM_GETCURRENTTOOL

TTM_GETCURRENTTOOL
    wParam = 0;
    lParam = (LPARAM)(LPTOOLINFO) lpti;

Retrieves the information for the current tool in a tooltip control.

  • Returns nonzero if successful, or zero otherwise. If lpti is NULL, returns nonzero if a current tool exists, or zero otherwise.
lpti
Address of a TOOLINFO structure that receives information about the current tool. If this value is NULL, the return value indicates the existence of the current tool without actually retrieving the tool information. If this value is not NULL, the cbSize member of the TOOLINFO structure must be filled in before sending this message.


TTM_GETDELAYTIME

TTM_GETDELAYTIME
    wParam = (DWORD) dwDuration;
    lParam = 0;

Retrieves the initial, pop-up, and reshow durations currently set for a tooltip control.

  • Returns an INT value that represents the specified duration, in milliseconds.
dwDuration
Flag that specifies which duration value will be retrieved. This parameter can be one of the following values:
TTDT_AUTOPOP | Retrieve the length of time the tooltip window remains visible if the pointer is stationary within a tool's bounding rectangle.
TTDT_INITIAL | Retrieve the length of time the pointer must remain stationary within a tool's bounding rectangle before the tooltip window appears.
TTDT_RESHOW | Retrieve the length of time it takes for subsequent tooltip windows to appear as the pointer moves from one tool to another.

Version 4.70.

See also TTM_SETDELAYTIME


TTM_GETMARGIN

TTM_GETMARGIN
    wParam = 0;
    lParam = (LPARAM)(LPRECT) lprc;

Retrieves the top, left, bottom, and right margins set for a tooltip window. A margin is the distance, in pixels, between the tooltip window border and the text contained within the tooltip window.

  • The return value for this message is not used.
lprc
Address of a RECT structure that will receive the margin information.

The members of the RECT structure do not define a bounding rectangle. For the purpose of this message, the structure members are interpreted as follows:
top | Distance between top border and top of tooltip text, in pixels.
left | Distance between left border and left end of tooltip text, in pixels.
bottom | Distance between bottom border and bottom of tooltip text, in pixels.
right | Distance between right border and right end of tooltip text, in pixels.

All four margins default to zero when you create the tooltip control.

Version 4.70.

See also TTM_SETMARGIN


TTM_GETMAXTIPWIDTH

TTM_GETMAXTIPWIDTH
    wParam = 0;
    lParam = 0;

Retrieves the maximum width for a tooltip window.

  • Returns an INT value that represents the maximum tooltip width, in pixels. If no maximum width was set previously, the message returns -1.

The maximum tooltip width value does not indicate a tooltip window's actual width. Rather, if a tooltip string exceeds the maximum width, the control breaks the text into multiple lines, using spaces to determine line breaks. If the text cannot be segmented into multiple lines, it will be displayed on a single line. The length of this line may exceed the maximum tooltip width.

Version 4.70.

See also TTM_SETMAXTIPWIDTH


TTM_GETTEXT

TTM_GETTEXT
    wParam = 0;
    lParam = (LPARAM) (LPTOOLINFO) lpti;

Retrieves the information a tooltip control maintains about a tool.

  • No return value.
lpti
Address of a TOOLINFO structure.
The cbSize member of this structure must be filled in before sending this message. Set the hwnd and uId members to identify the tool for which to retrieve information. Set the lpszText member to point to a buffer that receives the text. There currently is no way to specify the size of the buffer or to determine the required buffer size.


TTM_GETTIPBKCOLOR

TTM_GETTIPBKCOLOR
    wParam = 0;
    lParam = 0;

Retrieves the background color in a tooltip window.

  • Returns a COLORREF value that represents the background color.

Version 4.70.

See also TTM_SETTIPBKCOLOR


TTM_GETTIPTEXTCOLOR

TTM_GETTIPTEXTCOLOR
    wParam = 0;
    lParam = 0;

Retrieves the text color in a tooltip window.

  • Returns a COLORREF value that represents the text color.

Version 4.70.

See also TTM_SETTIPTEXTCOLOR


TTM_GETTOOLCOUNT

TTM_GETTOOLCOUNT
    wParam = 0;
    lParam = 0;

Retrieves a count of the tools maintained by a tooltip control.

  • Returns a count of tools.


TTM_GETTOOLINFO

TTM_GETTOOLINFO
    wParam = 0;
    lParam = (LPARAM) (LPTOOLINFO) lpti;

Retrieves the information that a tooltip control maintains about a tool.

  • Returns TRUE if successful, or FALSE otherwise.
lpti
Address of 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.


TTM_HITTEST

TTM_HITTEST
    wParam = 0;
    lParam = (LPARAM) (LPHITTESTINFO) lphti;

Tests a point to determine whether it is within the bounding rectangle of the specified tool and, if it is, retrieves information about the tool.

  • Returns TRUE if the tool occupies the specified point, or FALSE otherwise.
lphti
Address of a TTHITTESTINFO structure. When sending the message, the hwnd member must specify the handle to a tool and the pt member must specify the coordinates of a point. If the return value is TRUE, the ti member (a TOOLINFO structure) receives information about the tool that occupies the point. The cbSize member of the ti structure must be filled in before sending this message.


TTM_NEWTOOLRECT

TTM_NEWTOOLRECT
    wParam = 0;
    lParam = (LPARAM) (LPTOOLINFO) lpti;

Sets a new bounding rectangle for a tool.

  • No return value.
lpti
Address of a TOOLINFO structure. The hwnd and uId members identify a tool, and the rect member specifies the new bounding rectangle. The cbSize member of this structure must be filled in before sending this message.


TTM_POP

TTM_POP
    wParam = 0;
    lParam = 0;

Removes a displayed tooltip window from view.

  • The return value for this message is not used.

Version 4.70.


TTM_RELAYEVENT

TTM_RELAYEVENT
    wParam = 0;
    lParam = (LPARAM) (LPMSG) lpmsg;

Passes a mouse message to a tooltip control for processing.

  • No return value.
lpmsg
Address of an MSG structure that contains the message to relay.

A tooltip control processes only the following messages passed to it by the TTM_RELAYEVENT message:

  • WM_LBUTTONDOWN
  • WM_LBUTTONUP
  • WM_MBUTTONDOWN
  • WM_MBUTTONUP
  • WM_MOUSEMOVE
  • WM_RBUTTONDOWN
  • WM_RBUTTONUP

All other messages are ignored.


TTM_SETDELAYTIME

TTM_SETDELAYTIME
    wParam = (WPARAM)(DWORD) dwDuration;
    lParam = (LPARAM)(INT) MAKELONG(iTime,0);

Sets the initial, pop-up, and reshow durations for a tooltip control.

  • The return value for this message is not used.
dwDuration
Flag that specifies the duration value to set. This parameter can be one of the following values:
TTDT_AUTOPOP | Retrieve the length of time the tooltip window remains visible if the pointer is stationary within a tool's bounding rectangle.
TTDT_INITIAL | Retrieve the length of time the pointer must remain stationary within a tool's bounding rectangle before the tooltip window appears.
TTDT_RESHOW | Retrieve the length of time it takes for subsequent tooltip windows to appear as the pointer moves from one tool to another.
iTime | Delay time to be set, in milliseconds.

Version 4.70.

See also TTM_GETDELAYTIME


TTM_SETMARGIN

TTM_SETMARGIN
    wParam = 0;
    lParam = (LPARAM)(LPRECT) lprc;

Sets the top, left, bottom, and right margins for a tooltip window. A margin is the distance, in pixels, between the tooltip window border and the text contained within the tooltip window.

  • The return value for this message is not used.
lprc
Address of a RECT structure that contains the margin information to be set.

The members of the RECT structure do not define a bounding rectangle. For the purpose of this message, the structure members are interpreted as follows:
top | Distance between top border and top of tooltip text, in pixels.
left | Distance between left border and left end of tooltip text, in pixels.
bottom | Distance between bottom border and bottom of tooltip text, in pixels.
right | Distance between right border and right end of tooltip text, in pixels.

Version 4.70.

See also TTM_GETMARGIN


TTM_SETMAXTIPWIDTH

TTM_SETMAXTIPWIDTH
    wParam = 0;
    lParam = (LPARAM)(INT) iWidth;

Sets the maximum width for a tooltip window.

  • Returns an INT value that represents the previous maximum tooltip width.
iWidth
Maximum tooltip window width to be set.

The maximum tooltip width value does not indicate a tooltip window's actual width. Rather, if a tooltip string exceeds the maximum width, the control breaks the text into multiple lines, using spaces to determine line breaks. If the text cannot be segmented into multiple lines, it will be displayed on a single line. The length of this line may exceed the maximum tooltip width.

Version 4.70.

See also TTM_GETMAXTIPWIDTH


TTM_SETTIPBKCOLOR

TTM_SETTIPBKCOLOR
    wParam = (WPARAM)(COLORREF) clr;
    lParam = 0;

Sets the background color in a tooltip window.

  • The return value for this message is not used.
clr
New background color.

Version 4.70.

See also TTM_GETTIPBKCOLOR


TTM_SETTIPTEXTCOLOR

TTM_SETTIPTEXTCOLOR
    wParam = (WPARAM)(COLORREF) clr;
    lParam = 0;

Sets the text color in a tooltip window.

  • The return value for this message is not used.
clr
New text color.

Version 4.70.

See also TTM_GETTIPTEXTCOLOR


TTM_SETTOOLINFO

TTM_SETTOOLINFO
    wParam = 0;
    lParam = (LPARAM) (LPTOOLINFO) lpti;

Sets the information that a tooltip control maintains for a tool.

  • No return value.
lpti
Address of a TOOLINFO structure that specifies the information to set. The cbSize member of this structure must be filled in before sending this message.


TTM_TRACKACTIVATE

TTM_TRACKACTIVATE
    wParam = (WPARAM)(BOOL) bActivate;
    lParam = (LPARAM)(LPTOOLINFO) lpti;

Activates or deactivates a tracking tooltip.

  • The return value for this message is not used.
bActivate
Value specifying whether tracking is being activated or deactivated. This value can be one of the following:
TRUE | Activate tracking.
FALSE | Deactivate tracking.
lpti
Address of a TOOLINFO structure that identifies the tool to which this message applies. The hwnd and uId members identify the tool, and the cbSize member specifies the size of the structure. All other members are ignored.

Version 4.70.

See also Tracking Tooltips, TTM_TRACKPOSITION


TTM_TRACKPOSITION

TTM_TRACKPOSITION
    wParam = 0;
    lParam = (LPARAM)(DWORD) MAKELONG(xPos, yPos);

Sets the position of a tracking tooltip.

  • The return value for this message is not used.
xPos and yPos
The x- and y-coordinates of the point at which the tracking tooltip will be displayed, in screen coordinates.

The tooltip control chooses where to display the tooltip window based on the coordinates you provide with this message. This causes the tooltip window to appear beside the tool to which it corresponds. To have tooltip windows displayed at specific coordinates, include the TTF_ABSOLUTE flag in the uFlags member of the TOOLINFO structure when adding the tool.

Version 4.70.

See also Tracking Tooltips, TTM_TRACKACTIVATE


TTM_UPDATE

TTM_UPDATE
    wParam = 0;
    lParam = 0;

Forces the current tool to be redrawn.

  • The return value for this message is not used.

Version 4.71.


TTM_UPDATETIPTEXT

TTM_UPDATETIPTEXT
    wParam = 0;
    lParam = (LPARAM) (LPTOOLINFO) lpti;

Sets the tooltip text for a tool.

  • No return value.
lpti
Address of a TOOLINFO structure. The hinst and lpszText members must specify the instance handle and the address of the text. The hwnd and uId members identify the tool to update. The cbSize member of this structure must be filled in before sending this message.


TTM_WINDOWFROMPOINT

TTM_WINDOWFROMPOINT
    wParam = 0;
    lParam = (POINT FAR *) lppt;

Allows a subclass procedure to cause a tooltip to display text for a window other than the one beneath the mouse cursor.

  • The return value is the handle to the window that contains the point, or NULL if no window exists at the specified point.
lppt
Address of a POINT structure that defines the point to be checked.

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.


Tooltip Control Notification Messages

This section contains information about the notification messages sent by tooltip controls.

NM_CUSTOMDRAW (tooltip)

TTN_GETDISPINFO

TTN_POP

TTN_SHOW


NM_CUSTOMDRAW (tooltip)

NM_CUSTOMDRAW
    lpNMCustomDraw = (LPNMTTCUSTOMDRAW) lParam;

Sent by a tooltip control to notify its parent windows about drawing operations. This notification is sent in the form of a WM_NOTIFY message.

  • The value your application can return depends on the current drawing stage. The dwDrawStage member of the associated NMCUSTOMDRAW structure holds a value that specifies the drawing stage. You must return one of the following values.

    When dwDrawStage equals CDDS_PREPAINT:
    CDRF_DODEFAULT
    The control will draw itself. It will not send any additional NM_CUSTOMDRAW messages for this paint cycle.
    CDRF_NOTIFYITEMDRAW
    The control will notify the parent of any item-related drawing operations. It will send NM_CUSTOMDRAW notification messages before and after drawing items.
    CDRF_NOTIFYITEMERASE
    The control will notify the parent when an item will be erased. It will send NM_CUSTOMDRAW notification messages before and after erasing items.
    CDRF_NOTIFYPOSTERASE
    The control will notify the parent after erasing an item.
    CDRF_NOTIFYPOSTPAINT
    The control will notify the parent after painting an item.
    CDRF_NOTIFYSUBITEMDRAW
    Version 4.71. The control will notify the parent when a list view subitem is being drawn.

    When dwDrawStage equals CDDS_ITEMPREPAINT:
    CDRF_NEWFONT
    Your application specified a new font for the item; the control will use the new font. For more information on changing fonts, see Changing fonts and colors.
    CDRF_SKIPDEFAULT
    Your application drew the item manually. The control will not draw the item.

lpNMCustomDraw
Address of an NMTTCUSTOMDRAW structure that contains information about the drawing operation.

Version 4.70

See also Using Custom Draw


TTN_GETDISPINFO

TTN_GETDISPINFO
    lpnmtdi = (LPNMTTDISPINFO)lParam;

#define TTN_NEEDTEXT TTN_GETDISPINFO

Sent by a tooltip control to retrieve information needed to display a tooltip window. This notification supersedes the TTN_NEEDTEXT notification. This notification is sent in the form of a WM_NOTIFY message.

  • The return value for this notification is not used.
lpnmtdi
Address of an NMTTDISPINFO structure that identifies the tool that needs text and receives the requested information.

Fill the structure's appropriate fields to return the requested information to the tooltip control. If your message handler sets the uFlags field of the NMTTDISPINFO structure to TTF_DI_SETITEM, the tooltip control stores the information and will not request it again.

Version 4.70


TTN_POP

TTN_POP
    idTT = (int) wParam;
    pnmh = (LPNMHDR) lParam;

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.

  • No return value.
idTT
Identifier of the tooltip control.
pnmh
Address of an NMHDR structure.


TTN_SHOW

TTN_SHOW
    idTT = (int) wParam;
    pnmh = (LPNMHDR) lParam;

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.

  • No return value.
idTT
Identifier of the tooltip control.
pnmh
Address of an NMHDR structure.


Tooltip Control Structures

This section contains information about the structures used with tooltip controls.

NMTTCUSTOMDRAW

NMTTDISPINFO

TOOLINFO

TTHITTESTINFO


NMTTCUSTOMDRAW

typedef struct tagNMTTCUSTOMDRAW {
    NMCUSTOMDRAW nmcd;
    UINT         uDrawFlags;
} NMTTCUSTOMDRAW, FAR * LPNMTTCUSTOMDRAW;

Contains information specific to an NM_CUSTOMDRAW notification message sent by a tooltip control.

nmcd
NMCUSTOMDRAW structure that contains general custom draw information.
uDrawFlags
UINT value specifying how tooltip text will be formatted when it is displayed. This value is passed to the DrawText function internally. All values for the uFormat parameter of DrawText are valid.

Version 4.70


NMTTDISPINFO

typedef struct tagNMTTDISPINFO {
    NMHDR      hdr;
    LPTSTR     lpszText;
    char       szText[80];
    HINSTANCE  hinst;
    UINT       uFlags;
#if (_WIN32_IE >= 0x0300)
    LPARAM     lParam;
#endif
} NMTTDISPINFO, FAR *LPNMTTDISPINFO;

#define TOOLTIPTEXT NMTTDISPINFO

Contains information used in handling the TTN_GETDISPINFO notification message. This structure supersedes the TOOLTIPTEXT structure.

hdr
NMHDR structure that contains additional information about the notification message.
lpszText
Address of a null-terminated string that will be displayed as the tooltip text. 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 instead of 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 address of the tooltip text string, this member must be NULL.
uFlags
Flags that indicates how to interpret the idFrom member of the included NMHDR structure. If this member is the TTF_IDISHWND flag, idFrom is the tool's handle. Otherwise, it is the tool's identifier.

If you add the TTF_RTLREADING flag to this member while processing the notification, then text on Hebrew or Arabic systems is displayed using right-to-left reading order.

Version 4.70. If you add the TTF_DI_SETITEM flag to this member while processing the notification, the tooltip control will retain the supplied information and not request it again.

lParam
Version 4.70. Application-defined data associated with the tool.


TOOLINFO

typedef struct tagTOOLINFO{
    UINT      cbSize;
    UINT      uFlags;
    HWND      hwnd;
    UINT      uId;
    RECT      rect;
    HINSTANCE hinst;
    LPTSTR    lpszText;
#if (_WIN32_IE >= 0x0300)
    LPARAM lParam;
#endif
} TOOLINFO, NEAR *PTOOLINFO, FAR *LPTOOLINFO;

Contains information about a tool in a tooltip control.

cbSize
Size of the TOOLINFO structure, in bytes. This member must be specified.
uFlags
Set of bit flags. This member can be a combination of the following flags:
TTF_ABSOLUTE | Version 4.70. Positions the tooltip window at the same coordinates provided by TTM_TRACKPOSITION. This flag must be used with the TTF_TRACK flag.
TTF_CENTERTIP | Centers the tooltip window below the tool specified by the uId member.
TTF_IDISHWND | Indicates that the uId member is the window handle to the tool. If this flag is not set, uId is the tool's identifier.
TTF_RTLREADING | 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 must 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.
TTF_TRACK | Version 4.70. Positions the tooltip window next to the tool to which it corresponds and moves the window according to coordinates supplied by the TTM_TRACKPOSITION messages. You must activate this type of tool using the TTM_TRACKACTIVATE message.
TTF_TRANSPARENT | Version 4.70. Causes the tooltip control to forward mouse event messages to the parent window. This is limited to mouse events that occur within the bounds of the tip window.
hwnd
Handle to the window that contains the tool. If lpszText includes the LPSTR_TEXTCALLBACK value, this member identifies the window that receives the TTN_GETDISPINFO notification messages.
uId
Application-defined identifier of the tool. If uFlags includes the TTF_IDISHWND flag, uId must specify the window handle to the tool.
rect
Tool's bounding rectangle coordinates. 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 flag, 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
Address of 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.
lParam
Version 4.70. A 32-bit application defined value that is associated with the tool.


TTHITTESTINFO

typedef struct _TT_HITTESTINFO {
    HWND hwnd;
    POINT pt;
    TOOLINFO ti;
} TTHITTESTINFO, FAR * LPHITTESTINFO;

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.

hwnd
Handle to the tool or window with the specified tool.
pt
Client coordinates of the point to test.
ti
TOOLINFO structure. If the point specified by pt is in the tool specified by hwnd, this structure receives information about the tool. The cbSize member of this structure must be filled in before sending this message.

This structure is used with the TTM_HITTEST message.


Trackbar Controls

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.

About Trackbar Controls

Using Trackbar Controls

Trackbar Control Updates in Internet Explorer

Trackbar Control Reference

About Trackbar Controls

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 following illustration shows a typical trackbar.

A typical trackbar.

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 from zero to five, the slider can occupy only 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. After you have created a trackbar, you can use trackbar messages to set and retrieve 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 Messages

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

A trackbar automatically displays tick marks at its beginning and end, unless you specify the TBS_NOTICKS style. You can use the TBS_AUTOTICKS style to automatically display additional tick marks at regular intervals along the trackbar. By default, a TBS_AUTOTICKS trackbar displays a tick mark at each increment of the trackbar's range. To specify a different interval for the automatic tick marks, send the TBM_SETTICFREQ message to the trackbar. For example, you could use this message to display only 10 tick marks in a range of 1 through 100.

To set the position of a single tick mark, send the TBM_SETTIC message. A trackbar maintains an array of DWORD values that stores the position of each tick mark. The array does not include the first and last tick marks that the trackbar creates automatically. You can specify an index in this array when you send the TBM_GETTIC message to get the position of the corresponding tick mark. Alternatively, you can send the TBM_GETPTICS message to get a pointer to the array. The number of elements in the array is equal to two less than the tick count returned by the TBM_GETNUMTICS message. This is because the count returned by TBM_GETNUMTICS includes the first and last tick marks that are not included in the array. To retrieve the physical position of a tick mark, in client coordinates of the trackbar's window, send the TBM_GETTICPOS message. The TBM_CLEARTICS message removes all but the first and last of a trackbar's tick marks.

A trackbar's line size determines how far the slider moves in response to keyboard input from the arrow keys, such as the RIGHT ARROW or DOWN ARROW key. To retrieve or set the line size, send the TBM_GETLINESIZE and TBM_SETLINESIZE messages. The trackbar also sends the TB_LINEUP and TB_LINEDOWN notification messages to its parent window when the user presses the arrow keys.

A trackbar's page size determines how far the slider moves in response to keyboard input, such as the PAGE UP or PAGE DOWN keys, or mouse input, such as clicks in the trackbar channel. To retrieve or set the page size, send the TBM_GETPAGESIZE and TBM_SETPAGESIZE messages. The trackbar also sends the TB_PAGEUP and TB_PAGEDOWN notification messages to its parent window when it receives keyboard or mouse input that scrolls the page. For more information, see Trackbar Notification Messages.

An application can send messages to retrieve the dimensions of a trackbar. The TBM_GETTHUMBRECT message retrieves the bounding rectangle for the slider. The TBM_GETTHUMBLENGTH message retrieves the length of the slider. The TBM_GETCHANNELRECT message retrieves the bounding rectangle for the trackbar's channel, which is the area over which the slider moves. It contains the highlight when a range is selected. If a trackbar has the TBS_FIXEDLENGTH style, you can send the TBM_SETTHUMBLENGTH message to change the length of the slider.

A trackbar with the TBS_ENABLESELRANGE style can indicate a selection range by highlighting a range of the trackbar's channel and displaying triangular tick marks at the start and end of the selection. When a trackbar has this style, you can send messages to set and retrieve the selection range. Typically, an application handles the trackbar notification messages and sets the trackbar's selection range according to the user's input. 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. To retrieve the starting and ending positions of a selection range, send the TBM_GETSELSTART and TBM_GETSELEND messages. To clear a selection range, send the TBM_CLEARSEL message.

Trackbar Notification Messages

A trackbar notifies its parent window of user actions by sending the parent WM_HSCROLL or WM_VSCROLL messages. A trackbar with the TBS_HORZ style sends WM_HSCROLL messages. A trackbar with the TBS_VERT style sends WM_VSCROLL messages. The low-order word of the wParam parameter of WM_HSCROLL or WM_VSCROLL contains the notification code. For the TB_THUMBPOSITION and TB_THUMBTRACK notifications, the high-order word of the wParam parameter specifies the position of the slider. For all other notifications, the high-order word is zero; send the TBM_GETPOS message to determine the slider position. 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, such as setting the line size, page size, and tick mark frequency to default values.
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. If the wParam parameter is non-NULL, the control assumes that the value is an HDC and paints using that device context.
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 Trackbar Controls

This section provides examples that demonstrate how to create a trackbar and process 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.

A dialog containing a trackbar with the TBS_VERT style could use this function when it receives a WM_VSCROLL message.

    // 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 Control Updates in Internet Explorer

Trackbar controls in Microsoft® Internet Explorer support the following new features.

Buddy Windows
Trackbar controls now provide support for up to two buddy windows. Trackbar buddy windows are automatically positioned by the control to appear centered at the ends of the trackbar control. To assign an existing window to a trackbar, use the TBM_SETBUDDY message. To retrieve the handle to a given buddy window, send the TBM_GETBUDDY message.
Tooltips
Trackbar controls now support tooltips. A trackbar creates a default tooltip control when created with the TBS_TOOLTIPS style. However, you can assign a new tooltip control to a trackbar by sending the TBM_SETTOOLTIPS message. To retrieve the handle to an assigned tooltip control, use the TBM_GETTOOLTIPS message.


Trackbar Control Reference

This section contains information about the following programming elements used with trackbar controls.

Trackbar Control Styles

Messages
TBM_CLEARSEL
TBM_CLEARTICS
TBM_GETBUDDY
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_GETTOOLTIPS
TBM_GETUNICODEFORMAT
TBM_SETBUDDY
TBM_SETLINESIZE
TBM_SETPAGESIZE
TBM_SETPOS
TBM_SETRANGE
TBM_SETRANGEMAX
TBM_SETRANGEMIN
TBM_SETSEL
TBM_SETSELEND
TBM_SETSELSTART
TBM_SETTHUMBLENGTH
TBM_SETTIC
TBM_SETTICFREQ
TBM_SETTIPSIDE
TBM_SETTOOLTIPS
TBM_SETUNICODEFORMAT

Notifications
NM_CUSTOMDRAW (trackbar)
NM_RELEASEDCAPTURE (trackbar)

Trackbar Control Styles

Custom Draw Values

Trackbar Control Messages

Trackbar Control Notifications


Trackbar Control Styles

This section contains information about the styles used with trackbar controls.
TBS_AUTOTICKS | The trackbar control will have a tick mark for each increment in its range of values.
TBS_BOTH | The trackbar control will display tick marks on both sides of the control. This will be both top and bottom when used with TBS_HORZ or both left and right if used with TBS_VERT.
TBS_BOTTOM | The trackbar control will display tick marks below the control. This style is only valid with TBS_HORZ.
TBS_ENABLESELRANGE | The trackbar control can display a selection range only. 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.
TBS_FIXEDLENGTH | The trackbar control allows the size of the slider to be changed with the TBM_SETTHUMBLENGTH message.
TBS_HORZ | The trackbar control will be oriented vertically. This is the default orientation.
TBS_LEFT | The trackbar control will display tick marks to the left of the control. This style is only valid with TBS_VERT.
TBS_NOTHUMB | The trackbar control does not display a slider.
TBS_NOTICKS | The trackbar control will not display any tick marks.
TBS_RIGHT | The trackbar control will display tick marks to the right of the control. This style is only valid with TBS_VERT.
TBS_TOOLTIPS | Version 4.70. The trackbar control will support tooltips. When a trackbar control is created using this style, it automatically creates a default tooltip control that displays the slider's current position. You can change where the tooltips are displayed by using the TBM_SETTIPSIDE message.
TBS_TOP | The trackbar control will display tick marks above the control. This style is only valid with TBS_HORZ.
TBS_VERT | The trackbar control will be oriented vertically. This is the default orientation.


Custom Draw Values

Trackbar controls use the following values to identify a control's parts. One of these values is specified in the dwItemSpec member of the NMCUSTOMDRAW structure.
TBCD_CHANNEL | Identifies the channel that the trackbar control's thumb marker slides along. This is the part of the control that the user moves.
TBCD_THUMB | Identifies the trackbar control's thumb marker.
TBCD_TICS | Identifies the tick marks that are displayed along the trackbar control's edge.


Trackbar Control Messages

This section contains information about the messages used with trackbar controls.

TBM_CLEARSEL

TBM_CLEARTICS

TBM_GETBUDDY

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_GETTOOLTIPS

TBM_GETUNICODEFORMAT

TBM_SETBUDDY

TBM_SETLINESIZE

TBM_SETPAGESIZE

TBM_SETPOS

TBM_SETRANGE

TBM_SETRANGEMAX

TBM_SETRANGEMIN

TBM_SETSEL

TBM_SETSELEND

TBM_SETSELSTART

TBM_SETTHUMBLENGTH

TBM_SETTIC

TBM_SETTICFREQ

TBM_SETTIPSIDE

TBM_SETTOOLTIPS

TBM_SETUNICODEFORMAT


TBM_CLEARSEL

TBM_CLEARSEL
    wParam = (WPARAM) (BOOL) fRedraw;
    lParam = 0;

Clears the current selection range in a trackbar.

  • No return value.
fRedraw
Redraw flag. If this parameter is TRUE, the trackbar is redrawn after the selection is cleared.

A trackbar can have a selection range only if you specified the TBS_ENABLESELRANGE style when you created it.

See also TBM_SETSEL, TBM_SETSELEND, TBM_SETSELSTART


TBM_CLEARTICS

TBM_CLEARTICS
    wParam = (WPARAM) (BOOL) fRedraw;
    lParam = 0;

Removes the current tick marks from a trackbar. This message does not remove the first and last tick marks, which are created automatically by the trackbar.

  • No return value.
fRedraw
Redraw flag. If this parameter is TRUE, the trackbar is redrawn after the tick marks are cleared. If this parameter is FALSE, the message clears the tick marks but does not redraw the trackbar.


TBM_GETBUDDY

TBM_GETBUDDY
    wParam = (WPARAM)(BOOL) fLocation;
    lParam = 0;

Retrieves the handle to a trackbar control buddy window at a given location. The specified location is relative to the control's orientation (horizontal or vertical).

  • Returns the handle to the buddy window at the location specified by fLocation, or NULL if no buddy window exists at that location.
fLocation
Value indicating which buddy window handle will be retrieved, by relative location. This value can be one of the following:
TRUE | Retrieves the handle to the buddy to the left of the trackbar. If the trackbar control uses the TBS_VERT style, the message will retrieve the buddy above the trackbar.
FALSE | Retrieves the handle to the buddy to the right of the trackbar. If the trackbar control uses the TBS_VERT style, the message will retrieve the buddy below the trackbar.

Version 4.70


TBM_GETCHANNELRECT

TBM_GETCHANNELRECT
    wParam = 0;
    lParam = (LPARAM) (LPRECT) lprc;

Retrieves the size and position of the bounding rectangle for a trackbar's channel. (The channel is the area over which the slider moves. It contains the highlight when a range is selected.)

  • No return value.
lprc
Address of a RECT structure. The message fills this structure with the channel's bounding rectangle, in client coordinates of the trackbar's window.


TBM_GETLINESIZE

TBM_GETLINESIZE
    wParam = 0;
    lParam = 0;

Retrieves the number of logical positions the trackbar's slider moves in response to keyboard input from the arrow keys, such as the RIGHT ARROW or DOWN ARROW keys. The logical positions are the integer increments in the trackbar's range of minimum to maximum slider positions.

  • Returns a 32-bit value that specifies the line size for the trackbar.

The default setting for the line size is 1.

The trackbar also sends the TB_LINEUP and TB_LINEDOWN notification messages to its parent window when the user presses the arrow keys.

See also TBM_SETLINESIZE


TBM_GETNUMTICS

TBM_GETNUMTICS
    wParam = 0;
    lParam = 0;

Retrieves the number of tick marks in a trackbar.

  • Returns the number of tick marks.

The TBM_GETNUMTICS message counts all of the tick marks, including the first and last tick marks created by the trackbar.


TBM_GETPAGESIZE

TBM_GETPAGESIZE
    wParam = 0;
    lParam = 0;

Retrieves the number of logical positions the trackbar's slider moves in response to keyboard input, such as the PAGE UP or PAGE DOWN keys, or mouse input, such as clicks in the trackbar's channel. The logical positions are the integer increments in the trackbar's range of minimum to maximum slider positions.

  • Returns a 32-bit value that specifies the page size for the trackbar.

The trackbar also sends the TB_PAGEUP and TB_PAGEDOWN notification messages to its parent window when it receives keyboard or mouse input that scrolls the page.

See also TBM_SETPAGESIZE


TBM_GETPOS

TBM_GETPOS
    wParam = 0;
    lParam = 0;

Retrieves the current logical position of the slider in a trackbar. The logical positions are the integer values in the trackbar's range of minimum to maximum slider positions.

  • Returns a 32-bit value that specifies the current logical position of the trackbar's slider.

See also TBM_SETPOS


TBM_GETPTICS

TBM_GETPTICS
    wParam = 0;
    lParam = 0;

Retrieves the address of an array that contains the positions of the tick marks for a trackbar.

  • Returns the address of an array of DWORD values. The elements of the array specify the logical positions of the trackbar's tick marks, not including the first and last tick marks created by the trackbar. The logical positions can be any of the integer values in the trackbar's range of minimum to maximum slider positions.

The number of elements in the array is two less than the tick count returned by the TBM_GETNUMTICS message. Note that the values in the array may include duplicate positions and may not be in sequential order. The returned pointer is valid until you change the trackbar's tick marks.


TBM_GETRANGEMAX

TBM_GETRANGEMAX
    wParam = 0;
    lParam = 0;

Retrieves the maximum position for the slider in a trackbar.

  • Returns a 32-bit value that specifies the maximum position in the trackbar's range of minimum to maximum slider positions.

See also TBM_GETRANGEMIN, TBM_SETRANGE, TBM_SETRANGEMAX


TBM_GETRANGEMIN

TBM_GETRANGEMIN
    wParam = 0;
    lParam = 0;

Retrieves the minimum position for the slider in a trackbar.

  • Returns a 32-bit value that specifies the minimum position in the trackbar's range of minimum to maximum slider positions.

See also TBM_GETRANGEMAX, TBM_SETRANGE, TBM_SETRANGEMAX


TBM_GETSELEND

TBM_GETSELEND
    wParam = 0;
    lParam = 0;

Retrieves the ending position of the current selection range in a trackbar.

  • Returns a 32-bit value that specifies the ending position of the current selection range.

A trackbar can have a selection range only if you specified the TBS_ENABLESELRANGE style when you created it.

See also TBM_GETSELSTART, TBM_SETSEL, TBM_SETSELEND, TBM_SETSELSTART


TBM_GETSELSTART

TBM_GETSELSTART
    wParam = 0;
    lParam = 0;

Retrieves the starting position of the current selection range in a trackbar.

  • Returns a 32-bit value that specifies the starting position of the current selection range.

A trackbar can have a selection range only if you specified the TBS_ENABLESELRANGE style when you created it.

See also TBM_GETSELEND, TBM_SETSEL, TBM_SETSELEND, TBM_SETSELSTART


TBM_GETTHUMBLENGTH

TBM_GETTHUMBLENGTH
    wParam = 0;
    lParam = 0;

Retrieves the length of the slider in a trackbar.

  • Returns the length, in pixels, of the slider.

See also TBM_GETTHUMBRECT, TBM_SETTHUMBLENGTH


TBM_GETTHUMBRECT

TBM_GETTHUMBRECT
    wParam = 0;
    lParam = (LPARAM) (LPRECT) lprc;

Retrieves the size and position of the bounding rectangle for the slider in a trackbar.

  • No return value.
lprc
Address of a RECT structure. The message fills this structure with the bounding rectangle of the trackbar's slider, in client coordinates of the trackbar's window.


TBM_GETTIC

TBM_GETTIC
    wParam = (WPARAM) (WORD) iTic;
    lParam = 0;

Retrieves the logical position of a tick mark in a trackbar. The logical position can be any of the integer values in the trackbar's range of minimum to maximum slider positions.

  • Returns the logical position of the specified tick mark, or -1 if iTic does not specify a valid index.
iTic
Zero-based index identifying a tick mark. Valid indexes are in the range from zero to two less than the tick count returned by the TBM_GETNUMTICS message.


TBM_GETTICPOS

TBM_GETTICPOS
    wParam = (WPARAM) (WORD) iTic;
    lParam = 0;

Retrieves the current physical position of a tick mark in a trackbar.

  • Returns the distance, in client coordinates, from the left or top of the trackbar's client area to the specified tick mark. The return value is the x-coordinate of the tick mark for a horizontal trackbar or the y-coordinate for a vertical trackbar. If iTic is not a valid index, the return value is -1.
iTic
Zero-based index identifying a tick mark. Valid indexes are in the range from zero to two less than the tick count returned by the TBM_GETNUMTICS message.


TBM_GETTOOLTIPS

TBM_GETTOOLTIPS
    wParam = 0;
    lParam = 0;

Retrieves the handle to the tooltip control assigned to the trackbar, if any.

  • Returns the handle to the tooltip control assigned to the trackbar, or NULL if tooltips are not in use. If the trackbar control does not use the TBS_TOOLTIPS style, the return value is NULL.

Version 4.70


TBM_GETUNICODEFORMAT

TBM_GETUNICODEFORMAT
    wParam = 0;
    lParam = 0;

Retrieves the UNICODE character format flag for the control.

  • Returns the UNICODE format flag for the control. If this value is nonzero, the control is using UNICODE characters. If this value is zero, the control is using ANSI characters.

See also TBM_SETUNICODEFORMAT


TBM_SETBUDDY

TBM_SETBUDDY
    wParam = (WPARAM)(BOOL) fLocation;
    lParam = (LPARAM)(HWND) hwndBuddy;

Assigns a window as the buddy window for a trackbar control. Trackbar buddy windows are automatically displayed in a location relative to the control's orientation (horizontal or vertical).

  • Returns the handle to the window that was previously assigned to the control at that location.
fLocation
Value specifying the location at which to display the buddy window. This value can be one of the following:
TRUE | The buddy will appear to the left of the trackbar if the trackbar control uses the TBS_HORZ style. If the trackbar uses the TBS_VERT style, the buddy appears above the trackbar control.
FALSE | The buddy will appear to the right of the trackbar if the trackbar control uses the TBS_HORZ style. If the trackbar uses the TBS_VERT style, the buddy appears below the trackbar control.
hwndBuddy
Handle to the window that will be set as the trackbar control's buddy.

Note Trackbar controls support up to two buddy windows. This can be useful when you must display text or images at each end of the control.

Version 4.70


TBM_SETLINESIZE

TBM_SETLINESIZE
    wParam = 0;
    lParam = (LONG) lLineSize;

Sets the number of logical positions the trackbar's slider moves in response to keyboard input from the arrow keys, such as the RIGHT ARROW or DOWN ARROW keys. The logical positions are the integer increments in the trackbar's range of minimum to maximum slider positions.

  • Returns a 32-bit value that specifies the previous line size.
lLineSize
New line size.

The default setting for the line size is 1.

The trackbar also sends the TB_LINEUP and TB_LINEDOWN notification messages to its parent window when the user presses the arrow keys.

See also TBM_GETLINESIZE


TBM_SETPAGESIZE

TBM_SETPAGESIZE
    wParam = 0;
    lParam = (LONG) lPageSize;

Sets the number of logical positions the trackbar's slider moves in response to keyboard input, such as the PAGE UP or PAGE DOWN keys, or mouse input, such as clicks in the trackbar's channel. The logical positions are the integer increments in the trackbar's range of minimum to maximum slider positions.

  • Returns a 32-bit value that specifies the previous page size.
lPageSize
New page size.

The trackbar also sends the TB_PAGEUP and TB_PAGEDOWN notification messages to its parent window when it receives keyboard or mouse input that scrolls the page.

See also TBM_GETPAGESIZE


TBM_SETPOS

TBM_SETPOS
    wParam = (WPARAM) (BOOL) fPosition;
    lParam = (LPARAM) (LONG) lPosition;

Sets the current logical position of the slider in a trackbar.

  • No return value.
fPosition
Redraw flag. If this parameter is TRUE, the message redraws the control with the slider at the position given by lPosition. If this parameter is FALSE, the message does not redraw the slider at the new position. Note that the message sets the value of the slider position (as returned by the TBM_GETPOS message) regardless of the fPosition parameter.
lPosition
New logical position of the slider. Valid logical positions are the integer values in the trackbar's range of minimum to maximum slider positions. If this value is outside the control's maximum and minimum range, the position is set to the maximum or minimum value.


TBM_SETRANGE

TBM_SETRANGE
    wParam = (WPARAM) (BOOL) fRedraw;
    lParam = (LPARAM) MAKELONG(lMinimum, lMaximum);

Sets the range of minimum and maximum logical positions for the slider in a trackbar.

  • No return value.
fRedraw
Redraw flag. If this parameter is TRUE, the trackbar is redrawn after the range is set. If this parameter is FALSE, the message sets the range but does not redraw the trackbar.
lMinimum
Minimum position for the slider.
lMaximum
Maximum position for the slider.

If the current slider position is outside the new range, the TBM_SETRANGE message sets the slider position to the new maximum or minimum value.

See also TBM_SETRANGEMAX, TBM_SETRANGEMIN


TBM_SETRANGEMAX

TBM_SETRANGEMAX
    wParam = (WPARAM) fRedraw;
    lParam = (LPARAM) lMaximum;

Sets the maximum logical position for the slider in a trackbar.

  • No return value.
fRedraw
Redraw flag. If this parameter is TRUE, the trackbar is redrawn after the range is set. If this parameter is FALSE, the message sets the range but does not redraw the trackbar.
lMaximum
Maximum position for the slider.

If the current slider position is greater than the new maximum, the TBM_SETRANGEMAX message sets the slider position to the new maximum value.

See also TBM_SETRANGE, TBM_SETRANGEMIN


TBM_SETRANGEMIN

TBM_SETRANGEMIN
    wParam = (WPARAM) fRedraw;
    lParam = (LPARAM) lMinimum;

Sets the minimum logical position for the slider in a trackbar.

  • No return value.
fRedraw
Redraw flag. If this parameter is TRUE, the message redraws the trackbar after the range is set. If this parameter is FALSE, the message sets the range but does not redraw the trackbar.
lMinimum
Minimum position for the slider.

If the current slider position is less than the new minimum, the TBM_SETRANGEMIN message sets the slider position to the new minimum value.

See also TBM_SETRANGE, TBM_SETRANGEMAX


TBM_SETSEL

TBM_SETSEL
    wParam = (WPARAM) (BOOL) fRedraw;
    lParam = (LPARAM) MAKELONG(lMinimum, lMaximum);

Sets the starting and ending logical positions for the current selection range in a trackbar. This message is ignored if the trackbar does not have the TBS_ENABLESELRANGE style.

  • No return value.
fRedraw
Redraw flag. If this parameter is TRUE, the message redraws the trackbar after the selection range is set. If this parameter is FALSE, the message sets the selection range but does not redraw the trackbar.
lMinimum
Starting logical position for the selection range.
lMaximum
Ending logical position for the selection range.

See also TBM_GETSELEND, TBM_GETSELSTART, TBM_SETSELEND, TBM_SETSELSTART


TBM_SETSELEND

TBM_SETSELEND
    wParam = (WPARAM) (BOOL) fRedraw;
    lParam = (LPARAM) (LONG) lEnd;

Sets the ending logical position of the current selection range in a trackbar. This message is ignored if the trackbar does not have the TBS_ENABLESELRANGE style.

  • No return value.
fRedraw
Redraw flag. If this parameter is TRUE, the message redraws the trackbar after the selection range is set. If this parameter is FALSE, the message sets the selection range but does not redraw the trackbar.
lEnd
Ending logical position of the selection range.

See also TBM_GETSELEND, TBM_GETSELSTART, TBM_SETSEL, TBM_SETSELSTART


TBM_SETSELSTART

TBM_SETSELSTART
    wParam = (WPARAM) (BOOL) fRedraw;
    lParam = (LPARAM) (LONG) lStart;

Sets the starting logical position of the current selection range in a trackbar. This message is ignored if the trackbar does not have the TBS_ENABLESELRANGE style.

  • No return value.
fRedraw
Redraw flag. If this parameter is TRUE, the message redraws the trackbar after the selection range is set. If this parameter is FALSE, the message sets the selection range but does not redraw the trackbar.
lStart
Starting position of the selection range.

See also TBM_GETSELEND, TBM_GETSELSTART, TBM_SETSEL, TBM_SETSELEND


TBM_SETTHUMBLENGTH

TBM_SETTHUMBLENGTH
    wParam = (WPARAM) (UINT) iLength;
    lParam = 0;

Sets the length of the slider in a trackbar. This message is ignored if the trackbar does not have the TBS_FIXEDLENGTH style.

  • No return value.
iLength
Length, in pixels, of the slider.

See also TBM_GETTHUMBLENGTH


TBM_SETTIC

TBM_SETTIC
    wParam = 0;
    lParam = (LPARAM) (LONG) lPosition;

Sets a tick mark in a trackbar at the specified logical position.

  • Returns TRUE if the tick mark is set, or FALSE otherwise.
lPosition
Position of the tick mark. This parameter can be any of the integer values in the trackbar's range of minimum to maximum slider positions.

A trackbar creates its own first and last tick marks. Do not use this message to set the first and last tick marks.

See also TBM_GETPTICS, TBM_GETTIC


TBM_SETTICFREQ

TBM_SETTICFREQ
    wParam = (WPARAM) wFreq;
    lParam = (LPARAM) 0;

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.

  • No return value.
wFreq
Frequency of the tick marks.

The trackbar must have the TBS_AUTOTICKS style to use this message.


TBM_SETTIPSIDE

TBM_SETTIPSIDE
    wParam = (WPARAM)(int) fLocation;
    lParam = 0;

Positions a tooltip control used by a trackbar control. Trackbar controls that use the TBS_TOOLTIPS style display tooltips.

  • Returns a value that represents the tooltip control's previous location. The return value equals one of the possible values for fLocation.
fLocation
Value representing the location at which to display the tooltip control. This value can be one of the following:
TBTS_TOP | The tooltip control will be positioned above the trackbar. This flag is for use with horizontal trackbars.
TBTS_LEFT | The tooltip control will be positioned to the left of the trackbar. This flag is for use with vertical trackbars.
TBTS_BOTTOM | The tooltip control will be positioned below the trackbar. This flag is for use with horizontal trackbars.
TBTS_RIGHT | The tooltip control will be positioned to the right of the trackbar. This flag is for use with vertical trackbars.

Version 4.70


TBM_SETTOOLTIPS

TBM_SETTOOLTIPS
    wParam = (WPARAM)(HWND) hwndTT;
    lParam = 0;

Assigns a tooltip control to a trackbar control.

  • The return value for this message is not used.
hwndTT
Handle to an existing tooltip control.

When a trackbar control is created with the TBS_TOOLTIPS style, it creates a default tooltip control that appears next to the slider, displaying the slider's current position.

Version 4.70


TBM_SETUNICODEFORMAT

TBM_SETUNICODEFORMAT
    wParam = (WPARAM)(BOOL)fUnicode;
    lParam = 0;

Sets the UNICODE character format flag for the control. This message allows you to change the character set used by the control at run time rather than having to re-create the control.

  • Returns the previous UNICODE format flag for the control.
fUnicode
Determines the character set that is used by the control. If this value is nonzero, the control will use UNICODE characters. If this value is zero, the control will use ANSI characters.

See also TBM_GETUNICODEFORMAT


Trackbar Control Notifications

This section contains information about the notification messages used with trackbar controls.

NM_CUSTOMDRAW (trackbar)

NM_RELEASEDCAPTURE (trackbar)


NM_CUSTOMDRAW (trackbar)

NM_CUSTOMDRAW
    lpNMCustomDraw = (LPNMCUSTOMDRAW) lParam;

Sent by a trackbar control to notify its parent windows about drawing operations. This notification is sent in the form of a WM_NOTIFY message.

  • The value your application can return depends on the current drawing stage. The dwDrawStage member of the associated NMCUSTOMDRAW structure holds a value that specifies the drawing stage. You must return one of the following values.

    When dwDrawStage equals CDDS_PREPAINT:
    CDRF_DODEFAULT
    The control will draw itself. It will not send any additional NM_CUSTOMDRAW messages for this paint cycle.
    CDRF_NOTIFYITEMDRAW
    The control will notify the parent of any item-related drawing operations. It will send NM_CUSTOMDRAW notification messages before and after drawing items.
    CDRF_NOTIFYITEMERASE
    The control will notify the parent when an item will be erased. It will send NM_CUSTOMDRAW notification messages before and after erasing items.
    CDRF_NOTIFYPOSTERASE
    The control will notify the parent after erasing an item.
    CDRF_NOTIFYPOSTPAINT
    The control will notify the parent after painting an item.
    CDRF_NOTIFYSUBITEMDRAW
    Version 4.71. The control will notify the parent when a list view subitem is being drawn.

    When dwDrawStage equals CDDS_ITEMPREPAINT:
    CDRF_NEWFONT
    Your application specified a new font for the item; the control will use the new font. For more information on changing fonts, see Changing fonts and colors.
    CDRF_SKIPDEFAULT
    Your application drew the item manually. The control will not draw the item.

lpNMCustomDraw
Address of an NMCUSTOMDRAW structure that contains information about the drawing operation. The dwItemSpec member of this structure will contain one of the Custom Draw Values that indicates which part of the control is being drawn. Trackbar controls insert the following values into the dwItemSpec member of this structure to identify the portion of the control being drawn:
TBCD_CHANNEL | Identifies the channel that the trackbar control's thumb marker slides along.
TBCD_THUMB | Identifies the trackbar control's thumb marker. This is the portion of the control that the user moves.
TBCD_TICS | Identifies the increment tick marks that appear along the edge of the trackbar control.

Version 4.70

See also Using Custom Draw


NM_RELEASEDCAPTURE (trackbar)

NM_RELEASEDCAPTURE
    lpnmh = (LPNMHDR) lParam;

Notifies a trackbar control's parent window that the control is releasing mouse capture. This notification is sent in the form of a WM_NOTIFY message.

  • The control ignores the return value from this notification.
lpnmh
Address of an NMHDR structure that contains additional information about this notification message.

Version 4.71.


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 or collapse the associated list of subitems.

About Tree View Controls

Using Tree View Controls

Tree View Control Updates in Internet Explorer

Tree View Control Reference

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. The following illustration shows a tree view control that displays a table of contents.

Tree view control that displays a table of contents.

After creating a tree view control, you add, remove, arrange, or otherwise manipulate items by sending messages to the control. Each message has one or more corresponding macros that you can use instead of sending the message explicitly.

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 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 once instead of double-clicking the parent item to expand or collapse the child. 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 that it is subordinate to the parent. An item that has no parent appears at the top of the hierarchy and is called a root item.

To add an item to a tree view control, send the TVM_INSERTITEM message to the control. The message returns a handle to the HTREEITEM type, which uniquely identifies the item. When adding an item, you must specify the handle to the new item's parent item. If you specify NULL or the TVI_ROOT value instead of a parent item handle in the TVINSERTSTRUCT 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 TVITEM 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 TVITEM 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 NMTVDISPINFO 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 an NMTVDISPINFO structure. The item member is a TVITEM structure that identifies the item and includes the edited text. The parent window is responsible for updating the item's label if it wishes to keep the new label. The pszText member of TVITEM is zero if editing is canceled.

During label editing, typically in response to the TVN_BEGINLABELEDIT notification message, you can get the handle to 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 TVINSERTSTRUCT structure that specifies the handle to the parent item and the handle to 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 in 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. The state information for each item includes a set of bit flags as well as image list indexes that indicate the item's state image and overlay image. The bit flags indicate whether the item is selected, disabled, expanded, and so on. For the most part, a 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 you can retrieve the current state of an item by using the TVM_GETITEM message. For a complete list of item states, see Tree View Control Item States.

An item's current state is specified by the state member of the TVITEM 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 TVITEM 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 8 bits by using the INDEXTOOVERLAYMASK macro. The index can be zero to specify no overlay image.

To set an item's state image, stateMask of TVITEM must include the TVIS_STATEIMAGEMASK value, and state 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. 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, and returning FALSE allows the change.

An application can change the selection by sending the TVM_SELECTITEM message.

Item Information

Tree view controls support a number of messages that retrieve information about items in the control.

The TVM_GETITEM message can retrieve an item's handle and attributes. An item's attributes include its current state, the indexes in the control's image list of the item's selected and nonselected bitmapped images, a flag that indicates whether the item has child items, the address of the item's label string, and the item's 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 can be fully 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 four bitmapped images associated with it:

  • An image, such as an open folder, displayed when the item is selected.
  • An image, such as a closed folder, displayed when the item is not selected.
  • An overlay image that is drawn transparently over the selected or nonselected image.
  • A state image, which is an additional image displayed to the left of the selected or nonselected image. You can use state images, such as checked and cleared check boxes, to indicate application-defined item states.

By default, a tree view control does not display item images. To display item images, you must create image lists and associate them with the control. For more information about image lists, see Image Lists.

A tree view control can have two image lists: a normal image list and a state image list. A normal image list stores the selected, nonselected, and overlay images. A state image list stores state images. Use the ImageList_Create function to create an image list, and use other image list functions to add bitmaps to the image list. Then, to associate the image list with the tree view control, use the TVM_SETIMAGELIST message. The TVM_GETIMAGELIST message retrieves a handle to one of a tree view control's image lists. This message is useful if you need to add more images to the list.

In addition to the selected and nonselected images, a tree view control's normal image list can contain up to four overlay images. Overlay images are identified by a one-based index and are designed to be drawn transparently over the selected and nonselected images. To assign an overlay mask index to an image in the normal image list, call the ImageList_SetOverlayImage function.

By default, all items display the first image in the normal image list for both the selected and nonselected states. Also, by default, items do not display overlay images or state images. You can change these default behaviors for an item by sending the TVM_INSERTITEM or TVM_SETITEM messages. These messages use the TVITEM structure to specify image list indexes for an item.

To specify an item's selected and nonselected images, set the TVIF_SELECTEDIMAGE and TVIF_IMAGE bits in the mask member of the TVITEM structure and specify indexes from the control's normal image list in the iSelectImage and iImage members. Alternatively, you can specify the I_IMAGECALLBACK value in iSelectImage and iImage instead of specifying indexes. This causes the control to query its parent window for an image list index each time the item is about to be redrawn. The control sends the TVN_GETDISPINFO notification message to get the index.

To associate an overlay image with an item, use the INDEXTOOVERLAYMASK macro to specify an overlay mask index in the state member of the item's TVITEM structure. You must also set the TVIS_OVERLAYMASK bits in the stateMask member. Overlay mask indexes are one-based; an index of zero indicates that no overlay image was specified.

To associate a state image with an item, use the INDEXTOSTATEIMAGEMASK macro to specify a state image index in the state member of the item's TVITEM structure. The index identifies an image in the control's state image list. Although image list indexes are zero-based, the control uses one-based indexes to identify state images. This means that the first image in a control's state image list is at state image index one. A state image index of zero indicates that an item has no state image. For more information about a tree view item's state member, see Tree View Item States Overview.

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 to 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, see Dragging a Tree View Item.

If items in a tree view control are to be the targets of drag-and-drop operations, 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 TVHITTESTINFO 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 to 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 that the right mouse button has started a drag-and-drop operation.
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 Control Message Processing

This section describes the window message processing performed by a tree view control. Messages specific to tree view controls are discussed in other sections of this document, so 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 to the current label font.
WM_HSCROLL | Scrolls the tree view control. It returns TRUE if scrolling occurs, or FALSE otherwise.
WM_KEYDOWN | Sends the TVN_KEYDOWN notification message to the parent window for all keys. 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 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 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. If the wParam parameter is non-NULL, the control assumes that the value is an HDC and paints using that device context.
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

This section contains examples that demonstrate the following tasks:

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

Note: When you create a treeview control, you may also send it a WM_SETFONT message to set the font to be used for the text in the treeview. By default, a treeview uses the icon title font. Although you can customize the font on a per-item basis (by using custom draw), the treeview control uses the dimensions of the font specified by the WM_SETFONT message to determine spacing and layout.

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 to the new control if successful,
//  or NULL otherwise.
// hwndParent - handle to 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 to 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, first use the image list functions to create an image list and add images to it. Then 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 to 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 to image list
    HBITMAP hbmp;     // handle to 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 the address of a TVINSERTSTRUCT structure, specifying the parent item, the item after which the new item is inserted, and a TVITEM 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 demonstrates how to create 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.

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 to the tree view control.
// lpszFileName - name of file with headings.

BOOL InitTreeViewItems(HWND hwndTV, LPSTR lpszFileName)
{
    HANDLE hf;            // handle to file
    char szItemText[128]; // label text of tree view item
    int nLevel;           // heading level

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

    // Call private function to parse the file looking for headings.
    while ( GetNextHeadingAndLevelFromFile(hf, szItemText, &nLevel) )
         // Add the item to the tree view control.
         AddItemToTree(hwndTV, szItemText, nLevel);

    return TRUE;
}

// AddItemToTree - adds items to a tree view control.
// Returns the handle to the newly added item.
// hwndTV - handle to 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)
{
    TVITEM tvi;
    TVINSERTSTRUCT 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) (LPTVINSERTSTRUCT) &tvins);

    // Save the handle to 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.

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 NMTREEVIEW structure. The members of this structure include the screen coordinates of the mouse cursor and a TVITEM 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(   // application-defined function
                         hwndTV, (LPNMTREEVIEW) lParam);
             break;

        // Handle other notifications here.

       }
     break;

Beginning the drag operation involves using the ImageList_BeginDrag function. The function's parameters include the handle to 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 to the image list.
// lpnmtv - address of information about the item being dragged.

void Main_OnBeginDrag(HWND hwndTV, LPNMTREEVIEW lpnmtv)
{
    HIMAGELIST himl;    // handle to 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, 0, 0, 0);

    // 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 demonstrates how to perform 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 to the parent window.
// hwndTV - handle to 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 to target item
    TVHITTESTINFO 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 following example shows how to end 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;
}

Working with state image indexes

There is often confusion about how to set and retrieve the state image index in a tree view control. The following examples demonstrate the proper method for setting and retrieving the state image index. The examples assume that there are only two state image indexes in the tree view control, unchecked and checked. If your application contains more than two, these functions will need to be modified to handle that case.

The following example function illustrates how to set an item's check state.

BOOL TreeView_SetCheckState(HWND hwndTreeView, HTREEITEM hItem, BOOL fCheck)
{
    TVITEM tvItem;

    tvItem.mask = TVIF_HANDLE | TVIF_STATE;
    tvItem.hItem = hItem;
    tvItem.stateMask = TVIS_STATEIMAGEMASK;

    /*
    Since state images are one-based, 1 in this macro turns the check off, and
    2 turns it on.
    */
    tvItem.state = INDEXTOSTATEIMAGEMASK((fCheck ? 2 : 1));

    return TreeView_SetItem(hwndTreeView, &tvItem);
}

The following example function illustrates how to retrieve an item's check state.

BOOL TreeView_GetCheckState(HWND hwndTreeView, HTREEITEM hItem)
{
    TVITEM tvItem;

    // Prepare to receive the desired information.
    tvItem.mask = TVIF_HANDLE | TVIF_STATE;
    tvItem.hItem = hItem;
    tvItem.stateMask = TVIS_STATEIMAGEMASK;

    // Request the information.
    TreeView_GetItem(hwndTreeView, &tvItem);

    // Return zero if it's not checked, or nonzero otherwise.
    return ((BOOL)(tvItem.state >> 12) -1);
}

Tree View Control Updates in Internet Explorer

Tree view controls in Microsoft® Internet Explorer support the following new features.

Tooltips
Tree view controls now automatically display tooltips when an item is not entirely within the view area.
New Item State
Tree view controls now support a new item state for parent items, TVIS_EXPANDPARTIAL. When a parent item is set to this state, the child items are displayed and the parent's plus sign remains visible. The TVM_EXPAND message and the TreeView_Expand macro have been updated to support this feature.
Single-Click Expansion
The TVS_SINGLEEXPAND style causes a tree view item to be expanded when it becomes selected and to be closed when it becomes unselected.
Adjustable Maximum Scroll Time
The TVM_SETSCROLLTIME message allows you to set the maximum amount of time that a scroll operation can take. The TVM_GETSCROLLTIME message allows you to retrieve the maximum scroll time.


Tree View Control Reference

This section contains information about the following new or updated API elements used with tree view controls.

Tree View Control Window Styles

Tree View Control Item States

Messages
TVM_CREATEDRAGIMAGE
TVM_DELETEITEM
TVM_EDITLABEL
TVM_ENDEDITLABELNOW
TVM_ENSUREVISIBLE
TVM_EXPAND
TVM_GETBKCOLOR
TVM_GETCOUNT
TVM_GETEDITCONTROL
TVM_GETIMAGELIST
TVM_GETINDENT
TVM_GETINSERTMARKCOLOR
TVM_GETISEARCHSTRING
TVM_GETITEM
TVM_GETITEMHEIGHT
TVM_GETITEMRECT
TVM_GETNEXTITEM
TVM_GETSCROLLTIME
TVM_GETTEXTCOLOR
TVM_GETTOOLTIPS
TVM_GETUNICODEFORMAT
TVM_GETVISIBLECOUNT
TVM_HITTEST
TVM_INSERTITEM
TVM_SELECTITEM
TVM_SETBKCOLOR
TVM_SETIMAGELIST
TVM_SETINDENT
TVM_SETINSERTMARK
TVM_SETINSERTMARKCOLOR
TVM_SETITEM
TVM_SETITEMHEIGHT
TVM_SETSCROLLTIME
TVM_SETTEXTCOLOR
TVM_SETTOOLTIPS
TVM_SETUNICODEFORMAT
TVM_SORTCHILDREN
TVM_SORTCHILDRENCB

Utility Macros
TreeView_CreateDragImage
TreeView_DeleteAllItems
TreeView_DeleteItem
TreeView_EditLabel
TreeView_EndEditLabelNow
TreeView_EnsureVisible
TreeView_Expand
TreeView_GetBkColor
TreeView_GetChild
TreeView_GetCount
TreeView_GetDropHilight
TreeView_GetEditControl
TreeView_GetFirstVisible
TreeView_GetImageList
TreeView_GetIndent
TreeView_GetInsertMarkColor
TreeView_GetISearchString
TreeView_GetItem
TreeView_GetItemHeight
TreeView_GetItemRect
TreeView_GetLastVisible
TreeView_GetNextItem
TreeView_GetNextSibling
TreeView_GetNextVisible
TreeView_GetParent
TreeView_GetPrevSibling
TreeView_GetPrevVisible
TreeView_GetRoot
TreeView_GetScrollTime
TreeView_GetSelection
TreeView_GetTextColor
TreeView_GetToolTips
TreeView_GetUnicodeFormat
TreeView_GetVisibleCount
TreeView_HitTest
TreeView_InsertItem
TreeView_Select
TreeView_SelectDropTarget
TreeView_SelectItem
TreeView_SelectSetFirstVisible
TreeView_SetBkColor
TreeView_SetImageList
TreeView_SetIndent
TreeView_SetInsertMark
TreeView_SetInsertMarkColor
TreeView_SetItem
TreeView_SetItemHeight
TreeView_SetScrollTime
TreeView_SetTextColor
TreeView_SetToolTips
TreeView_SetUnicodeFormat
TreeView_SortChildren
TreeView_SortChildrenCB

Notifications
NM_CLICK (tree view)
NM_CUSTOMDRAW (tree view)
NM_DBLCLK (tree view)
NM_KILLFOCUS (tree view)
NM_RCLICK (tree view)
NM_RETURN (tree view)
NM_SETCURSOR (tree view)
NM_SETFOCUS (tree view)
TVN_BEGINDRAG
TVN_BEGINLABELEDIT
TVN_BEGINRDRAG
TVN_DELETEITEM
TVN_ENDLABELEDIT
TVN_GETDISPINFO
TVN_GETINFOTIP
TVN_ITEMEXPANDED
TVN_ITEMEXPANDING
TVN_KEYDOWN
TVN_SELCHANGED
TVN_SELCHANGING
TVN_SETDISPINFO
TVN_SINGLEEXPAND

Structures
NM_TREEVIEW
NMTREEVIEW
NMTVCUSTOMDRAW
NMTVDISPINFO
NMTVGETINFOTIP
NMTVKEYDOWN
TV_DISPINFO
TV_HITTESTINFO
TV_INSERTSTRUCT
TV_ITEM
TV_KEYDOWN
TV_SORTCB
TVHITTESTINFO
TVINSERTSTRUCT
TVITEM
TVITEMEX
TVSORTCB


Tree View Control Window Styles

The following window styles are used when creating tree view controls.
TVS_CHECKBOXES | Version 4.70. Enables check boxes for items in a tree view control. Effectively, when set to this style, the control creates and sets a state image list using DrawFrameControl. For more information, see Working with state image indexes. Once the control is created with this style, it cannot be removed. If it is necessary to remove this style, the control must be destroyed and a new one created in its place.
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_FULLROWSELECT | Version 4.71. Enables full-row selection in the tree view. The entire row of the selected item is highlighted, and clicking anywhere on an item's row will cause it to be selected. This style cannot be used in conjunction with the TVS_HASLINES style.
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_INFOTIP | Version 4.71. The tree view control will send the TVN_GETINFOTIP notification to obtain tooltip information.
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_NONEVENHEIGHT | Version 4.71. The height of the items can be set to an odd height with the TVM_SETITEMHEIGHT message. By default, the height of items must be an even value.
TVS_NOSCROLL | Version 4.71. Disables both horizontal and vertical scrolling in the control. The control will not display any scroll bars.
TVS_NOTOOLTIPS | Version 4.70. The tree view control does not support tooltips.
TVS_RTLREADING | Version 4.70. Displays text using right-to-left reading order on Hebrew or Arabic systems.
TVS_SHOWSELALWAYS | Causes a selected item to remain selected when the tree view control loses focus.
TVS_SINGLEEXPAND | Version 4.71. When this style is enabled, changing the selection in the tree view will automatically cause the item being selected to expand and the item being unselected to collapse. If the mouse is used to single-click the selected item and that item is closed, it will be expanded. If the selected item is single-clicked when it is open, it will be collapsed.
TVS_TRACKSELECT | Version 4.70. Enables hot tracking in a tree view control.


Tree View Control Item States

The following item state flags are used to indicate the state of an item in a tree view control.
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 generated for parent items that have this state set in response to a TVM_EXPAND message. Using TVE_COLLAPSE and TVE_COLLAPSERESET with TVM_EXPAND will cause this state to be reset. This value applies only to parent items.
TVIS_EXPANDPARTIAL | Version 4.70. A partially expanded tree view item. In this state, some, but not all, of the child items are visible and the parent item's plus symbol is displayed.
TVIS_SELECTED | The item is selected. Its appearance depends on whether it has the focus. The item will be drawn using the system colors for selection.

When you set or retrieve an item's overlay image index or state image index, you must specify the following masks in the stateMask member of the TVITEM structure. These values can also be used to mask off the state bits that are not of interest.
TVIS_OVERLAYMASK | Mask for the bits used to specify the item's overlay image index.
TVIS_STATEIMAGEMASK | Mask for the bits used to specify the item's state image index.
TVIS_USERMASK | Same as TVIS_STATEIMAGEMASK.


Tree View Control Messages

This section contains information about the messages used with tree view controls.

TVM_CREATEDRAGIMAGE

TVM_DELETEITEM

TVM_EDITLABEL

TVM_ENDEDITLABELNOW

TVM_ENSUREVISIBLE

TVM_EXPAND

TVM_GETBKCOLOR

TVM_GETCOUNT

TVM_GETEDITCONTROL

TVM_GETIMAGELIST

TVM_GETINDENT

TVM_GETINSERTMARKCOLOR

TVM_GETISEARCHSTRING

TVM_GETITEM

TVM_GETITEMHEIGHT

TVM_GETITEMRECT

TVM_GETNEXTITEM

TVM_GETSCROLLTIME

TVM_GETTEXTCOLOR

TVM_GETTOOLTIPS

TVM_GETUNICODEFORMAT

TVM_GETVISIBLECOUNT

TVM_HITTEST

TVM_INSERTITEM

TVM_SELECTITEM

TVM_SETBKCOLOR

TVM_SETIMAGELIST

TVM_SETINDENT

TVM_SETINSERTMARK

TVM_SETINSERTMARKCOLOR

TVM_SETITEM

TVM_SETITEMHEIGHT

TVM_SETSCROLLTIME

TVM_SETTEXTCOLOR

TVM_SETTOOLTIPS

TVM_SETUNICODEFORMAT

TVM_SORTCHILDREN

TVM_SORTCHILDRENCB


TVM_CREATEDRAGIMAGE

TVM_CREATEDRAGIMAGE
    wParam = 0;
    lParam = (LPARAM) (HTREEITEM) hitem;

Creates a dragging bitmap for the specified item in a tree view control. The message also 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.

  • Returns the handle to the image list to which the dragging bitmap was added if successful, or NULL otherwise.
hitem
Handle to the item that receives the new dragging bitmap.

If you create a tree view control without an associated image list, you cannot use the TVM_CREATEDRAGIMAGE message to create the image to display during a drag operation. You must implement your own method of creating a drag cursor.


TVM_DELETEITEM

TVM_DELETEITEM
    wParam = 0;
    lParam = (LPARAM) (HTREEITEM) hitem;

Removes an item from a tree view control. You can send this message explicitly or by using the TreeView_DeleteItem or TreeView_DeleteAllItems macro.

  • Returns TRUE if successful, or FALSE otherwise.
hitem
Handle to the item to delete. If hitem is the TVI_ROOT value, all items are deleted from the tree view control.

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.


TVM_EDITLABEL

TVM_EDITLABEL
    wParam = 0;
    lParam = (LPARAM) (HTREEITEM) hitem;

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.

  • Returns the handle to the edit control used to edit the item text if successful, or NULL otherwise.
hitem
Handle to the item to edit.

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.


TVM_ENDEDITLABELNOW

TVM_ENDEDITLABELNOW
    wParam = (WPARAM) (BOOL) fCancel;
    lParam = 0;

Ends the editing of a tree view item's label. You can send this message explicitly or by using the TreeView_EndEditLabelNow macro.

  • Returns TRUE if successful, or FALSE otherwise.
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.

This message causes the TVN_ENDLABELEDIT notification message to be sent to the parent window of the tree view control.


TVM_ENSUREVISIBLE

TVM_ENSUREVISIBLE
    wParam = 0;
    lParam = (LPARAM) (HTREEITEM) hitem;

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.

  • Returns nonzero if the system scrolled the items in the tree view control and no items were expanded. Otherwise, the message returns zero.
hitem
Handle to the item.

If the TVM_ENSUREVISIBLE message expands the parent item, the parent window receives the TVN_ITEMEXPANDING and TVN_ITEMEXPANDED notification messages.


TVM_EXPAND

TVM_EXPAND
    wParam = (WPARAM) (UINT) flag;
    lParam = (LPARAM) (HTREEITEM) hItem;

Expands or collapses the list of child items associated with the specified parent item, if any. You can send this message explicitly or by using the TreeView_Expand macro.

  • Returns nonzero if a change took place, or zero otherwise.
flag
Action flag. This parameter can be one or more of the following values:
TVE_COLLAPSE | Collapses the list.
TVE_COLLAPSERESET | Collapses the list and removes the child items. This flag must be used with the TVE_COLLAPSE flag.
TVE_EXPAND | Expands the list.
TVE_EXPANDPARTIAL | Version 4.70. Partially expands the list. In this state, the child items are visible and the parent item's plus symbol is displayed. This flag must be used in combination with the TVE_EXPAND flag.
TVE_TOGGLE | Collapses the list if it is expanded or expands it if it is collapsed.
hItem
Handle to the parent item to expand or collapse.

The TVM_EXPAND message will cause the TVN_ITEMEXPANDING and TVN_ITEMEXPANDED notification messages to be generated if the item being expanded does not have the TVIS_EXPANDEDONCE state bit set. This state gets set when a parent item is expanded for the first time. Using TVE_COLLAPSE and TVE_COLLAPSERESET with TVM_EXPAND will cause the TVIS_EXPANDEDONCE state to be reset.

If the item already has the TVIS_EXPANDEDONCE state set, the TVM_EXPAND message will not cause the TVN_ITEMEXPANDING and TVN_ITEMEXPANDED notification messages to be generated.


TVM_GETBKCOLOR

TVM_GETBKCOLOR
    wParam = 0;
    lParam = 0;

Retrieves the current background color of the control. You can send this message explicitly or by using the TreeView_GetBkColor macro.

  • Returns a COLORREF value that represents the current background color. If this value is -1, the control is using the system color for the background color.

Version 4.71

See also TVM_SETBKCOLOR


TVM_GETCOUNT

TVM_GETCOUNT
    wParam = 0;
    lParam = 0;

Retrieves a count of the items in a tree view control. You can send this message explicitly or by using the TreeView_GetCount macro.

  • Returns the count of items.


TVM_GETEDITCONTROL

TVM_GETEDITCONTROL
    wParam = 0;
    lParam = 0;

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.

  • Returns the handle to the edit control if successful, or NULL otherwise.


TVM_GETIMAGELIST

TVM_GETIMAGELIST
    wParam = (WPARAM) iImage;
    lParam = 0;

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.

  • Returns an HIMAGELIST handle to the specified image list.
iImage
Type of image list to retrieve. This parameter can be one of the following values:
TVSIL_NORMAL | Indicates the normal image list, which contains selected, nonselected, and overlay images for the items of a tree view control.
TVSIL_STATE | Indicates the state image list. You can use state images to indicate application-defined item states. A state image is displayed to the left of an item's selected or nonselected image.

See also TVM_SETIMAGELIST


TVM_GETINDENT

TVM_GETINDENT
    wParam = 0;
    lParam = 0;

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.

  • Returns the amount of indentation.


TVM_GETINSERTMARKCOLOR

TVM_GETINSERTMARKCOLOR
    wParam = 0;
    lParam = 0;

Retrieves the color used to draw the insertion mark for the tree view. You can send this message explicitly or by using the TreeView_GetInsertMarkColor macro.

  • Returns a COLORREF value that contains the current insertion mark color.

Version 4.71

See also TVM_SETINSERTMARKCOLOR


TVM_GETISEARCHSTRING

TVM_GETISEARCHSTRING
    wParam = 0;
    lParam = (LPARAM) (LPSTR) lpsz;

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. You can send this message explicitly or by using the TreeView_GetISearchString macro.

  • Returns the number of characters in the incremental search string.
lpsz
Address of the buffer that receives the incremental search string.

If the tree view control is not in incremental search mode, the return value is zero.


TVM_GETITEM

TVM_GETITEM
    wParam = 0;
    lParam = (LPARAM) (LPTVITEM) pitem;

Retrieves some or all of a tree view item's attributes. You can send this message explicitly or by using the TreeView_GetItem macro.

  • Returns TRUE if successful, or FALSE otherwise.
pitem
Address of a TVITEM 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 the mask member specifies the TVIF_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.
If the mask member specifies the TVIF_STATE value, the stateMask member must specify the item state bits to retrieve. On output, the state member contains the values of the specified state bits.


TVM_GETITEMHEIGHT

TVM_GETITEMHEIGHT
    wParam = 0;
    lParam = 0;

Retrieves the current height of the each tree view item. You can send this message explicitly or by using the TreeView_GetItemHeight macro.

  • Returns the height of each item, in pixels.

Version 4.71

See also TVM_SETITEMHEIGHT


TVM_GETITEMRECT

TVM_GETITEMRECT
    wParam = (WPARAM) (BOOL) fItemRect;
    lParam = (LPARAM) (LPRECT) prc;

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.

  • If the item is visible and the bounding rectangle was successfully retrieved, the return value is TRUE. Otherwise, the message returns FALSE and does not retrieve the bounding rectangle.
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.
prc
Address of a RECT structure that, when sending the message, contains the handle of the item to retrieve the rectangle for. See the example below for more information on how to place the item handle in this parameter. After returning from the message, this parameter contains the bounding rectangle. The coordinates are relative to the upper-left corner of the tree view control.

When sending this message, the prc parameter contains the handle of the item that the rectangle is being retrieved for. The handle is placed in prc as shown in the following example:

RECT rc;
*(HTREEITEM*)&rc = hTreeItem;
SendMessage(hwndTreeView, TVM_GETITEMRECT, FALSE, (LPARAM)&rc);


TVM_GETNEXTITEM

TVM_GETNEXTITEM
    wParam = (WPARAM) (UINT) flag;
    lParam = (LPARAM) (HTREEITEM) hitem;

Retrieves the tree view item that bears the specified relationship to a specified item. You can send this message explicitly, by using the TreeView_GetNextItem macro, or by using one of these related macros:

TreeView_GetChild
TreeView_GetDropHilight
TreeView_GetFirstVisible
TreeView_GetLastVisible
TreeView_GetNextSibling
TreeView_GetNextVisible
TreeView_GetParent
TreeView_GetPrevSibling
TreeView_GetPrevVisible
TreeView_GetRoot
TreeView_GetSelection

  • Returns the handle to the item if successful, or NULL otherwise.
flag
Flag specifying the item to retrieve. This parameter can be one of the following values:
TVGN_CARET | Retrieves the currently selected item. You can use the TreeView_GetSelection macro to send this message.
TVGN_CHILD | Retrieves the first child item of the item specified by the hitem parameter. You can use the TreeView_GetChild macro to send this message.
TVGN_DROPHILITE | Retrieves the item that is the target of a drag-and-drop operation. You can use the TreeView_GetDropHilight macro to send this message.
TVGN_FIRSTVISIBLE | Retrieves the first item that is visible in the tree view window. You can use the TreeView_GetFirstVisible macro to send this message.
TVGN_LASTVISIBLE | Version 4.71. Retrieves the last expanded item in the tree. This does not retrieve the last item visible in the tree view window. You can use the TreeView_GetLastVisible macro to send this message.
TVGN_NEXT | Retrieves the next sibling item. You can use the TreeView_GetNextSibling macro to send this message.
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. You can use the TreeView_GetNextVisible macro to send this message.
TVGN_PARENT | Retrieves the parent of the specified item. You can use the TreeView_GetParent macro to send this message.
TVGN_PREVIOUS | Retrieves the previous sibling item. You can use the TreeView_GetPrevSibling macro to send this message.
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. You can use the TreeView_GetPrevVisible macro to send this message.
TVGN_ROOT | Retrieves the topmost or very first item of the tree view control. You can use the TreeView_GetRoot macro to send this message.
hitem
Handle to an item.


TVM_GETSCROLLTIME

TVM_GETSCROLLTIME
    wParam = 0;
    lParam = 0;

Retrieves the maximum scroll time for the tree view control. You can send this message explicitly or by using the TreeView_GetScrollTime macro.

  • Returns the maximum scroll time, in milliseconds.

The maximum scroll time is the longest amount of time that a scroll operation can take. The scrolling will be adjusted so that the scroll will take place within the maximum scroll time. A scroll operation may take less time than the maximum.

See also TVM_SETSCROLLTIME


TVM_GETTEXTCOLOR

TVM_GETTEXTCOLOR
    wParam = 0;
    lParam = 0;

Retrieves the current text color of the control. You can send this message explicitly or by using the TreeView_GetTextColor macro.

  • Returns a COLORREF value that represents the current text color. If this value is -1, the control is using the system color for the text color.

Version 4.71

See also TVM_SETTEXTCOLOR


TVM_GETTOOLTIPS

TVM_GETTOOLTIPS
    wParam = 0;
    lParam = 0;

Retrieves the handle to the child tooltip control used by a tree view control. You can send this message explicitly or by using the TreeView_GetToolTips macro.

  • Returns the handle to the child tooltip control, or NULL if the control is not using tooltips.

When created, tree view controls automatically create a child tooltip control. To cause a tree view control not to use tooltips, create the control with the TVS_NOTOOLTIPS style.

Version 4.70

See also TVM_SETTOOLTIPS


TVM_GETUNICODEFORMAT

TVM_GETUNICODEFORMAT
    wParam = 0;
    lParam = 0;

Retrieves the UNICODE character format flag for the control. You can send this message explicitly or use the TreeView_GetUnicodeFormat macro.

  • Returns the UNICODE format flag for the control. If this value is nonzero, the control is using UNICODE characters. If this value is zero, the control is using ANSI characters.

See also TVM_SETUNICODEFORMAT


TVM_GETVISIBLECOUNT

TVM_GETVISIBLECOUNT
    wParam = 0;
    lParam = 0;

Obtains the number of items that can be fully visible in the client window of a tree view control. You can send this message explicitly or by using the TreeView_GetVisibleCount macro.

  • Returns the number of items that can be fully visible in the client window of the tree view control.

The number of items that can be fully visible may be greater than the number of items in the control. The control calculates this value by dividing the height of the client window by the height of an item.

Note that the return value is the number of items that can be fully visible. If you can see all of 20 items and part of one more item, the return value is 20.


TVM_HITTEST

TVM_HITTEST
    wParam = 0;
    lParam = (LPARAM) (LPTVHITTESTINFO) lpht;

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.

  • Returns the handle to the tree view item that occupies the specified point, or NULL if no item occupies the point.
lpht
Address of a TVHITTESTINFO 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 TVHITTESTINFO structure.


TVM_INSERTITEM

TVM_INSERTITEM
    wParam = 0;
    lParam = (LPARAM) (LPTVINSERTSTRUCT) lpis;

Inserts a new item in a tree view control. You can send this message explicitly or by using the TreeView_InsertItem macro.

  • Returns the handle to the new item if successful, or NULL otherwise.
lpis
Address of a TVINSERTSTRUCT structure that specifies the attributes of the tree view item.

See also TVN_ENDLABELEDIT


TVM_SELECTITEM

TVM_SELECTITEM
    wParam = (WPARAM) flag;
    lParam = (LPARAM) (HTREEITEM) hitem;

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.

  • Returns TRUE if successful, or FALSE otherwise.
flag
Action flag. This parameter can be one of the following values:
TVGN_CARET | Sets the selection to the specified item. The tree view control's parent window receives the TVN_SELCHANGING and TVN_SELCHANGED notification messages.
TVGN_DROPHILITE | Redraws the specified item in the style used to indicate the target of a drag-and-drop operation.
TVGN_FIRSTVISIBLE | Ensures that the specified item is visible, and, if possible, displays it at the top of the control's window. Tree view controls display as many items as will fit in the window. If the specified item is near the bottom of the control's hierarchy of items, it might not become the first visible item, depending on how many items fit in the window.
hitem
Handle to an item. If hitem is NULL, the control is set to have no selected item.

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 control's 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.


TVM_SETBKCOLOR

TVM_SETBKCOLOR
    wParam = 0;
    lParam = (LPARAM)(COLORREF) clrBk;

Sets the background color of the control. You can send this message explicitly or by using the TreeView_SetBkColor macro.

  • Returns a COLORREF value that represents the previous background color. If this value is -1, the control was using the system color for the background color.
clrBk
COLORREF value that contains the new background color. If this value is -1, the control will revert to using the system color for the background color.

Version 4.71

See also TVM_GETBKCOLOR


TVM_SETIMAGELIST

TVM_SETIMAGELIST
    wParam = (WPARAM) iImage;
    lParam = (LPARAM) (HIMAGELIST) himl;

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.

  • Returns the handle to the previous image list, if any, or NULL otherwise.
iImage
Type of image list to set. This parameter can be one of the following values:
TVSIL_NORMAL | Indicates the normal image list, which contains selected, nonselected, and overlay images for the items of a tree view control.
TVSIL_STATE | Indicates the state image list. You can use state images to indicate application-defined item states. A state image is displayed to the left of an item's selected or nonselected image.
himl
Handle to the image list. If himl is NULL, the message removes the specified image list from the tree view control.

See also TVM_GETIMAGELIST


TVM_SETINDENT

TVM_SETINDENT
    wParam = (WPARAM) indent;
    lParam = 0;

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.

  • The return value is not used.
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.


TVM_SETINSERTMARK

TVM_SETINSERTMARK
    wParam = (WPARAM)(BOOL) fAfter;
    lParam = (LPARAM)(HTREEITEM) htiInsert;

Sets the insertion mark in a tree view control. You can send this message explicitly or by using the TreeView_SetInsertMark macro.

  • Returns nonzero if successful, or zero otherwise.
fAfter
BOOL value that specifies if the insertion mark is placed before or after the specified item. If this argument is nonzero, the insertion mark will be placed after the item. If this argument is zero, the insertion mark will be placed before the item.
htiInsert
HTREEITEM that specifies at which item the insertion mark will be placed. If this argument is NULL, the insertion mark is removed.

Version 4.71


TVM_SETINSERTMARKCOLOR

TVM_SETINSERTMARKCOLOR
    wParam = 0;
    lParam = (LPARAM)(COLORREF)clrInsertMark;

Sets the color used to draw the insertion mark for the tree view. You can send this message explicitly or by using the TreeView_SetInsertMarkColor macro.

  • Returns a COLORREF value that contains the previous insertion mark color.
clrInsertMark
COLORREF value that contains the new insertion mark color.

Version 4.71

See also TVM_GETINSERTMARKCOLOR


TVM_SETITEM

TVM_SETITEM
    wParam = 0;
    lParam = (LPARAM) (const LPTVITEM) pitem;

Sets some or all of a tree view item's attributes. You can send this message explicitly or by using the TreeView_SetItem macro.

  • Returns TRUE if successful, or FALSE otherwise.
pitem
Address of a TVITEM 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 address of 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.


TVM_SETITEMHEIGHT

TVM_SETITEMHEIGHT
    wParam = (WPARAM)(SHORT) cyItem;
    lParam = 0;

Sets the height of the tree view items. You can send this message explicitly or by using the TreeView_SetItemHeight macro.

  • Returns the previous height of the items, in pixels.
cyItem
New height of every item in the tree view, in pixels. If this argument is less than the height of the images, it will be set to the height of the images. If this argument is not even and the tree view control does not have the TVS_NONEVENHEIGHT style, this value will be rounded down to the nearest even value. If this argument is -1, the control will revert to using its default item height.

The tree view control uses this value for the height of all items. To modify the height of individual items, see the description of the iIntegral member of the TVITEMEX structure.

Version 4.71

See also TVM_GETITEMHEIGHT


TVM_SETSCROLLTIME

TVM_SETSCROLLTIME
    wParam = (WPARAM)(UINT)uScrollTime;
    lParam = 0;

Sets the maximum scroll time for the tree view control. You can send this message explicitly or by using the TreeView_SetScrollTime macro.

  • Returns the previous maximum scroll time, in milliseconds.
uScrollTime
New maximum scroll time, in milliseconds. If this value is less than 100, it will be rounded up to 100.

The maximum scroll time is the longest amount of time that a scroll operation can take. Scrolling will be adjusted so that the scroll will take place within the maximum scroll time. A scroll operation may take less time than the maximum.

See also TVM_GETSCROLLTIME


TVM_SETTEXTCOLOR

TVM_SETTEXTCOLOR
    wParam = 0;
    lParam = (LPARAM)(COLORREF) clrText;

Sets the text color of the control. You can send this message explicitly or by using the TreeView_SetTextColor macro.

  • Returns a COLORREF value that represents the previous text color. If this value is -1, the control was using the system color for the text color.
clrText
COLORREF value that contains the new text color. If this argument is -1, the control will revert to using the system color for the text color.

Version 4.71

See also TVM_GETTEXTCOLOR


TVM_SETTOOLTIPS

TVM_SETTOOLTIPS
    wParam = (WPARAM)(HWND) hwndTooltip;
    lParam = 0;

Sets a tree view control's child tooltip control. You can send this message explicitly or by using the TreeView_SetToolTips macro.

  • Returns the handle to tooltip control previously set for the tree view control, or NULL if tooltips were not previously used.
hwndTooltip
Handle to a tooltip control.

When created, tree view controls automatically create a child tooltip control. To prevent a tree view control from using tooltips, create the control with the TVS_NOTOOLTIPS style.

Version 4.70

See also TVM_GETTOOLTIPS


TVM_SETUNICODEFORMAT

TVM_SETUNICODEFORMAT
    wParam = (WPARAM)(BOOL)fUnicode;
    lParam = 0;

Sets the UNICODE character format flag for the control. This message allows you to change the character set used by the control at run time rather than having to re-create the control. You can send this message explicitly or use the TreeView_SetUnicodeFormat macro.

  • Returns the previous UNICODE format flag for the control.
fUnicode
Determines the character set that is used by the control. If this value is nonzero, the control will use UNICODE characters. If this value is zero, the control will use ANSI characters.

See also TVM_GETUNICODEFORMAT


TVM_SORTCHILDREN

TVM_SORTCHILDREN
    wParam = (WPARAM)(BOOL) fRecurse;
    lParam = (LPARAM)(HTREEITEM) hitem;

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.

  • Returns TRUE if successful, or FALSE otherwise.
fRecurse
Reserved for future use. Must be zero.
hitem
Handle to the parent item whose child items are to be sorted.


TVM_SORTCHILDRENCB

TVM_SORTCHILDRENCB
    wParam = (WPARAM)(BOOL) fRecurse;
    lParam = (LPARAM) (LPTVSORTCB) psort;

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.

  • Returns TRUE if successful, or FALSE otherwise.
fRecurse
Reserved for future use. Must be zero.
psort
Address of a TVSORTCB structure. The lpfnCompare member is the address of 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 TVSORTCB.


Tree View Control Macros

This section contains information about the macros that are used with tree view controls.

TreeView_CreateDragImage

TreeView_DeleteAllItems

TreeView_DeleteItem

TreeView_EditLabel

TreeView_EndEditLabelNow

TreeView_EnsureVisible

TreeView_Expand

TreeView_GetBkColor

TreeView_GetChild

TreeView_GetCount

TreeView_GetDropHilight

TreeView_GetEditControl

TreeView_GetFirstVisible

TreeView_GetImageList

TreeView_GetIndent

TreeView_GetInsertMarkColor

TreeView_GetISearchString

TreeView_GetItem

TreeView_GetItemHeight

TreeView_GetItemRect

TreeView_GetLastVisible

TreeView_GetNextItem

TreeView_GetNextSibling

TreeView_GetNextVisible

TreeView_GetParent

TreeView_GetPrevSibling

TreeView_GetPrevVisible

TreeView_GetRoot

TreeView_GetScrollTime

TreeView_GetSelection

TreeView_GetTextColor

TreeView_GetToolTips

TreeView_GetUnicodeFormat

TreeView_GetVisibleCount

TreeView_HitTest

TreeView_InsertItem

TreeView_Select

TreeView_SelectDropTarget

TreeView_SelectItem

TreeView_SetBkColor

TreeView_SelectSetFirstVisible

TreeView_SetImageList

TreeView_SetIndent

TreeView_SetInsertMark

TreeView_SetInsertMarkColor

TreeView_SetItem

TreeView_SetItemHeight

TreeView_SetScrollTime

TreeView_SetTextColor

TreeView_SetToolTips

TreeView_SetUnicodeFormat

TreeView_SortChildren

TreeView_SortChildrenCB


TreeView_CreateDragImage

HIMAGELIST TreeView_CreateDragImage(
    HWND hwndTV,
    HTREEITEM hitem
);

Creates a dragging bitmap for the specified item in a tree view control. The macro also 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 use this macro or send the TVM_CREATEDRAGIMAGE message explicitly.

  • Returns the handle to the image list to which the dragging bitmap was added if successful, or NULL otherwise.
hwndTV
Handle to the tree view control.
hitem
Handle to the item that receives the new dragging bitmap.

If you create a tree view control without an associated image list, you cannot use the TreeView_CreateDragImage macro to create the image to display during a drag operation. You must implement your own method of creating a drag cursor.


TreeView_DeleteAllItems

BOOL TreeView_DeleteAllItems(
    HWND hwndTV
);

Removes an item from a tree view control. You can use this macro, the TreeView_DeleteItem macro, or send the TVM_DELETEITEM message explicitly.

  • Returns TRUE if successful, or FALSE otherwise.
hwndTV
Handle to the tree view control.

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.


TreeView_DeleteItem

BOOL TreeView_DeleteItem(
    HWND hwndTV,
    HTREEITEM hitem
   );

Removes an item from a tree view control. You can use this macro, the TreeView_DeleteAllItems macro, or send the TVM_DELETEITEM message explicitly.

  • Returns TRUE if successful, or FALSE otherwise.
hwndTV
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.

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.


TreeView_EditLabel

HWND TreeView_EditLabel(
   HWND hwndTV,
   HTREEITEM hitem
   );

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 macro implicitly selects and focuses the specified item. You can use this macro or send the TVM_EDITLABEL message explicitly.

  • Returns the handle to the edit control used to edit the item text if successful, or NULL otherwise.
hwndTV
Handle to the tree view control.
hitem
Handle to the item to edit.

This macro 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 call this macro. Focus can be set using the SetFocus function.


TreeView_EndEditLabelNow

BOOL TreeView_EndEditLabelNow(
    HWND hwndTV,
    BOOL fCancel
   );

Ends the editing of a tree view item's label. You can use this macro or send the TVM_ENDEDITLABELNOW message explicitly.

  • Returns TRUE if successful, or FALSE otherwise.
hwndTV
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.

This macro causes the TVN_ENDLABELEDIT notification message to be sent to the parent window of the tree view control.


TreeView_EnsureVisible

BOOL TreeView_EnsureVisible(
   HWND hwndTV,
   HTREEITEM hitem
   );

Ensures that a tree view item is visible, expanding the parent item or scrolling the tree view control, if necessary. You can use this macro or send the TVM_ENSUREVISIBLE message explicitly.

  • Returns nonzero if the system scrolled the items in the tree view control and no items were expanded. Otherwise, the message returns zero.
hwndTV
Handle to the tree view control.
hitem
Handle to the item.

If the TreeView_EnsureVisible macro expands the parent item, the parent window receives the TVN_ITEMEXPANDING and TVN_ITEMEXPANDED notification messages.


TreeView_Expand

BOOL TreeView_Expand(
    HWND hwndTV,
    HTREEITEM hItem,
    UINT flag
);

Expands or collapses the list of child items associated with the specified parent item, if any. You can use this macro or send the TVM_EXPAND message explicitly.

  • Returns nonzero if a change took place, or zero otherwise.
hwndTV
Handle to a tree view control.
hItem
Handle to the parent item that will be expanded or collapsed.
flag
Action flag. See the description of the flag argument in TVM_EXPAND for a list of possible values.

The TreeView_Expand macro will cause the TVN_ITEMEXPANDING and TVN_ITEMEXPANDED notification messages to be generated if the item being expanded does not have the TVIS_EXPANDEDONCE state bit set. This state gets set when a parent item is expanded for the first time. Using TVE_COLLAPSE and TVE_COLLAPSERESET with TreeView_Expand will cause the TVIS_EXPANDEDONCE state to be reset.

If the item already has the TVIS_EXPANDEDONCE state set, the TreeView_Expand macro will not cause the TVN_ITEMEXPANDING and TVN_ITEMEXPANDED notification messages to be generated.


TreeView_GetBkColor

COLORREF TreeView_GetBkColor(
    HWND hwndTV
);

Retrieves the current background color of the control. You can use this macro or send the TVM_GETBKCOLOR message explicitly.

  • Returns a COLORREF value that represents the current background color. If this value is -1, the control is using the system color for the background color.
hwndTV
Handle to a tree view control.

Version 4.71

See also TreeView_SetBkColor


TreeView_GetChild

HTREEITEM TreeView_GetChild(
    HWND hwndTV,
    HTREEITEM hitem,
);

Retrieves the first child item of the specified tree view item. You can use this macro, or you can explicitly send the TVM_GETNEXTITEM message with the TVGN_CHILD flag.

  • Returns the handle to the item if successful, or NULL otherwise.
hwndTV
Handle to the tree view control.
hitem
Handle to a tree view item.

See also TreeView_GetNextItem, TreeView_GetNextSibling, TreeView_GetParent, TreeView_GetPrevSibling


TreeView_GetCount

UINT TreeView_GetCount(
    HWND hwndTV
);

Retrieves a count of the items in a tree view control. You can use this macro or send the TVM_GETCOUNT message explicitly.

  • Returns the count of items.
hwndTV
Handle to the tree view control.


TreeView_GetDropHilight

HTREEITEM TreeView_GetDropHilight(
    HWND hwndTV
);

Retrieves the tree view item that is the target of a drag-and-drop operation. You can use this macro, or you can explicitly send the TVM_GETNEXTITEM message with the TVGN_DROPHILITE flag.

  • Returns the handle to the item if successful, or NULL otherwise.
hwndTV
Handle to the tree view control.


TreeView_GetEditControl

HWND TreeView_GetEditControl(
    HWND hwndTV
);

Retrieves the handle to the edit control being used to edit a tree view item's text. You can use this macro or send the TVM_GETEDITCONTROL message explicitly.

  • Returns the handle to the edit control if successful, or NULL otherwise.
hwndTV
Handle to the tree view control.


TreeView_GetFirstVisible

HTREEITEM TreeView_GetFirstVisible(
    HWND hwndTV
);

Retrieves the first visible item in a tree view control window. You can use this macro, or you can explicitly send the TVM_GETNEXTITEM message with the TVGN_FIRSTVISIBLE flag.

  • Returns the handle to the item if successful, or NULL otherwise.
hwndTV
Handle to the tree view control.

See also TreeView_GetNextVisible, TreeView_GetPrevVisible, TreeView_GetLastVisible, TVM_GETITEMRECT


TreeView_GetImageList

HIMAGELIST TreeView_GetImageList(
    HWND hwndTV,
    INT iImage
);

Retrieves the handle to the normal or state image list associated with a tree view control. You can use this macro or send the TVM_GETIMAGELIST message explicitly.

  • Returns an HIMAGELIST handle to the specified image list.
hwndTV
Handle to the tree view control.
iImage
Type of image list to retrieve. This parameter can be one of the following values:
TVSIL_NORMAL | Indicates the normal image list, which contains selected, nonselected, and overlay images for the items of a tree view control.
TVSIL_STATE | Indicates the state image list. You can use state images to indicate application-defined item states. A state image is displayed to the left of an item's selected or nonselected image.

See also TreeView_SetImageList


TreeView_GetIndent

UINT TreeView_GetIndent(
    HWND hwndTV
);

Retrieves the amount, in pixels, that child items are indented relative to their parent items. You can use this macro or send the TVM_GETINDENT message explicitly.

  • Returns the amount of indentation.
hwndTV
Handle to the tree view control.


TreeView_GetInsertMarkColor

COLORREF TreeView_GetInsertMarkColor(
     HWND hwndTV
);

Retrieves the color used to draw the insertion mark for the tree view. You can use this macro or send the TVM_GETINSERTMARKCOLOR message explicitly.

  • Returns a COLORREF value that contains the current insertion mark color.
hwndTV
Handle to the tree view control.

Version 4.71

See also TreeView_SetInsertMarkColor


TreeView_GetISearchString

BOOL TreeView_GetISearchString(
   HWND hwndTV,
   LPTSTR lpsz
);

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. You can use this macro or send the TVM_GETISEARCHSTRING message explicitly.

  • Returns the number of characters in the incremental search string.
hwndTV
Handle to the tree view control.
lpsz
Address of the buffer that receives the incremental search string.

If the tree view control is not in incremental search mode, the return value is zero.


TreeView_GetItem

BOOL TreeView_GetItem(
   HWND hwndTV,
   LPTVITEM pitem
   );

Retrieves some or all of a tree view item's attributes. You can use this macro or send the TVM_GETITEM message explicitly.

  • Returns TRUE if successful, or FALSE otherwise.
hwndTV
Handle to the tree view control.
pitem
Address of a TVITEM structure that specifies the information to retrieve and receives information about the item. When the TVM_GETITEM message is sent, the hItem member identifies the item to retrieve information about, and the mask member specifies the attributes to retrieve.
If the mask member specifies the TVIF_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.
If the mask member specifies the TVIF_STATE value, the stateMask member must specify the item state bits to retrieve. On output, the state member contains the values of the specified state bits.


TreeView_GetItemHeight

int TreeView_GetItemHeight(
    HWND hwndTV
);

Retrieves the current height of the tree view items. You can use this macro or send the TVM_GETITEMHEIGHT message explicitly.

  • Returns the height of the items, in pixels.
hwndTV
Handle to a tree view control.

Version 4.71

See also TreeView_SetItemHeight


TreeView_GetItemRect

BOOL TreeView_GetItemRect(
   HWND hwndTV,
   HTREEITEM hitem,
   LPRECT prc,
   BOOL fItemRect
);

Retrieves the bounding rectangle for a tree view item and indicates whether the item is visible. You can use this macro or send the TVM_GETITEMRECT message explicitly.

  • If the item is visible and the bounding rectangle is successfully retrieved, the return value is TRUE. Otherwise, the TVM_GETITEMRECT message returns FALSE and does not retrieve the bounding rectangle.
hwndTV
Handle to the tree view control.
hitem
Handle to the tree view item.
prc
Address of 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.


TreeView_GetLastVisible

HTREEITEM TreeView_GetLastVisible(
    HWND hwndTV
);

Retrieves the last expanded item in a tree view control. This does not retrieve the last item visible in the tree view window. You can use this macro, or you can explicitly send the TVM_GETNEXTITEM message with the TVGN_LASTVISIBLE flag.

  • Returns the handle to the item if successful, or NULL otherwise.
hwndTV
Handle to the tree view control.

Version 4.71.

See also TreeView_GetFirstVisible, TreeView_GetNextVisible, TreeView_GetPrevVisible, TVM_GETITEMRECT


TreeView_GetNextItem

HTREEITEM TreeView_GetNextItem(
    HWND hwndTV,
    HTREEITEM hitem,
    UINT flag
);

Retrieves the tree view item that bears the specified relationship to a specified item. You can use this macro, use one of the TreeView_Get macros described below, or send the TVM_GETNEXTITEM message explicitly.

  • Returns the handle to the item if successful, or NULL otherwise.
hwndTV
Handle to the tree view control.
hitem
Handle to an item.
flag
Flag specifying the item to retrieve. This parameter can be one of the following values:
TVGN_CARET | Retrieves the currently selected item. You can use the TreeView_GetSelection macro to send this message.
TVGN_CHILD | Retrieves the first child item of the item specified by the hitem parameter. You can use the TreeView_GetChild macro to send this message.
TVGN_DROPHILITE | Retrieves the item that is the target of a drag-and-drop operation. You can use the TreeView_GetDropHilight macro to send this message.
TVGN_FIRSTVISIBLE | Retrieves the first visible item. You can use the TreeView_GetFirstVisible macro to send this message.
TVGN_NEXT | Retrieves the next sibling item. You can use the TreeView_GetNextSibling macro to send this message.
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. You can use the TreeView_GetNextVisible macro to send this message.
TVGN_PARENT | Retrieves the parent of the specified item. You can use the TreeView_GetParent macro to send this message.
TVGN_PREVIOUS | Retrieves the previous sibling item. You can use the TreeView_GetPrevSibling macro to send this message.
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. You can use the TreeView_GetPrevVisible macro to send this message.
TVGN_ROOT | Retrieves the topmost or very first item of the tree view control. You can use the TreeView_GetRoot macro to send this message.


TreeView_GetNextSibling

HTREEITEM TreeView_GetNextSibling(
    HWND hwndTV,
    HTREEITEM hitem
);

Retrieves the next sibling item of a specified item in a tree view control. You can use this macro, or you can explicitly send the TVM_GETNEXTITEM message with the TVGN_NEXT flag.

  • Returns the handle to the item if successful, or NULL otherwise.
hwndTV
Handle to the tree view control.
hitem
Handle to an item.

See also TreeView_GetChild, TreeView_GetNextItem, TreeView_GetParent, TreeView_GetPrevSibling


TreeView_GetNextVisible

HTREEITEM TreeView_GetNextVisible(
    HWND hwndTV,
    HTREEITEM hitem
);

Retrieves the next visible item that follows a specified item in a tree view control. You can use this macro, or you can explicitly send the TVM_GETNEXTITEM message with the TVGN_NEXTVISIBLE flag.

  • Returns the handle to the item if successful, or NULL otherwise.
hwndTV
Handle to the tree view control.
hitem
Handle to an item. The specified item must be visible. Use the TVM_GETITEMRECT message to determine whether an item is visible.

See also TreeView_GetFirstVisible, TreeView_GetNextItem, TreeView_GetPrevVisible


TreeView_GetParent

HTREEITEM TreeView_GetParent(
    HWND hwndTV,
    HTREEITEM hitem
);

Retrieves the parent item of the specified tree view item. You can use this macro, or you can explicitly send the TVM_GETNEXTITEM message with the TVGN_PARENT flag.

  • Returns the handle to the item if successful, or NULL otherwise.
hwndTV
Handle to the tree view control.
hitem
Handle to an item.

See also TreeView_GetChild, TreeView_GetNextItem, TreeView_GetNextSibling, TreeView_GetPrevSibling


TreeView_GetPrevSibling

HTREEITEM TreeView_GetPrevSibling(
    HWND hwndTV,
    HTREEITEM hitem
);

Retrieves the previous sibling item of a specified item in a tree view control. You can use this macro, or you can explicitly send the TVM_GETNEXTITEM message with the TVGN_PREVIOUS flag.

  • Returns the handle to the item if successful, or NULL otherwise.
hwndTV
Handle to the tree view control.
hitem
Handle to an item.

See also TreeView_GetChild, TreeView_GetNextItem, TreeView_GetNextSibling, TreeView_GetParent


TreeView_GetPrevVisible

HTREEITEM TreeView_GetPrevVisible(
    HWND hwndTV,
    HTREEITEM hitem
);

Retrieves the first visible item that precedes a specified item in a tree view control. You can use this macro, or you can explicitly send the TVM_GETNEXTITEM message with the TVGN_PREVIOUSVISIBLE flag.

  • Returns the handle to the item if successful, or NULL otherwise.
hwndTV
Handle to the tree view control.
hitem
Handle to an item. The specified item must be visible. Use the TVM_GETITEMRECT message to determine whether an item is visible.

See also TreeView_GetFirstVisible, TreeView_GetNextItem, TreeView_GetNextVisible


TreeView_GetRoot

HTREEITEM TreeView_GetRoot(
    HWND hwndTV
);

Retrieves the topmost or very first item of the tree view control. You can use this macro, or you can explicitly send the TVM_GETNEXTITEM message with the TVGN_ROOT flag.

  • Returns the handle to the item if successful, or NULL otherwise.
hwndTV
Handle to the tree view control.

See also TreeView_GetNextItem


TreeView_GetScrollTime

UINT TreeView_GetScrollTime(
    HWND hwndTV
);

Retrieves the maximum scroll time for the tree view control. You can use this macro or send the TVM_GETSCROLLTIME message explicitly.

  • Returns the maximum scroll time, in milliseconds.
hwndTV
Handle to the tree view control.

The maximum scroll time is the longest amount of time that a scroll operation can take. Scrolling will be adjusted so that the scroll will take place within the maximum scroll time. A scroll operation may take less time than the maximum.

See also TreeView_SetScrollTime


TreeView_GetSelection

HTREEITEM TreeView_GetSelection(
    HWND hwndTV
);

Retrieves the currently selected item in a tree view control. You can use this macro, or you can explicitly send the TVM_GETNEXTITEM message with the TVGN_CARET flag.

  • Returns the handle to the item if successful, or NULL otherwise.
hwndTV
Handle to the tree view control.

See also TreeView_GetNextItem


TreeView_GetTextColor

COLORREF TreeView_GetTextColor(
    HWND hwndTV
);

Retrieves the current text color of the control. You can use this macro or send the TVM_GETTEXTCOLOR message explicitly.

  • Returns a COLORREF value that represents the current text color. If this value is -1, the control is using the system color for the text color.
hwndTV
Handle to a tree view control.

Version 4.71

See also TreeView_SetTextColor


TreeView_GetToolTips

HWND TreeView_GetToolTips(
    HWND hwndTV
);

Retrieves the handle to the child tooltip control used by a tree view control. You can use this macro or send the TVM_GETTOOLTIPS message explicitly.

  • Returns the handle to the child tooltip control, or NULL if the control is not using tooltips.
hwndTV
Handle to a tree view control.

When created, tree view controls automatically create a child tooltip control. To prevent a tree view control from using tooltips, create the control with the TVS_NOTOOLTIPS style.

Version 4.70

See also TreeView_SetToolTips


TreeView_GetUnicodeFormat

BOOL TreeView_GetUnicodeFormat(
    HWND hwnd
);

Retrieves the UNICODE character format flag for the control. You can use this macro or send the TVM_GETUNICODEFORMAT message explicitly.

  • Returns the UNICODE format flag for the control. If this value is nonzero, the control is using UNICODE characters. If this value is zero, the control is using ANSI characters.
hwnd
Handle to the control.

See also TreeView_SetUnicodeFormat


TreeView_GetVisibleCount

UINT TreeView_GetVisibleCount(
    HWND hwndTV
);

Obtains the number of items that can be fully visible in the client window of a tree view control. You can use this macro or send the TVM_GETVISIBLECOUNT message explicitly.

  • Returns the number of items that can be fully visible in the client window of the tree view control.
hwndTV
Handle to the tree view control.

The number of items that can be fully visible may be greater than the number of items in the control. The control calculates this value by dividing the height of the client window by the height of an item.

Note that the return value is the number of items that can be fully visible. If you can see all of 20 items and part of one more item, the return value is 20.


TreeView_HitTest

HTREEITEM TreeView_HitTest(
    HWND hwndTV,
    LPTVHITTESTINFO lpht
);

Determines the location of the specified point relative to the client area of a tree view control. You can use this macro or send the TVM_HITTEST message explicitly.

  • Returns the handle to the tree view item that occupies the specified point, or NULL if no item occupies the point.
hwndTV
Handle to the tree view control.
lpht
Address of a TVHITTESTINFO 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 TVHITTESTINFO structure.


TreeView_InsertItem

HTREEITEM TreeView_InsertItem(
    HWND hwndTV,
    LPTVINSERTSTRUCT lpis
);

Inserts a new item in a tree view control. You can use this macro or send the TVM_INSERTITEM message explicitly.

  • Returns the handle to the new item if successful, or NULL otherwise.
hwndTV
Handle to the tree view control.
lpis
Address of a TVINSERTSTRUCT structure that specifies the attributes of the tree view item.

See also TVN_ENDLABELEDIT


TreeView_Select

BOOL TreeView_Select(
    HWND hwndTV,
    HTREEITEM hitem,
    UINT flag
);

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 use this macro or the TreeView_SelectItem, TreeView_SelectSetFirstVisible, or TreeView_SelectDropTarget macros, or you can send the TVM_SELECTITEM message explicitly.

  • Returns TRUE if successful, or FALSE otherwise.
hwndTV
Handle to the tree view control.
hitem
Handle to an item. If the hitem parameter is NULL, the control is set to have no selected item.
flag
Action flag. This parameter can be one of the following values:
TVGN_CARET | Sets the selection to the given item. The control's parent window receives the TVN_SELCHANGING and TVN_SELCHANGED notification messages.
TVGN_DROPHILITE | Redraws the given item in the style used to indicate the target of a drag-and-drop operation.
TVGN_FIRSTVISIBLE | Ensures that the specified item is visible, and, if possible, displays it at the top of the control's window. Tree view controls display as many items as will fit in the window. If the specified item is near the bottom of the control's hierarchy of items, it might not become the first visible item, depending on how many items fit in the window.

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.


TreeView_SelectDropTarget

BOOL TreeView_SelectDropTarget(
    HWND hwndTV,
    HTREEITEM hitem
);

Redraws a specified tree view control item in the style used to indicate the target of a drag-and-drop operation. You can use this macro or the TreeView_Select macro, or you can send the TVM_SELECTITEM message explicitly.

  • Returns TRUE if successful, or FALSE otherwise.
hwndTV
Handle to the tree view control.
hitem
Handle to an item. If the hitem parameter is NULL, the control is set to have no selected item.

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_SelectDropTarget macro is equivalent to sending the TVM_SELECTITEM message with its flag parameter set to the TVGN_DROPHILITE value.


TreeView_SelectItem

BOOL TreeView_SelectItem(
    HWND hwndTV,
    HTREEITEM hitem
);

Selects the specified tree view item. You can use this macro or the TreeView_Select macro, or you can send the TVM_SELECTITEM message explicitly.

  • Returns TRUE if successful, or FALSE otherwise.
hwndTV
Handle to the tree view control.
hitem
Handle to an item. If the hitem parameter is NULL, the control is set to have no selected item.

When you call the TreeView_SelectItem macro, the control's 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 its flag parameter set to the TVGN_CARET value.


TreeView_SetBkColor

COLORREF TreeView_SetBkColor(
    HWND hwndTV
    COLORREF clrBk;
);

Sets the background color of the control. You can use this macro or send the TVM_SETBKCOLOR message explicitly.

  • Returns a COLORREF value that represents the previous background color. If this value is -1, the control was using the system color for the background color.
hwndTV
Handle to a tree view control.
clrBk
COLORREF value that contains the new background color. If this argument is -1, the control will revert to using the system color for the background color.

Version 4.71

See also TreeView_GetBkColor


TreeView_SelectSetFirstVisible

BOOL TreeView_SelectSetFirstVisible(
    HWND hwndTV,
    HTREEITEM hitem
);

Scrolls the tree view control vertically to ensure that the specified item is visible. If possible, the specified item becomes the first visible item at the top of the control's window. You can use this macro or the TreeView_Select macro, or you can send the TVM_SELECTITEM message explicitly.

  • Returns TRUE if successful, or FALSE otherwise.
hwndTV
Handle to the tree view control.
hitem
Handle to an item. If the hitem parameter is NULL, the control is set to have no selected item.

Tree view controls display as many items as will fit in the window. If the specified item is near the bottom of the control's hierarchy of items, it might not become the first visible item, depending on how many items fit in the window.

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_SelectSetFirstVisible macro is equivalent to sending the TVM_SELECTITEM message with its flag parameter set to the TVGN_FIRSTVISIBLE value.


TreeView_SetImageList

HIMAGELIST TreeView_SetImageList(
    HWND hwndTV,
    HIMAGELIST himl,
    INT iImage
   );

Sets the normal or state image list for a tree view control and redraws the control using the new images. You can use this macro or send the TVM_SETIMAGELIST message explicitly.

  • Returns the HIMAGELIST handle to the previous image list, if any, or NULL otherwise.
hwndTV
Handle to the tree view control.
himl
The HIMAGELIST handle to the image list. If himl is NULL, the message removes the specified image list from the tree view control.
iImage
Type of image list to set. This parameter can be one of the following values:
TVSIL_NORMAL | Indicates the normal image list, which contains selected, nonselected, and overlay images for the items of a tree view control.
TVSIL_STATE | Indicates the state image list. You can use state images to indicate application-defined item states. A state image is displayed to the left of an item's selected or nonselected image.

See also TreeView_GetImageList, TVM_GETIMAGELIST


TreeView_SetIndent

BOOL TreeView_SetIndent(
    HWND hwndTV,
    INT indent
   );

Sets the width of indentation for a tree view control and redraws the control to reflect the new width. You can use this macro or send the TVM_SETINDENT message explicitly.

  • The return value is not used.
hwndTV
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.


TreeView_SetInsertMark

BOOL TreeView_SetInsertMark(
    HWND hwndTV,
    HTREEITEM htiInsert,
    BOOL fAfter
);

Sets the insertion mark in a tree view control. You can use this macro or send the TVM_SETINSERTMARK message explicitly.

  • Returns nonzero if successful, or zero otherwise.
hwndTV
Handle to a tree view control.
htiInsert
HTREEITEM that specifies at which item the insertion mark will be placed. If this argument is NULL, the insertion mark is removed.
fAfter
BOOL value that specifies if the insertion mark is placed before or after the specified item. If this argument is nonzero, the insertion mark will be placed after the item. If this argument is zero, the insertion mark will be placed before the item.

Version 4.71


TreeView_SetInsertMarkColor

COLORREF TreeView_SetInsertMarkColor(
    HWND hwndTV,
    COLORREF clrInsertMark
);

Sets the color used to draw the insertion mark for the tree view. You can use this macro or send the TVM_SETINSERTMARKCOLOR message explicitly.

  • Returns a COLORREF value that contains the previous insertion mark color.
hwndTV
Handle to a tree view control.
clrInsertMark
COLORREF value that contains the new insertion mark color.

Version 4.71

See also TreeView_GetInsertMarkColor


TreeView_SetItem

BOOL TreeView_SetItem(
    HWND hwndTV,
    LPTVITEM pitem
);

Sets some or all of a tree view item's attributes. You can use this macro or send the TVM_SETITEM message explicitly.

  • Returns zero if successful, or -1 otherwise.
hwndTV
Handle to the tree view control.
pitem
Address of a TVITEM 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 address of 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.


TreeView_SetItemHeight

int TreeView_SetItemHeight(
    HWND hwndTV,
    SHORT cyItem
);

Sets the height of the tree view items. You can use this macro or send the TVM_SETITEMHEIGHT message explicitly.

  • Returns the previous height of the items, in pixels.
hwndTV
Handle to a tree view control.
cyItem
New height of every item in the tree view, in pixels. If this value is less than the height of the images, then it will be set to the height of the images. If this argument is not even, it will be rounded down to the nearest even value. If this argument is -1, the control will revert to using its default item height.

The tree view control uses this value for the height of all items. To modify the height of individual items, see the description of the iIntegral member of the TVITEMEX structure.

Version 4.71

See also TreeView_GetItemHeight


TreeView_SetScrollTime

UINT TreeView_SetScrollTime(
    HWND hwndTV,
    UINT uMaxScrollTime
);

Sets the maximum scroll time for the tree view control. You can use this macro or send the TVM_SETSCROLLTIME message explicitly.

  • Returns the previous scroll time, in milliseconds.
hwndTV
Handle to a tree view control.
uMaxScrollTime
New maximum scroll time, in milliseconds. If this value is less than 100, it will be rounded up to 100.

The maximum scroll time is the longest amount of time that a scroll operation can take. Scrolling will be adjusted so that the scroll will take place within the maximum scroll time. A scroll operation may take less time than the maximum.

See also TVM_GETSCROLLTIME


TreeView_SetTextColor

COLORREF TreeView_SetTextColor(
    HWND hwndTV
    COLORREF clrText;
);

Sets the text color of the control. You can use this macro or send the TVM_SETTEXTCOLOR message explicitly.

  • Returns a COLORREF value that represents the previous text color. If this value is -1, the control was using the system color for the text color.
hwndTV
Handle to a tree view control.
clrText
COLORREF value that contains the new text color. If this argument is -1, the control will revert to using the system color for the text color.

Version 4.71

See also TreeView_GetTextColor


TreeView_SetToolTips

HWND TreeView_SetToolTips(
    HWND hwndTV,
    HWND hwndTooltip
);

Sets a tree view control's child tooltip control. You can use this macro or send the TVM_SETTOOLTIPS message explicitly.

  • Returns the handle to tooltip control previously set for the tree view control, or NULL if tooltips were not previously used.
hwndTV
Handle to a tree view control.
hwndTooltip
Handle to a tooltip control.

When created, tree view controls automatically create a child tooltip control. To prevent a tree view control from using tooltips, create the control with the TVS_NOTOOLTIPS style.

Version 4.70

See also TreeView_GetToolTips


TreeView_SetUnicodeFormat

BOOL TreeView_SetUnicodeFormat(
    HWND hwnd,
    BOOL fUnicode
);

Sets the UNICODE character format flag for the control. This message allows you to change the character set used by the control at run time rather than having to re-create the control. You can use this macro or send the TVM_SETUNICODEFORMAT message explicitly.

  • Returns the previous UNICODE format flag for the control.
hwnd
Handle to the control.
fUnicode
Determines the character set that is used by the control. If this value is nonzero, the control will use UNICODE characters. If this value is zero, the control will use ANSI characters.

See also TreeView_GetUnicodeFormat


TreeView_SortChildren

BOOL TreeView_SortChildren(
    HWND hwndTV,
    HTREEITEM hitem,
    BOOL fRecurse
);

Sorts the child items of the specified parent item in a tree view control. You can use this macro or send the TVM_SORTCHILDREN message explicitly.

  • Returns TRUE if successful, or FALSE otherwise.
hwndTV
Handle to the tree view control.
hitem
Handle to the parent item whose child items are to be sorted.
fRecurse
Reserved for future use. Must be zero.


TreeView_SortChildrenCB

BOOL TreeView_SortChildrenCB(
    HWND hwndTV,
    LPTVSORTCB psort,
    BOOL fRecurse
);

Sorts tree view items using an application-defined callback function that compares the items. You can use this macro or send the TVM_SORTCHILDRENCB message explicitly.

  • Returns TRUE if successful, or FALSE otherwise.
hwndTV
Handle to the tree view control.
psort
Address of a TVSORTCB structure. The lpfnCompare member is the address of 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 TVSORTCB.
fRecurse
Reserved for future use. Must be zero.


Tree View Notification Messages

This section contains information about the notification messages that are sent by tree view controls.

NM_CLICK (tree view)

NM_CUSTOMDRAW (tree view)

NM_DBLCLK (tree view)

NM_KILLFOCUS (tree view)

NM_RCLICK (tree view)

NM_RDBLCLK (tree view)

NM_RETURN (tree view)

NM_SETCURSOR (tree view)

NM_SETFOCUS (tree view)

TVN_BEGINDRAG

TVN_BEGINLABELEDIT

TVN_BEGINRDRAG

TVN_DELETEITEM

TVN_ENDLABELEDIT

TVN_GETDISPINFO

TVN_GETINFOTIP

TVN_ITEMEXPANDED

TVN_ITEMEXPANDING

TVN_KEYDOWN

TVN_SELCHANGED

TVN_SELCHANGING

TVN_SETDISPINFO

TVN_SINGLEEXPAND


NM_CLICK (tree view)

NM_CLICK
    lpnmh = (LPNMHDR) lParam;

Notifies a tree view control's parent window that the user has clicked the left mouse button within the control. This notification is sent in the form of a WM_NOTIFY message.

  • Return nonzero to prevent the default processing, or zero to allow the default processing.
lpnmh
Address of an NMHDR structure that contains additional information about this notification message.


NM_CUSTOMDRAW (tree view)

NM_CUSTOMDRAW
    lpNMCustomDraw = (LPNMTVCUSTOMDRAW) lParam;

Sent by a tree view control to notify its parent window about drawing operations. This notification is sent in the form of a WM_NOTIFY message.

  • The value your application can return depends on the current drawing stage. The dwDrawStage member of the associated NMCUSTOMDRAW structure holds a value that specifies the drawing stage. You must return one of the following values:

    When dwDrawStage equals CDDS_PREPAINT:
    CDRF_DODEFAULT
    The control will draw itself. It will not send any additional NM_CUSTOMDRAW messages for this paint cycle.
    CDRF_NOTIFYITEMDRAW
    The control will notify the parent of any item-related drawing operations. It will send NM_CUSTOMDRAW notification messages before and after drawing items.
    CDRF_NOTIFYITEMERASE
    The control will notify the parent when an item will be erased. It will send NM_CUSTOMDRAW notification messages before and after erasing items.
    CDRF_NOTIFYPOSTERASE
    The control will notify the parent after erasing an item.
    CDRF_NOTIFYPOSTPAINT
    The control will notify the parent after painting an item.
    CDRF_NOTIFYSUBITEMDRAW
    Version 4.71. The control will notify the parent when a list view subitem is being drawn.

    When dwDrawStage equals CDDS_ITEMPREPAINT:
    CDRF_NEWFONT
    Your application specified a new font for the item; the control will use the new font. For more information on changing fonts, see Changing fonts and colors.
    CDRF_SKIPDEFAULT
    Your application drew the item manually. The control will not draw the item.
    TVCDRF_NOIMAGES
    Version 4.71. The control will not draw the image for the item.

lpNMCustomDraw
Address of a NMTVCUSTOMDRAW structure that contains and receives information about the drawing operation. The dwItemSpec member of the nmcd member of this structure contains the handle of the item being drawn. The lItemlParam member of the nmcd member of this structure contains the lParam of the item being drawn.

Version 4.70

See also Using Custom Draw


NM_DBLCLK (tree view)

NM_DBLCLK
    lpnmh = (LPNMHDR) lParam;

Notifies a tree view control's parent window that the user has double-clicked the left mouse button within the control. This notification is sent in the form of a WM_NOTIFY message.

  • Return nonzero to prevent the default processing, or zero to allow the default processing.
lpnmh
Address of an NMHDR structure that contains additional information about this notification message.


NM_KILLFOCUS (tree view)

NM_KILLFOCUS
    lpnmh = (LPNMHDR) lParam;

Notifies a tree view control's parent window that the control has lost the input focus. This notification is sent in the form of a WM_NOTIFY message.

  • The return value is ignored.
lpnmh
Address of an NMHDR structure that contains additional information about this notification message.


NM_RCLICK (tree view)

NM_RCLICK
    lpnmh = (LPNMHDR) lParam;

Notifies a tree view control's parent window that the user has clicked the right mouse button within the control. This notification is sent in the form of a WM_NOTIFY message.

  • Return nonzero to prevent the default processing, or zero to allow the default processing.
lpnmh
Address of an NMHDR structure that contains additional information about this notification message.


NM_RETURN (tree view)

NM_RETURN
    lpnmh = (LPNMHDR) lParam;

Notifies a tree view control's parent window that the control has the input focus and that the user has pressed the ENTER key. This notification is sent in the form of a WM_NOTIFY message.

  • Return nonzero to prevent the default processing, or zero to allow the default processing.
lpnmh
Address of an NMHDR structure that contains additional information about this notification message.


NM_SETCURSOR (tree view)

NM_SETCURSOR
    lpnmm = (LPNMMOUSE) lParam;

Notifies a tree view control's parent window that the control is setting the cursor in response to a WM_SETCURSOR message. This notification is sent in the form of a WM_NOTIFY message.

  • Return nonzero to allow the control to set the cursor, or zero to prevent the control from setting the cursor.
lpnmm
Address of an NMMOUSE structure that contains additional information about this notification message.

Version 4.71.


NM_SETFOCUS (tree view)

NM_SETFOCUS
    lpnmh = (LPNMHDR) lParam;

Notifies a tree view control's parent window that the control has received the input focus. This notification is sent in the form of a WM_NOTIFY message.

  • The return value is ignored.
lpnmh
Address of an NMHDR structure that contains additional information about this notification message.


TVN_BEGINDRAG

TVN_BEGINDRAG
    pnmtv = (LPNMTREEVIEW) lParam

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.

  • The return value is ignored.
pnmtv
Address of an NMTREEVIEW structure. The itemNew member is a TVITEM 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.

A tree view control that has the TVS_DISABLEDRAGDROP style does not send this notification message.


TVN_BEGINLABELEDIT

TVN_BEGINLABELEDIT
    ptvdi = (LPNMTVDISPINFO) lParam

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.

  • Returns TRUE to cancel label editing.
ptvdi
Address of an NMTVDISPINFO structure. The item member is a TVITEM structure that contains valid information about the item being edited in the hItem, state, lParam, and pszText members.


TVN_BEGINRDRAG

TVN_BEGINRDRAG
    pnmtv = (LPNMTREEVIEW) lParam

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.

  • The return value is ignored.
pnmtv
Address of an NMTREEVIEW structure. The itemNew member is a TVITEM 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.


TVN_DELETEITEM

TVN_DELETEITEM
    pnmtv = (LPNMTREEVIEW) lParam

Notifies a tree view control's parent window that an item is being deleted. This notification message is sent in the form of a WM_NOTIFY message.

  • The return value is ignored.
pnmtv
Address of an NMTREEVIEW structure. The itemOld member is a TVITEM structure whose hItem and lParam members contain valid information about the item being deleted.

If the lParam member of the TVITEM structure points to memory allocated by your application, you can free it when you receive the TVN_DELETEITEM notification message.


TVN_ENDLABELEDIT

TVN_ENDLABELEDIT
    ptvdi = (LPNMTVDISPINFO) lParam

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.

  • If the pszText member is non-NULL, return TRUE to set the item's label to the edited text. Return FALSE to reject the edited text and revert to the original label.
ptvdi
Address of an NMTVDISPINFOstructure. The item member of this structure is a TVITEM structure whose hItem, lParam, and pszText members contain valid information about the item that was edited.
If label editing was canceled, the pszText member of the TVITEM structure is NULL; otherwise, pszText is the address of the edited text.

If the pszText member is NULL, the return value is ignored.

If you specified the LPSTR_TEXTCALLBACK value for this item and the pszText member is non-NULL, your TVN_ENDLABELEDIT handler should copy the text from pszText to your local storage.


TVN_GETDISPINFO

TVN_GETDISPINFO
    lptvdi = (LPNMTVDISPINFO) lParam

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.

  • The return value is ignored.
lptvdi
Address of an NMTVDISPINFO structure. The item member is a TVITEM 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.

This notification is sent under the following circumstances:

  • If the pszText member of the item's TVITEM structure is the LPSTR_TEXTCALLBACK value, the control sends this notification to retrieve the item's text. In this case, the mask member of lptvdi will have the TVIF_TEXT flag set.
  • If the iImage or iSelectedImage member of the item's TVITEM structure is the I_IMAGECALLBACK value, the control sends this notification to retrieve the index of an item's icons in the control's image list. In this case, if the item is selected, the mask member of lptvdi will have the TVIF_SELECTEDIMAGE flag set. If the item is not selected, the mask member of lptvdi will have the TVIF_IMAGE flag set.
  • If the cChildren member of the item's TVITEM structure is the I_CHILDRENCALLBACK value, the control sends this notification to retrieve a value that indicates whether the item has child items. In this case, the mask member of lptvdi will have the TVIF_CHILDREN flag set.


TVN_GETINFOTIP

TVN_GETINFOTIP
    lpGetInfoTip = (LPNMTVGETINFOTIP)lParam;

Sent by a tree view control that has the TVS_INFOTIP style. This notification is sent when the control is requesting additional text information to be displayed in a tooltip. The notification is sent in the form of a WM_NOTIFY message.

  • The control ignores the return value for this notification.
lpGetInfoTip
Address of an NMTVGETINFOTIP structure that contains information about this notification.

This notification is only sent by tree view controls that have the TVS_INFOTIP style.

Version 4.71


TVN_ITEMEXPANDED

TVN_ITEMEXPANDED
    pnmtv = (LPNMTREEVIEW) lParam

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.

  • The return value is ignored.
pnmtv
Address of an NMTREEVIEW structure. The itemNew member is a TVITEM 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.


TVN_ITEMEXPANDING

TVN_ITEMEXPANDING
    pnmtv = (LPNMTREEVIEW) lParam

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.

  • Returns TRUE to prevent the list from expanding or collapsing.
pnmtv
Address of an NMTREEVIEW structure. The itemNew member is a TVITEM 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.


TVN_KEYDOWN

TVN_KEYDOWN
    ptvkd = (LPNMTVKEYDOWN) lParam

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.

  • If the wVKey member of ptvkd is a character key code, the character will be used as part of an incremental search. Return nonzero to exclude the character from the incremental search, or zero to include the character in the search. For all other keys, the return value is ignored.
ptvkd
Address of an NMTVKEYDOWN structure. The wVKey member specifies the virtual key code.


TVN_SELCHANGED

TVN_SELCHANGED
    pnmtv = (LPNMTREEVIEW) lParam

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.

  • The return value is ignored.
pnmtv
Address of an NMTREEVIEW structure. The itemOld and itemNew members of the NMTREEVIEW structure are TVITEM structures that contain information about the previously selected item and the newly selected item. Only the mask, hItem, state, and lParam members of these structures are valid. The stateMask members of the TVITEM structures specified by itemOld and itemNew are undefined on input.
The action member of the NMTREEVIEW structure indicates the type of action that caused the selection to change. It can be one of the following values:
TVC_BYKEYBOARD | By a keystroke.
TVC_BYMOUSE | By a mouse click.
TVC_UNKNOWN | Unknown.


TVN_SELCHANGING

TVN_SELCHANGING
    pnmtv = (LPNMTREEVIEW) lParam

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.

  • Returns TRUE to prevent the selection from changing.
pnmtv
Address of an NMTREEVIEW 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.


TVN_SETDISPINFO

TVN_GETDISPINFO
    lptvdi = (LPNMTVDISPINFO) lParam

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.

  • The return value is ignored.
lptvdi
Address of an NMTVDISPINFO 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.

If the pszText member of the item's TVITEM structure is the LPSTR_TEXTCALLBACK value, the control sends this notification to set the item's text. In this case, the mask member of lptvdi will have the TVIF_TEXT flag set.


TVN_SINGLEEXPAND

TVN_SINGLEEXPAND
    lpnmtv = (LPNMTREEVIEW)lParam;

Sent by a tree view control with the TVS_SINGLEEXPAND style when the user opens or closes a tree item using a single click of the mouse. This notification is sent in the form of a WM_NOTIFY message.

  • The control ignores the return value for this notification.
lpnmtv
Address of an NMTREEVIEW structure that contains information about this notification.

This notification is only sent by tree view controls that have the TVS_SINGLEEXPAND style.

Version 4.71


Tree View Control Structures

This section contains information about the structures used with tree view controls.

NMTREEVIEW

NMTVCUSTOMDRAW

NMTVDISPINFO

NMTVGETINFOTIP

NMTVKEYDOWN

TVHITTESTINFO

TVINSERTSTRUCT

TVITEM

TVITEMEX

TVSORTCB


NMTREEVIEW

typedef struct tagNMTREEVIEW {
    NMHDR hdr;
    UINT action;
    TVITEM itemOld;
    TVITEM itemNew;
    POINT ptDrag;
} NMTREEVIEW, FAR *LPNMTREEVIEW;

Contains information about a tree view notification message. This structure is identical to the NM_TREEVIEW structure, but it has been renamed to follow current naming conventions.

hdr
NMHDR structure that contains information about this notification message.
action
Notification-specific action flag.
itemOld
TVITEM structure that contains information about the old item state. This member is zero for notification messages that do not use it.
itemNew
TVITEM structure that contains 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.

See also WM_NOTIFY


NMTVCUSTOMDRAW

typedef struct tagNMTVCUSTOMDRAW {
    NMCUSTOMDRAW nmcd;
    COLORREF clrText;
    COLORREF clrTextBk;
#if (_WIN32_IE >= 0x0400)
    int iLevel;
#endif
} NMTVCUSTOMDRAW, *LPNMTVCUSTOMDRAW;

Contains information specific to an NM_CUSTOMDRAW notification message sent by a tree view control.

nmcd
NMCUSTOMDRAW structure that contains general custom draw information.
clrText
COLORREF value representing the color that will be used to display text foreground in the list view control.
clrTextBk
COLORREF value representing the color that will be used to display text background in the list view control.
iLevel
Version 4.71. Zero-based level of the item being drawn. The root item is at level zero, a child of the root item is at level one, and so on.

Version 4.70


NMTVDISPINFO

typedef struct tagNMTVDISPINFO {
    NMHDR hdr;
    TVITEM item;
} NMTVDISPINFO, FAR *LPNMTVDISPINFO;

Contains and receives display information for a tree view item. This structure is identical to the TV_DISPINFO structure, but it has been renamed to follow current naming conventions.

hdr
NMHDR structure that contains information about this notification message.
item
TVITEM structure that identifies and contains information about the tree view item. The mask member of the TVITEM structure specifies which information is being set or retrieved. It can be one or more of the following values:
TVIF_CHILDREN | The cChildren member specifies, or is to receive, a value that indicates whether the item has child items.
TVIF_IMAGE | The iImage member specifies, or is to receive, the index of the item's nonselected icon in the image list.
TVIF_SELECTEDIMAGE | The iSelectedImage member specifies, or is to receive, the index of the item's selected icon in the image list.
TVIF_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, you typically copy the text to the buffer pointed to by the pszText member of the TVITEM 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.

See also TVN_SETDISPINFO, WM_NOTIFY


NMTVGETINFOTIP

typedef struct tagNMTVGETINFOTIP {
    NMHDR hdr;
    LPTSTR pszText;
    int cchTextMax;
    HTREEITEM hItem;
    LPARAM lParam;
} NMTVGETINFOTIP, *LPNMTVGETINFOTIP;

Contains and receives tree view item information needed to display a tooltip for an item. This structure is used with the TVN_GETINFOTIP notification message.

hdr
NMHDR structure that contains information about this notification message.
pszText
Address of a character buffer that contains the text to be displayed. If you wish to change the text displayed in the tooltip, you will need to modify the contents of this buffer. The size of this buffer is specified by the ccTextMax structure.
cchTextMax
Size of the buffer at pszText, in characters. Although you should never assume that this buffer will be of any particular size, the INFOTIPSIZE value can be used for design purposes.
hItem
Tree handle to the item for which the tooltip is being displayed.
lParam
32-bit, application-defined data associated with the item for which the tooltip is being displayed.


NMTVKEYDOWN

typedef struct tagTVKEYDOWN {
    NMHDR hdr;
    WORD wVKey;
    UINT flags;
} NMTVKEYDOWN, FAR *LPNMTVKEYDOWN;

Contains information about a keyboard event in a tree view control. This structure is used with the TVN_KEYDOWN notification message. The structure is identical to the TV_KEYDOWN structure, but it has been renamed to follow current naming conventions.

hdr
NMHDR structure that contains information about this notification message.
wVKey
Virtual key code.
flags
Always zero.

See also WM_NOTIFY


TVHITTESTINFO

 typedef struct tagTVHITTESTINFO {
    POINT pt;
    UINT flags;
    HTREEITEM hItem;
} TVHITTESTINFO, FAR *LPTVHITTESTINFO;

Contains information used to determine the location of a point relative to a tree view control. This structure is used with the TVM_HITTEST message. The structure is identical to the TV_HITTESTINFO structure, but it has been renamed to follow current naming conventions.

pt
Client coordinates of the 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:
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 left of the client area.
TVHT_TORIGHT | To the right of the client area.
hItem
Handle to the item that occupies the point.


TVINSERTSTRUCT

typedef struct tagTVINSERTSTRUCT {
    HTREEITEM hParent;
    HTREEITEM hInsertAfter;
#if (_WIN32_IE >= 0x0400)
    union
    {
        TVITEMEX itemex;
        TVITEM item;
    } DUMMYUNIONNAME;
#else
    TVITEM item;
#endif
} TVINSERTSTRUCT, FAR *LPTVINSERTSTRUCT;

Contains information used to add a new item to a tree view control. This structure is used with the TVM_INSERTITEM message. The structure is identical to the TV_INSERTSTRUCT structure, but it has been renamed to follow current naming conventions.

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:
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.
itemex
Version 4.71. TVITEMEX structure that contains information about the item to add.
item
TVITEM structure that contains information about the item to add.


TVITEM

typedef struct tagTVITEM{
    UINT      mask;
    HTREEITEM hItem;
    UINT      state;
    UINT      stateMask;
    LPTSTR    pszText;
    int       cchTextMax;
    int       iImage;
    int       iSelectedImage;
    int       cChildren;
    LPARAM    lParam;
} TVITEM, FAR *LPTVITEM;

Specifies or receives attributes of a tree view item. This structure is identical to the TV_ITEM structure, but it has been renamed to follow current naming conventions. New applications should use this structure.

mask
Array of flags that indicate which of the other structure members contain valid data. When this structure is used with the TVM_GETITEM message, the mask member indicates the item attributes to retrieve. This member can be one or more of the following values:
TVIF_CHILDREN | The cChildren member is valid.
TVIF_HANDLE | The hItem 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
Identifies the item to which this structure refers.
state
A set of bit flags and image list indexes that indicate the item's state. When setting the state of an item, the stateMask member indicates the bits of this member that are valid. When retrieving the state of an item, this member returns the current state for the bits indicated in the stateMask member.

Bits 0 through 7 of this member contain the item state flags. For a list of possible item state flags, see Tree View Control Item States.

Bits 8 through 11 of this member specify the one-based overlay image index. The overlay image is superimposed over the item's icon image. If these bits are zero, the item has no overlay image. To isolate these bits, use the TVIS_OVERLAYMASK mask. To set the overlay image index in this member, you should use the INDEXTOOVERLAYMASK macro. The image list's overlay images are set with the ImageList_SetOverlayImage function.

Bits 12 through 15 of this member specify the state image index. The state image is displayed next to an item's icon to indicate an application-defined state. If these bits are zero, the item has no state image. To isolate these bits, use the TVIS_STATEIMAGEMASK mask. To set the state image index, you should use the INDEXTOSTATEIMAGEMASK macro. The state image index specifies the index of the image in the state image list that should be drawn. The state image list is specified with the TVM_SETIMAGELIST message.

stateMask
Bits of the state member that are valid. If you are retrieving an item's state, set the bits of the stateMask member to indicate the bits to be returned in the state member. If you are setting an item's state, set the bits of the stateMask member to indicate the bits of the state member that you want to set. To set or retrieve an item's overlay image index, set the TVIS_OVERLAYMASK bits. To set or retrieve an item's state image index, set the TVIS_STATEIMAGEMASK bits.
pszText
Address of 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 address of the buffer that receives the item text.
cchTextMax
Size of the buffer pointed to by the pszText member, in characters. If this structure is being used to set item attributes, this member is ignored.
iImage
Index in the tree view control's image list of the icon image to use when the item is in the nonselected state.
If this member is the I_IMAGECALLBACK value, the parent window is responsible for storing the index. In this case, the tree view control sends the parent a TVN_GETDISPINFO notification message to get the index when it needs to display the image.
iSelectedImage
Index in the tree view control's image list of the icon image to use when the item is in the selected state.
If this member is the I_IMAGECALLBACK value, the parent window is responsible for storing the index. In this case, the tree view control sends the parent a TVN_GETDISPINFO notification message to get the index when it needs to display the image.
cChildren
Flag that indicates whether the item has associated child items. This member can be one of the following values:
zero | The item has no child items.
one | The item has one or more child items.
I_CHILDRENCALLBACK | The parent window keeps track of whether the item has child items. In this case, when the tree view control needs to display the item, the control sends the parent a TVN_GETDISPINFO notification message to determine whether the item has child items.
If the tree view control has the TVS_HASBUTTONS style, it uses this member to determine whether to display the button indicating the presence of child items. You can use this member to force the control to display the button even though the item does not have any child items inserted. This allows you to display the button while minimizing the control's memory usage by inserting child items only when the item is visible or expanded.
lParam
A 32-bit value to associate with the item.


TVITEMEX

typedef struct tagTVITEMEX{
    UINT      mask;
    HTREEITEM hItem;
    UINT      state;
    UINT      stateMask;
    LPTSTR    pszText;
    int       cchTextMax;
    int       iImage;
    int       iSelectedImage;
    int       cChildren;
    LPARAM    lParam;
    int       iIntegral;
} TVITEMEX, FAR *LPTVITEMEX;

Specifies or receives attributes of a tree view item. This structure is an enhancement to the TVITEM structure. New applications should use this structure where appropriate.

mask
Array of flags that indicate which of the other structure members contain valid data. When this structure is used with the TVM_GETITEM message, the mask member indicates the item attributes to retrieve. This member can be one or more of the following values:
TVIF_CHILDREN | The cChildren member is valid.
TVIF_HANDLE | The hItem member is valid.
TVIF_IMAGE | The iImage member is valid.
TVIF_INTEGRAL | The iIntegral 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
Identifies the item to which this structure refers.
state
Set of bit flags and image list indexes that indicate the item's state. When setting the state of an item, the stateMask member indicates the bits of this member that are valid. When retrieving the state of an item, this member returns the current state for the bits indicated in the stateMask member.

Bits 0 through 7 of this member contain the item state flags. For a list of possible item state flags, see Tree View Control Item States.

Bits 8 through 11 of this member specify the one-based overlay image index. The overlay image is superimposed over the item's icon image. If these bits are zero, the item has no overlay image. To isolate these bits, use the TVIS_OVERLAYMASK mask. To set the overlay image index in this member, you should use the INDEXTOOVERLAYMASK macro. The image list's overlay images are set with the ImageList_SetOverlayImage function.

Bits 12 through 15 of this member specify the state image index. The state image is displayed next to an item's icon to indicate an application-defined state. If these bits are zero, the item has no state image. To isolate these bits, use the TVIS_STATEIMAGEMASK mask. To set the state image index, use the INDEXTOSTATEIMAGEMASK macro. The state image index specifies the index of the image in the state image list that should be drawn. The state image list is specified with the TVM_SETIMAGELIST message.

stateMask
Bits of the state member that are valid. If you are retrieving an item's state, set the bits of the stateMask member to indicate the bits to be returned in the state member. If you are setting an item's state, set the bits of the stateMask member to indicate the bits of the state member that you want to set. To set or retrieve an item's overlay image index, set the TVIS_OVERLAYMASK bits. To set or retrieve an item's state image index, set the TVIS_STATEIMAGEMASK bits.
pszText
Address of 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 address of the buffer that receives the item text.
cchTextMax
Size of the buffer pointed to by the pszText member, in characters. If this structure is being used to set item attributes, this member is ignored.
iImage
Index in the tree view control's image list of the icon image to use when the item is in the nonselected state.
If this member is the I_IMAGECALLBACK value, the parent window is responsible for storing the index. In this case, the tree view control sends the parent a TVN_GETDISPINFO notification message to get the index when it needs to display the image.
iSelectedImage
Index in the tree view control's image list of the icon image to use when the item is in the selected state.
If this member is the I_IMAGECALLBACK value, the parent window is responsible for storing the index. In this case, the tree view control sends the parent a TVN_GETDISPINFO notification message to get the index when it needs to display the image.
cChildren
Flag that indicates whether the item has associated child items. This member can be one of the following values:
zero | The item has no child items.
one | The item has one or more child items.
I_CHILDRENCALLBACK | The parent window keeps track of whether the item has child items. In this case, when the tree view control needs to display the item, the control sends the parent a TVN_GETDISPINFO notification message to determine whether the item has child items.
If the tree view control has the TVS_HASBUTTONS style, it uses this member to determine whether to display the button indicating the presence of child items. You can use this member to force the control to display the button even though the item does not have any child items inserted. This allows you to display the button while minimizing the control's memory usage by inserting child items only when the item is visible or expanded.
lParam
A 32-bit value to associate with the item.
iIntegral
Height of the item. This height is in increments of the standard item height (see TVM_SETITEMHEIGHT). By default, each item gets one increment of item height. Setting this member to two will give the item twice the standard height, setting this member to three will give the item three times the standard height, and so on. The tree view control does not draw in this extra area. This extra space can be used by the application for drawing when using custom draw.

Version 4.71


TVSORTCB

typedef struct tagTVSORTCB{
    HTREEITEM hParent;
    PFNTVCOMPARE lpfnCompare;
    LPARAM lParam;
} TVSORTCB, FAR *LPTVSORTCB;

Contains information used to sort child items in a tree view control. This structure is used with the TVM_SORTCHILDRENCB message. This structure is identical to the TV_SORTCB structure, but it has been renamed to follow current naming conventions.

hParent
Handle to the parent item.
lpfnCompare
Address of 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 TVITEM structure for the two items being compared. The lParamSort parameter corresponds to the lParam member of this structure.

lParam
Application-defined 32-bit value that gets passed as the lParamSort argument in the callback function specified in lpfnCompare.


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

Up-Down Control Updates in Internet Explorer

Up-Down Control Reference

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

Up-down control with an edit control as its buddy window.

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.

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

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 or WM_HSCROLL message. A vertical up-down control (which does not have the UDS_HORZ style) sends a WM_VSCROLL message. A horizontal up-down control (which has the UDS_HORZ style) sends a WM_HSCROLL message.

About Up-Down Control Styles

Using window styles, you can manipulate 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 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 or WM_HSCROLL 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 button 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 standard Windows messages processed 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 | Completes the position change.
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 | Completes the position change 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. If the wParam parameter is non-NULL, the control assumes that the value is an HDC and paints using that device context.
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 Updates in Internet Explorer

Up-down controls in Microsoft® Internet Explorer support the following new feature.

Full 32-bit Range
The up-down control now supports a full 32-bit range. The UDM_SETRANGE32 and UDM_GETRANGE32 messages have been added to support this feature. The up-down control uses signed integers for its range, so it is necessary to set the range from -0x7FFFFFFF to +0x7FFFFFFF to utilize the full 32-bit range.


Up-Down Control Reference

This section contains information about the following programming elements used with up-down controls.

Up-Down Control Styles

Functions
CreateUpDownControl

Messages
UDM_GETACCEL
UDM_GETBASE
UDM_GETBUDDY
UDM_GETPOS
UDM_GETRANGE
UDM_GETRANGE32
UDM_GETUNICODEFORMAT
UDM_SETACCEL
UDM_SETBASE
UDM_SETBUDDY
UDM_SETPOS
UDM_SETRANGE
UDM_SETRANGE32
UDM_SETUNICODEFORMAT

Notifications
NM_RELEASEDCAPTURE (up-down)
UDN_DELTAPOS

Structures
NM_UPDOWN
NMUPDOWN
UDACCEL


Up-Down Control Styles

The following styles are used when creating 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 is 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_HOTTRACK | Version 4.70. Not currently implemented.
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.


Up-Down Control Functions Up-Down Control Functions *
  * Previous Topic: Up-Down Control Styles
  * Next Topic: CreateUpDownControl

Up-Down Control Functions

This section contains information about the functions used with up-down controls.

CreateUpDownControl


CreateUpDownControl

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
);

Creates an up-down control.

  • If the function succeeds, the return value is the window handle to the up-down control. If the function fails, the return value is NULL.
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.


Up-Down Control Messages

This section contains information about the messages used with up-down controls.

UDM_GETACCEL

UDM_GETBASE

UDM_GETBUDDY

UDM_GETPOS

UDM_GETRANGE

UDM_GETRANGE32

UDM_GETUNICODEFORMAT

UDM_SETACCEL

UDM_SETBASE

UDM_SETBUDDY

UDM_SETPOS

UDM_SETRANGE

UDM_SETRANGE32

UDM_SETUNICODEFORMAT


UDM_GETACCEL

UDM_GETACCEL
    wParam = (WPARAM) cAccels;
    lParam = (LPARAM) (LPUDACCEL) paAccels;

Retrieves acceleration information for an up-down control.

  • The return value is the number of accelerator structures retrieved.

    If the cAccels parameter is zero and the paAccels parameter is NULL, the return value is the number of accelerators currently set for the control.

cAccels
Number of elements in the array specified by paAccels.
paAccels
Address of an array of UDACCEL structures that receive acceleration information.

See also UDM_SETACCEL


UDM_GETBASE

UDM_GETBASE
    wParam = 0;
    lParam = 0;

Retrieves the current radix base (that is, either base 10 or 16) for an up-down control.

  • The return value is the current base value.


UDM_GETBUDDY

UDM_GETBUDDY
    wParam = 0;
    lParam = 0;

Retrieves the handle to the current buddy window.

  • The return value is the handle to the current buddy window.


UDM_GETPOS

UDM_GETPOS
    wParam = 0;
    lParam = 0;

Retrieves the current position of an up-down control.

  • The return value is the current position in the low-order word. If an error occurred, the high-order word is nonzero.

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

UDM_GETRANGE
    wParam = 0;
    lParam = 0;

Retrieves the minimum and maximum positions (range) for an up-down control.

  • 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_GETRANGE32

UDM_GETRANGE32
    wParam = (WPARAM)(LPINT) pLow;
    lParam = (LPARAM)(LPINT) pHigh;

Retrieves the 32-bit range of an up-down control.

  • The return value for this message is not used.
pLow
Address of a signed integer that receives the lower limit of the up-down control range. This parameter may be NULL.
pHigh
Address of a signed integer that receives the upper limit of the up-down control range. This parameter may be NULL.

Version 4.71


UDM_GETUNICODEFORMAT

UDM_GETUNICODEFORMAT
    wParam = 0;
    lParam = 0;

Retrieves the UNICODE character format flag for the control.

  • Returns the UNICODE format flag for the control. If this value is nonzero, the control is using UNICODE characters. If this value is zero, the control is using ANSI characters.

See also UDM_SETUNICODEFORMAT


UDM_SETACCEL

UDM_SETACCEL
    wParam = (WPARAM) nAccels;
    lParam = (LPARAM) (LPUDACCEL) aAccels;

Sets the acceleration for an up-down control.

  • Returns TRUE if successful, or FALSE otherwise.
nAccels
Number of UDACCEL structures specified by aAccels.
aAccels
Address of an array of UDACCEL structures that contain acceleration information. Elements should be sorted in ascending order based on the nSec member.

See also UDM_GETACCEL


UDM_SETBASE

UDM_SETBASE
    wParam = (WPARAM) nBase;
    lParam = 0;

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.

  • The return value is the previous base value. If an invalid base is given, the return value is zero.
nBase
New base value for the control. This parameter can be 10 for decimal or 16 for hexadecimal.


UDM_SETBUDDY

UDM_SETBUDDY
    wParam = (WPARAM) (HWND) hwndBuddy;
    lParam = 0;

Sets the buddy window for an up-down control.

  • The return value is the handle to the previous buddy window.
hwndBuddy
Handle to the new buddy window.


UDM_SETPOS

UDM_SETPOS
    wParam = 0;
    lParam = (LPARAM) MAKELONG((short) nPos, 0);

Sets the current position for an up-down control.

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


UDM_SETRANGE

UDM_SETRANGE
    wParam = 0;
    lParam = (LPARAM) MAKELONG((short) nUpper, (short) nLower);

Sets the minimum and maximum positions (range) for an up-down control.

  • No return value.
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.

The maximum position can be less than the minimum position. Clicking the up arrow button moves the current position closer to the maximum position, and clicking the down arrow button moves towards the minimum position.


UDM_SETRANGE32

UDM_SETRANGE32
    wParam = (WPARAM)(int) iLow;
    lParam = (LPARAM)(int) iHigh;

Sets the 32-bit range of an up-down control.

  • The return value for this message is not used.
iLow
Signed integer value that represents the new lower limit of the up-down control range.
iHigh
Signed integer value that represents the new upper limit of the up-down control range.

Version 4.71


UDM_SETUNICODEFORMAT

UDM_SETUNICODEFORMAT
    wParam = (WPARAM)(BOOL)fUnicode;
    lParam = 0;

Sets the UNICODE character format flag for the control. This message allows you to change the character set used by the control at run time rather than having to re-create the control.

  • Returns the previous UNICODE format flag for the control.
fUnicode
Determines the character set that is used by the control. If this value is nonzero, the control will use UNICODE characters. If this value is zero, the control will use ANSI characters.

See also UDM_GETUNICODEFORMAT


Up-Down Control Notification Messages

This section contains information about the notification messages sent by up-down controls.

NM_RELEASEDCAPTURE (up-down)

UDN_DELTAPOS


NM_RELEASEDCAPTURE (up-down)

NM_RELEASEDCAPTURE
    lpnmh = (LPNMHDR) lParam;

Notifies an up-down control's parent window that the control is releasing mouse capture. This notification is sent in the form of a WM_NOTIFY message.

  • The control ignores the return value from this notification.
lpnmh
Address of an NMHDR structure that contains additional information about this notification message.

Version 4.71.


UDN_DELTAPOS

UDN_DELTAPOS
    lpnmud = (LPNMUPDOWN) lParam;

Sent by the operating system 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 in the form of a WM_NOTIFY message.

  • Return nonzero to prevent the change in the control's position, or zero to allow the change.
lpnmud
Address of an NMUPDOWN 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 the up button, this is a positive value. If the user has clicked the down button, this is a negative value.

The UDN_DELTAPOS notification is sent before the WM_VSCROLL or WM_HSCROLL message, which actually changes the control's position. This lets you examine, allow, modify, or disallow the change.

See also WM_COMMAND


Up-Down Control Structures

This section contains information about the structures used with up-down controls.

NMUPDOWN

UDACCEL


NMUPDOWN

typedef struct _NM_UPDOWN {
    NMHDR hdr;
    int   iPos;
    int   iDelta;
} NMUPDOWN, FAR *LPNMUPDOWN;

Contains information specific to up-down control notification messages. It is identical to and replaces the NM_UPDOWN structure.

hdr
NMHDR structure that contains additional information about the notification message.
iPos
Signed integer value that represents the up-down control's current position.
iDelta
Signed integer value that represents the proposed change in the up-down control's position.

Version 4.70

See also UDN_DELTAPOS, WM_NOTIFY


UDACCEL

typedef struct {
    UINT nSec;
    UINT nInc;
}UDACCEL, FAR *LPUDACCEL;

Contains acceleration information for an up-down control.

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.


Backward Compatible Wizard97

[This is preliminary documentation and subject to change.]

Synopsis

This document summarizes changes in design for a new wizard user interface style.


Legal Information

[This is preliminary documentation and subject to change.]

This is a preliminary document and may be changed substantially prior to final commercial release. This document is provided for informational purposes only and Microsoft makes no warranties, either express or implied, in this document. Information in this document is subject to change without notice. The entire risk of the use or the results of the use of this document remains with the user. The names of companies, products, people, characters, and/or data mentioned herein are fictitious and are in no way intended to represent any real individual, company, product, or event, unless otherwise noted. Complying with all applicable copyright laws is the responsibility of the user. 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. If, however, your only means of access is electronic, permission to print one copy is hereby granted.

Portions of this document specify and accompany software that is still in development. Some of the information in this documentation may be inaccurate or may not be an accurate representation of the functionality of final documentation or software. Microsoft assumes no responsibility for any damages that might occur directly or indirectly from these inaccuracies.

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

© 1997 Microsoft Corporation. All rights reserved.

Microsoft, MS, Windows, and Windows NT are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries.

Other product and company names mentioned herein may be the trademarks of their respective owners.


Contents

[This is preliminary documentation and subject to change.]

Introduction and Goals

Features

Graphic Design and Layout

  1. Welcome and Completion pages
  2. Interior Pages
  3. Margin recommendations
  4. Paragraph and control spacing and layout
  5. Fonts

    Test Usage

  6. Welcome page text
  7. Interior pages header text
  8. Completion page text

Appendix

Diagram B1Back: Welcome and Completion pages

Diagram B2Back: Interior pages

Diagram C1: Paragraph spacing measurements in dialog units

Diagram C2: Control spacing measurements in dialog units

Development Information


Introduction

[This is preliminary documentation and subject to change.]

It is important, with the release of new versions and new products, to continually improve and update 'look and feel' of wizards as well as improve the user interface models as much as possible.


Goals

[This is preliminary documentation and subject to change.]

The primary goals for the new wizard design are:

  • To update and improve overall graphic design styling and layout:

    The new design calls for a new graphics style and a larger wizard size. (The UI design team is currently reviewing graphics styles and palette issues for the Wizard97 style. The next revision of this spec will include design and palette information for graphics)

    In addition, by slightly enlarging the overall wizard size, layout of wizard text and controls can be improved. Also, some 'negative space' within this slightly larger wizard gives a more contemporary look.

  • To provide a consistent and helpful user interface throughout the entire wizard:

    Wizards have been inconsistent in their use of introductory and finish pages, interior page titles (or the lack of) and their presentation of information. In the new wizard's Welcome page design, a general explanation of the Wizard's task or purpose is stated. A list of the main or specific tasks can also be included. On all interior pages, a header area will name the task particular to each page and include a brief one-sentence description. The Completion page can contain either a general description of what was accomplished by the wizard or actually list the specific items completed by the user. Following these simple guidelines will create consistent and easy to follow wizards.


Features

[This is preliminary documentation and subject to change.]

Graphic Design and Text Layout

  1. For the Welcome and Completion pages, a main graphic in the form of a bitmap covers the entire 'page' area. The text is placed on top of the bitmap. See Diagram B1Back.
  2. For the interior pages of the wizard, a header graphic in the form of a bitmap covers the entire header area. See Diagram B2Back. It is not desirable to have a different header graphic for each interior wizard page. The header graphic should reflect the design of the main graphic.
  3. The left and right margins in the Welcome and Completion pages should follow the diagram specifications. However, in the Interior wizard pages, depending on the content of the page, the margins can vary between the two specifications given in Diagram B2 Back for a normal margin or a small margin. Only use the small margin when the page contains particularly wide content; such as side by side list boxes.
  4. Paragraph and control spacing and layout. Please refer to Diagrams C1 and C2.
  5. The fonts: For the Welcome and Completion pages, 14 point Times New Roman bold is used for the large Wizard title, 8 point MS Sans bold for the initial line above the title, and 8 point MS Sans regular (MS Shell Dialog font) for all descriptive text. For the interior pages, the title in the header section is in MS Sans Bold and all other text is MS Shell Dialog.

Development Note: The title font name and size should be loaded from the resource file thus allowing localizers the ability to change it. If the wizard being designed is a system component, development should specify the font name as "MS Shell Dlg". This will allow system to remap the font if necessary.

Text Usage

To promote usability, the new wizard style provides for statements of purpose and summation on the Welcome and Completion pages respectively, and clearer, more consistent Interior page text in the form of a title and task description in the header section of each page.

A. Welcome page text:

States: 'Welcome to the (name that) Wizard', then gives a comprehensive explanation of the wizard's purpose. It can begin by stating, "This wizard helps you to…" (Example: This wizard helps you to create a new user account on this computer)." When appropriate, a list of the tasks performed by the wizard can be included. See Diagram B1Back

B. Interior pages header section text:

This text includes a short title that defines the subject or task of that particular page followed by a one-sentence description of the task to be perfomed by the page. See Diagram B2Back

The one-sentence description below the title can be written in several ways: as a question, as a description, or as a command (Imperative tense). Examples follow:

  1. As a question:

    Computer Operating System (title)

    Is the computer's operating system set up to operate with Small Business Server?

  2. As a description of the purpose of the particular page:

    Installing the Computer Operating System (title)

    Installation files will be copied to your hard drive.

  3. As a description in the second person singular:

    Sounds (title)

    You can choose a sound scheme then preview its different sound events.

  4. As a command (Imperative):

    User Permissions (title)

    Specify what the user is allowed to do.

C. Completion page text:

States: 'Completing the (name that) Wizard' and also – 'You have successfully …(done such and such)'. In some wizards it might be appropriate to actually list the tasks the user completed.


Appendix

[This is preliminary documentation and subject to change.]

Development:

Please use this specification when producing the new wizard style when backward compatibility with Microsoft® Windows NT® and Microsoft Windows® 95 is required. This wizard should be built using the same common controls as a typical Microsoft Windows 95 style wizard – but with the different page layout and use of graphics as described in this specification.

Note If the wizard you are building is going to be localized, The title font name and size should be loaded from the resource file, thus allowing localizers the ability to change it. If the wizard being designed is a system component, development should specify the font name as "MS Shell Dlg". This will allow a system to remap the font if necessary.


Wizard97

[This is preliminary documentation and subject to change.]

Synopsis

This document summarizes changes in design and development for a new wizard user interface style.


Contents

[This is preliminary documentation and subject to change.]

Introduction and Goals

Features

Graphic Design and Layout

  1. Welcome and Completion pages
  2. Interior Pages
  3. Margin recommendations
  4. Paragraph and control spacing and layout
  5. Fonts

    Test Usage

  6. Welcome page text
  7. Interior pages header text
  8. Completion page text

Appendix

Diagram B1: Welcome and Completion pages

Diagram B2: Interior pages

Diagram C1: Paragraph spacing measurements in dialog units

Diagram C2: Control spacing measurements in dialog units

Development Information


Goals

[This is preliminary documentation and subject to change.]

The primary goals for the new wizard design are:

  • To update and improve overall graphic design styling and layout:

    The new design calls for a new graphics style and a larger wizard size. (The UI design team is currently reviewing graphics styles and palette issues for the Wizard97 style. The next revision of this specification will include design and palette information for graphics)

    In addition, by slightly enlarging the overall wizard size, layout of wizard text and controls can be improved. Also, some 'negative space' within this slightly larger wizard gives a more contemporary look.

  • To provide a consistent and helpful user interface throughout the entire wizard:

    Wizards have been inconsistent in their use of introductory and finish pages, interior page titles (or the lack of) and their presentation of information. In the new wizard's Welcome page design, a general explanation of the Wizard's task or purpose is stated. A list of the main or specific tasks can also be included. On all interior pages, a header area will name the task particular to each page and include a brief one-sentence description. The Completion page can contain either a general description of what was accomplished by the wizard or actually list the specific items completed by the user. Following these simple guidelines will create consistent and easy to follow wizards.


Features

[This is preliminary documentation and subject to change.]

Graphic Design and Text Layout

  1. For the Welcome and Completion pages, a main graphic in the form of a bitmap covers the entire 'page' area. The text is placed on top of the bitmap. See Diagram B1. Note: The new wizard controls (see Appendix: Development) will use whatever palette comes with the graphics.
  2. For the Interior pages of the wizard, a header graphic in the form of a bitmap covers the entire header area. See Diagram B2. This graphic is automatically generated by the new wizard control – which grabs the top of the main graphic mentioned above, and inserts it in the header section of each interior page. Thus, designers should keep in mind that the top 59 pixels of the main graphic will be highly visable throughout the wizard.

    However, a unique header graphic can be designed and placed in the header sections if the wizard developer sets a flag in the Wizard97 common control code to allow this insertion. This unique header graphic will appear on all interior pages. It is not desirable to have a different header graphic for each interior wizard page. The header graphic should reflect the design of the main graphic.

  3. The left and right margins in the Welcome and Completion pages should follow the Diagram B1 specifications. However, in the Interior wizard pages, depending on the content of the page, the margins can vary between the two specifications given in Diagram B2 for a normal margin or a small margin. Only use the small margin when the page contains particularly wide content; such as side by side list boxes.
  4. Paragraph and control spacing and layout. Please refer to Diagrams C1 and C2 for spacing recommendations given in dialog units (dlus).
  5. The fonts: For the Welcome and Completion pages, 14 point Times New Roman Bold is used for the large Wizard title, 8 point MS Sans Bold for the initial line above the title, and 8 point MS Sans (MS Shell Dialog font) for all descriptive text. For the interior pages, the new wizard controls automatically generate the title in the header section in MS Sans Bold and the subtitle in MS Shell Dialog. The text in the body of the page should be MS Shell Dialog.

Development Note: In the Welcome and Completion pages, the title font name and size should be loaded from the resource file thus allowing localizers the ability to change it. If the wizard being designed is a system component, development should specify the font name as "MS Shell Dlg". This will allow system to remap the font if necessary.

Text Usage

To promote usability, the new wizard style provides for statements of purpose and summation on the Welcome and Completion pages respectively, and clearer, more consistent Interior page text by requiring a title and a subtitle in the header section of each page.

A. Welcome page text:

States: 'Welcome to the (name that) Wizard', then gives a comprehensive explanation of the wizard's purpose. It can begin by stating, "This wizard helps you to…" (Example: This wizard helps you to create a new user account on this computer)." When appropriate, a list of the tasks performed by the wizard can be included. See Diagram B1

B. Interior pages header section text:

This text includes a short title that defines the subject or task of that particular page followed by a one-sentence description of the task to be perfomed by the page. See Diagram B2

The one-sentence description below the title can be written in several ways: as a question, as a description, or as a command (Imperative tense). Examples follow:

  1. As a question:

    Computer Operating System (title)

    Is the computer's operating system set up to operate with Small Business Server?

  2. As a description of the purpose of the particular page:

    Installing the Computer Operating System (title)

    Installation files will be copied to your hard drive.

  3. As a description in the second person singular:

    Sounds (title)

    You can choose a sound scheme then preview its different sound events.

  4. As a command (Imperative):

    User Permissions (title)

    Specify what the user is allowed to do.

C. Completion page text:

States: 'Completing the (name that) Wizard' and also – 'You have successfully …(done such and such)'. In some wizards it might be appropriate to actually list the tasks the user completed.


Appendix

[This is preliminary documentation and subject to change.]

Development:

Please see the PROPSHEETHEADER and PROPSHEETPAGE references for details on PSH_WIZARD97.


Topic Not Found

No matching topic was found. Some possible reasons and remedies are as follows:

  • The file (.chm) that contains the destination topic is not in the expected location.

    Remedy: Rerun the MSDN Library Setup.

  • The file (.chm) that contains the current topic or destination topic is out-of-date and the link is no longer valid.

    Remedy: Install the latest version of the MSDN Library.

  • The MSDN Library CD is not in the CD-ROM drive.

    Remedy: Insert the MSDN Library CD into the CD-ROM drive.


Contents

Dynamic HTML *
  • Dynamic Styles
    • Changing Element Styles
    • Managing Style Sheets
    • Style Sheets and Printing
  • Dynamic Content
    • Using the TextRange Object
    • Finding Text in the Document
  • Positioning
    • What Is Positioning?
    • Absolute Positioning
    • Relative Positioning
    • Positioning Considerations
    • Controlling Content Visibility
    • Element Visibility
  • Filters and Transitions
    • Creating Multimedia Effects with Visual Filters and Transitions
    • Defining Visual Filters
    • Scripting Filters
    • Migrating from OBJECT-based Filters
    • Filter Design Considerations
    • Visual Filter Scenarios
    • Transitions
    • Interpage Transitions
    • Transition Design Considerations
    • Transition Scenarios
    • Visual and Transition Filters Reference
    • Visual Filter Effects Reference
    • Properties, Methods, and Events Reference
  • Font Embedding
    • Embedded Font Technology
    • Embedded Font Examples
    • Limitations in Internet Explorer 4.0
    • Internet Explorer 4.0 Security Alert
    • Using Microsoft WEFT
  • Data Binding
    • Data Binding Architecture
    • Adding a Data Source Object to a Page
    • Binding HTML Elements to Data
    • DHTML Object Model Support for Data Binding
    • DHTML Event Model Support for Data Binding
  • Document Object Model
    • Working with Windows, Frames, and Dialogs
    • Scripting with Elements and Collections
    • Understanding the Event Model
    • Cross-Frame Scripting and Security
  • DHTML Accessibility
  • DHTML References
    • Document Object Model References
    • HTML References
    • CSS Attributes Reference
    • Additional References
  • DHTML Tutorials
  • JScript & VBScript Tutorials and References
    • JScript Tutorial
    • JScript Language Reference
    • VBScript Tutorial
    • VBScript Language Reference
  • Multimedia
  • Samples and Tools
  • Cross-Platform Functionality
Delivering Content
to the Web 		*
  • Content Delivery Mechanisms
  • The User Experience
    • Active Channels
    • Active Desktop Items
    • Software Update Channels
  • Authoring for New Delivery Mechanisms
    • Creating Active Channels
    • Creating Active Desktop Items
    • Creating Software Update Channels
  • CDF Reference
    • CDF Reference for Active Channels
    • CDF Extensions for Active Desktop Items
    • CDF Extensions for Software Update Channels
  • Tools
    • Microsoft CDF Generator
    • Profile Assistant
Component Development *
  • COM Objects for the Internet
  • ActiveX Controls
    • Introduction to ActiveX Controls
    • Building ActiveX Controls for Internet Explorer 4.0
    • ActiveX Control Tutorial
    • Safe Initialization and Scripting for ActiveX Controls
    • Licensing ActiveX Controls
    • Signing Code with Microsoft Authenticode Technology
    • Packaging ActiveX Controls
    • Palette Management for ActiveX Objects
    • Registering an ActiveX Object as the Player for a Media Type
  • ActiveX Control Containers
  • Active Documents
    • Programming an Active Document Server
    • Programming an Active Document Container
    • Reference
  • ActiveX Scripting
    • Active Script Debugging Interfaces
    • ActiveX Scripting Hosts
    • ActiveX Scripting Engines
    • IDispatchEx
    • IProvideMultipleClassInfo
  • Microsoft Scriptlet Technology
Internet Tools & Technologies *
  • Active Desktop Interface
  • Asynchronous and URL Monikers
    • Asynchronous and URL Monikers Overview
    • Asynchronous and URL Monikers Reference
  • Cache Container Tool
  • Common Controls
    • Common Controls
    • Custom Draw
    • Animation Controls
    • ComboBoxEx Controls
    • Date and Time Picker Controls
    • Drag List Boxes
    • Flat Scroll Bars
    • Header Controls
    • Hot Key Controls
    • Image Lists
    • IP Address Controls
    • List View Controls
    • Month Calendar Controls
    • Pager Controls
    • Progress Bar Control
    • Property Sheets
    • Rebar Controls
    • Status Bars
    • Tab Controls
    • Toolbar Controls
    • Tooltip Controls
    • Trackbar Controls
    • Tree View Controls
    • Up-Down Controls
  • Microsoft CryptoAPI 2.0
  • Microsoft DirectX Media SDK
  • Hit Logging API
  • HTML Clipboard Format
  • HTMLHelp API Reference
  • Hyperlinks
  • IE4/MSHTML Data Binding Interfaces
    • COM Objects as Data Providers
    • OLE-DB Simple Provider: A Data Binding API for IE4/MSHTML
    • Java Applets as Data Providers
    • OLE-DB Simple Provider for Java: A Data Binding API for IE4/MSHTML
  • Information Delivery API
    • Microsoft Information Delivery API Overview
    • Microsoft Information Delivery API Reference
  • Microsoft Internet Component Download
    • Microsoft Internet Component Download Overview
    • Microsoft Internet Component Download Reference
  • Internet Explorer Address Book
  • Internet Mail and News Registry Layout
  • Internet Ratings
  • Internet Shortcuts API Reference
  • Offline Browsing
  • Open Software Description (OSD)
    • Open Software Description Overview
    • Open Software Description Reference
  • Pluggable Protocols
    • Pluggable Protocols Overview
    • Pluggable Protocols Reference
  • Predefined Protocols
  • Programming the Document Object Model from C/C++
  • Reusing the WebBrowser and MSHTML
    • Overview
    • HTML Dialog Boxes
    • Reusing the WebBrowser Control
    • Reusing MSHTML
    • Advanced Hosting Interfaces
    • Dependencies
    • Licensing and Distribution
  • Microsoft Script Debugger for Internet Explorer
  • Task Scheduler API
    • About the Task Scheduler
    • Programming the Task Scheduler
    • Task Scheduler Reference
  • URL Security Zones
    • URL Security Zones Overview
    • URL Security Zones Reference
  • Microsoft Web Publishing SDK
    • Web Publishing Overview
    • Web Publishing Programmer's Reference
  • Windows Scripting Host
  • Windows Shell API
    • Shell Versions
    • Application Desktop Toolbars
    • Band Objects
    • Briefcase Reconcilers
    • Control Panel Applications
    • Debugging With the Shell
    • Dragging and Dropping
    • File Manager Extensions
    • File Parsers
    • File Viewers
    • Help
    • Screen Saver Library
    • Shell Dynamic Data Exchange Interface
    • Shell Extensions
    • Shell Library
    • Shell Links
    • Shell Namespace
    • Shell Objects for Scripting and Visual Basic
    • Shell Utility APIs
    • Taskbar
    • Shell Reference
  • WinInet API
    • Microsoft Win32 Internet Functions Overview
    • Microsoft Win32 Internet Functions Reference
  • XML Object Model
Component Library *
  • ActiveMovie Control
  • Microsoft ActiveX Data Objects
  • Microsoft Agent
  • Microsoft Chat Controls
    • Microsoft Chat Control 1.1
    • Microsoft Chat Protocol 2.0
    • Microsoft Chat 1.0j
  • NetMeeting API
  • Microsoft NetShow
  • Microsoft Remote Data Service
  • Tabular Data Control (TDC)


Authoring Data Binding for Other Browsers

This article guides Web authors through the process of developing pages that support data binding while still maintaining compatibility with down-level browsers.

When writing content for the Internet, Web authors are often interested in reaching the widest possible audience, and that means creating content that works with the myriad of available Web browsers. This section shows authors how to use server scripts to construct pages that are targeted toward both Microsoft® Internet Explorer 4.0 and other down-level browsers. By detecting the user agent on the server, Web authors can provide a superior user experience by taking advantage of the data binding features in Internet Explorer 4.0 and still maintain compatibility with other clients that do not support data binding.

Most pages that deal with data provide the user with one or more of the following capabilities:

  • Displaying the current record. Navigational support allows the user to sequentially view additional records.

  • Displaying all the records that meet a given criteria. These records are typically displayed in tabular format.

  • Updating the data. Elements on the page can be edited, and changes can be synchronized with the database.

Given these features, the Web author should consider the implementation of four functional areas so that they leverage Internet Explorer 4.0 and are still compatible with other browsers:

  • Generating a Template on the Server
  • Conditionally Supplying Data Source Objects
  • Scripting the User interface
  • Supporting Data Update

Generating a Template on the Server

Typically, a template processor, such as Active Server Pages (ASP), is used to generate HTML on the server before sending it to the client. The template processor accesses the data and expands the template into an HTML page that contains the data. To take advantage of the Internet Explorer 4.0 data binding features, authors should take the following steps when authoring their pages:

  • Isolate the elements on the page into groups of bound elements and static elements. To accomplish this, break the page into frames, or isolate portions of the page using the DIV element.

  • For current record functionality:

    1. Write a server-side template that displays the bound elements in the page.

    2. Within this template, differentiate between browsers as follows:

      • For Internet Explorer 4.0, write out the elements with the data binding attributes.

      • For other browsers, perform the same operations as today.

That is, expand the template with a single record and manage state on the server so a page with the next and previous records can be sent to users when requested.

  • For table repetition functionality:

    1. For Internet Explorer 4.0, write out only the table template with the data binding attributes.

    2. For other browsers, perform the same operations as today. That is, expand the table on the server and generate the HTML.

Examples

The following examples demonstrate current record functionality and table repetition.

Current record functionality

When Internet Explorer is the browser, include the current record template in the page.

First create a frame set as the base document.

<FRAMESET ROWS="20%, 50%, 30%">
<FRAME SRC="nav.htm" NAME="nav_frame" SCROLLING=NO NORESIZE>
<FRAME SRC="product.asp" NAME="product_frame" SCROLLING=NO NORESIZE>
<FRAME SRC="similar.asp" NAME="similar_frame" SCROLLING=YES NORESIZE>
</FRAMESET>

In the server-side script, author code to conditionally build the page.

.
.
.
<DIV DATASRC="#ProductList" DATAFLD="Product_Title">
    <% If Not IsIE4OrLater() Then %> <%= RSProductList("Product_Title") %>
    <% End If %>
</DIV>

<HR>

<H2>Overview</H2>

.
.
.
Price: <INPUT TYPE=TEXT DATASRC=#ProductList      DATAFLD="Column9"     <% If Not IsIE4OrLater() Then %>     VALUE=<%= RSProductList("Price")%>     <% End If %>>
.
.
.

RSProductList is a reference to a recordset opened at the start of the page (not shown). This recordset is only created on the server if Internet Explorer 4.0 is not the browser.

When Internet Explorer 4.0 is not being used, the contents of the DIV is filled with data from the Title field in the database, and the VALUE of the INPUT tag is set to the value supplied by the recordset. When Internet Explorer 4.0 is used, these elements are synchronized with data supplied by the data source object on the client side. The DATASRC attribute is applied in both cases since down-level browsers ignore unrecognized tags. Code to insert a data source object when the browser is Internet Explorer 4.0 is shown below.

Table Repetition

When Internet Explorer 4.0 is the browser, the frame identified as similar_frame in the above FRAMESET example contains a template in which the table containing the list of similar products is bound on the client.

The code for the table follows:

<TABLE DATASRC="#SimilarList">
  <% If Not IsIE4OrLater() Then %>
    <% Do While Not RsSimilarList.EOF %>
      <TR> <TD><%= RsSimilarList("Product Name") %></TD> <TD><%= RsSimilarList("Price") %></TD>
      </TR>
    <% RsSimilarList.MoveNext
       Loop
    %>
  <% Else %>
      <TR> <TD><SPAN DATAFLD="#Product_Title"></SPAN></TD> <TD><SPAN DATAFLD="#Price"></SPAN></TD>
      </TR>
  <% End If %>
</TABLE>

When Internet Explorer 4.0 is not the client browser, the server expands the table with the rows on the server. When Internet Explorer 4.0 is the browser, data binding is used. In either case, the DATASRC attribute is applied to the TABLE because down-level browsers simply ignore it.

Conditionally Supplying Data Source Objects

To enable data binding on the client, Internet Explorer 4.0 uses a data source object (DSO) on the page to supply the data. Other browsers rely on server processing to merge data from a database into an HTML template. A number of approaches can be used to conditionally include the DSO on the page:

Examples

Write a conditional statement in the server script that includes the DSO only when Internet Explorer 4.0 is detected as the browser.

<% If IsIE4OrLater() Then %>
    <OBJECT ID=DSC1 CLASSID="clsid:..."> <PARAM
    </OBJECT>
<% End If %>

Write client-side script that first checks the browser version and then dynamically adds the object to the page if appropriate. The following code relies upon the existence of a DIV element as a placeholder and sets its innerHTML property to an OBJECT tag represented by a Tabular Data Control.

<SCRIPT>
if (((navigator.appVersion.indexOf("4.0")>0)
    && (navigator.appVersion.indexOf("MSIE"))>0)) divDSO.innerHTML = "<OBJECT      classid="clsid:333C7BC4-460F-11D0-BC04-0080C7055A83"     ID=tdcComposers HEIGHT=0 WIDTH=0>         <PARAM NAME="DataURL" VALUE="composer.csv">         <PARAM NAME="UseHeader" VALUE="True">     </OBJECT>";
</SCRIPT>

Include the object tag regardless of the browser type. Non-Internet Explorer 4.0 browsers will ignore the component.

Scripting the User Interface

Since Internet Explorer 4.0 performs all data operations such as navigation on the client, while other browsers require a round-trip to the server and a new page to be rendered, authors should detect the user agent and script user interface elements to work in both scenarios.

Example

The following example illustrates event-handling code behind a button that moves to the next record in the data set. This script can be used on all browsers.

<SCRIPT FOR=cmdNext EVENT=onclick>
    if (((navigator.appVersion.indexOf("4.0")>0) &&     (navigator.appVersion.indexOf("MSIE"))>0)) document.product_frame.dsc1.recordset.MoveNext();
    else <!-- ask server for new page containing next record -->
</SCRIPT>

Supporting Data Update

The current model for presenting data to users for update requires writing a form and then using the HTML SUBMIT functionality to send the updates to the server, where a server process changes the values in the database. A more detailed look at this model follows:

  1. A page is displayed on the client consisting of a form page containing elements for user input as well as a Submit button. The values of the elements are set to the current values in the database.

  2. After the user completes the edits, she clicks the Submit button.

  3. All the data on the form is sent to a server process (CGI, ISAPI, ASP). The process determines which data was changed and updates the database appropriately.

  4. The process returns an HTML page to the browser indicating the success or failure of the update.

To incorporate the Internet Explorer 4.0 data binding model into this scenario, the author can do the following:

  1. Add a data source object (DSO) that supports data update to the page.

  2. Use the data binding extensions to bind the user input elements on the page to the DSO.

  3. Allow the user to modify the data.

  4. Provide the user with an element, such as a button, that calls the DSO-specific method that commits changes and updates the database. For RDS this method is SubmitChanges.

Using Internet Explorer 4.0, the user remains on the page to do subsequent processing. A new page is not required because changes are committed to the data on the back end.

Example

In the example scenario, the price of the product is displayed. The user can edit this price by changing the data in the text box. This behavior is identical in all browsers. The key difference is the code behind the button that submits the data. In Internet Explorer 4.0, this button calls the DSO-specific method that commits the changes. Other browsers require the use of a Submit button.

The script for a Submit button follows:

<SCRIPT>
  <SCRIPT FOR=cmdSubmit EVENT=onclick>
  {
    if (((navigator.appVersion.indexOf("4.0")>0) &&       (navigator.appVersion.indexOf("MSIE"))>0))
    {
      document.ProductList.SubmitChanges();
      return false; // disable default processing
    }
  }
</SCRIPT>


Internet Client SDK

Internet Client SDK Internet Client SDK *
 Last Updated: December 19, 1997
Internet Client SDK Top Menu

The Internet Client SDK makes it easy to find what you need. The tools, information, and samples are divided into the following downloadable components. This content is best viewed with Internet Explorer 4.0 or later. Navigate to the Internet Explorer download page to get the latest version.

Dynamic HTML

Dynamic HTML Illustrates the innovative features that allow content providers to create compelling content for the Web.

Delivering Content to the Web

 Delivering Content to the Web Contains information on new ways Web publishers can deliver their content with Internet Explorer 4.0 and explains several new features using "push" technologies, including Active Channels, Active Desktop items, and Software Update Channels.

Component Development

 Component Development Provides the hard-core details you need to create ActiveX Controls and Java applets for your own applications.

Internet Tools & Technologies

 Inet SDK Describes the services and technologies provided with Internet Explorer 4.0 and explains how to exploit them in your own components and applications.

Component Library

 Component Library Contains documentation on reusable components that can be used to enhance your Web pages.

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


Further Reading

The descriptions for the following items are contained in the Microsoft® Platform Software Development Kit (SDK).

CLSCTX
CLSIDFromProgID
CoCreateInstance
CoInitialize
CoUninitialize
CoTaskMemAlloc
CoTaskMemFree
DoDragDrop
DVTARGETDEVICE
FAILED
FORMATETC
GetClassFile
IAdviseSink::OnViewChange
IAdviseSink
IBindCtx::RegisterObjectBound
IBindCtx
ICatRegister::RegisterClassImplCategories
IClassFactory::CreateInstance
IClassFactory::LockServer
IClassFactory
IConnectionPoint::Unadvise
IConnectionPoint
IConnectionPointContainer
IDataObject::EnumFormatEtc
IDataObject::GetData
IDataObject::GetDataHere
IDataObject::QueryGetData
IDataObject::SetData
IDataObject
IDropSource::GiveFeedback
IDropSource::QueryContinueDrag
IDropSource
IDropTarget::DragEnter
IDropTarget::DragLeave
IDropTarget::DragOver
IDropTarget::Drop
IDropTarget
IEnumFORMATETC
IEnumString
IEnumXXXX
IMalloc::Free
IMalloc
IMoniker::BindToObject
IMoniker::BindToStorage
IMoniker::GetDisplayName
IMoniker::ParseDisplayName
IMoniker
IObjectWithSite
IOleClientSite
IOleControlSite::TranslateAccelerator
IOleInPlaceActiveObject::EnableModeless
IOleInPlaceActiveObject::OnDocWindowActivate
IOleInPlaceActiveObject::OnFrameWindowActivate
IOleInPlaceActiveObject::ResizeBorder
IOleInPlaceActiveObject::TranslateAccelerator
IOleInPlaceActiveObject
IOleInPlaceFrame::EnableModeless
IOleInPlaceFrame::InsertMenus
IOleInPlaceFrame::RemoveMenus
IOleInPlaceFrame::SetMenu
IOleInPlaceFrame::SetStatusText
IOleInPlaceFrame
IOleInPlaceObject::InPlaceDeactivate
IOleInPlaceObject
IOleInPlaceSite::OnInPlaceActivate
IOleInPlaceSite::OnUIActivate
IOleInPlaceSite::OnUIDeactivate
IOleInPlaceSite
IOleInPlaceUIWindow
IOleObject::Advise
IOleObject::DoVerb
IOleObject::GetUserClassID
IOleObject::GetUserType
IOleObject::SetClientSite
IOleObject
IOleWindow::GetWindow
IOleWindow
IParseDisplayName::ParseDisplayName
IParseDisplayName
IPersist::GetClassID
IPersist
IPersist*::InitNew
IPersist*::Load
IPersist*::Save
IPersist*
IPersisteMoniker::Load
IPersistFile::GetCurFile
IPersistFile::IsDirty
IPersistFile::Load
IPersistFile::Save
IPersistFile::SaveCompleted
IPersistFile
IPersistStorage::InitNew
IPersistStorage::Load
IPersistStorage
IPersistStream
IPersistStreamInit::InitNew
IPersistStreamInit
IPropertyNotifySink
IServiceProvider::QueryService
IServiceProvider
IStorage::CreateStorage
IStorage::CreateStream
IStorage::Stat
IStorage
IStream::Read
IStream
AddRef
IUnknown::AddRef
IUnknown::QueryInterface
QueryInterface
IUnknown::Release
Release
IUnknown
IViewObject::GetColorSet
MkParseDisplayName
OleCreateFromData
OleCreateFromFile
OleInitialize
OleRun
OleSave
OleUninitialize
ResultFromScode
RevokeDragDrop
STGM
MAPI
ACCELERATEABSDI
DISMISSMODELESS
IAddrBook
IMAPIFolder
IMAPIProp
IMAPITable
IMessage
MAPIAllocateBuffer
MAPIAllocateMore
MAPIFreeBuffer
MAPINAMEID
BSTR
EXCEPINFO
IDispatch::GetIDsOfNames
IDispatch::GetTypeInfo
IDispatch::GetTypeInfoCount
IDispatch::Invoke
ITypeInfo
IDispatch
SAFEARRAY
VARIANT
VARIANTARG
VariantInit
ERROR_INSUFFICIENT_BUFFER
HRESULT
BORDERWIDTHS
CB_DELETESTRING
CB_FINDSTRINGEXACT
CB_GETCOUNT
CB_GETCURSEL
CB_GETDROPPEDCONTROLRECT
CB_GETDROPPEDSTATE
CB_GETEXTENDEDUI
CB_GETITEMDATA
CB_GETITEMHEIGHT
CB_GETLBTEXT
CB_GETLBTEXTLEN
CB_LIMITTEXT
CB_RESETCONTENT
CB_SELECTSTRING
CB_SETCURSEL
CB_SETDROPPEDWIDTH
CB_SETEXTENDEDUI
CB_SETITEMDATA
CB_SETITEMHEIGHT
CB_SHOWDROPDOWN
CloseHandle
COLORREF
CreateDialogIndirect
CreateFile
CreateIcon
CreateProcess
CreateWindow
CreateWindowEx
DefDlgProc
DefWindowProc
DeleteMenu
DeleteObject
DestroyWindow
DEVMODE
DispatchMessage
DLGITEMTEMPLATE
DLGTEMPLATE
DllCanUnloadNow
DllEntryPoint
DllGetClassObject
DM_SETDEFID
DestroyIcon
DrawFrameControl
DRAWITEMSTRUCT
DrawText
EM_LIMITTEXT
EM_SETLIMITTEXT
EN_CHANGE
EN_KILLFOCUS
EN_UPDATE
EnableScrollBar
EndDialog
ExitWindowsEx
ExtractAssociatedIcon
ExtractIcon
ExtractIconEx
FD_FLAGS
FILETIME
FindFirstChangeNotification
FindFirstFile
FindResource
FlashWindow
FindWindow
FormatMessage
FreeLibrary
GetCurrentDirectory
GetCursorPos
GetDCEx
GetFileAttributes
GetLastError
GetModuleHandle
GetMessage
GetParent
GetProcAddress
GetScrollInfo
GetScrollPos
GetScrollRange
GetSubMenu
GetSysColor
GetSystemMetrics
GetThreadPriority
GetWindowLong
GlobalAlloc
InsertMenu
IsDialogMessage
HPALETTE
LBItemFromPoint
LoadIcon
LoadImage
LoadLibrary
LoadResource
LocalAlloc
LocalFree
LOGBRUSH
LOGFONT
LOGPEN
MAKEINTRESOURCE
MapWindowPoints
MessageBox
MoveWindow
MSG
NETRESOURCE
OpenFile
PeekMessage
POINT
POINTL
POINTS
PostMessage
PostQuitMessage
ReadFile
RECT
RegEnumValue
RegisterClipboardFormat
RegisterDragDrop
RegisterHotKey
RegisterWindowMessage
SCROLLINFO
SECURITY_ATTRIBUTES
SendMessage
SetBkColor
SetCurrentDirectory
SetFocus
SetMenu
SetParent
SetScrollInfo
SetScrollPos
SetScrollRange
SetTextColor
SetThreadPriority
SetWindowLong
SetWindowPos
SetWindowRgn
SetWindowText
ShowCursor
ShowScrollBar
ShowWindow
SIZE
SOANGLE
SOCOLORREF
SOMAXPOINTS
SOPALETTE
SOPutText
STARTUPINFO
STGMEDIUM
StgOpenStorage
SystemParametersInfo
SYSTEMTIME
TerminateProcess
TrackPopupMenu
TrackPopupMenuEx
TranslateMessage
UpdateWindow
VwStreamDynamicName
VwStreamSaveName
VwStreamDynamicType
VwStreamSectionName
VwStreamIdName
VwStreamIdCount
VwStreamUserSaveType
WIN32_FIND_DATA
WINDOWPOS
WinMain
WM_ACTIVATE
WM_ACTIVATEAPP
WM_CANCELMODE
WM_CHARTOITEM
WM_CLOSE
WM_COMMAND
WM_CONTEXTMENU
WM_CREATE
WM_DESTROY
WM_DRAWITEM
WM_ENABLE
WM_ERASEBKGND
WM_GETDLGCODE
WM_GETFONT
WM_GETHOTKEY
WM_HOTKEY
WM_HSCROLL
WM_INITDIALOG
WM_INITMENUPOPUP
WM_KEYDOWN
WM_KEYUP
WM_KILLFOCUS
WM_LBUTTONDBLCLK
WM_LBUTTONDOWN
WM_LBUTTONUP
WM_MBUTTONDOWN
WM_MEASUREITEM
WM_MENUCHAR
WM_MENUSELECT
WM_MOUSEMOVE
WM_NCACTIVATE
WM_NCHITTEST
WM_NCPAINT
WM_PAINT
WM_RBUTTONDOWN
WM_RBUTTONUP
WM_SETCURSOR
WM_SETFOCUS
WM_SETFONT
WM_SETHOTKEY
WM_SETREDRAW
WM_SIZE
WM_STYLECHANGED
WM_SYSCOLORCHANGE
WM_SYSCOMMAND
WM_TIMER
WM_VKEYTOITEM
WM_VSCROLL
WM_WINDOWPOSCHANGED
WM_WININICHANGE
WritePrivateProfileString


Frequently Asked Questions

Frequently Asked Questions Frequently Asked Questions *
  * Next Topic: Internet Client SDK Support

Internet Client SDK Top Menu

This FAQ is also available online at http://support.microsoft.com/support/inetsdk/faq/. Please check the online version for more regular updates.

Active Desktop

question How do I turn off scrollbars in my Active Desktop item?
question Why is my CDF file not downloading correctly?
question My Active Desktop item containing a JAVA applet does not display properly?
question Why does my Active Desktop item fail to show up on my desktop right after I download the CDF file?
question Why is the size information specified in my Active Desktop item seemingly ignored after I modified my CDF file?
question Why are my JavaScript calls failing from my Active Desktop item?
question How can I get rid of the vertical scrollbar?

Channels

question What MIME type do I specify in my dynamically generated CDF file?
question When dynamically generating a CDF file from an Active Server Pages (ASP) page, is the ASP file the one the user needs to subscribe to?
question I cannot use the ampersand character in my CDF TITLE. Do I have to treat certain characters special when working with CDF files?
question Is it necessary to specify the <!DOCTYPE> tag in my CDF file?
question Is http://www.w3c.org/channel.dtd a valid URL for a <!DOCTYPE> tag?
question Is there a way to detect from an HTML page whether the user is already subscribed to it?
question Is there a difference between the subscription cache and the regular cache that Internet Explorer maintains?
question If the user is browsing a subscribed channel while they are connected to the Internet, is content pulled from the cache, or does Internet Explorer query the server again?
question Does the actual download of the HTML page occur upon subscription to the site, or only during a subscription update?
question From a CDF file, is there a way to specify items to be cached, without having the items appear in the channel bar's item list? For example, can I specify a WAV file to be downloaded as part of the subscription update so that it gets cached and is available when the user browses offline?
question Is there a way to specify the order of items to be cached from a CDF file? We want to ensure that high priority items are downloaded first during a subscription update.
question Is it possible to specify multiple schedules for updates in one CDF file?
question Is it possible to specify a global time for the <SCHEDULE> tag, so that my channel updates occur between certain times, regardless of the time zone?
question How do I keep Internet Explorer 4.0 from opening a new window when a user clicks on a link from a desktop component?
question I haven't been able to get my desktop component to work unless I put it on a separate CDF from the rest of my channel. Is this how it's designed to work?
question I notice that a TDC contained in a Desktop component does not render data correctly. What am I doing wrong?
question I notice that the text I specified in my <ABSTRACT> tag gets truncated when displayed as a tooltip from the Channel Bar. Is there a limit to the number of characters I can specify in my channel's <ABSTRACT> tag?
question Is there any way my application can get notified when a channel gets updated?
question Is there any way to find out when a channel was last updated?
question What exactly does <USAGE VALUE="Email"/> mean to my channel?
question After a user subscribes to my CDF file, my specified logo does not seem to show up correctly in the Active Desktop channel bar. The generic satellite dish icon seems to be displayed instead. What's wrong?
question How does one delete a channel subscription completely from IE's cache?
question Is there any way to specify a placement order for my channel in the channel bar? I want to add my channel to the top of the bar.
question We are trying to distinguish between genuine hits on our channel versus periodic hits from the IE4 WebCrawler, trying to update content. Is there a way to do this using the User-Agent HTTP header?

Dynamic HTML

question Is there a way to implement a custom tooltip over anchors in Internet Explorer 4.0 (the same way you can use the ALT attribute in an <IMG> tag)? By default, Internet Explorer 4.0 renders the URL of the HREF as a tooltip, which may not always be the desired behavior.
question How can I change the HTML or text associated with an element? I used to be able to do this using the rangeFromElement method, but now I keep getting the error "Object does not support this property or method." Have things changed?
question How do I determine the client width and height?
question How do I change the current cursor being used as mouse pointer?
question Why do I get the error "Wrong number of arguments" in my event handlers?
question I'm finding that IFRAMES within a relatively positioned <DIV> tag causes Internet Explorer 4.0 to crash every time. This makes it difficult to relatively position IFRAMES. Is this a known problem, and is there a workaround?
question How do I make my data-bound pages work in both Internet Explorer 4.0 and other down-level browsers that don't support data binding?

WebBrowser Control

question In the WebBrowser documentation for Visual Basic developers, the Navigate and Navigate2 methods look identical. Is there a difference?
question I have an application that uses the WebBrowser control. Is it possible to install just the WebBrowser control, without installing Internet Explorer 4.0?
question I'm unable to script a Web Browser control embedded in an HTML page when surfing across domains. What's wrong?

Component Packaging

question When downloading a digitally signed file, rather than popping up the Certificate dialog box as expected, a message box comes up indicating that the file has been digitally signed but that it cannot be confirmed. What's wrong?
question What version of the MFC DLLs will ship with Internet Explorer 4.0? I'd like to know so I don't have to worry about packaging the MFC DLLs with my ActiveX Control.
question Is there a way to see a debug trace of code download activity in Internet Explorer 4.0?
question I've written an ActiveX control that I've marked as Safe for Scripting, and I'm having trouble getting it to work when running off a page on a local hard drive. What am I doing wrong?

Control Development

question How can I improve performance in my ActiveX control?
question What is the secret to debugging a control embedded in an HTML page in Internet Explorer 4.0? Whenever I try to start a debug session with Internet Explorer 4.0 in the Visual C++ debugger, I get kicked out of the debugger.

Scripting

question How do I determine from a script if the Internet Explorer 4.0 browser is running off line or not?
question Why do I get a Permission Denied error whenever I try to access a frame's document from a script written in another frame's document. The same code runs fine in Internet Explorer 3.x.
question Why do I get a Permission Denied error whenever I try to access a frame on a different first tier domain, but on the same second tier domain?
question From a client-side script, how do I check for the browser version so my application can degrade gracefully if the browser does not support the new Internet Explorer 4.0 features?

HTML

question Why are my HTML pages with frames not showing up in Internet Explorer 4.0? They used to work fine in Internet Explorer 3.x.
question Why doesn't Internet Explorer 4.0 close the <PLAINTEXT> container like Internet Explorer 3.x did?

Font Embedding

question Which fonts can I use?
question What are the different levels of font embedding?
question How can I check the embedding permissions of my fonts?
question Should I embed common core fonts like Arial or Times New Roman?
question Can I use Type 1 fonts?

Miscellaneous

question Is it possible to have Internet Explorer 3.x and Internet Explorer 4.0 coexist on the same machine?
question What is the difference between ADO and ADOR, and which should I be using on my Web pages?
question What do I need to do to migrate my Web application from IE3.x to IE4.0?
question I don't see the debug versions of wininet.dll and urlmon.dll in the Internet Client SDK. This used to be very helpful for me in IE3.x; where did they go?
question Where can I find more information about the NetMeeting API?

How do I turn off scrollbars in my Active Desktop item?
Specifying the appropriate width and height using the <WIDTH> and <HEIGHT> tags as child elements to the <USAGE> tag.

<USAGE VALUE="DesktopComponent">
    <OpenAs VALUE="HTML" />
    <Width VALUE="400" />
    <Height VALUE="130" />
</USAGE>

For details, refer to the "CDF Extensions for Active Desktop Items" section under the "CDF Reference" of the Internet Client SDK docs.

Up Back to list of questions

Why is my CDF file not downloading correctly when I click on an Active Desktop item's CDF file?
CDF files were not supported in IE 4.0 PP1 release. The PP2 version, however, through the final release of Internet Explorer 4.0, provides full support for CDF files.

The following JavaScript code will solve this problem. It detects the user's browser, then redirects the user to the appropriate URL. If the user is running PP2, the browser will correctly navigate to the CDF file, otherwise it will go to a page that tells users to download PP2:

<SCRIPT LANGUAGE="JavaScript">
<!--
function isIE4(ua)
{
    var msie = ua.indexOf( "MSIE " );
    if ( msie == -1 )
        return 0;
    var ver = parseInt ( ua.substring ( msie+5, ua.indexOf ( ".", msie ) ) )
    return ver >= 4;
}

function RedirectBrowser()
{
    var ua = window.navigator.userAgent;

    if( ua.indexOf( "MSIE 4.0b1" ) != -1 )
        { window.location.href="http://www.microsoft.com/ie/ie40/gallery/ie_msg.htm"; }
    else if ( isIE4(ua) )
        { window.location.href="yourCDF.cdf"; }
    else
        { window.location.href="http://www.microsoft.com/ie/ie40/gallery/ie_msg.htm"; }
}

</SCRIPT>

<FORM>
<INPUT TYPE="button" VALUE="Add to my Desktop" NAME="button1" onClick="RedirectBrowser()">
</FORM>

Up Back to list of questions

My Active Desktop item containing a JAVA applet does not display properly?
This was a problem in the IE4.0 PP2 release that has been fixed for the final release. In PP2, desktop items ran with the Ambient variable set to Offline, ie if a Java applet tries to get data by going through wininet (for example by requesting a file for HTTP using the java.net object), it will not go to the network to get the latest data. Instead, WinInet will attempt to find the requested information in the local cache. If the requested data is not in the cache, WinInet fails and the Java applet will not get any data.

The final release of Internet Explorer 4.0 toggles the Ambient variable between Online and Offline modes, depending on whether or not a live network connection is available.

There are two ways to get fresh data to a Java applet:

Solution 1: Do not go through wininet to fetch your data. This means opening your own socket connection to a server, and retrieving the data manually.

Solution 2: Make your Java applet read from the cache, and use the scheduling mechanism in the CDF to refresh your data. To do this the Java applet needs to use java.net.URLConnection objects, and call setUseCaches(TRUE).

Up Back to list of questions

Why does my Active Desktop item fail to show up on my desktop right after I download the CDF file?
IE 4.0 PP2 did not always refresh the desktop properly after a CDF download. This means that the desktop item can be downloaded into the cache, but nothing shows up on the user's desktop. This problem should be fixed in the final version of Internet Explorer 4.0.

As a workaround, users must refresh their desktops manually, by right-clicking on the Desktop and selecting Refresh.

Up Back to list of questions

Why is the size information specified in my Active Desktop item seemingly ignored after I modified my CDF file?
When IE 4.0 updates a desktop item, it will refresh each item specified in the CDF. Additionally, IE will also refresh the CDF itself, but it will ignore the size attributes of the desktop item, even if they have changed.

To change the size of a desktop item, users will have to delete it from their desktops, then re-subscribe to the newer version of the Active Desktop item.

Up Back to list of questions

Why are my JavaScript calls failing from my Active Desktop item?
Scripts that rely on the <a href="javascript:foo()> method for opening new windows will not work from the Active Desktop.

The problem is that this method makes some assumptions about the context in which the code will run. In a browser window, this code would look for foo within the document itself. But since desktop items are implemented as IFRAMEs of their parent window, on the Active Desktop this code would not find foo. This is analogous to right-clicking on a javascript:url and choosing to open it in a new window. For example, the following code to open a new window will not work from the Active Desktop:

<A HREF="javascript:foo()">

<SCRIPT LANGUAGE="JavaScript">
<!--
function foo()
{
    window.open ("your parameters here");
}
//-->
</SCRIPT>

When developing for the Active Desktop, never make any assumptions about the context that your are in. For example in this case, the function foo is in the context of the current document. For this to work from the Active Desktop, add an explicit _self reference, like this:

<A HREF="javascript:foo()" TARGET=_self>

<SCRIPT LANGUAGE="JavaScript">
<!--
function foo()
{
    window.open ("your parameters here");
}
//-->
</SCRIPT>

Up Back to list of questions

How can I get rid of the vertical scrollbar?
Most desktop items want to specify excactly what size they should be on the Active Destkop. This is done by setting the HEIGHT and WIDTH fields of the <USAGE> tag in the CDF file. But if the content of the CDF is a Java app or image that occupies those excact measurements, a vertical scrollbar will appear in desktop item.

For example, this sample CDF:

<CHANNEL>
    <ITEM = "foo.htm">
        <USAGE VALUE="DesktopComponent">
            <WIDTH  = 100/>
            <HEIGHT = 100/>
        </USAGE>
    </ITEM>
</CHANNEL>

where foo.htm looked something like this:

<HTML>
<BODY>
<APPLET CODEBASE=foo width=100 height=100>
</APPLET>
</BODY>
</HTML>

would result in a little snippet of HTML appearing beneath the desktop item, thus causing the creation of a scrollbar. The problem is that spaces and carriage returns (CRs) are considered text characters, and text characters have descent - space below the baseline.

There are two workarounds to address this issue:
Make the CDF HEIGHT a few pixels bigger. This will work for non-resizable CDFs, but will not work for a Java app that tries to occupy 100% of the available item real-estate (HEIGHT=100%).
Remove any spaces or carriage-returns from your HTML file. For example, foo.htm would now look like this:
<HTML><BODY><APPLET CODEBASE=foo width=100 height=100></APPLET></BODY></HTML>

This will work in all configurations, even for resizable desktop items.

Up Back to list of questions

What MIME type do I specify in my dynamically generated CDF file?
CDF files that are dynamically generated through Active Server Pages (ASP) should insert the following line at the top of the file (before any CDF lines):

<% Response.ContentType = "application/x-cdf" %>

This ensures that servers return the correct MIME/content type "application/x-cdf".

Problems with CDF files being displayed as HTML text inside the Internet Explorer 4.0 browser, instead of invoking the subscription wizard, may likely be caused by the server returning the incorrect MIME type of "text/html" instead of the desired "application/x-cdf".

Up Back to list of questions

When dynamically generating a CDF file from an Active Server Pages (ASP) page, is the ASP file the one the user needs to subscribe to?
Yes, assuming that the correct CDF MIME type is specified in the ASP page, as illustrated in the FAQ above, double-clicking on a link to the ASP file should bring up the CDF subscription wizard appropriately.

Up Back to list of questions

I can't use the ampersand character in my CDF TITLE. Do I have to treat certain characters special when working with CDF files?
As mentioned in the "CDF Parsing Rules and Hints" section of the CDF Reference, CDF supports encoding of ASCII characters with the format &#nnn. The ampersand character, therefore, could be encoded with its ASCII decimal value of 38 by using the string &#038.

To specify "Peaches&Cream", for instance, here's what your <TITLE> tag would look like:

<TITLE>Peaches&#038;Cream</TITLE>

Up Back to list of questions

Is it necessary to specify the <!DOCTYPE> tag in my CDF file?
No, Internet Explorer 4.0 does not use the <!DOCTYPE> tag.

Up Back to list of questions

Is http://www.w3c.org/channel.dtd a valid URL for a <!DOCTYPE> tag?
No, this URL is only an example, does not actually exist, and is best not used in actual CDF files.

Up Back to list of questions

Is there a way to detect from an HTML page whether the user is already subscribed to it?
Yes, there is a way to do this, both in script and in C++ using the ISubscriptionMgr interface that IE4.0 exposes.

In script, the way to do this is to use the window.external.IsSubscribed() method.

In C++, the code to do this looks something like this:

#include <windows.h>
   #include <subsmgr.h>
   #include <stdio.h>

    ISubscriptionMgr *pSubscriptionMgr;
    CoInitialize(NULL);

    HRESULT hr = CoCreateInstance(CLSID_SubscriptionMgr, NULL, CLSCTX_INPROC_SERVER,
                                  IID_ISubscriptionMgr, (void**)&pSubscriptionMgr);
    if (SUCCEEDED(hr))
    {

        BOOL Bool;
        BSTR bstrURL = SysAllocString(L"http://example.microsoft.com/sample.cdf");
        hr = pSubscriptionMgr->IsSubscribed(bstrURL, &Bool);

        pSubscriptionMgr->Release();

        printf("IsSubscribed returned %ld\n", Bool);
        SysFreeString (bstrURL);
    }

    CoUninitialize();

Up Back to list of questions

Is there a difference between the subscription cache and the regular cache that Internet Explorer maintains?
All subscription information go into the same cache maintained by Internet Explorer. The subscription content in the cache, however, is especially marked so that it does not get deleted when a user clears the cache.

Up Back to list of questions

If the user is browsing a subscribed channel while they are connected to the Internet, is content pulled from the cache, or does Internet Explorer query the server again?
Internet Explorer looks at the expires HTTP header returned by the server when the page was retrieved and checks to see if the cached page is still valid. If it is, then content is pulled from the cache; otherwise, Internet Explorer queries the server again for the content. Note that with the latter, when Internet Explorer re-queries the server for content, in most cases, Internet Explorer will issue an HTTP GET request with an If-Modified-Since header, which helps reduce the server load.

Up Back to list of questions

Does the actual download of the HTML page occur upon subscription to the site, or only during a subscription update?
Actual download occurs during subscription update. However, users can manually update a subscription any time they want.

Up Back to list of questions

From a CDF file, is there a way to specify items to be cached, without having the items appear in the channel bar's item list? For example, can I specify a WAV file to be downloaded as part of the subscription update, so that it gets cached and is available when the user browses offline?
Yes, here's the correct way to do this:

<ITEM HREF="http://example.microsoft.com/sound.wav">
      <USAGE VALUE="NONE"></USAGE>
</ITEM>

Note that in XML, an element that does not have child elements can be represented in a more compact format. For instance, the above <USAGE> line could be written more compactly in this manner (note the final / at the end of the tag):

<USAGE VALUE="NONE"/>

Also, when listing multiple items that are to be cached but not viewed in the channel pane, instead of marking each one with a <USAGE VALUE="NONE"/>, it is better to place them all in one sub-channel that is marked with a usage tag, as illustrated in the example below:

<CHANNEL>
      <USAGE VALUE="NONE"/>
      <ITEM HREF="http://example.microsoft.com/sound1.wav"/>
      <ITEM HREF="http://example.microsoft.com/sound2.wav"/>
      <ITEM HREF="http://example.microsoft.com/sound3.wav"/>
</CHANNEL>

Up Back to list of questions

Is there a way to specify the order of items to be cached from a CDF file? We want to ensure that high priority items are downloaded first during a subscription update.
No, there are no plans to support for this for Internet Explorer 4.0.

Up Back to list of questions

Is it possible to specify multiple schedules for updates in one CDF file?
No, only one schedule can be specified per CDF in Internet Explorer 4.0.
Also, a desktop component cannot be bundled with a channel in one CDF. They have to be two separate CDFs to work correctly.

Up Back to list of questions

Is it possible to specify a global time for the <SCHEDULE> tag, so that my channel updates occur between certain times, regardless of the time zone?
Currently there is no way to specify local or global time in a CDF file. Information specified in the <EARLIESTTIME> and <LATESTTIME> tags are both considered local and ignore any timezone information specified in the <STARTDATE> and <STOPDATE> tags.

Up Back to list of questions

How do I keep Internet Explorer 4.0 from opening a new window when a user clicks on a link from a desktop component?
The way to do this is to specify a TARGET="_top" with the <A HREF> tag.

Up Back to list of questions

I haven't been able to get my desktop component to work unless I put it on a separate CDF from the rest of my channel. Is this how it's designed to work?
Yes, desktop components have to be in a separate CDF file from the rest of the channel.

Up Back to list of questions

I notice that a TDC contained in a Desktop component does not render data correctly. What am I doing wrong?
This was a problem in Platform Preview 2 and has been fixed in the released version of Internet Explorer 4.0.

Up Back to list of questions

I notice that the text I specified in my <ABSTRACT> tag gets truncated when displayed as a tooltip from the Channel Bar. Is there a limit to the number of characters I can specify in my channel's <ABSTRACT> tag?
This was a bug in the Platform Preview 2 version of the Channel bar and has been fixed in the released version of IE4.0.

Up Back to list of questions

Is there any way my application can get notified when a channel gets updated?
IE 4.0 will not be providing support for this. The set of APIs that would have provided this functionality did not reach a point of stability and robustness that we felt our partners would find acceptable so this feature has been postponed to the next version of IE.

Up Back to list of questions

Is there any way to find out when a channel was last updated?
Yes, through the WinInet API GetUrlCacheEntryInfoEx. This API, which takes a URL as a parameter, returns an INTERNET_CACHE_ENTRY_INFO struct containing information such as local cache UNC path, LastModifiedTime, and similar type of information about a cached file.

Up Back to list of questions

What exactly does <USAGE VALUE="Email"/> mean to my channel?
The URL specified is e-mailed to the subscribed user when the channel content is updated. For an email client that is not HTML-aware, the link to the URL is sent instead.

Up Back to list of questions

After a user subscribes to my CDF file, my specified logo does not seem to show up correctly in the Active Desktop channel bar. The generic satellite dish icon seems to be displayed instead. What's wrong?
Any of the following could cause this problem to occur:
Don't use the <SELF> tag
Don't have <LOGO> tags pointing to non-existent files
Author CDFs on PCs if possible, or convert to PC text file format before copying to the server.

Up Back to list of questions

How does one delete a channel subscription completely from IE's cache?
You should be able to do this by right-clicking on the channel logo in the channel bar and selecting delete. This causes channel information to get deleted from these places:
Temporary Internet Files cache (under c:\windows)
Subscription folder (under c:\windows, also from the Manage Subscriptions submenu of the Favorites menu)

Up Back to list of questions

Is there any way to specify a placement order for my channel in the channel bar? I want to add my channel to the top of the bar.
No, there is no way to do this. By default new channels will be added to the bottom of the channel bar.

Up Back to list of questions

We are trying to distinguish between genuine hits on our channel versus periodic hits from the IE4 WebCrawler, trying to update content. Is there a way to do this using the User-Agent HTTP header?
Yes, this is determined by the presence or absence of the "MSIECrawler" string in the User-Agent string passed in the HTTP request to the server.

The IE4 WebCrawler sends the following User-Agent string, as it tries to update content on the client machine:

"Mozilla/4.0 (compatible; MSIE 4.0; MSIECrawler; Windows 95)" or "Mozilla/4.0 (compatible; MSIE 4.0; MSIECrawler; Windows NT)"

whereas IE4 generally sends the following User-Agent string (without the MSIECrawler):

"Mozilla/4.0 (compatible; MSIE 4.0; Windows 95)" or "Mozilla/4.0 (compatible; MSIE 4.0; Windows NT)"

Up Back to list of questions

Is there a way to implement a custom tooltip over anchors in Internet Explorer 4.0 (the same way you can use the ALT attribute in an <IMG> tag)? By default, Internet Explorer 4.0 renders the URL of the HREF as a tooltip, which may not always be the desired behavior.
Yes, the way to do this is to specify the tooltip in the TITLE attribute of the <A tag> as in this example:

<a href="file.htm" TITLE="Tooltip goes here">some text</a>

Up Back to list of questions

How can I change the HTML or text associated with an element? I used to be able to do this using the rangeFromElement method, but now I keep getting the error "Object does not support this property or method." Have things changed?
Yes, the rangeFromElement method has been removed. Use innterHTML/outerHTML and innerText/outerText to manipulate text or HTML.

Up Back to list of questions

How do I determine the client width and height?
There are new properties on the body object, clientWidth and clientHeight, which can be used for this purpose.

Up Back to list of questions

How do I change the current cursor being used as mouse pointer?
Yes, there is a cursor CSS attribute that can be used. Refer to the Internet Client SDK documentation under Dynamic HTML\HTML and CSS Reference section for more information.

Up Back to list of questions

Why do I get the error "Wrong number of arguments" in my event handlers?
Events do not have parameters. All information can be retrieved using the window.event object.

Up Back to list of questions

I'm finding that IFRAMES within a relatively positioned <DIV> tag causes Internet Explorer 4.0 to crash every time. This makes it difficult to relatively position IFRAMES. Is this a known problem, and is there a workaround?
Yes, this is a known problem. The workaround is to put the positioning on the <IFRAME> directly.

Up Back to list of questions

How do I make my data-bound pages work in both Internet Explorer 4.0 and other down-level browsers that don't support data binding?
See the document on Authoring Data Binding for Other Browsers in the Internet Client SDK.

Up Back to list of questions

In the WebBrowser documentation for Visual Basic developers, the Navigate and Navigate2 methods look identical. Is there a difference?
The only difference is that the URL parameter is packaged as a VARIANT in Navigate2 instead of a BSTR. (You could verify this in the WebBrowser documentation for C/C++ developers.) Unlike a C++ application, a Visual Basic application is not able to use the WebBrowser control to navigate into special folders in the shell namespace like "My Computer." Currently, the shell does not expose an object that provides a PIDL, which a VB application can then use in a Navigate2 call.

For more information on WebBrowser navigation using a PIDL from a C++ application, refer to article Q167834 in the Microsoft Knowledge Base.

Up Back to list of questions

When downloading a digitally signed file, rather than popping up the Certificate dialog box as expected, a message box comes up indicating that the file has been digitally signed but that it cannot be confirmed. What's wrong?
Microsoft has recently confirmed a rare Certificate Verification bug caused by the REG files offered as part of the tools set of the ActiveX SDK. The bug is that the REG files, Wvtston.reg and Wvtstoff.reg, sets the system to check Verisign's revocation server extraneously. This error occurs only when your system is set to check the Revocation server, and the Revocation server itself is down (a very rare occurrence).

The recommended solution is to use SetReg.exe available in the Internet Client SDK's \Inetsdk\Bin folder, rather than the REG files in the ActiveX SDK. SetReg.exe should be used to disable Revocation checking on your machine.

By issuing the following command, the off-line revocation server for individual certificates is disabled:

setreg 4 true

By issuing the following command, the off-line revocation server for commercial certificates is disabled:

setreg 5 true

Up Back to list of questions

What version of the MFC DLLs will ship with Internet Explorer 4.0? I'd like to know so I don't have to worry about packaging the MFC DLLs with my ActiveX Control.
Any component should be careful not to rely on the presence of any MFC DLLs with the currently installed browser, as Internet Explorer 4.0 and future versions of Internet Explorer may ship alternative versions, or may not even ship any MFC DLLs at all.

A component that uses the MFC DLLs as dependencies should package the MFC DLLs accordingly. More information on how to correctly package MFC DLLs correctly with your MFC component, can be found in article Q167158 in the Microsoft Knowledge Base.

Up Back to list of questions

Is there a way to see a debug trace of code download activity in Internet Explorer 4.0?
In Internet Explorer 3.x, this was made possible by installing the debug versions of Urlmon.dll and Wininet.dll, as outlined in article Q169437 in the Microsoft Knowledge Base.

In Internet Explorer 4.0, there is a tool available in the Internet Client SDK that allows you to do this more easily. Check out \Inetsdk\Bin\Cdllogvw.exe. There is also a Cdllogvw.txt available in the same directory for more details.

Up Back to list of questions

I've written an ActiveX control that I've marked as Safe for Scripting and I'm having trouble getting it to work when running off a page on a local hard drive. What am I doing wrong?
The problem may be due to any of the following:
A missing dependent DLL
Necessary security level set on the wrong zone
A control that is not marked as "safe for scripting and initialization" will not be loaded if the page that references the control is being accessed from the local hard drive. Note that this behavior may or may not change in future builds of Internet Explorer.

For more information on marking ActiveX controls as "safe for scripting and initialization", please refer to the Internet Client SDK docs on "Safe Initialization and Scripting for ActiveX Controls" under the Component Development/ActiveX Controls section.

Up Back to list of questions

How can I improve performance in my ActiveX Control?
For better performance make your control an apartment model control. Internet Explorer 4.0 uses multiple threads and may host the control in a secondary thread. If the control is not created as apartment model aware and marked as such, it is created and executed in the context of the calling application's primary thread, requiring calls on the control's methods to be marshaled between threads. This can cause a performance hit and can be very prominent if there are many non-apartment model controls in an HTML page. To make a control apartment model, the control needs to be marked as such in the registry and has to be written so that it is apartment model safe.

More information on apartment model and other threading models can be found in article Q150777 in the Microsoft Knowledge Base.

Up Back to list of questions

What is the secret to debugging a control embedded in an HTML page in Internet Explorer 4.0? Whenever I try to start a debug session with Internet Explorer 4.0 in the Visual C++ debugger, I get kicked out of the debugger.
With Internet Explorer 4.0's shell integration, this is not as straightforward as debugging controls in Internet Explorer 3.x. The details on how to do this correctly are outlined in article Q167715 in the Microsoft Knowledge Base.

Up Back to list of questions

How do I determine from a script if the Internet Explorer 4.0 browser is running offline or not?
From a script, the way to do this is through the window.navigator.onLine property which returns a BOOL value.

In C++, IWebBrowser2 interface provides a get/put_Offline method that indicates whether or not the WebBrowser is reading from the cache.

Up Back to list of questions

I have an application that uses the WebBrowser control. Is it possible to install just the WebBrowser control, without installing Internet Explorer 4.0?
No, there is no way to do this for both Internet Explorer 3.x and Internet Explorer 4.0. The minimal install will install the browser. Also, note that Internet Explorer 3.x and 4.0 cannot coexist on the same machine.

More information on redistributing Internet Explorer can be found in the IEAK page on http://www.microsoft.com/ie/ieak/.

Up Back to list of questions

I'm unable to script a Web Browser control embedded in an HTML page when surfing across domains. What's wrong?
The Webbrowser control is not safe for scripting. This behavior is by design and we recommend using an IFRAME instead.

Up Back to list of questions

Why do I get a Permission Denied error whenever I try to access a frame's document from a script written in another frame's document. The same code runs fine in Internet Explorer 3.x.
This is due to a cross-frame security feature that's implemented in Internet Explorer 4.0, but not in Internet Explorer 3.x. A frame running on one server is not able to access another frame's document running on another server. Similarly, with the introduction of zones in Internet Explorer 4.0 Preview 2, a script cannot access pages across zones.

For more information on this new cross-frame security in Internet Explorer 4.0, please refer to article Q167796 in the Microsoft Knowledge Base.

Up Back to list of questions

Why do I get a Permission Denied error whenever I try to access a frame on a different first tier domain, but on the same second tier domain?
This is another side effect of Internet Explorer 4.0's cross-frame security feature described above. A frame running on example1.microsoft.com cannot access a frame on example2.microsoft.com.

The correct way to do this is to set the domain property on both pages to the common substring domain. In this case, setting the domain to microsoft.com, as illustrated below:

<SCRIPT>
      document.domain = "microsoft.com"
   </SCRIPT>

Up Back to list of questions

From a client-side script, how do I check for the browser version so my application can degrade gracefully if the browser does not support the new Internet Explorer 4.0 features?
You can use the JScript function below to determine the version of the browser it is running on from a client-side script. The function returns the major version number for any Microsoft Internet Explorer browser, and zero (0) for others. Use of this function assures that the script is compatible with future versions of the Internet Explorer.

// This function returns Internet Explorer's major version number, // or 0 for others. It works by finding the "MSIE " string and
   // extracting the version number following the space, up to the decimal
   // point, ignoring the minor version number

   <SCRIPT LANGUAGE="JavaSCRIPT">
   function msieversion()
   {
      var ua = window.navigator.userAgent
      var msie = ua.indexOf ( "MSIE " )

      if ( msie > 0 )      // If IE, return version number
         return parseInt (ua.substring (msie+5, ua.indexOf (".", msie )))
      else                 // If another browser, return 0
         return 0
   }
   </SCRIPT>

For more information, refer to article Q167820 in the Microsoft Knowledge Base.

Up Back to list of questions

Why are my HTML pages with frames not showing up in Internet Explorer 4.0? They used to work fine in Internet Explorer 3.x.
Unlike Internet Explorer 3.0, Internet Explorer 4.0 does not support <FRAMESET> tags embedded within <BODY> tags. This was done in Internet Explorer 4.0 to ensure compatibility with Netscape. To work around the problem, move the <FRAMESET> outside the <BODY> tags.

In some cases, a <NOFRAMES> element is specified within the <FRAMESET> tags, as in the example below:

   <BODY>
      <FRAMESET>
        <NOFRAMES>Sorry, your browser does not support frames!</NOFRAMES>
      </FRAMESET>
   </BODY>

Although Internet Explorer 4.0 supports frames, when the above HTML code is displayed in Internet Explorer 4.0, the content specified within the <NOFRAMES> tag is displayed. Moving the <FRAMESET> outside the <BODY> tags causes the page to display correctly.

Up Back to list of questions

Why doesn't Internet Explorer 4.0 close the <PLAINTEXT> container like Internet Explorer 3.x did?
The <PLAINTEXT> tag is designed to render all of a Web page's subsequent text without parsing any tags, including its own </PLAINTEXT> tag. Internet Explorer 4.0 supports this tag as it is defined by the HTML DTD. This element is not recommended as different browsers may not support it consistently. Instead, use the <PRE> tag and display all reserved characters (such as brackets) with their corresponding HTML character entities.

Instead, use the <PRE> tag and display all reserved characters (such as brackets) with their corresponding HTML character entities. The <XMP> element is not a recommended substitute, as it is a legacy of the original HTML 1.0 specification that will eventually not be supported by Web browsers. Using <PRE> will assure that your content is displayed accurately on all browsers, now and in the future.

Up Back to list of questions

Which fonts can I use?
There are thousands of TrueType fonts available and most of these can be embedded within Web pages using Microsoft Web Embedding Fonts Tool. However, WEFT will not let you embed certain categories of font such as 'no embedding' fonts and those that contain serious errors.

Up Back to list of questions

What are the different levels of font embedding?
TrueType fonts have embedding permissions encoded within them. There are four levels of embedding:
A small proportion of available fonts have their embedding permissions set to "No Embedding". The creators of these fonts have decided not to allow embedding. Some foundries set their fonts to no embedding but offer upgrades to embeddable versions. If you come across a no embedding font that you would really like to use, contact the supplier, and ask about a possible upgrade.
"Print and Preview" fonts may be embedded, but only within pages that remain static on the client side. If a page allows client-side interaction that results in content displayed using the font changing, then 'editable' or 'installable' fonts must be used. An example of such a page may be one that contains an inline Java based word processor, or e-mail editor.
"Editable" fonts may be embedded using WEFT without the restrictions imposed on 'Print and Preview' fonts.
"Installable" fonts are treated as editable fonts by Microsoft Internet Explorer 4.0. Installable fonts will not be installed in your visitors fonts folder. The main reason for this is that during the course of a users Web travels they could easily find their fonts folder stuffed up with hundreds of full and subsetted fonts that they do not want or need.

Up Back to list of questions

How can I check the embedding permissions of my fonts?
You can check the embedding permissions of any font using our free Microsoft Font Properties Extension. WEFT also has a font check feature that will report the permissions of fonts you have installed on your system.

You may come across very old TrueType fonts, or converted Macintosh TrueType fonts that do not have any embedding permissions encoded within them. WEFT treats these as a 'no embedding' fonts. In the unlikely event that you encounter such a font, your best option is to contact the foundry that created the font, and ask about an upgrade.

Up Back to list of questions

Should I embed common core fonts like Arial or Times New Roman?
WEFT will identify common fonts that your readers are likely to have installed. These include Windows core fonts like Arial, Times New Roman and Courier New. You can still embed these fonts, however Internet Explorer 4.0 will download, decompress and temporarily install font objects even if the real font is present on the user's computer.

The current version of WEFT does not identify the fonts supplied with Internet Explorer 4.0 as common core fonts. Users who have installed Internet Explorer 4.0 will have added Verdana, Comic Sans MS, Arial Black, Impact and Webdings to their system. Although it is possible that a few users might remove these fonts from their system, we do not recommend that you embed them.

Up Back to list of questions

Can I use Type 1 fonts?
If you have specified Type 1 fonts as your first choice fonts and have Adobe Type Manager installed, these fonts will be identified by WEFT. However, they will be flagged as 'status unknown', and you will not be able to embed them using the public preview version of WEFT.

Up Back to list of questions

Is it possible to have Internet Explorer 3.x and Internet Explorer 4.0 coexist on the same machine?
No, there are no plans to support the coexistence of these two Internet Explorer versions at this time. Internet Explorer 3.x and Internet Explorer 4.0 share system components that cannot exist in multiple copies on the same machine.

Up Back to list of questions

What is the difference between ADO and ADOR, and which should I be using on my Web pages?
The Active Data Object (ADO) components ship in two forms - one for a Web server, and another for the client. The ADO component installed with Internet Explorer 4.0 is the ADO Recordset (ADOR). ADOR provides an object model for script access to data supplied by a data source object (DSO) embedded in a Web page. It does not, however, provide ADO Connection or Command objects. These are provided only as part of the server installation.

Included with the Internet Client SDK in self-extracting archives is the full set of ADO components. When building applications using ADO for Internet Explorer 4.0, your client side scripts should depend only on the availability of the Recordset object. The full ADO interfaces are intended for use with Active Server Pages and custom business objects that run on a Web server. Refer to Mdac.txt in the Inetsdk\Bin folder for more details.

Up Back to list of questions

What do I need to do to migrate my Web application from IE3.x to IE4.0?
Refer to iecompat.htm under \inetsdk\help for compatibility issues between IE3.x and IE4.0.

Up Back to list of questions

I don't see the debug versions of wininet.dll and urlmon.dll in the Internet Client SDK. This used to be very helpful for me in IE3.x; where did they go?
The debug version of these DLL's (urlmon pending) ship with the Internet Client SDK under the \inetsdk\lib\debug subdirectory. Along with it is a file, inetdbg.txt, with information on how to enable debugging and how to interpret the generated log file.

Up Back to list of questions

Where can I find more information about the NetMeeting API?
The NetMeeting API's are documented under the Component Library section of the Internet Client SDK. That section also includes an FAQ on the NetMeeting SDK.

Up Back to list of questions


Authoring Notes for Migrating from Internet Explorer 3.0 to Internet Explorer 4.0

Compatibility is a key priority for Microsoft® Internet Explorer 4.0. As much as possible, we want to ensure that users who upgrade from Internet Explorer 3.0 will not be affected adversely. Goals for compatibility are:

  • Compliance with existing W3C standards—CSS1, HTML 4, and so on.

  • Accurate rendering of content on the Web. Web site authors expect Internet Explorer 4.0 to render their pages as they designed them.

Users should experience the behavior they expect, and Internet Explorer achieves this within the boundaries of the aforementioned goals. The combination of these factors and some bug fixes causes Internet Explorer 4.0 to render some pages differently from Internet Explorer 3.0. While we have kept these differences to a minimum, some issues are unavoidable. The following sections outline the most salient differences that authors will encounter.

  • General Authoring Issues

  • CSS Compatibility with Internet Explorer 3.0

  • Using Different Style Sheets

  • International Issues

General Authoring Issues

Summary or Symptom in IE4  | Description  | Reason

FRAMESET inside a BODY is ignored. FRAMESET and BODY are mutually exclusive tags for IE4. Either use one, or the other. If you use both, the second one will be ignored.
If you are using the BODY element to set attributes for the contents of the FRAMESET, move these attributes to the FRAMESET.

Any SCRIPT or OBJECT tags used in a FRAMESET definition document should be defined in the HEAD section of the document, otherwise they will imply a BODY element, and the FRAMESET will be ignored.
Compliance with HTML 4 DTD

Improved table width algorithm. IE4 calculates the width of a table more accurately than IE3, and consequently matches the way many web sites were designed. For example, if the combined widths of the cells in a table exceed the width set for the TABLE, IE4 uses the cumulative width of the cells to override the width set for TABLE. IE3 would have adjusted the widths of the cells to fit the width of the TABLE.
TFOOT, TBODY, THEAD were rendered in source order for IE3. According to W3C specifications, the order of these table elements should not matter. IE4 matches the spec. For example, if a TFOOT appears first in source order, IE4 will still render the contents of the TFOOT at the end of the table.
Better compatibility with real-world pages.

Case sensitivity Javascript is case sensitive in IE4. Some real-world pages rely on capitalization to result in different variables being defined. Case insensitivity was breaking those scripts.
Entities are case-sensitive. They were not in IE3, except where case-sensitivity was meaningful. For example, &nbsp works for both, but &NBSP will only work on IE3.
Javascript compatibility
Microsoft applications read and generate case sensitive HTML entities.

Use system's Window color  | If a document does not have its own BGCOLOR specified, IE4 sets the background color based on the system's Windows color, where as IE3 set the window background to the system's default button-face color.  | Consistency with other Microsoft applications.

mouse* events renamed  | mouse* events are non-standard. They are now onmouse*.  | JavaScript compatibility

Unknown attributes are exposed as implicitly declared variables ("expando feature")  | Any unknown attribute on an element is exposed as an implicitly declared property on the element. This enables authors to specify initial values for implicitly declared properties in their HTML pages. Also known as the "expando" feature.  | Enhancement - better compatibility with real world pages.

Accessing X-object properties for ActiveX controls  | X-object properties are properties which are exposed by the IE4 container on all objects in IE4. If an object has a property or method which conflicts with an X-object property/method, then the object's property/method should be accessed explicitly as item.object.property, instead of item.property.  | Enhancement

Page cache (1) IE3 kept the last 4 pages in memory as they were rendered. When the user hit the back arrow, IE3 pulled the page straight from cache to the screen. This caused some subtle problems. For instance, Scripts were not re-run (for instance, the onload event was not fired), dynamically generated content was not up-to-date (like a script generating the local time), and this mechanism used a lot of memory.
IE4 implements a history mechanism, which stores the URL of a page (or the URL list of a frameset) and associates a "history stream" with the URL . When the user navigates away from a page, the document and the objects living in the document get a chance to save their state. Things that are saved as part of the history of the document include the document's vertical scroll position, form values, and information from controls which specifically implement the IPersistHistory interface.  Controls which want to persist their state must support IPersistHistory.
Better support for dynamic pages and existing content

Page caching (2) IE30 - doesn't always pull from the cache for a repeat visit to a page with a form.
IE40 - always pulls from the cache if HTTP (won't pull from cache for HTTPs).

Solution:

Put the following in the META tag in the HEAD of the document:

<META HTTP-EQUIV="expires" CONTENT="0">
Bug fix

Form submission with a GET method <FORM METHOD=get
ACTION="http://www.Microsoft.com?value1=boo">

For the above HTML, IE3 would submit the name/value pair "value1=boo" to the server. IE4 ignores the part of the action after the "?" and forms the submit string based on the contents of the form.
Better compatibility with existing content.

CSS Compatibility with Internet Explorer 3.0

Internet Explorer 3.0 introduced cascading style sheets (CSS) to the Web with the first implementation of a working draft from the World Wide Web Consortium (W3C). Since this time, the W3C style sheets working group has published a CSS recommendation. The Internet Explorer 4.0 implementation of CSS is based on the final CSS recommendation. What this means for authors is that the CSS implementation is a richer, complete implementation that also includes bug fixes and reflects any specification changes made from earlier drafts. The following is a list of issues that might affect authors who have authored pages using CSS in Internet Explorer 3.0. In some cases, we've fixed bugs, and in other cases there have been specification changes or clarifications.

Authors might choose to use separate style sheets for Internet Explorer 3.0 and Internet Explorer 4.0. See the section following the table for ideas on how to use separate style sheets for each browser.

Summary or Symptom in IE4  | Description  | Reason

Multiple stylesheets  | IE3 applied only one (the last) styleSheets for a page. IE4 supports multiple stylesheets per page - including multiple linked and imported stylesheets.  | Better CSS support

HTML vs. CSS inheritance Correct inheritance when style properties are mixed with HTML properties. In IE3, style properties always override any non-styleSheets rendering properties. For example, if text-decoration is set to "none" on the <HTML> tag, <A> tags would not be underlined (this is incorrect). In IE4, underlining is removed only if text-decoration is set to "none" on all <A> tags, not the <HTML> tag.
Another example: IE3 would set margins on the BODY relative to the default BODY margins or the margins set with the TOPMARGIN and LEFTMARGIN attributes. IE4 correctly overrides HTML settings with CSS, so these attributes (as well as the default margin settings) are overridden with a CSS margin set for the BODY.
Spec Compliance

Better CSS support - margins IE4 correctly implements vertical margin (top and bottom) collapsing; inserted non-overridable margins between paragraph elements. IE4 collapses vertical margins together, as per specifications, and vertical paragraph margins are overridden by any top- and bottom-margins on the paragraphs.
IE4 replaces margin values, where IE3 would add the margin value to the default margin value.
Spec Compliance

Better CSS support - line-height  | An earlier working draft of the CSS specification said that line-height should be measured between baselines. The CSS Recommendation states that line-height is calculated as the "line-box" (includes leading for ascenders and decenders) and that the balance of space is split between the top and bottom of the line.  | Spec Compliance

CSS inheritance in tables IE3.0 - TABLE, TR, TD were treated as any other element, and CSS inheritance rules applied as they would to any other element.
IE4.0 - treats CSS formatting for tables the same as HTML formatting elements. Precedence for HTML formatting attributes dictate that TABLE formatting does not inherit from previous content. Therefore, CSS attributes are not inherited by TABLE elements either.

NOTE: the defaults for these formatting elements can be set by the BODY, and do not necessarily default to their initial values.

BODY and LINKed stylesheets  | IE3 didn't handle background images and body properties set through linked stylesheets. IE4 does.  | Bug fix

Comments  | IE3 supported C++ style comments - IE4 does not  | Spec compliance

HR inherits color property from the BODY  | Setting the color property for the BODY would affect the color of an HR. IE4 does not pick up the color from the BODY.   | Spec Compliance

background on block level elements In IE3, the background would not extend to the complete width of the element. In IE4 it does.
For example, in IE3, only the text contained in a DIV would have a background color. In IE4 the entire rectangle for the DIV gets the background setting.
Spec compliance

font-size calculation IE3 - the font size is calculated as a percent of the elements default/initial font size
IE4 - the font-size is calculated as a percent of the parent element's font size

If you set a font-size style for H1 to 85%, for example, the font will be slightly smaller than a normal H1 in IE3, but it will be smaller than normal text in IE4.
Bug fix

Error handling  | IE3 would throw errors for missing/bad linked stylesheets - IE4 will fail silently  | Better user experience

Using Different Style Sheets

Several techniques can be used to tailor your page for use in Internet Explorer 3.0 and Internet Explorer 4.0 using cascading style sheets. This section describes two of them:

  • use multiple style sheets, and place Internet Explorer 4.0 specific styles in the primary style sheet, or

  • use @import to import Internet Explorer 4.0 specific styles

  • use the Document Object Model to manipulate the style sheets if Internet Explorer 4.0 is in use

Using Multiple Style Sheets

To use this technique, observe these facts about Internet Explorer 3.0:

  • only a single style sheet is supported

  • the disabled attribute is not supported

Define multiple style sheets using the STYLE or LINK elements within a document. Add Internet Explorer 3.0 specific style information to the last style sheet defined in the document. Internet Explorer 3.0 uses the last style sheet it encounters. To prevent Internet Explorer 4.0 from using it, add the disabled attribute.

For example, given the following style sheet:

<STYLE TITLE=css_ie4>
   body   {font-weight:bold}
</STYLE>
<STYLE TITLE=css_ie3 DISABLED>
   body   {font-style:italic}
</STYLE>

Internet Explorer 4.0 will set the content within the body of the document to bold, but Internet Explorer 3.0 will italicize that same content.

Use @import

Internet Explorer 3.0 does not support @import, so define Internet Explorer 4.0 specific styles in a separate file, and use @import to import them.

When Internet Explorer 4.0 loads a document containing the following HTML code, it will import and use the style sheet information in "ie4specfic.css". Because the LINK element includes the disabled attribute, Internet Explorer 4.0 will not apply the styles. On the other hand, Internet Explorer 3.0 will use the styles defined in "ie3specific.css" because:

  1. it is the last style sheet encountered

  2. the disabled attribute is ignored

<STYLE>
   @import url(ie4specific.css);
</STYLE>
<LINK disabled REL="stylesheet" HREF ="ie3specific.css">

In the following example, Internet Explorer 4.0 uses the styles contained within "ie4specific.css" as well as the styles defined directly within the STYLE tag. Internet Explorer 3.0 only applies the h1 and h2 styles.

<STYLE>
   @import url(ie4specific.css);
   h1  {color:green}
   h2  {font-style:italic}
</STYLE>

Using the Document Object Model to Manipulate Style Sheets

Internet Explorer 4.0 exposes styles and style sheets through the Document Object Model. Styles and style sheets can be added, styles can be removed, and style sheets can be disabled using any installed scripting language. To use this technique,

  • check for Internet Explorer 4.0 or greater at document load time,

  • disable the first style sheet in the styleSheets collection,

  • add a new style sheet

The following code can be associated with the onload event of the body.

<SCRIPT>
function HandleOnLoad()
{
   cUA = window.navigator.userAgent;
   if (parseInt(cUA.substring(cUA.indexOf("MSIE ")+5,
      cUA.indexOf( ".", cUA.indexOf ( "MSIE " ) ))) >= 4)
   {
      document.styleSheets[0].disabled = true;
      document.createStyleSheet("ie4specific.css");
   }
}
</SCRIPT>

International Issues

Summary or Symptom in IE4  | Description  | Reason

One NCR represents one character  | Under DBCS language, such as Japanese, Chinese, and Korean, a pair of NCRs (Numeric Character References) are treated as one double byte character in IE3. For instance, &#136;&#159; is rendered as Chinese character U+4e9c (Unicode codepoint) in IE3 with charset=Shift_JIS. In IE4 the same pair is displayed as two high-ANSI characters in IE4.  | Bug Fix

Line spacing   | For FE fonts where leading is not 0, IE4 increases the font height by 1/8 for better readability of ascenders and decenders.  | Enhancement

Font linking Font linking enables display characters that are not supported by the specified font.
<FONT FACE=Arial>some double byte characters here</FONT>.

For IE3, non ASCII characters enclosed by a FONT element are displayed in default glyphs (looks like garbage to the end user). For the same scenario, IE4 fontlinking picks up an appropriate font if IE4 can find one. IE4 uses the information you provide under View.Options.Fonts. You can use the Multilanguage support offered on the IE4 download site or shipped with NT4 to add fonts for languages that are not native to your system.
Enhancement

Express Unicode values directly.  | IE3 interpreted NCRs (&#nnn) as bytes within the system's active code page. IE4 interprets the NCRs as Unicode code points. This breaks compatibility with pages authored for IE3 using NCRs and designed for character sets other than Latin1. (IE4 treats less than 256 as Latin1, and greater than 256 as Unicode.)  | Better compatibility with existing pages.

Carriage return is treated as white space  | In IE3, carriage returns (White space) in the source of FE characters result in one single space regardless of the contents.  IE4 collapses the space if the carriage return is between FE characters in source.  | Enhancement

FORM posting  | IE3 submits a <FORM> using the Window's character set of the local machine. IE4 submits form data using the character set that the <FORM> element is embedded in.  | Bug Fix


Index

Cabinet (CAB) Files, Tasks
CacheSize Property (ADO)
CacheSize Property Example (ADO)
Caching, Tasks
Cancel Method
Cancel Method Example
CancelBatch Method (ADO)
cancelBubble
CancelConnectLogin
CancelConnectLogin Method
CancelEntering
CancelEntering Method
CancelUpdate Method
CancelUpdate Method (ADO)
CancelUpdate Method Example
CANRESIZE
CANRESIZEX
CANRESIZEY
CAPTION (HTML Elements)
CAPTION (Objects)
caption (Properties)
CascadeWindows Method
CaseSensitive
CB_DELETESTRING
CB_FINDSTRINGEXACT
CB_GETCOUNT
CB_GETCURSEL
CB_GETDROPPEDCONTROLRECT
CB_GETDROPPEDSTATE
CB_GETEXTENDEDUI
CB_GETITEMDATA
CB_GETITEMHEIGHT
CB_GETLBTEXT
CB_GETLBTEXTLEN
CB_LIMITTEXT
CB_RESETCONTENT
CB_SELECTSTRING
CB_SETCURSEL
CB_SETDROPPEDWIDTH
CB_SETEXTENDEDUI
CB_SETITEMDATA
CB_SETITEMHEIGHT
CB_SHOWDROPDOWN
CBEM_DELETEITEM
CBEM_GETCOMBOCONTROL
CBEM_GETEDITCONTROL
CBEM_GETEXTENDEDSTYLE
CBEM_GETIMAGELIST
CBEM_GETITEM
CBEM_GETUNICODEFORMAT
CBEM_HASEDITCHANGED
CBEM_INSERTITEM
CBEM_SETEXTENDEDSTYLE
CBEM_SETIMAGELIST
CBEM_SETITEM
CBEM_SETUNICODEFORMAT
CBEN_BEGINEDIT
CBEN_DELETEITEM
CBEN_DRAGBEGIN
CBEN_ENDEDIT
CBEN_GETDISPINFO
CBEN_INSERTITEM
CBES_EX_CASESENSITIVE
CBES_EX_NOEDITIMAGE
CBES_EX_NOEDITIMAGEINDENT
CBES_EX_NOSIZELIMIT
CBES_EX_PATHWORDBREAKPROC
CCS_ADJUSTABLE
CCS_BOTTOM
CCS_LEFT
CCS_NODIVIDER
CCS_NOMOVEX
CCS_NOMOVEY
CCS_NOPARENTALIGN
CCS_NORESIZE
CCS_RIGHT
CCS_TOP
CCS_VERT
cellIndex
cellPadding
CELLPADDING=
cells
cellSpacing
CELLSPACING=
CENTER (HTML Elements)
CENTER (Objects)
center (showModalDialog)
CHANENUM_CHANNELFOLDER
CHANENUM_DESKTOPFOLDER
CHANENUM_PATH
CHANENUM_SOFTUPDATEFOLDER
CHANENUM_SUBSCRIBESTATE
CHANENUM_TITLE
CHANENUM_URL
ChangeChannelProperty
ChangeChannelProperty Method
ChangeColor Method
ChangeMemberProperty
ChangeMemberProperty Method
ChangeNickname
ChangeNickname Method
ChangeStrength Method
ChangeUserProperty
ChangeUserProperty Method
Changing HTML Content
CHANNEL (CDF Elements)
Channel (Object Properties)
Channel Definition Format (CDF), Tasks
Channel Manager Object
Channel Properties
CHANNEL_AGENT_DYNAMIC_SCHEDULE
CHANNEL_AGENT_FLAGS
CHANNEL_AGENT_PRECACHE_ALL
CHANNEL_AGENT_PRECACHE_SCRNSAVER
CHANNEL_AGENT_PRECACHE_SOME
ChannelAgeMax
ChannelAgeMin
CHANNELCATEGORYINFO
ChannelCount
CHANNELENUMFLAGS
CHANNELENUMINFO
channelmode
ChannelName
ChannelName Property
ChannelProperty (Channel Object: Properties)
ChannelProperty (MsChatPr Object: Properties)
ChannelProperty Property (Channel Object: Properties)
ChannelProperty Property (MsChatPr Object: Properties)
Channels
Channels (User Properties)
Channels Property
Channels, Tasks
CHANNELSHORTCUTINFO
ChannelState
ChannelState Property
ChannelTopic
ChannelTopic Property
charset
CharSet (Properties)
Chat Control, Tasks
checkbox
checkbox (type)
checked
children
choosecolordlg (IHTMLOptionsHolder)
ChrCmpI
Chroma Filter Effect
chsClosed
chsOpen
chsOpening
CIDA
CIP_STATUS
CITE (HTML Elements)
CITE (Objects)
CLASS
class ID (CLSID) <definition>
CLASS= (A)
CLASS= (ACRONYM)
CLASS= (ADDRESS)
CLASS= (APPLET)
CLASS= (AREA)
CLASS= (B)
CLASS= (BASEFONT)
CLASS= (BGSOUND)
CLASS= (BIG)
CLASS= (BLOCKQUOTE)
CLASS= (BODY)
CLASS= (BR)
CLASS= (BUTTON)
CLASS= (CAPTION)
CLASS= (CENTER)
CLASS= (CITE)
CLASS= (CODE)
CLASS= (COL)
CLASS= (COLGROUP)
CLASS= (DD)
CLASS= (DEL)
CLASS= (DFN)
CLASS= (DIR)
CLASS= (DIV)
CLASS= (DL)
CLASS= (DT)
CLASS= (EM)
CLASS= (EMBED)
CLASS= (FIELDSET)
CLASS= (FONT)
CLASS= (FORM)
CLASS= (FRAME)
CLASS= (FRAMESET)
CLASS= (HEAD)
CLASS= (Hn)
CLASS= (HR)
CLASS= (I)
CLASS= (IFRAME)
CLASS= (IMG)
CLASS= (INPUT)
CLASS= (INS)
CLASS= (ISINDEX)
CLASS= (KBD)
CLASS= (LABEL)
CLASS= (LEGEND)
CLASS= (LI)
CLASS= (MAP)
CLASS= (MARQUEE)
CLASS= (MENU)
CLASS= (OBJECT)
CLASS= (OL)
CLASS= (OPTION)
CLASS= (P)
CLASS= (PLAINTEXT)
CLASS= (PRE)
CLASS= (Q)
CLASS= (S)
CLASS= (SAMP)
CLASS= (SCRIPT)
CLASS= (SELECT)
CLASS= (SMALL)
CLASS= (SPAN)
CLASS= (STRIKE)
CLASS= (STRONG)
CLASS= (SUB)
CLASS= (SUP)
CLASS= (TABLE)
CLASS= (TBODY)
CLASS= (TD)
CLASS= (TEXTAREA)
CLASS= (TFOOT)
CLASS= (TH)
CLASS= (THEAD)
CLASS= (TR)
CLASS= (TT)
CLASS= (U)
CLASS= (UL)
CLASS= (VAR)
CLASS= (WBR)
CLASS= (XMP)
classid
CLASSID= (CLASS)
CLASSID= (CODE)
CLASSID= (OBJECT)
CLASSID= (TYPELIB)
className
clear (CSS Attributes)
clear (Methods: 1)
clear (Methods: 2)
clear (Properties: 1)
clear (Properties: 2)
clear (IHTMLDocument2)
clear (IHTMLSelectionObject)
Clear Method
Clear Method (ADO)
CLEAR=
ClearHistory
ClearHistory Method
clearInterval
clearInterval (IHTMLWindow2)
clearRequest
clearRequest (IHTMLOpsProfile)
clearTimeout
clearTimeout (IHTMLWindow2)
click
click (IHTMLElement)
client tier <definition>
ClientData
ClientGuid
clientHeight
clientInformation
clientLeft
clientTop
ClientToWindow
ClientToWindow (IWebBrowser2)
ClientToWindow Method
clientWidth
clientX
clientY
clip (CSS Attributes)
clip (Properties)
Clone
Clone (IActiveScript)
Clone (IEnumChannels)
Clone (IEnumIDList)
Clone (IEnumOleDocumentViews)
Clone (IEnumWorkItems)
Clone (IHlinkBrowseContext)
Clone (IOleDocumentView)
Clone Method (ADO)
Clone Method Example (ADO)
CloneList
Close (Hyperlinks: Reference: IHlinkBrowseContext)
close (Methods: 1)
close (Methods: 2)
Close (IActiveScript)
Close (IHlinkBrowseContext)
close (IHTMLDialog)
close (IHTMLDocument2)
close (IHTMLWindow2)
Close Method (ADO)
closed
CloseDW (IDockingWindow)
CloseHandle
CloseView (IOleDocumentView)

* More entries...


Index

DAILY
data
Data Binding
Data Binding, Adding Navigation Support
Data Binding, Adding Records
Data Binding, Architecture
Data Binding, Binding Agent
Data Binding, Binding Consumers to Data
Data Binding, Data Consumer Events
Data Binding, Data Source Object Events
Data Binding, Deleting Records
Data Binding, Document Object Model Support
Data Binding, Element Quick Reference
Data Binding, Event Quick Reference
Data Binding, Extensions
Data Binding, Handling Events
Data Binding, Inserting a Data Source Object
Data Binding, Introducing
Data Binding, Introducing Data Consumers
Data Binding, Introducing Data Source Objects
Data Binding, Modifying Records
Data Binding, Repetition Agent
Data Binding, Supported Elements
Data Binding, Using ADO
Data Binding, Using MSHTML as a Data Source Object
Data Binding, Using RDS as a Data Source Object
Data Binding, Using the JDBC Data Source Object
Data Binding, Using the TDC as a Data Source Object
data provider <definition>
data source <definition>
data source tier <definition>
DATA=
data-aware control <definition>
DataControl Object (API Reference)
DataFactory Object (API Reference)
dataFld
DATAFLD= (A)
DATAFLD= (APPLET)
DATAFLD= (BUTTON)
DATAFLD= (DIV)
DATAFLD= (FRAME)
DATAFLD= (IFRAME)
DATAFLD= (IMG)
DATAFLD= (LABEL)
DATAFLD= (MARQUEE)
DATAFLD= (OBJECT)
DATAFLD= (PARAM)
DATAFLD= (SELECT)
DATAFLD= (SPAN)
DATAFLD= (TEXTAREA)
dataFormatAs
DATAFORMATAS= (BUTTON)
DATAFORMATAS= (DIV)
DATAFORMATAS= (LABEL)
DATAFORMATAS= (MARQUEE)
DATAFORMATAS= (PARAM)
DATAFORMATAS= (SPAN)
dataPageSize
DATAPAGESIZE=
DataSpace Object (API Reference)
dataSrc
DATASRC= (A)
DATASRC= (APPLET)
DATASRC= (BUTTON)
DATASRC= (DIV)
DATASRC= (FRAME)
DATASRC= (IFRAME)
DATASRC= (IMG)
DATASRC= (LABEL)
DATASRC= (MARQUEE)
DATASRC= (OBJECT)
DATASRC= (PARAM)
DATASRC= (SELECT)
DATASRC= (SPAN)
DATASRC= (TABLE)
DATASRC= (TEXTAREA)
DataURL
DateTime_GetMonthCal
DateTime_GetMonthCalColor
DateTime_GetMonthCalFont
DateTime_GetRange
DateTime_GetSystemtime
DateTime_SetFormat
DateTime_SetMonthCalColor
DateTime_SetMonthCalFont
DateTime_SetRange
DateTime_SetSystemtime
DAY= (EARLIESTTIME)
DAY= (INTERVALTIME)
DAY= (LATESTTIME)
DBID_BANDINFOCHANGED
DBID_MAXIMIZEBAND
DCOM <definition>
DD (HTML Elements)
DD (Objects)
Debug Property Interfaces
Default URL Security Zones
defaultCharset
defaultChecked
DefaultDatabase Property (ADO)
defaultSelected
defaultStatus
defaultValue
DefDlgProc
Defer (Properties: 1)
defer (Properties: 2)
DefinedSize Property (ADO)
Defining a Recordset
Defining Custom Events
Defining Event Handlers
DefScreenSaverProc
DefWindowProc
DEL (HTML Elements)
DEL (Objects)
Delete
Delete (ITaskScheduler)
Delete Command
Delete Method (Collection - ADO)
Delete Method (Recordset - ADO)
Delete Method Example (ADO)
deleteCaption
deleteCaption (IHTMLTable)
DeleteCategory (IChannelMgr)
deleteCell
deleteCell (IHTMLTableRow)
DeleteChannelShortcut (IChannelMgr)
DeleteEntries (IABContainer)
DeleteEntries (IDistList)
DeleteFile
DeleteGroup
DeleteItem
DeleteMemberByDispID
DeleteMemberByDispID (IDispatchEx)
DeleteMemberByName
DeleteMemberByName (IDispatchEx)
DeleteMenu
DeleteObject
DELETEONINSTALL
DeleteProps (IABContainer)
DeleteProps (IAddrBook)
DeleteProps (IDistList)
DeleteProps (IMailUser)
deleteRow
deleteRow (IHTMLTable)
deleteRow (IHTMLTableSection)
DeleteSubscription (ISubscriptionMgr)
DeleteTab (ITaskbarList)
deleteTFoot
deleteTFoot (IHTMLTable)
deleteTHead
deleteTHead (IHTMLTable)
DeleteTrigger (IScheduledWorkItem)
DeleteUrlCacheEntry
DeleteUrlCacheGroup
DEPENDENCY
Description Property (ADO)
Description, HelpContext, HelpFile, NativeError, Number, Source, and SQLState Properties Example (ADO)
design time <definition>
Designing a Scriptlet
Designing and Using Scriptlets
Designing Characters for Microsoft Agent
DESKBANDINFO
DestroyIcon
DestroyPropertySheetPage
DestroyViewWindow (IShellView)
DestroyWindow
DestroyZoneEnumerator (IInternetZoneManager)
Detailed Control Flow
Details (IAddrBook)
Developing Remote Data Service Applications
DEVMODE
DFN (HTML Elements)
DFN (Objects)
dialogArguments
dialogHeight
dialogHeight (showModalDialog)
dialogLeft
dialogLeft (showModalDialog)
dialogTop
dialogTop (showModalDialog)
dialogWidth
dialogWidth (showModalDialog)
DIR (HTML Elements)
DIR (Objects)
direction
Direction Property (ADO)
DIRECTION=
directories
DISABLED (HTML Elements: BUTTON: 1)
DISABLED (HTML Elements: INPUT: 2)
DISABLED (HTML Elements: LINK: 3)
DISABLED (HTML Elements: SELECT: 4)
DISABLED (HTML Elements: STYLE: 5)
DISABLED (HTML Elements: TEXTAREA: 6)
disabled (Properties: 1)
disabled (Properties: 2)
Disconnect
Disconnect Method
disconnected recordset <definition>
DISMISSMODELESS
DispatchMessage
DISPID_AMBIENT_DLCTL
display (CSS Attributes)
display (Properties)
DisplayBackColor Property
DisplayForeColor Property
Displaying Data Through a Bound Control
DisplayMode Property
DisplayModeChange Event
DIV (HTML Elements)
DIV (Objects)
DL (HTML Elements)
DL (Objects)
DL_BEGINDRAG
DL_CANCELDRAG
DL_DRAGGING
DL_DROPPED
DLCTL_BGSOUNDS
DLCTL_DLIMAGES
DLCTL_DOWNLOADONLY
DLCTL_FORCEOFFLINE
DLCTL_NO_CLIENTPULL
DLCTL_NO_DLACTIVEXCTLS
DLCTL_NO_FRAMEDOWNLOAD
DLCTL_NO_JAVA
DLCTL_NO_RUNACTIVEXCTLS
DLCTL_NO_SCRIPTS
DLCTL_OFFLINE
DLCTL_OFFLINEIFNOTCONNECTED
DLCTL_PRAGMA_NO_CACHE
DLCTL_RESYNCHRONIZE
DLCTL_SILENT
DLCTL_VIDEOS
DLGITEMTEMPLATE
DLGTEMPLATE
DLL (dynamic-link library) <definition>
DllCanUnloadNow
DllEntryPoint
DllGetClassObject
DllGetVersion
DLLGETVERSIONPROC
DLLVERSIONINFO
DM_SETDEFID
DOCHOSTUIDBLCLK
DOCHOSTUIFLAG
DOCHOSTUIINFO
DOCMISC
document
Document (Properties)
Document Property
DocumentComplete
DocumentComplete (DWebBrowserEvents2)
DocumentComplete Event
DoDragDrop
DoIt Method
domain
doReadRequest
doReadRequest (IHTMLOpsProfile)
DownloadBegin
DownloadBegin (DWebBrowserEvents2)
DownloadBegin Event
DownloadComplete
DownloadComplete (DWebBrowserEvents2)
DownloadComplete Event
DragAcceptFiles
DragFinish
DRAGLISTINFO
DragQueryFile
DragQueryPoint
DrawFrameControl
DrawInsert
DRAWITEMSTRUCT
DrawStatusText
DrawText
Drop Shadow Filter Effect
DROPFILES
DT (HTML Elements)
DT (Objects)
DTM_GETMCCOLOR
DTM_GETMCFONT
DTM_GETMONTHCAL
DTM_GETRANGE
DTM_GETSYSTEMTIME
DTM_SETFORMAT
DTM_SETMCCOLOR
DTM_SETMCFONT
DTM_SETRANGE
DTM_SETSYSTEMTIME
DTN_CLOSEUP

* More entries...


Index

GenerateDesktopItemHtml (IActiveDesktop)
get__newEnum (IHTMLAreasCollection)
get__newEnum (IHTMLElementCollection)
get__newEnum (IHTMLFiltersCollection)
get__newEnum (IHTMLFontNamesCollection)
get__newEnum (IHTMLFontSizesCollection)
get__newEnum (IHTMLFormElement)
get__newEnum (IHTMLSelectElement)
get__newEnum (IHTMLStyleSheetsCollection)
get__newEnum (IHTMLWindow2)
get_accessKey (IHTMLAnchorElement)
get_accessKey (IHTMLControlElement)
get_accessKey (IHTMLLabelElement)
get_action (IHTMLFormElement)
get_action (IHTMLIsIndexElement)
get_activeElement (IHTMLDocument2)
get_AddressBar (IWebBrowser2)
get_align (IHTMLDivElement)
get_align (IHTMLDivPosition)
get_align (IHTMLFieldSetElement)
get_align (IHTMLHeaderElement)
get_align (IHTMLHRElement)
get_align (IHTMLIFrameElement)
get_align (IHTMLImgElement)
get_align (IHTMLInputImage)
get_align (IHTMLLegendElement)
get_align (IHTMLObjectElement)
get_align (IHTMLParaElement)
get_align (IHTMLSpanFlow)
get_align (IHTMLTable)
get_align (IHTMLTableCaption)
get_align (IHTMLTableCell)
get_align (IHTMLTableCol)
get_align (IHTMLTableRow)
get_align (IHTMLTableSection)
get_aLink (IHTMLBodyElement)
get_alinkColor (IHTMLDocument2)
get_all (IHTMLDocument2)
get_all (IHTMLElement)
get_alt (IHTMLAreaElement)
get_alt (IHTMLImgElement)
get_alt (IHTMLInputImage)
get_altHtml (IHTMLObjectElement)
get_altKey (IHTMLEventObj)
get_anchors (IHTMLDocument2)
get_appCodeName (IOmNavigator)
get_applets (IHTMLDocument2)
get_Application (IWebBrowser2)
get_appMinorVersion (IOmNavigator)
get_appName (IOmNavigator)
get_appVersion (IOmNavigator)
get_areas (IHTMLMapElement)
get_Attribute (IXMLElement)
get_availHeight (IHTMLScreen)
get_availWidth (IHTMLScreen)
get_background (IHTMLBodyElement)
get_background (IHTMLRuleStyle)
get_background (IHTMLStyle)
get_background (IHTMLTable)
get_background (IHTMLTableCell)
get_backgroundAttachment (IHTMLRuleStyle)
get_backgroundAttachment (IHTMLStyle)
get_backgroundColor (IHTMLRuleStyle)
get_backgroundColor (IHTMLStyle)
get_backgroundImage (IHTMLRuleStyle)
get_backgroundImage (IHTMLStyle)
get_backgroundPosition (IHTMLRuleStyle)
get_backgroundPosition (IHTMLStyle)
get_backgroundPositionX (IHTMLRuleStyle)
get_backgroundPositionX (IHTMLStyle)
get_backgroundPositionY (IHTMLRuleStyle)
get_backgroundPositionY (IHTMLStyle)
get_backgroundRepeat (IHTMLRuleStyle)
get_backgroundRepeat (IHTMLStyle)
get_balance (IHTMLBGsound)
get_BaseHref (IHTMLObjectElement)
get_behavior (IHTMLMarqueeElement)
get_bgColor (IHTMLBodyElement)
get_bgColor (IHTMLDocument2)
get_bgColor (IHTMLMarqueeElement)
get_bgColor (IHTMLTable)
get_bgColor (IHTMLTableCell)
get_bgColor (IHTMLTableRow)
get_bgColor (IHTMLTableSection)
get_bgProperties (IHTMLBodyElement)
get_body (IHTMLDocument2)
get_border (IHTMLFrameBase)
get_border (IHTMLFrameSetElement)
get_border (IHTMLImgElement)
get_border (IHTMLInputImage)
get_border (IHTMLRuleStyle)
get_border (IHTMLStyle)
get_border (IHTMLTable)
get_borderBottom (IHTMLRuleStyle)
get_borderBottom (IHTMLStyle)
get_borderBottomColor (IHTMLRuleStyle)
get_borderBottomColor (IHTMLStyle)
get_borderBottomStyle (IHTMLRuleStyle)
get_borderBottomStyle (IHTMLStyle)
get_borderBottomWidth (IHTMLRuleStyle)
get_borderBottomWidth (IHTMLStyle)
get_borderColor (IHTMLFrameElement)
get_borderColor (IHTMLFrameSetElement)
get_borderColor (IHTMLRuleStyle)
get_borderColor (IHTMLStyle)
get_borderColor (IHTMLTable)
get_borderColor (IHTMLTableCell)
get_borderColor (IHTMLTableRow)
get_borderColorDark (IHTMLTable)
get_borderColorDark (IHTMLTableCell)
get_borderColorDark (IHTMLTableRow)
get_borderColorLight (IHTMLTable)
get_borderColorLight (IHTMLTableCell)
get_borderColorLight (IHTMLTableRow)
get_borderLeft (IHTMLRuleStyle)
get_borderLeft (IHTMLStyle)
get_borderLeftColor (IHTMLRuleStyle)
get_borderLeftColor (IHTMLStyle)
get_borderLeftStyle (IHTMLRuleStyle)
get_borderLeftStyle (IHTMLStyle)
get_borderLeftWidth (IHTMLRuleStyle)
get_borderLeftWidth (IHTMLStyle)
get_borderRight (IHTMLRuleStyle)
get_borderRight (IHTMLStyle)
get_borderRightColor (IHTMLRuleStyle)
get_borderRightColor (IHTMLStyle)
get_borderRightStyle (IHTMLRuleStyle)
get_borderRightStyle (IHTMLStyle)
get_borderRightWidth (IHTMLRuleStyle)
get_borderRightWidth (IHTMLStyle)
get_borderStyle (IHTMLRuleStyle)
get_borderStyle (IHTMLStyle)
get_borderTop (IHTMLRuleStyle)
get_borderTop (IHTMLStyle)
get_borderTopColor (IHTMLRuleStyle)
get_borderTopColor (IHTMLStyle)
get_borderTopStyle (IHTMLRuleStyle)
get_borderTopStyle (IHTMLStyle)
get_borderTopWidth (IHTMLRuleStyle)
get_borderTopWidth (IHTMLStyle)
get_borderWidth (IHTMLRuleStyle)
get_borderWidth (IHTMLStyle)
get_bottomMargin (IHTMLBodyElement)
get_browserLanguage (IOmNavigator)
get_bufferDepth (IHTMLScreen)
get_Busy (IWebBrowser2)
get_button (IHTMLEventObj)
get_cancelBubble (IHTMLEventObj)
get_caption (IHTMLTable)
get_cellIndex (IHTMLTableCell)
get_cellPadding (IHTMLTable)
get_cells (IHTMLTableRow)
get_cellSpacing (IHTMLTable)
get_charset (IHTMLDocument2)
get_charset (IHTMLMetaElement)
get_charset (IXMLDocument)
get_checked (IHTMLOptionButtonElement)
get_children (IHTMLElement)
get_children (IXMLElement)
get_classid (IHTMLObjectElement)
get_className (IHTMLElement)
get_clear (IHTMLBlockElement)
get_clear (IHTMLBRElement)
get_clear (IHTMLRuleStyle)
get_clear (IHTMLStyle)
get_clientHeight (IHTMLControlElement)
get_clientInformation (IHTMLWindow2)
get_clientLeft (IHTMLControlElement)
get_clientTop (IHTMLControlElement)
get_clientWidth (IHTMLControlElement)
get_clientX (IHTMLEventObj)
get_clientY (IHTMLEventObj)
get_clip (IHTMLRuleStyle)
get_clip (IHTMLStyle)
get_closed (IHTMLWindow2)
get_code (IHTMLObjectElement)
get_codeBase (IHTMLObjectElement)
get_codeType (IHTMLObjectElement)
get_color (IHTMLBaseFontElement)
get_color (IHTMLFontElement)
get_color (IHTMLHRElement)
get_color (IHTMLRuleStyle)
get_color (IHTMLStyle)
get_colorDepth (IHTMLScreen)
get_cols (IHTMLFrameSetElement)
get_cols (IHTMLTable)
get_cols (IHTMLTextAreaElement)
get_colSpan (IHTMLTableCell)
get_compact (IHTMLDListElement)
get_compact (IHTMLOListElement)
get_compact (IHTMLUListElement)
get_complete (IHTMLImgElement)
get_complete (IHTMLInputImage)
get_connectionSpeed (IOmNavigator)
get_Container (IWebBrowser2)
get_content (IHTMLMetaElement)
get_cookie (IHTMLDocument2)
get_cookieEnabled (IOmNavigator)
get_coords (IHTMLAreaElement)
get_cpuClass (IOmNavigator)
get_cssText (IHTMLRuleStyle)
get_cssText (IHTMLStyle)
get_cssText (IHTMLStyleSheet)
get_ctrlKey (IHTMLEventObj)
get_cursor (IHTMLRuleStyle)
get_cursor (IHTMLStyle)
get_data (IHTMLObjectElement)
get_dataFld (IHTMLDatabinding)
get_dataFormatAs (IHTMLDatabinding)
get_dataPageSize (IHTMLTable)
get_dataSrc (IHTMLDatabinding)
get_defaultCharset (IHTMLDocument2)
get_defaultChecked (IHTMLOptionButtonElement)
get_defaultSelected (IHTMLOptionElement)
get_defaultStatus (IHTMLWindow2)
get_defaultValue (IHTMLInputTextElement)
get_defaultValue (IHTMLTextAreaElement)
get_defer (IHTMLScriptElement)
get_dialogArguments (IHTMLDialog)
get_dialogHeight (IHTMLDialog)
get_dialogLeft (IHTMLDialog)

* More entries...


Index

I (HTML Elements)
I (Objects)
IABContainer
IABContainer::CopyEntries
IABContainer::CopyProps
IABContainer::CopyTo
IABContainer::CreateEntry
IABContainer::DeleteEntries
IABContainer::DeleteProps
IABContainer::GetContentsTable
IABContainer::GetHierarchyTable
IABContainer::GetIDsFromNames
IABContainer::GetLastError
IABContainer::GetNamesFromIDs
IABContainer::GetPropList
IABContainer::GetProps
IABContainer::GetSearchCriteria
IABContainer::OpenEntry
IABContainer::OpenProperty
IABContainer::ResolveNames
IABContainer::SaveChanges
IABContainer::SetProps
IABContainer::SetSearchCriteria
IABTable::Abort
IABTable::Advise
IABTable::CollapseRow
IABTable::CreateBookmark
IABTable::ExpandRow
IABTable::FindRow
IABTable::FreeBookmark
IABTable::GetCollapseState
IABTable::GetLastError
IABTable::GetRowCount
IABTable::GetStatus
IABTable::QueryColumns
IABTable::QueryPosition
IABTable::QueryRows
IABTable::QuerySortOrder
IABTable::Restrict
IABTable::SeekRow
IABTable::SeekRowApprox
IABTable::SetCollapseState
IABTable::SetColumns
IABTable::SortTable
IABTable::Unadvise
IABTable::WaitForCompletion
IActiveDesktop
IActiveDesktop::AddDesktopItem
IActiveDesktop::AddDesktopItemWithUI
IActiveDesktop::AddUrl
IActiveDesktop::ApplyChanges
IActiveDesktop::GenerateDesktopItemHtml
IActiveDesktop::GetDesktopItem
IActiveDesktop::GetDesktopItemByID
IActiveDesktop::GetDesktopItemBySource
IActiveDesktop::GetDesktopItemCount
IActiveDesktop::GetDesktopItemOptions
IActiveDesktop::GetPattern
IActiveDesktop::GetWallpaper
IActiveDesktop::GetWallpaperOptions
IActiveDesktop::ModifyDesktopItem
IActiveDesktop::RemoveDesktopItem
IActiveDesktop::SetDesktopItemOptions
IActiveDesktop::SetPattern
IActiveDesktop::SetWallpaper
IActiveDesktop::SetWallpaperOptions
IActiveScript::AddNamedItem
IActiveScript::AddTypeLib
IActiveScript::Clone
IActiveScript::Close
IActiveScript::GetCurrentScriptThreadID
IActiveScript::GetScriptDispatch
IActiveScript::GetScriptSite
IActiveScript::GetScriptState
IActiveScript::GetScriptThreadID
IActiveScript::GetScriptThreadState
IActiveScript::InterruptScriptThread
IActiveScript::SetScriptSite
IActiveScript::SetScriptState
IActiveScriptError::GetExceptionInfo
IActiveScriptError::GetSourceLineText
IActiveScriptError::GetSourcePosition
IActiveScriptParse::AddScriptlet
IActiveScriptParse::InitNew
IActiveScriptParse::ParseScriptText
IActiveScriptSite::GetDocVersionString
IActiveScriptSite::GetItemInfo
IActiveScriptSite::GetLCID
IActiveScriptSite::OnEnterScript
IActiveScriptSite::OnLeaveScript
IActiveScriptSite::OnScriptError
IActiveScriptSite::OnScriptTerminate
IActiveScriptSite::OnStateChange
IActiveScriptSiteWindow::EnableModeless
IActiveScriptSiteWindow::GetWindow
IAddrBook
IAddrBook::Address
IAddrBook::Advise
IAddrBook::CompareEntryIDs
IAddrBook::CopyProps
IAddrBook::CopyTo
IAddrBook::CreateOneOff
IAddrBook::DeleteProps
IAddrBook::Details
IAddrBook::GetDefaultDir
IAddrBook::GetIDsFromNames
IAddrBook::GetLastError
IAddrBook::GetNamesFromIDs
IAddrBook::GetPAB
IAddrBook::GetPropList
IAddrBook::GetProps
IAddrBook::GetSearchPath
IAddrBook::NewEntry
IAddrBook::OpenEntry
IAddrBook::OpenProperty
IAddrBook::PrepareRecips
IAddrBook::QueryDefaultRecipOpt
IAddrBook::RecipOptions
IAddrBook::ResolveName
IAddrBook::SaveChanges
IAddrBook::SetDefaultDir
IAddrBook::SetPAB
IAddrBook::SetProps
IAddrBook::SetSearchPath
IAddrBook::Unadvise
IAdviseSink
IAdviseSink::OnViewChange
IAsyncMoniker
IAuthenticate
IAuthenticate::Authenticate
IBindCtx
IBindCtx::RegisterObjectBound
IBindHost
IBindHost::CreateMoniker
IBindHost::CreateMoniker (The IBindHost Interface)
IBindHost::MonikerBindToObject
IBindHost::MonikerBindToObject (The IBindHost Interface)
IBindHost::MonikerBindToStorage
IBindHost::MonikerBindToStorage (The IBindHost Interface)
IBinding
IBinding::Abort
IBinding::GetBindResult
IBinding::GetPriority
IBinding::Resume
IBinding::SetPriority
IBinding::Suspend
IBindProtocol
IBindStatusCallback
IBindStatusCallback::GetBindInfo
IBindStatusCallback::GetPriority
IBindStatusCallback::OnDataAvailable
IBindStatusCallback::OnLowResource
IBindStatusCallback::OnObjectAvailable
IBindStatusCallback::OnProgress
IBindStatusCallback::OnStartBinding
IBindStatusCallback::OnStopBinding
ICatRegister::RegisterClassImplCategories
IChannelMgr
IChannelMgr::AddCategory
IChannelMgr::AddChannelShortcut
IChannelMgr::DeleteCategory
IChannelMgr::DeleteChannelShortcut
IChannelMgr::EnumChannels
IClassFactory
IClassFactory::CreateInstance
IClassFactory::LockServer
ICodeInstall
ICommDlgBrowser
ICommDlgBrowser::IncludeObject
ICommDlgBrowser::OnDefaultCommand
ICommDlgBrowser::OnStateChange
ICON
IConnectionPoint
IConnectionPoint::Unadvise
IConnectionPointContainer
IContextMenu
IContextMenu::GetCommandString
IContextMenu::InvokeCommand
IContextMenu::QueryContextMenu
IContextMenu2
IContextMenu2::GetCommandString
IContextMenu2::HandleMenuMsg
IContextMenu2::InvokeCommand
IContextMenu2::QueryContextMenu
IContextMenu3
IContextMenu3::HandleMenuMsg2
IContinueCallback::FContinue
IContinueCallback::FContinuePrinting
ICopyHook
ICopyHook::CopyCallback
ICSSFilter::OnAmbientPropertyChange
ICSSFilter::SetSite
ICSSFilterSite::FireOnFilterChangeEvent
ICSSFilterSite::GetElement
ICustomDoc::SetUIHandler
id
ID= (A)
ID= (ACRONYM)
ID= (ADDRESS)
ID= (APPLET)
ID= (AREA)
ID= (B)
ID= (BASEFONT)
ID= (BGSOUND)
ID= (BIG)
ID= (BLOCKQUOTE)
ID= (BODY)
ID= (BR)
ID= (BUTTON)
ID= (CAPTION)
ID= (CENTER)
ID= (CITE)
ID= (CODE)
ID= (COL)
ID= (COLGROUP)
ID= (COMMENT)
ID= (DD)
ID= (DEL)
ID= (DFN)
ID= (DIR)
ID= (DIV)
ID= (DL)
ID= (DT)
ID= (EM)
ID= (EMBED)
ID= (FIELDSET)
ID= (FONT)
ID= (FORM)
ID= (FRAME)
ID= (FRAMESET)
ID= (HEAD)
ID= (Hn)
ID= (HR)
ID= (I)
ID= (IFRAME)
ID= (IMG)
ID= (INPUT)
ID= (INS)
ID= (ISINDEX)
ID= (KBD)
ID= (LABEL)
ID= (LEGEND)
ID= (LI)
ID= (LINK)
ID= (LISTING)
ID= (MAP)
ID= (MARQUEE)
ID= (MENU)
ID= (NOBR)
ID= (NOFRAMES)
ID= (OBJECT)
ID= (OL)
ID= (OPTION)
ID= (P)
ID= (PLAINTEXT)
ID= (PRE)
ID= (Q)
ID= (S)
ID= (SAMP)
ID= (SCRIPT)
ID= (SELECT)
ID= (SMALL)
ID= (SPAN)
ID= (STRIKE)
ID= (STRONG)
ID= (SUB)
ID= (SUP)
ID= (TABLE)
ID= (TBODY)
ID= (TD)
ID= (TEXTAREA)
ID= (TFOOT)
ID= (TH)
ID= (THEAD)
ID= (TITLE)
ID= (TR)
ID= (TT)
ID= (U)
ID= (UL)
ID= (VAR)
ID= (WBR)
ID= (XMP)

* More entries...


Index

LABEL (HTML Elements)
LABEL (Objects)
Lag
lang
LANG= (A)
LANG= (ACRONYM)
LANG= (ADDRESS)
LANG= (AREA)
LANG= (B)
LANG= (BASEFONT)
LANG= (BGSOUND)
LANG= (BIG)
LANG= (BLOCKQUOTE)
LANG= (BODY)
LANG= (BR)
LANG= (BUTTON)
LANG= (CAPTION)
LANG= (CENTER)
LANG= (CITE)
LANG= (CODE)
LANG= (COMMENT)
LANG= (DD)
LANG= (DEL)
LANG= (DFN)
LANG= (DIR)
LANG= (DIV)
LANG= (DL)
LANG= (DT)
LANG= (EM)
LANG= (FIELDSET)
LANG= (FONT)
LANG= (FORM)
LANG= (FRAME)
LANG= (FRAMESET)
LANG= (Hn)
LANG= (HR)
LANG= (HTML)
LANG= (I)
LANG= (IFRAME)
LANG= (IMG)
LANG= (INPUT)
LANG= (INS)
LANG= (ISINDEX)
LANG= (KBD)
LANG= (LABEL)
LANG= (LEGEND)
LANG= (LI)
LANG= (LISTING)
LANG= (MAP)
LANG= (MARQUEE)
LANG= (MENU)
LANG= (OBJECT)
LANG= (OL)
LANG= (OPTION)
LANG= (P)
LANG= (PLAINTEXT)
LANG= (PRE)
LANG= (Q)
LANG= (S)
LANG= (SAMP)
LANG= (SELECT)
LANG= (SMALL)
LANG= (SPAN)
LANG= (STRIKE)
LANG= (STRONG)
LANG= (SUB)
LANG= (SUP)
LANG= (TABLE)
LANG= (TBODY)
LANG= (TD)
LANG= (TEXTAREA)
LANG= (TFOOT)
LANG= (TH)
LANG= (THEAD)
LANG= (TR)
LANG= (TT)
LANG= (U)
LANG= (UL)
LANG= (VAR)
LANG= (WBR)
LANG= (XMP)
language
LANGUAGE (CDF Elements)
Language (Object Properties: Channel Properties)
Language (Properties)
Language Codes
LANGUAGE= (A)
LANGUAGE= (ACRONYM)
LANGUAGE= (ADDRESS)
LANGUAGE= (AREA)
LANGUAGE= (B)
LANGUAGE= (BIG)
LANGUAGE= (BLOCKQUOTE)
LANGUAGE= (BODY)
LANGUAGE= (BR)
LANGUAGE= (BUTTON)
LANGUAGE= (CAPTION)
LANGUAGE= (CENTER)
LANGUAGE= (CITE)
LANGUAGE= (CODE)
LANGUAGE= (DD)
LANGUAGE= (DEL)
LANGUAGE= (DFN)
LANGUAGE= (DIR)
LANGUAGE= (DIV)
LANGUAGE= (DL)
LANGUAGE= (DT)
LANGUAGE= (EM)
LANGUAGE= (FIELDSET)
LANGUAGE= (FONT)
LANGUAGE= (FORM)
LANGUAGE= (FRAME)
LANGUAGE= (FRAMESET)
LANGUAGE= (Hn)
LANGUAGE= (HR)
LANGUAGE= (I)
LANGUAGE= (IFRAME)
LANGUAGE= (IMG)
LANGUAGE= (INPUT)
LANGUAGE= (INS)
LANGUAGE= (ISINDEX)
LANGUAGE= (KBD)
LANGUAGE= (LABEL)
LANGUAGE= (LEGEND)
LANGUAGE= (LI)
LANGUAGE= (LISTING)
LANGUAGE= (MARQUEE)
LANGUAGE= (OBJECT)
LANGUAGE= (OL)
LANGUAGE= (OPTION)
LANGUAGE= (P)
LANGUAGE= (PLAINTEXT)
LANGUAGE= (PRE)
LANGUAGE= (Q)
LANGUAGE= (S)
LANGUAGE= (SAMP)
LANGUAGE= (SCRIPT)
LANGUAGE= (SELECT)
LANGUAGE= (SMALL)
LANGUAGE= (SPAN)
LANGUAGE= (STRIKE)
LANGUAGE= (STRONG)
LANGUAGE= (SUB)
LANGUAGE= (SUP)
LANGUAGE= (TABLE)
LANGUAGE= (TBODY)
LANGUAGE= (TD)
LANGUAGE= (TEXTAREA)
LANGUAGE= (TFOOT)
LANGUAGE= (TH)
LANGUAGE= (THEAD)
LANGUAGE= (TR)
LANGUAGE= (TT)
LANGUAGE= (U)
LANGUAGE= (UL)
LANGUAGE= (VAR)
LANGUAGE= (WBR)
LANGUAGE= (XMP)
LanguageOp
LastMessageReceived
LastMessageReceived Property
LastMessageSent
LastMessageSent Property
LASTMOD= (CHANNEL)
LASTMOD= (ITEM)
lastModified
LATESTTIME
LBItemFromPoint
LBItemFromPt
LDAPUrl (IWABObject)
LeaveChannel
LeaveChannel Method
left (CSS Attributes)
left (open)
left (Properties)
Left (Reusing the WebBrowser Control: Reference for Visual Basic Developers: Properties)
Left Property
leftMargin
LEFTMARGIN=
LEGEND (HTML Elements)
LEGEND (Objects)
length
letterSpacing
letter-spacing
LEVEL= (CHANNEL)
LEVEL= (ITEM)
LI (HTML Elements)
LI (Objects)
Light Filter Effect
lineHeight
line-height
link (CSS Attributes)
LINK (HTML Elements)
LINK (Objects)
link (Properties)
LINK=
linkColor
links
ListChannels
ListChannels Method
ListCount
LISTING (HTML Elements)
LISTING (Objects)
ListMembers
ListMembers Method
listStyle
list-style
listStyleImage
list-style-image
listStylePosition
list-style-position
listStyleType
list-style-type
ListUsers
ListUsers Method
ListView_ApproximateViewRect
ListView_Arrange
ListView_CreateDragImage
ListView_DeleteAllItems
ListView_DeleteColumn
ListView_DeleteItem
ListView_EditLabel
ListView_EnsureVisible
ListView_FindItem
ListView_GetBkColor
ListView_GetBkImage
ListView_GetCallbackMask
ListView_GetCheckState
ListView_GetColumn
ListView_GetColumnOrderArray
ListView_GetColumnWidth
ListView_GetCountPerPage
ListView_GetEditControl
ListView_GetExtendedListViewStyle
ListView_GetHeader
ListView_GetHotCursor
ListView_GetHotItem
ListView_GetHoverTime
ListView_GetImageList
ListView_GetISearchString
ListView_GetItem
ListView_GetItemCount
ListView_GetItemPosition
ListView_GetItemRect
ListView_GetItemSpacing
ListView_GetItemState
ListView_GetItemText
ListView_GetNextItem
ListView_GetNumberOfWorkAreas
ListView_GetOrigin
ListView_GetSelectedCount
ListView_GetSelectionMark
ListView_GetStringWidth
ListView_GetSubItemRect
ListView_GetTextBkColor
ListView_GetTextColor
ListView_GetToolTips
ListView_GetTopIndex
ListView_GetUnicodeFormat
ListView_GetViewRect
ListView_GetWorkAreas
ListView_HitTest
ListView_InsertColumn
ListView_InsertItem
ListView_RedrawItems
ListView_Scroll
ListView_SetBkColor
ListView_SetBkImage
ListView_SetCallbackMask
ListView_SetColumn
ListView_SetColumnOrderArray
ListView_SetColumnWidth
ListView_SetExtendedListViewStyle
ListView_SetExtendedListViewStyleEx
ListView_SetHotCursor
ListView_SetHotItem
ListView_SetHoverTime
ListView_SetIconSpacing
ListView_SetImageList
ListView_SetItem
ListView_SetItemCount
ListView_SetItemCountEx
ListView_SetItemPosition
ListView_SetItemPosition32
ListView_SetItemState
ListView_SetItemText
ListView_SetSelectionMark
ListView_SetTextBkColor
ListView_SetTextColor
ListView_SetToolTips
ListView_SetUnicodeFormat
ListView_SetWorkAreas
ListView_SortItems
ListView_SubItemHitTest

* More entries...


Index

P (HTML Elements)
P (Objects)
PACKAGE
padding (CSS Attributes)
padding (Properties)
paddingBottom
padding-bottom
paddingLeft
padding-left
paddingRight
padding-right
paddingTop
padding-top
pageBreakAfter
page-break-after
pageBreakBefore
page-break-before
PageCount Property (ADO)
Pager_ForwardMouse
Pager_GetBkColor
Pager_GetBorder
Pager_GetButtonSize
Pager_GetButtonState
Pager_GetDropTarget
Pager_GetPos
Pager_RecalcSize
Pager_SetBkColor
Pager_SetBorder
Pager_SetButtonSize
Pager_SetChild
Pager_SetPos
PAGERANGE
PAGESET
PageSize Property (ADO)
palette
PARAM
Parameter Object (ADO)
Parameters Collection (ADO)
parent
Parent (Properties)
Parent Property (Folder Object)
Parent Property (FolderItem Object)
Parent Property (FolderItems Object)
Parent Property (FolderItemVerb Object)
Parent Property (FolderItemVerbs Object)
Parent Property (Properties)
Parent Property (Shell Object)
Parent Property (ShellFolderView Object)
parentElement (Methods)
parentElement (Properties)
parentElement (IHTMLTxtRange)
ParentFolder Property
parentStyleSheet
parentTextEdit
parentWindow
PARSE_ANCHOR
PARSE_CANONICALIZE
PARSE_DECODE
PARSE_DOCUMENT
PARSE_DOMAIN
PARSE_ENCODE
PARSE_FRIENDLY
PARSE_LOCATION
PARSE_MIME
PARSE_PATH_FROM_URL
PARSE_ROOTDOCUMENT
PARSE_SCHEMA
PARSE_SECURITY_DOMAIN
PARSE_SECURITY_URL
PARSE_SERVER
PARSE_SITE
PARSE_URL_FROM_PATH
PARSEACTION
ParseDisplayName (IShellFolder)
ParseName Method
ParseScriptText (IActiveScriptParse)
ParseUrl (IInternetProtocolInfo)
Passing Updated Recordsets to the Middle Tier
password
password (type)
Paste
Paste Command
pasteHTML
pasteHTML (IHTMLTxtRange)
Path
Path Property (FolderItem Object)
Path Property (Properties)
PathAddBackslash
PathAddExtension
PathAppend
PathBuildRoot
PathCanonicalize
PathCombine
PathCommonPrefix
PathCompactPath
PathCompactPathEx
PathFileExists
PathFindExtension
PathFindFileName
PathFindNextComponent
PathFindOnPath
PathGetArgs
PathGetCharType
PathGetDriveNumber
PathIsContentType
PathIsDirectory
PathIsFileSpec
PathIsHTMLFile
PathIsPrefix
PathIsRelative
PathIsRoot
PathIsSameRoot
PathIsSystemFolder
PathIsUNC
PathIsUNCServer
PathIsUNCServerShare
PathIsURL
PathMakePretty
PathMakeSystemFolder
PathMatchSpec
pathname
PathParseIconLocation
PathQuoteSpaces
PathRelativePathTo
PathRemoveArgs
PathRemoveBackslash
PathRemoveBlanks
PathRemoveExtension
PathRemoveFileSpec
PathRenameExtension
PathSearchAndQualify
PathSetDlgItemPath
PathSkipRoot
PathStripPath
PathStripToRoot
PathUnmakeSystemFolder
PathUnquoteSpaces
Pause Method
PBM_DELTAPOS
PBM_GETPOS
PBM_GETRANGE
PBM_SETBARCOLOR
PBM_SETBKCOLOR
PBM_SETPOS
PBM_SETRANGE
PBM_SETRANGE32
PBM_SETSTEP
PBM_STEPIT
PBRANGE
PBS_SMOOTH
PBS_VERTICAL
PD_FORCE_SWITCH
PGM_FORWARDMOUSE
PGM_GETBKCOLOR
PGM_GETBORDER
PGM_GETBUTTONSIZE
PGM_GETBUTTONSTATE
PGM_GETDROPTARGET
PGM_GETPOS
PGM_RECALCSIZE
PGM_SETBKCOLOR
PGM_SETBORDER
PGM_SETBUTTONSIZE
PGM_SETCHILD
PGM_SETPOS
PGN_CALCSIZE
PGN_SCROLL
PGS_AUTOSCROLL
PGS_DRAGNDROP
PGS_HORZ
PGS_VERT
PI_APARTMENTTHREADED
PI_CLASSINSTALL
PI_CLSIDLOOKUP
PI_DATAPROGRESS
PI_FILTER_MODE
PI_FLAGS
PI_FORCE_ASYNC
PI_MIMEVERIFICATION
PI_PARSE_URL
PI_SYNCHRONOUS
PI_USE_WORKERTHREAD
pixelHeight
pixelLeft
pixelTop
pixelWidth
PLAINTEXT (HTML Elements)
PLAINTEXT (Objects)
platform
Play Method
PlayCount Property
PlayImage
PlayImage Command
PLUGIN_AUTH_FLAGS_CAN_HANDLE_NO_PASSWD
PLUGIN_AUTH_FLAGS_CAN_HANDLE_UI
PLUGIN_AUTH_FLAGS_KEEP_ALIVE_NOT_REQUIRED
PLUGIN_AUTH_FLAGS_NO_REALM
PLUGIN_AUTH_FLAGS_UNIQUE_CONTEXT_PER_TCPIP
plugins (Collections)
plugins (Properties)
pluginspage
pmtAction
pmtAway
pmtCTCP
pmtData
pmtDataRaw
pmtDataReply
pmtDataRequest
pmtInfo
pmtLagTime
pmtLocalTime
pmtNormal
pmtNotice
pmtSound
pmtVersion
POINT
POINTL
POINTS
PopupItemMenu Method
port
posHeight
position (CSS Attributes)
position (Properties)
PositionChange Event
Positioning and Animation
posLeft
PostFiles
PostMessage
posTop
PostQuitMessage
posWidth
PRE (HTML Elements)
PRE (Objects)
PRECACHE= (CHANNEL)
PRECACHE= (ITEM)
PRECACHE= (SOFTPKG)
Precision Property (ADO)
Prepared Property (ADO)
Prepared Property Example (ADO)
PrepareRecips (IAddrBook)
previousPage
previousPage (IHTMLTable)
Print (IPrint)
PRINTFLAG
PrintTo (IFileViewer)
PROCESSOR
ProcessProtocolMessages
ProcessProtocolMessages Property
ProcessUrlAction (IInternetHostSecurityManager)
ProcessUrlAction (IInternetSecurityManager)
Profile Assistant, Tasks
Programming the Microsoft Agent Control
Programming the Microsoft Agent Server Interface
ProgressChange
ProgressChange (DWebBrowserEvents2)
ProgressChange Event
prompt
prompt (IHTMLWindow2)
PROMPT=
PromptAction (IInternetZoneManager)
PROP_LG_CXDLG
PROP_LG_CYDLG
PROP_MED_CXDLG
PROP_MED_CYDLG
PROP_SM_CXDLG
PROP_SM_CYDLG
PROPBAG2
PROPBAG2_TYPE
Properties Collection (ADO)
Property Object (ADO)
PropertyAccessTimeOut
PropertyAccessTimeOut Property
PropertyChange
PropertyChange (DWebBrowserEvents2)
PropertyChange Event
PropertySheet
PropSheet_AddPage
PropSheet_Apply
PropSheet_CancelToClose
PropSheet_Changed
PropSheet_GetCurrentPageHwnd
PropSheet_GetTabControl
PropSheet_IsDialogMessage
PropSheet_PressButton
PropSheet_QuerySiblings

* More entries...


Index

S (HTML Elements)
S (Objects)
SAFEARRAY
SAMP (HTML Elements)
SAMP (Objects)
Sample and Demo Applications
Save (IPersistMemory)
Save (IPersistMoniker)
Save (IPersistPropertyBag)
Save (IPersistPropertyBag2)
SaveChanges (IABContainer)
SaveChanges (IAddrBook)
SaveChanges (IDistList)
SaveChanges (IMailUser)
SaveCompleted (IPersistMoniker)
savefiledlg (IHTMLOptionsHolder)
SaveHistory (IPersistHistory)
SaveViewState (IOleDocumentView)
SaveViewState (IShellView)
SB_GETBORDERS
SB_GETPARTS
SB_GETRECT
SB_GETTEXT
SB_GETTEXTLENGTH
SB_GETTIPTEXT
SB_GETUNICODEFORMAT
SB_ISSIMPLE
SB_SETBKCOLOR
SB_SETICON
SB_SETMINHEIGHT
SB_SETPARTS
SB_SETTEXT
SB_SETTIPTEXT
SB_SETUNICODEFORMAT
SB_SIMPLE
SBARS_SIZEGRIP
SBN_SIMPLEMODECHANGE
SCHEDULE
SCOPE=
screen
ScreenSaverConfigureDialog
ScreenSaverProc
screenX
screenY
SCRIPT (HTML Elements)
SCRIPT (Objects)
Script Property
Scriptlet Container Object Reference
Scriptlet Model Extensions
Scriptlets Overview
scripts
SCRIPTSTATE
SCRIPTTHREADSTATE
scroll (Methods)
scroll (Properties)
scroll (IHTMLWindow2)
SCROLL=
scrollAmount
SCROLLAMOUNT=
Scrollbar Property (1)
scrollbar Property (2)
scrollbars
scrollBy
scrollBy (IHTMLWindow2)
scrollDelay
SCROLLDELAY=
scrollHeight
SCROLLINFO
scrolling
SCROLLING= (FRAME)
SCROLLING= (IFRAME)
scrollIntoView
scrollIntoView (IHTMLControlRange)
scrollIntoView (IHTMLElement)
scrollIntoView (IHTMLTxtRange)
scrollLeft
scrollTo
scrollTo (IHTMLWindow2)
scrollTop
scrollWidth
search
SECOND_IPADDRESS
sectionRowIndex
Security Zones, Tasks
SECURITY_ATTRIBUTES
SecurityPackages
See the Code in Action
Seek (IInternetProtocol)
SeekRow (IABTable)
SeekRowApprox (IABTable)
SELECT (HTML Elements)
select (Methods: 1)
select (Methods: 2)
SELECT (Objects)
select (IHTMLControlRange)
select (IHTMLInputFileElement)
select (IHTMLInputTextElement)
select (IHTMLTextAreaElement)
select (IHTMLTxtRange)
selectableContent Property
SelectAll
SelectAll Command
selected
SELECTED (OPTION)
selectedIndex
SelectedItems Method
selection
SelectionChanged Event
SelectionEnd Property
SelectionStart Property
SelectItem (IShellView)
SelectItem Method
select-multiple
select-one
SelectParticipants
SelectParticipants Method
self
SendControlMsg (IShellBrowser)
SendInvitation (Channel Object: Methods)
SendInvitation (MsChatPr Object: Methods)
SendInvitation Method (Channel Object: Methods)
SendInvitation Method (MsChatPr Object: Methods)
SendMessage
SendMessage (Methods)
SendMessage (Methods)
SendMessage Method
SendMessage Method (Methods)
SendPrivateMessage
SendPrivateMessage Method
SendProtocolMessage
SendProtocolMessage Method
Server
Server Properties
Server Property
Server Property Example
ServerInfo
ServerLogin
ServerLogout
ServerName
ServerName (User Properties)
ServerName Property
ServerProperty
ServerProperty Property
ServicePath
SetAbortCallback (IReconcileInitiator)
SetAccountInformation (IScheduledWorkItem)
SetActiveAlt (ITaskbarList)
SetAdditionalParams
SetAdditionalParams (IHlink)
SetApplicationName (ITask)
SetArguments (IShellLink)
setAttribute
setAttribute (IHTMLElement)
setAttribute (IHTMLRuleStyle)
setAttribute (IHTMLStyle)
setAttribute (IXMLElement)
SetAway
SetAway Method
SetBindingParam
SetBkColor
SetBorderSpaceDW (IDockingWindowSite)
SetBrowseContext
SetBrowseContext (IHlinkFrame)
SetBrowseContext (IHlinkTarget)
SetBrowseWindowInfo
SetBrowseWindowInfo (IHlinkBrowseContext)
SetCache (IInternetSession)
SetCollapseState (IABTable)
SetColumns (IABTable)
SetComment (IScheduledWorkItem)
setContextMenu Method
SetCreator (IScheduledWorkItem)
SetCurrentDirectory
SetCurrentHlink
SetCurrentHlink (IHlinkBrowseContext)
SetDefaultDir (IAddrBook)
SetDescription (IShellLink)
SetDesktopItemOptions (IActiveDesktop)
setEndPoint
setEndPoint (IHTMLTxtRange)
SetErrorRetryCount (IScheduledWorkItem)
SetErrorRetryInterval (IScheduledWorkItem)
SetFlags (IScheduledWorkItem)
SetFocus
SetFolder (INewShortcutHook)
SetFriendlyName
SetFriendlyName (IHlink)
SetHlinkSite
SetHlinkSite (IHlink)
SetHotkey (IShellLink)
SetIconLocation (IShellLink)
SetIdleWait (IScheduledWorkItem)
SetIDList (IShellLink)
SetInitialPageNum (IPrint)
SetInPlaceSite (IOleDocumentView)
SetInterfaceSafetyOptions
SetInterfaceSafetyOptions (IObjectSafety)
setInterval
setInterval (IHTMLWindow2)
SetMaxRunTime (ITask)
SetMe (IWABObject)
SetMenu
SetMenuContextHelpId
SetMenuSB (IShellBrowser)
SetMonikerReference
SetMonikerReference (IHlink)
SetNameOf (IShellFolder)
SetPAB (IAddrBook)
SetParam
SetParameters (ITask)
SetParent
SetParticipantStatus
SetParticipantStatus Method
SetPath (IShellLink)
SetPattern (IActiveDesktop)
SetPinnedWindow (IFileViewerSite)
SetPositionCookie (IPersistHistory)
SetPriority (IBinding)
SetPriority (ITask)
SetProgressFeedback (IReconcileInitiator)
SetProgressUpdateProc
SetProps (IABContainer)
SetProps (IAddrBook)
SetProps (IDistList)
SetProps (IMailUser)
SetRect (IOleDocumentView)
SetRectComplex (IOleDocumentView)
SetReferent (INewShortcutHook)
SetRelativePath (IShellLink)
SetScriptSite (IActiveScript)
SetScriptState (IActiveScript)
SetScrollInfo
SetScrollPos
SetScrollRange
SetSearchCriteria (IABContainer)
SetSearchCriteria (IDistList)
SetSearchPath (IAddrBook)
SetSecuritySite (IInternetSecurityManager)
SetSessionOption (IInternetSession)
SetShowCmd (IShellLink)
SetSite (ICSSFilter)
SetSite (IObjectWithSite)
SetStatusTextSB (IShellBrowser)
SetStringReference
SetStringReference (IHlink)
SetTargetComputer (ITaskScheduler)
SetTargetFrameName
SetTargetFrameName (IHlink)
SetTaskFlags (ITask)
SetTextColor
SetThreadPriority
SetTime Method
setTimeout
setTimeout (IHTMLWindow2)
Setting Up Remote Data Service (Getting Started)
SetToolbarItems (IShellBrowser)
SetTrigger (ITaskTrigger)
SetUIHandler (ICustomDoc)
SetURL (IUniformResourceLocator)

* More entries...


Index

Tab Control Extended Styles
Tab Control Item States
Tab Control Styles
TabCtrl_AdjustRect
TabCtrl_DeleteAllItems
TabCtrl_DeleteItem
TabCtrl_DeselectAll
TabCtrl_GetCurFocus
TabCtrl_GetCurSel
TabCtrl_GetExtendedStyle
TabCtrl_GetImageList
TabCtrl_GetItem
TabCtrl_GetItemCount
TabCtrl_GetItemRect
TabCtrl_GetRowCount
TabCtrl_GetToolTips
TabCtrl_GetUnicodeFormat
TabCtrl_HighlightItem
TabCtrl_HitTest
TabCtrl_InsertItem
TabCtrl_RemoveImage
TabCtrl_SetCurFocus
TabCtrl_SetCurSel
TabCtrl_SetExtendedStyle
TabCtrl_SetImageList
TabCtrl_SetItem
TabCtrl_SetItemExtra
TabCtrl_SetItemSize
TabCtrl_SetMinTabWidth
TabCtrl_SetPadding
TabCtrl_SetToolTips
TabCtrl_SetUnicodeFormat
tabIndex
TABINDEX= (A)
TABINDEX= (AREA)
TABINDEX= (INPUT)
TABINDEX= (OBJECT)
TABINDEX= (SELECT)
TABINDEX= (TEXTAREA)
TABLE (HTML Elements)
TABLE (Objects)
Tabular Data Control, Tasks
tagName
tags
tags (IHTMLAreasCollection)
tags (IHTMLElementCollection)
tags (IHTMLFormElement)
tags (IHTMLSelectElement)
taintEnabled
taintEnabled (IOmNavigator)
target
TARGET= (A)
TARGET= (AREA)
TARGET= (BASE)
TARGET= (FORM)
Task List, Active Channels
Task List, Active Desktop
Task List, Active Documents
Task List, ActiveX Controls
Task List, ActiveX Scripting
Task List, Authentication
Task List, Cabinet (CAB) Files
Task List, Caching
Task List, Channel Definition Format (CDF)
Task List, Channels
Task List, Chat Control
Task List, Common Controls
Task List, Connecting to the Internet
Task List, Downloading Internet Resources
Task List, Dynamic HTML
Task List, Extensible Markup Language (XML)
Task List, File Transfer Protocol (FTP)
Task List, Internet Cache
Task List, Microsoft Chat Control
Task List, MIME
Task List, Open Software Description (OSD)
Task List, Profile Assistant
Task List, Redistribution
Task List, Security Zones
Task List, Software Update Channels
Task List, Tabular Data Control (TDC)
Task List, Task Scheduler
Task List, Taskbar
Task List, URL Security Zones
Task List, WebBrowser Control
Task List, Windows Shell
Task Scheduler, Tasks
TASK_TRIGGER
TASK_TRIGGER_TYPE
Taskbar, Tasks
TASKPAGE
TB_ADDBITMAP
TB_ADDBUTTONS
TB_ADDSTRING
TB_AUTOSIZE
TB_BOTTOM
TB_BUTTONCOUNT
TB_BUTTONSTRUCTSIZE
TB_CHANGEBITMAP
TB_CHECKBUTTON
TB_COMMANDTOINDEX
TB_CUSTOMIZE
TB_DELETEBUTTON
TB_ENABLEBUTTON
TB_ENDTRACK
TB_GETANCHORHIGHLIGHT
TB_GETBITMAP
TB_GETBITMAPFLAGS
TB_GETBUTTON
TB_GETBUTTONINFO
TB_GETBUTTONSIZE
TB_GETBUTTONTEXT
TB_GETCOLORSCHEME
TB_GETDISABLEDIMAGELIST
TB_GETEXTENDEDSTYLE
TB_GETHOTIMAGELIST
TB_GETHOTITEM
TB_GETIMAGELIST
TB_GETINSERTMARK
TB_GETINSERTMARKCOLOR
TB_GETITEMRECT
TB_GETMAXSIZE
TB_GETOBJECT
TB_GETPADDING
TB_GETRECT
TB_GETROWS
TB_GETSTATE
TB_GETSTYLE
TB_GETTEXTROWS
TB_GETTOOLTIPS
TB_GETUNICODEFORMAT
TB_HIDEBUTTON
TB_HITTEST
TB_INDETERMINATE
TB_INSERTBUTTON
TB_INSERTMARKHITTEST
TB_ISBUTTONCHECKED
TB_ISBUTTONENABLED
TB_ISBUTTONHIDDEN
TB_ISBUTTONHIGHLIGHTED
TB_ISBUTTONINDETERMINATE
TB_ISBUTTONPRESSED
TB_LINEDOWN
TB_LINEUP
TB_LOADIMAGES
TB_MAPACCELERATOR
TB_MARKBUTTON
TB_MOVEBUTTON
TB_PAGEDOWN
TB_PAGEUP
TB_PRESSBUTTON
TB_REPLACEBITMAP
TB_SAVERESTORE
TB_SETANCHORHIGHLIGHT
TB_SETBITMAPSIZE
TB_SETBUTTONINFO
TB_SETBUTTONSIZE
TB_SETBUTTONWIDTH
TB_SETCMDID
TB_SETCOLORSCHEME
TB_SETDISABLEDIMAGELIST
TB_SETDRAWTEXTFLAGS
TB_SETEXTENDEDSTYLE
TB_SETHOTIMAGELIST
TB_SETHOTITEM
TB_SETIMAGELIST
TB_SETINDENT
TB_SETINSERTMARK
TB_SETINSERTMARKCOLOR
TB_SETMAXTEXTROWS
TB_SETPADDING
TB_SETPARENT
TB_SETROWS
TB_SETSTATE
TB_SETSTYLE
TB_SETTOOLTIPS
TB_SETUNICODEFORMAT
TB_THUMBPOSITION
TB_THUMBTRACK
TB_TOP
TBADDBITMAP
TBBUTTON
TBBUTTONINFO
TBINSERTMARK
TBM_CLEARSEL
TBM_CLEARTICS
TBM_GETBUDDY
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_GETTOOLTIPS
TBM_GETUNICODEFORMAT
TBM_SETBUDDY
TBM_SETLINESIZE
TBM_SETPAGESIZE
TBM_SETPOS
TBM_SETRANGE
TBM_SETRANGEMAX
TBM_SETRANGEMIN
TBM_SETSEL
TBM_SETSELEND
TBM_SETSELSTART
TBM_SETTHUMBLENGTH
TBM_SETTIC
TBM_SETTICFREQ
TBM_SETTIPSIDE
TBM_SETTOOLTIPS
TBM_SETUNICODEFORMAT
TBN_BEGINADJUST
TBN_BEGINDRAG
TBN_CUSTHELP
TBN_DELETINGBUTTON
TBN_DRAGOUT
TBN_DROPDOWN
TBN_ENDADJUST
TBN_ENDDRAG
TBN_GETBUTTONINFO
TBN_GETDISPINFO
TBN_GETINFOTIP
TBN_GETOBJECT
TBN_HOTITEMCHANGE
TBN_QUERYDELETE
TBN_QUERYINSERT
TBN_RESET
TBN_TOOLBARCHANGE
tbodies
TBODY (HTML Elements)
TBODY (Objects)
TBREPLACEBITMAP
TBS_AUTOTICKS
TBS_BOTH
TBS_BOTTOM
TBS_ENABLESELRANGE
TBS_FIXEDLENGTH
TBS_HORZ
TBS_LEFT
TBS_NOTHUMB
TBS_NOTICKS
TBS_RIGHT
TBS_TOOLTIPS
TBS_TOP
TBS_VERT
TBSAVEPARAMS
TBSTATE_CHECKED
TBSTATE_ELLIPSES
TBSTATE_ENABLED
TBSTATE_HIDDEN
TBSTATE_INDETERMINATE
TBSTATE_MARKED
TBSTATE_PRESSED
TBSTATE_WRAP
TBSTYLE_ALTDRAG
TBSTYLE_AUTOSIZE
TBSTYLE_BUTTON
TBSTYLE_CHECK
TBSTYLE_CHECKGROUP
TBSTYLE_CUSTOMERASE
TBSTYLE_DROPDOWN
TBSTYLE_EX_DRAWDDARROWS
TBSTYLE_FLAT
TBSTYLE_GROUP
TBSTYLE_LIST
TBSTYLE_NOPREFIX
TBSTYLE_REGISTERDROP
TBSTYLE_SEP
TBSTYLE_TOOLTIPS
TBSTYLE_TRANSPARENT
TBSTYLE_WRAPABLE
TC_HITTESTINFO
TC_ITEM
TC_ITEMHEADER
TC_KEYDOWN

* More entries...


Index

CLSCTX
CLSIDFromProgID
cmAuditorium
cmAuthOnly
cmClone
cmCloneable
cmCreateOnly
cmHidden
cmInvite
CMINVOKECOMMANDINFO
cmKnock
cmModerated
cmNoExtern
cmNoFormat
cmNone
cmNoWhisper
cmPrivate
cmPublic
cmRegistered
cmSecret
cmService
cmTopicop
CoCreateInstance
CODE (CDF Extensions for Software Update Channels: CDF Elements)
CODE (HTML Elements)
CODE (Objects)
code (Properties)
Code Signing
CODE= (APPLET)
CODE= (EMBED)
CODE= (OBJECT)
CODEBASE (CDF Extensions for Software Update Channels: CDF Elements)
codeBase (Properties: 1)
codeBase (Properties: 2)
CODEBASE= (APPLET)
CODEBASE= (EMBED)
CODEBASE= (OBJECT)
codeType
CODETYPE=
CoGetClassObjectFromURL
CoInitialize
CoInternetCombineUrl
CoInternetCompareUrl
CoInternetCreateSecurityManager
CoInternetCreateZoneManager
CoInternetGetProtocolFlags
CoInternetGetSecurityURL
CoInternetGetSession
CoInternetParseUrl
CoInternetQueryInfo
COL (HTML Elements)
COL (Objects)
COLGROUP (HTML Elements)
COLGROUP (Objects)
collapse
collapse (IHTMLTxtRange)
CollapseRow (IABTable)
color (CSS Attributes)
color (Properties: 1)
color (Properties: 2)
COLOR= (BASEFONT)
COLOR= (FONT)
COLOR= (HR)
colorDepth
COLORMAP
COLORREF
COLORSCHEME
cols (Properties: 1)
cols (Properties: 2)
cols (Properties: 3)
COLS= (FRAMESET)
COLS= (TABLE)
COLS= (TEXTAREA)
colSpan
COLSPAN= (TD)
COLSPAN= (TH)
CombineUrl (IInternetProtocolInfo)
ComboBoxEx control extended styles
COMBOBOXEXITEM
Command Object (ADO)
CommandStateChange
CommandStateChange (DWebBrowserEvents2)
CommandStateChange Event
CommandStateChangeConstants
CommandText Property (ADO)
CommandTimeout Property (ADO)
CommandType Property (ADO)
COMMENT (HTML Elements)
COMMENT (Objects)
Commit
CommitUrlCacheEntry
Common Controls, Tasks
commonParentElement (IHTMLControlRange)
COMP_ELEM_ALL
COMP_ELEM_CHECKED
COMP_ELEM_DIRTY
COMP_ELEM_FRIENDLYNAME
COMP_ELEM_NOSCROLL
COMP_ELEM_POS_LEFT
COMP_ELEM_POS_TOP
COMP_ELEM_POS_ZINDEX
COMP_ELEM_SIZE_HEIGHT
COMP_ELEM_SIZE_WIDTH
COMP_ELEM_SOURCE
COMP_ELEM_TYPE
COMP_TYPE_CFHTML
COMP_TYPE_CONTROL
COMP_TYPE_HTMLDOC
COMP_TYPE_MAX
COMP_TYPE_PICTURE
COMP_TYPE_WEBSITE
compact
COMPACT (DL)
compareEndPoints
compareEndPoints (IHTMLTxtRange)
CompareEntryIDs (IAddrBook)
CompareIDs (IShellFolder)
CompareUrl (IInternetProtocolInfo)
complete
COMPONENT
component <definition>
Component Object Model (COM) <definition>
COMPONENT_TOP
COMPONENTSOPT
COMPPOS
confirm
confirm (IHTMLWindow2)
Connect
Connect Method
Connect Property
Connect Property Example
Connection Object (ADO)
connection pooling <definition>
connectionSpeed
ConnectionState
ConnectionState Property
ConnectionString Property (ADO)
ConnectionString, ConnectionTimeout, and State Properties Example (ADO)
ConnectionTimeout Property (ADO)
ConnectionType
ConnectionType Property
Container
Container Property
contains
contains (IHTMLElement)
content
CONTENT=
context object <definition>
Continue (IInternetProtocolRoot)
ControlPanelItem Method
ConvertedString
ConvertedString Property
ConvertToString Method
ConvertToString Method Example
cookie
cookieEnabled
coords
COORDS=
Copy
Copy Command
CopyBindInfo
CopyCallback (ICopyHook)
CopyEntries (IABContainer)
CopyEntries (IDistList)
CopyHere Method
CopyProps (IABContainer)
CopyProps (IAddrBook)
CopyProps (IDistList)
CopyProps (IMailUser)
CopyStgMedium
CopyTo (IABContainer)
CopyTo (IAddrBook)
CopyTo (IDistList)
CopyTo (IMailUser)
CoTaskMemAlloc
CoTaskMemFree
Count
Count Property (FolderItems Object)
Count Property (FolderItemVerbs Object)
Count Property (Properties)
Count Property (ShellWindows Object)
Count Property (ADO)
Count Property Example (ADO)
CountProperties (IPropertyBag2)
CPL_DBLCLK
CPL_EXIT
CPL_GETCOUNT
CPL_INIT
CPL_INQUIRE
CPL_NEWINQUIRE
CPL_SELECT
CPL_STOP
CPlApplet
CPLINFO
cpuClass
create (IHTMLImageElementFactory)
create (IHTMLOptionElementFactory)
CreateAsyncBindCtx
CreateAsyncBindCtxEx
CreateBinding (IInternetSession)
CreateBookmark
CreateBookmark (IABTable)
CreateBookmark Command
createCaption
createCaption (IHTMLTable)
CreateChannel
CreateChannel Method
createControlRange (IHTMLTextContainer)
CreateDialogIndirect
createElement
createElement (IHTMLDocument2)
createElement (IXMLDocument)
CreateEntry (IABContainer)
CreateEntry (IDistList)
CreateFile
CreateFormatEnumerator
CreateGroup
CreateIcon
CreateLink
CreateLink Command
CreateMappedBitmap
CreateMoniker (IBindHost)
CreateMoniker (IBindHost) (The IBindHost Interface)
CreateObject Method
CreateOneOff (IAddrBook)
CreateParameter Method (ADO)
CreatePermBinding
CreateProcess
CreatePropertySheetPage
createRange
createRange (IHTMLSelectionObject)
CreateRecordset Method
CreateRecordset Method Example
CreateStatusWindow
createStyleSheet
CREATESUBS_ADDTOFAVORITES
CREATESUBS_FROMFAVORITES
CREATESUBS_NOSAVE
CREATESUBS_NOUI
CREATESUBS_SOFTWAREUPDATE
CreateSubscription (ISubscriptionMgr)
CREATESUBSCRIPTIONFLAGS
CreateTempBinding
createTextRange
createTextRange (IHTMLBodyElement)
createTextRange (IHTMLButtonElement)
createTextRange (IHTMLInputHiddenElement)
createTextRange (IHTMLInputTextElement)
createTextRange (IHTMLTextAreaElement)
createTFoot
createTFoot (IHTMLTable)
createTHead
createTHead (IHTMLTable)
CreateToolbarEx
CreateTrigger (IScheduledWorkItem)
CreateUpDownControl
CreateURLBinding
CreateUrlCacheEntry
CreateUrlCacheGroup
CreateURLMoniker
CreateView (IOleDocument)
CreateViewObject (IShellFolder)
CreateViewWindow (IShellView)
CreateWindow
CreateWindowEx
CreateZoneEnumerator (IInternetZoneManager)
Creating a Public_Description Object
Creating Tracking Tooltips
CreationTime
csConnected
csConnecting
csDisconnected
csDisconnecting
csLogged
csLogging
cssText
ctIRC
ctIRCX
ctrlKey

* More entries...


Index

DTN_DATETIMECHANGE
DTN_DROPDOWN
DTN_FORMAT
DTN_FORMATQUERY
DTN_USERSTRING
DTN_WMKEYDOWN
DTS_APPCANPARSE
DTS_LONGDATEFORMAT
DTS_RIGHTALIGN
DTS_SHORTDATEFORMAT
DTS_SHOWNONE
DTS_TIMEFORMAT
DTS_UPDOWN
duplicate
duplicate (IHTMLTxtRange)
Duration Property
DVTARGETDEVICE
DWebBrowserEvents2::BeforeNavigate2
DWebBrowserEvents2::CommandStateChange
DWebBrowserEvents2::DocumentComplete
DWebBrowserEvents2::DownloadBegin
DWebBrowserEvents2::DownloadComplete
DWebBrowserEvents2::NavigateComplete2
DWebBrowserEvents2::NewWindow2
DWebBrowserEvents2::OnFullScreen
DWebBrowserEvents2::OnMenuBar
DWebBrowserEvents2::OnQuit
DWebBrowserEvents2::OnStatusBar
DWebBrowserEvents2::OnTheaterMode
DWebBrowserEvents2::OnToolBar
DWebBrowserEvents2::OnVisible
DWebBrowserEvents2::ProgressChange
DWebBrowserEvents2::PropertyChange
DWebBrowserEvents2::StatusTextChange
DWebBrowserEvents2::TitleChange
Dynamic Content
Dynamic HTML Object Model
Dynamic HTML, Tasks
Dynamic Styles
dynsrc
DYNSRC=


Index

get_dialogTop (IHTMLDialog)
get_dialogWidth (IHTMLDialog)
get_dir (IHTMLFormElement)
get_direction (IHTMLMarqueeElement)
get_disabled (IHTMLButtonElement)
get_disabled (IHTMLInputButtonElement)
get_disabled (IHTMLInputFileElement)
get_disabled (IHTMLInputHiddenElement)
get_disabled (IHTMLInputImage)
get_disabled (IHTMLInputTextElement)
get_disabled (IHTMLLinkElement)
get_disabled (IHTMLOptionButtonElement)
get_disabled (IHTMLSelectElement)
get_disabled (IHTMLStyleElement)
get_disabled (IHTMLStyleSheet)
get_disabled (IHTMLTextAreaElement)
get_display (IHTMLRuleStyle)
get_display (IHTMLStyle)
get_doctype (IXMLDocument)
get_document (IHTMLElement)
get_document (IHTMLOptionsHolder)
get_document (IHTMLWindow2)
get_Document (IWebBrowser2)
get_domain (IHTMLDocument2)
get_dynsrc (IHTMLImgElement)
get_dynsrc (IHTMLInputImage)
get_elements (IHTMLFormElement)
get_embeds (IHTMLDocument2)
get_encoding (IHTMLFormElement)
get_errorCharacter (IHTMLOptionsHolder)
get_errorCode (IHTMLOptionsHolder)
get_errorDebug (IHTMLOptionsHolder)
get_errorLine (IHTMLOptionsHolder)
get_errorMessage (IHTMLOptionsHolder)
get_event (IHTMLScriptElement)
get_event (IHTMLWindow2)
get_execArg (IHTMLOptionsHolder)
get_expando (IHTMLDocument2)
get_external (IHTMLWindow2)
get_face (IHTMLBaseFontElement)
get_face (IHTMLFontElement)
get_fgColor (IHTMLDocument2)
get_fileCreatedDate (IHTMLDocument2)
get_fileCreatedDate (IHTMLImgElement)
get_fileModifiedDate (IHTMLDocument2)
get_fileModifiedDate (IHTMLImgElement)
get_fileModifiedDate (IXMLDocument)
get_fileSize (IHTMLDocument2)
get_fileSize (IHTMLImgElement)
get_fileSize (IXMLDocument)
get_fileUpdatedDate (IHTMLDocument2)
get_fileUpdatedDate (IHTMLImgElement)
get_fileUpdatedDate (IXMLDocument)
get_filter (IHTMLRuleStyle)
get_filter (IHTMLStyle)
get_filters (IHTMLElement)
get_findText (IHTMLOptionsHolder)
get_font (IHTMLRuleStyle)
get_font (IHTMLStyle)
get_fontFamily (IHTMLRuleStyle)
get_fontFamily (IHTMLStyle)
get_fonts (IHTMLOptionsHolder)
get_fontSize (IHTMLRuleStyle)
get_fontSize (IHTMLStyle)
get_fontSmoothingEnabled (IHTMLScreen)
get_fontStyle (IHTMLRuleStyle)
get_fontStyle (IHTMLStyle)
get_fontVariant (IHTMLRuleStyle)
get_fontVariant (IHTMLStyle)
get_fontWeight (IHTMLRuleStyle)
get_fontWeight (IHTMLStyle)
get_forFont (IHTMLFontSizesCollection)
get_form (IHTMLButtonElement)
get_form (IHTMLInputButtonElement)
get_form (IHTMLInputFileElement)
get_form (IHTMLInputHiddenElement)
get_form (IHTMLInputTextElement)
get_form (IHTMLObjectElement)
get_form (IHTMLOptionButtonElement)
get_form (IHTMLOptionElement)
get_form (IHTMLSelectElement)
get_form (IHTMLTextAreaElement)
get_forms (IHTMLDocument2)
get_frame (IHTMLTable)
get_frameBorder (IHTMLFrameBase)
get_frameBorder (IHTMLFrameSetElement)
get_frames (IHTMLDocument2)
get_frames (IHTMLWindow2)
get_frameSpacing (IHTMLFrameBase)
get_frameSpacing (IHTMLFrameSetElement)
get_fromElement (IHTMLEventObj)
get_FullName (IWebBrowser2)
get_FullScreen (IWebBrowser2)
get_hash (IHTMLAnchorElement)
get_hash (IHTMLAreaElement)
get_hash (IHTMLLocation)
get_height (IHTMLEmbedElement)
get_height (IHTMLImgElement)
get_height (IHTMLInputImage)
get_height (IHTMLMarqueeElement)
get_height (IHTMLObjectElement)
get_height (IHTMLRuleStyle)
get_height (IHTMLScreen)
get_height (IHTMLStyle)
get_height (IHTMLTable)
get_height (IHTMLTableCell)
get_Height (IWebBrowser2)
get_hidden (IHTMLEmbedElement)
get_history (IHTMLWindow2)
get_host (IHTMLAnchorElement)
get_host (IHTMLAreaElement)
get_host (IHTMLLocation)
get_hostname (IHTMLAnchorElement)
get_hostname (IHTMLAreaElement)
get_hostname (IHTMLLocation)
get_href (IHTMLAnchorElement)
get_href (IHTMLAreaElement)
get_href (IHTMLBaseElement)
get_href (IHTMLImgElement)
get_href (IHTMLLinkElement)
get_href (IHTMLLocation)
get_href (IHTMLStyleSheet)
get_hspace (IHTMLIFrameElement)
get_hspace (IHTMLImgElement)
get_hspace (IHTMLInputImage)
get_hspace (IHTMLMarqueeElement)
get_hspace (IHTMLObjectElement)
get_htmlFor (IHTMLLabelElement)
get_htmlFor (IHTMLScriptElement)
get_htmlText (IHTMLTxtRange)
get_httpEquiv (IHTMLMetaElement)
get_HWND (IWebBrowser2)
get_id (IHTMLElement)
get_id (IHTMLStyleSheet)
get_Image (IHTMLWindow2)
get_images (IHTMLDocument2)
get_imports (IHTMLStyleSheet)
get_indeterminate (IHTMLOptionButtonElement)
get_index (IHTMLOptionElement)
get_innerHTML (IHTMLElement)
get_innerText (IHTMLElement)
get_isMap (IHTMLImgElement)
get_isTextEdit (IHTMLElement)
get_keyCode (IHTMLEventObj)
get_lang (IHTMLElement)
get_language (IHTMLElement)
get_lastModified (IHTMLDocument2)
get_left (IHTMLRuleStyle)
get_left (IHTMLStyle)
get_Left (IWebBrowser2)
get_leftMargin (IHTMLBodyElement)
get_length
get_length (IHTMLAreasCollection)
get_length (IHTMLControlRange)
get_length (IHTMLElementCollection)
get_length (IHTMLFiltersCollection)
get_length (IHTMLFontNamesCollection)
get_length (IHTMLFontSizesCollection)
get_length (IHTMLFormElement)
get_length (IHTMLFramesCollection2)
get_length (IHTMLMimeTypesCollection)
get_length (IHTMLPluginsCollection)
get_length (IHTMLSelectElement)
get_length (IHTMLStyleSheetRulesCollection)
get_length (IHTMLStyleSheetsCollection)
get_length (IOmHistory)
get_length (IXMLElementCollection)
get_letterSpacing (IHTMLRuleStyle)
get_letterSpacing (IHTMLStyle)
get_lineHeight (IHTMLRuleStyle)
get_lineHeight (IHTMLStyle)
get_link (IHTMLBodyElement)
get_linkColor (IHTMLDocument2)
get_links (IHTMLDocument2)
get_listStyle (IHTMLRuleStyle)
get_listStyle (IHTMLStyle)
get_listStyleImage (IHTMLRuleStyle)
get_listStyleImage (IHTMLStyle)
get_listStylePosition (IHTMLRuleStyle)
get_listStylePosition (IHTMLStyle)
get_listStyleType (IHTMLRuleStyle)
get_listStyleType (IHTMLStyle)
get_location (IHTMLDocument2)
get_location (IHTMLWindow2)
get_LocationName (IWebBrowser2)
get_LocationURL (IWebBrowser2)
get_loop (IHTMLBGsound)
get_loop (IHTMLImgElement)
get_loop (IHTMLInputImage)
get_loop (IHTMLMarqueeElement)
get_lowsrc (IHTMLImgElement)
get_lowsrc (IHTMLInputImage)
get_margin (IHTMLRuleStyle)
get_margin (IHTMLStyle)
get_marginBottom (IHTMLRuleStyle)
get_marginBottom (IHTMLStyle)
get_marginHeight (IHTMLFrameBase)
get_marginLeft (IHTMLRuleStyle)
get_marginLeft (IHTMLStyle)
get_marginRight (IHTMLRuleStyle)
get_marginRight (IHTMLStyle)
get_marginTop (IHTMLRuleStyle)
get_marginTop (IHTMLStyle)
get_marginWidth (IHTMLFrameBase)
get_maxLength (IHTMLInputFileElement)
get_maxLength (IHTMLInputTextElement)
get_media (IHTMLLinkElement)
get_media (IHTMLStyleElement)
get_media (IHTMLStyleSheet)
get_MenuBar (IWebBrowser2)
get_method (IHTMLFormElement)
get_Methods (IHTMLAnchorElement)
get_mimeType (IHTMLAnchorElement)
get_mimeType (IHTMLDocument2)
get_mimeType (IHTMLImgElement)
get_mimeType (IXMLDocument)
get_mimeTypes (IOmNavigator)
get_multiple (IHTMLSelectElement)
get_n (IHTMLNextIdElement)
get_name (IHTMLAnchorElement)
get_name (IHTMLButtonElement)
get_name (IHTMLEmbedElement)
get_name (IHTMLFormElement)
get_name (IHTMLFrameBase)
get_name (IHTMLFrameSetElement)

* More entries...


Index

IDataFilter
IDataObject
IDataObject::EnumFormatEtc
IDataObject::GetData
IDataObject::GetDataHere
IDataObject::QueryGetData
IDataObject::SetData
Identify the Database
Identity (Member Properties)
Identity (User Properties)
IDeskBand
IDeskBand::GetBandInfo
IDispatch
IDispatch::GetIDsOfNames
IDispatch::GetTypeInfo
IDispatch::GetTypeInfoCount
IDispatch::Invoke
IDispatchEx::DeleteMemberByDispID
IDispatchEx::DeleteMemberByName
IDispatchEx::GetDispID
IDispatchEx::GetMemberName
IDispatchEx::GetMemberProperties
IDispatchEx::GetNameSpaceParent
IDispatchEx::GetNextDispID
IDispatchEx::InvokeEx
IDistList::CopyEntries
IDistList::CopyProps
IDistList::CopyTo
IDistList::CreateEntry
IDistList::DeleteEntries
IDistList::DeleteProps
IDistList::GetContentsTable
IDistList::GetHierarchyTable
IDistList::GetIDsFromNames
IDistList::GetLastError
IDistList::GetNamesFromIDs
IDistList::GetPropList
IDistList::GetProps
IDistList::GetSearchCriteria
IDistList::OpenEntry
IDistList::OpenProperty
IDistList::ResolveNames
IDistList::SaveChanges
IDistList::SetProps
IDistList::SetSearchCriteria
IdleTime
IDocHostShowUI::ShowHelp
IDocHostShowUI::ShowMessage
IDocHostUIHandler::EnableModeless
IDocHostUIHandler::FilterDataObject
IDocHostUIHandler::GetDropTarget
IDocHostUIHandler::GetExternal
IDocHostUIHandler::GetHostInfo
IDocHostUIHandler::GetOptionKeyPath
IDocHostUIHandler::HideUI
IDocHostUIHandler::OnDocWindowActivate
IDocHostUIHandler::OnFrameWindowActivate
IDocHostUIHandler::ResizeBorder
IDocHostUIHandler::ShowContextMenu
IDocHostUIHandler::ShowUI
IDocHostUIHandler::TranslateAccelerator
IDocHostUIHandler::TranslateUrl
IDocHostUIHandler::UpdateUI
IDockingWindow
IDockingWindow::CloseDW
IDockingWindow::ResizeBorderDW
IDockingWindow::ShowDW
IDockingWindowFrame
IDockingWindowFrame::AddToolbar
IDockingWindowFrame::FindToolbar
IDockingWindowFrame::RemoveToolbar
IDockingWindowSite
IDockingWindowSite::GetBorderDW
IDockingWindowSite::RequestBorderSpaceDW
IDockingWindowSite::SetBorderSpaceDW
IDropSource
IDropSource::GiveFeedback
IDropSource::QueryContinueDrag
IDropTarget
IDropTarget::DragEnter
IDropTarget::DragLeave
IDropTarget::DragOver
IDropTarget::Drop
IEncodingFilterFactory
IEnumChannels
IEnumChannels::Clone
IEnumChannels::Next
IEnumChannels::Reset
IEnumChannels::Skip
IEnumFORMATETC
IEnumIDList
IEnumIDList::Clone
IEnumIDList::Next
IEnumIDList::Reset
IEnumIDList::Skip
IEnumOleDocumentViews::Clone
IEnumOleDocumentViews::Next
IEnumOleDocumentViews::Reset
IEnumOleDocumentViews::Skip
IEnumString
IEnumWorkItems
IEnumWorkItems::Clone
IEnumWorkItems::Next
IEnumWorkItems::Reset
IEnumWorkItems::Skip
IEnumXXXX
IErrorLog::AddError
IExtractIcon
IExtractIcon::Extract
IExtractIcon::GetIconLocation
IFileViewer
IFileViewer::PrintTo
IFileViewer::Show
IFileViewer::ShowInitialize
IFileViewerSite
IFileViewerSite::GetPinnedWindow
IFileViewerSite::SetPinnedWindow
IFRAME (HTML Elements)
IFRAME (Objects)
IgnoredUsers
IgnoreUsers
IgnoreUsers Method
IHlink::GetAdditionalParams
IHlink::GetFriendlyName
IHlink::GetHlinkSite
IHlink::GetMiscStatus
IHlink::GetMonikerReference
IHlink::GetStringReference
IHlink::GetTargetFrameName
IHlink::Navigate
IHlink::SetAdditionalParams
IHlink::SetFriendlyName
IHlink::SetHlinkSite
IHlink::SetMonikerReference
IHlink::SetStringReference
IHlink::SetTargetFrameName
IHlinkBrowseContext::Clone
IHlinkBrowseContext::Close
IHlinkBrowseContext::EnumNavigationStack
IHlinkBrowseContext::GetBrowseWindowInfo
IHlinkBrowseContext::GetHlink
IHlinkBrowseContext::GetObject
IHlinkBrowseContext::OnNavigateHlink
IHlinkBrowseContext::QueryHlink
IHlinkBrowseContext::Register
IHlinkBrowseContext::Revoke
IHlinkBrowseContext::SetBrowseWindowInfo
IHlinkBrowseContext::SetCurrentHlink
IHlinkFrame::GetBrowseContext
IHlinkFrame::Navigate
IHlinkFrame::OnNavigate
IHlinkFrame::SetBrowseContext
IHlinkFrame::UpdateHlink
IHlinkSite::GetMoniker
IHlinkSite::OnNavigationComplete
IHlinkSite::QueryService
IHlinkSite::ReadyToNavigate
IHlinkTarget::GetBrowseContext
IHlinkTarget::GetFriendlyName
IHlinkTarget::GetMoniker
IHlinkTarget::Navigate
IHlinkTarget::SetBrowseContext
IHTMLAnchorElement::blur
IHTMLAnchorElement::focus
IHTMLAnchorElement::get_accessKey
IHTMLAnchorElement::get_hash
IHTMLAnchorElement::get_host
IHTMLAnchorElement::get_hostname
IHTMLAnchorElement::get_href
IHTMLAnchorElement::get_Methods
IHTMLAnchorElement::get_mimeType
IHTMLAnchorElement::get_name
IHTMLAnchorElement::get_nameProp
IHTMLAnchorElement::get_onblur
IHTMLAnchorElement::get_onfocus
IHTMLAnchorElement::get_pathname
IHTMLAnchorElement::get_port
IHTMLAnchorElement::get_protocol
IHTMLAnchorElement::get_protocolLong
IHTMLAnchorElement::get_rel
IHTMLAnchorElement::get_rev
IHTMLAnchorElement::get_search
IHTMLAnchorElement::get_tabIndex
IHTMLAnchorElement::get_target
IHTMLAnchorElement::get_urn
IHTMLAnchorElement::put_accessKey
IHTMLAnchorElement::put_hash
IHTMLAnchorElement::put_host
IHTMLAnchorElement::put_hostname
IHTMLAnchorElement::put_href
IHTMLAnchorElement::put_Methods
IHTMLAnchorElement::put_name
IHTMLAnchorElement::put_onblur
IHTMLAnchorElement::put_onfocus
IHTMLAnchorElement::put_pathname
IHTMLAnchorElement::put_port
IHTMLAnchorElement::put_protocol
IHTMLAnchorElement::put_rel
IHTMLAnchorElement::put_rev
IHTMLAnchorElement::put_search
IHTMLAnchorElement::put_tabIndex
IHTMLAnchorElement::put_target
IHTMLAnchorElement::put_urn
IHTMLAreaElement::blur
IHTMLAreaElement::focus
IHTMLAreaElement::get_alt
IHTMLAreaElement::get_coords
IHTMLAreaElement::get_hash
IHTMLAreaElement::get_host
IHTMLAreaElement::get_hostname
IHTMLAreaElement::get_href
IHTMLAreaElement::get_noHref
IHTMLAreaElement::get_onblur
IHTMLAreaElement::get_onfocus
IHTMLAreaElement::get_pathname
IHTMLAreaElement::get_port
IHTMLAreaElement::get_protocol
IHTMLAreaElement::get_search
IHTMLAreaElement::get_shape
IHTMLAreaElement::get_tabIndex
IHTMLAreaElement::get_target
IHTMLAreaElement::put_alt
IHTMLAreaElement::put_coords
IHTMLAreaElement::put_hash
IHTMLAreaElement::put_host
IHTMLAreaElement::put_hostname
IHTMLAreaElement::put_href
IHTMLAreaElement::put_noHref
IHTMLAreaElement::put_onblur
IHTMLAreaElement::put_onfocus
IHTMLAreaElement::put_pathname
IHTMLAreaElement::put_port
IHTMLAreaElement::put_protocol
IHTMLAreaElement::put_search
IHTMLAreaElement::put_shape
IHTMLAreaElement::put_tabIndex
IHTMLAreaElement::put_target
IHTMLAreasCollection::add
IHTMLAreasCollection::get__newEnum
IHTMLAreasCollection::get_length
IHTMLAreasCollection::item

* More entries...


Index

ListView_Update
Load (IPersistMemory)
Load (IPersistMoniker)
Load (IPersistPropertyBag)
Load (IPersistPropertyBag2)
LoadHistory (IPersistHistory)
LoadIcon
LoadImage
LoadLibrary
LoadObject (IPropertyBag2)
LoadResource
LocalAlloc
LOCALE_SLONGDATEFORMAT
LOCALE_SSHORTDATE
LOCALE_STIMEFORMAT
LocalFree
location (Methods: open)
location (Objects)
location (Properties)
LocationName
LocationName Property
LocationURL
LocationURL Property
LockRequest (IInternetProtocol)
LockType Property (ADO)
LOG
LogAction (IInternetZoneManager)
LOGBRUSH
LOGFONT
LOGIN
Login (Methods)
Login Method
LOGO
LOGPEN
LOGTARGET
loop
LOOP= (BGSOUND)
LOOP= (IMG)
LOOP= (MARQUEE)
lowsrc
LOWSRC=
LV_COLUMN
LV_DISPINFO
LV_FINDINFO
LV_HITTESTINFO
LV_ITEM
LV_KEYDOWN
LVBKIMAGE
LVCOLUMN
LVFINDINFO
LVHITTESTINFO
LVIS_ACTIVATING
LVIS_CUT
LVIS_DROPHILITED
LVIS_FOCUSED
LVIS_OVERLAYMASK
LVIS_SELECTED
LVIS_STATEIMAGEMASK
LVITEM
LVM_APPROXIMATEVIEWRECT
LVM_ARRANGE
LVM_CREATEDRAGIMAGE
LVM_DELETEALLITEMS
LVM_DELETECOLUMN
LVM_DELETEITEM
LVM_EDITLABEL
LVM_ENSUREVISIBLE
LVM_FINDITEM
LVM_GETBKCOLOR
LVM_GETBKIMAGE
LVM_GETCALLBACKMASK
LVM_GETCOLUMN
LVM_GETCOLUMNORDERARRAY
LVM_GETCOLUMNWIDTH
LVM_GETCOUNTPERPAGE
LVM_GETEDITCONTROL
LVM_GETEXTENDEDLISTVIEWSTYLE
LVM_GETHEADER
LVM_GETHOTCURSOR
LVM_GETHOTITEM
LVM_GETHOVERTIME
LVM_GETIMAGELIST
LVM_GETISEARCHSTRING
LVM_GETITEM
LVM_GETITEMCOUNT
LVM_GETITEMPOSITION
LVM_GETITEMRECT
LVM_GETITEMSPACING
LVM_GETITEMSTATE
LVM_GETITEMTEXT
LVM_GETNEXTITEM
LVM_GETNUMBEROFWORKAREAS
LVM_GETORIGIN
LVM_GETSELECTEDCOUNT
LVM_GETSELECTIONMARK
LVM_GETSTRINGWIDTH
LVM_GETSUBITEMRECT
LVM_GETTEXTBKCOLOR
LVM_GETTEXTCOLOR
LVM_GETTOOLTIPS
LVM_GETTOPINDEX
LVM_GETUNICODEFORMAT
LVM_GETVIEWRECT
LVM_GETWORKAREAS
LVM_HITTEST
LVM_INSERTCOLUMN
LVM_INSERTITEM
LVM_REDRAWITEMS
LVM_SCROLL
LVM_SETBKCOLOR
LVM_SETBKIMAGE
LVM_SETCALLBACKMASK
LVM_SETCOLUMN
LVM_SETCOLUMNORDERARRAY
LVM_SETCOLUMNWIDTH
LVM_SETEXTENDEDLISTVIEWSTYLE
LVM_SETHOTCURSOR
LVM_SETHOTITEM
LVM_SETHOVERTIME
LVM_SETICONSPACING
LVM_SETIMAGELIST
LVM_SETITEM
LVM_SETITEMCOUNT
LVM_SETITEMPOSITION
LVM_SETITEMPOSITION32
LVM_SETITEMSTATE
LVM_SETITEMTEXT
LVM_SETSELECTIONMARK
LVM_SETTEXTBKCOLOR
LVM_SETTEXTCOLOR
LVM_SETTOOLTIPS
LVM_SETUNICODEFORMAT
LVM_SETWORKAREAS
LVM_SORTITEMS
LVM_SUBITEMHITTEST
LVM_UPDATE
LVN_BEGINDRAG
LVN_BEGINLABELEDIT
LVN_BEGINRDRAG
LVN_COLUMNCLICK
LVN_DELETEALLITEMS
LVN_DELETEITEM
LVN_ENDLABELEDIT
LVN_GETDISPINFO
LVN_GETINFOTIP
LVN_HOTTRACK
LVN_INSERTITEM
LVN_ITEMACTIVATE
LVN_ITEMCHANGED
LVN_ITEMCHANGING
LVN_KEYDOWN
LVN_MARQUEEBEGIN
LVN_ODCACHEHINT
LVN_ODFINDITEM
LVN_ODSTATECHANGED
LVN_SETDISPINFO
LVS_ALIGNLEFT
LVS_ALIGNMASK
LVS_ALIGNTOP
LVS_AUTOARRANGE
LVS_EDITLABELS
LVS_EX_CHECKBOXES
LVS_EX_FLATSB
LVS_EX_FULLROWSELECT
LVS_EX_GRIDLINES
LVS_EX_HEADERDRAGDROP
LVS_EX_INFOTIP
LVS_EX_MULTIWORKAREAS
LVS_EX_ONECLICKACTIVATE
LVS_EX_REGIONAL
LVS_EX_SUBITEMIMAGES
LVS_EX_TRACKSELECT
LVS_EX_TWOCLICKACTIVATE
LVS_EX_UNDERLINECOLD
LVS_EX_UNDERLINEHOT
LVS_ICON
LVS_LIST
LVS_NOCOLUMNHEADER
LVS_NOLABELWRAP
LVS_NOSCROLL
LVS_NOSORTHEADER
LVS_OWNERDATA
LVS_OWNERDRAWFIXED
LVS_REPORT
LVS_SHAREIMAGELISTS
LVS_SHOWSELALWAYS
LVS_SINGLESEL
LVS_SMALLICON
LVS_SORTASCENDING
LVS_SORTDESCENDING
LVS_TYPEMASK
LVS_TYPESTYLEMASK


Index

PropSheet_RebootSystem
PropSheet_RemovePage
PropSheet_RestartWindows
PropSheet_SetCurSel
PropSheet_SetCurSelByID
PropSheet_SetFinishText
PropSheet_SetTitle
PropSheet_SetWizButtons
PropSheet_UnChanged
PROPSHEETHEADER
PROPSHEETPAGE
PropSheetPageProc
PropSheetProc
protocol
PROTOCOLDATA
PROTOCOLFILTERDATA
Provider and DefaultDatabase Properties Example (ADO)
Provider Property (ADO)
proxy <definition>
PSHNOTIFY
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
PSN_APPLY
PSN_GETOBJECT
PSN_HELP
PSN_KILLACTIVE
PSN_QUERYCANCEL
PSN_RESET
PSN_SETACTIVE
PSN_WIZBACK
PSN_WIZFINISH
PSN_WIZNEXT
PSU_DEFAULT
PSU_SECURITY_URL_ONLY
PSUACTION
PUAF
PUAF_CHECK_TIFS
PUAF_DEFAULT
PUAF_FORCEUI_FOREGROUND
PUAF_ISFILE
PUAF_NOUI
PUAF_WARN_IF_DENIED
PURGETIME
put_accessKey (IHTMLAnchorElement)
put_accessKey (IHTMLControlElement)
put_accessKey (IHTMLLabelElement)
put_action (IHTMLFormElement)
put_action (IHTMLIsIndexElement)
put_align (IHTMLDivElement)
put_align (IHTMLDivPosition)
put_align (IHTMLFieldSetElement)
put_align (IHTMLHeaderElement)
put_align (IHTMLHRElement)
put_align (IHTMLIFrameElement)
put_align (IHTMLImgElement)
put_align (IHTMLInputImage)
put_align (IHTMLLegendElement)
put_align (IHTMLObjectElement)
put_align (IHTMLParaElement)
put_align (IHTMLSpanFlow)
put_align (IHTMLTable)
put_align (IHTMLTableCaption)
put_align (IHTMLTableCell)
put_align (IHTMLTableCol)
put_align (IHTMLTableRow)
put_align (IHTMLTableSection)
put_aLink (IHTMLBodyElement)
put_alinkColor (IHTMLDocument2)
put_alt (IHTMLAreaElement)
put_alt (IHTMLImgElement)
put_alt (IHTMLInputImage)
put_altHtml (IHTMLObjectElement)
put_background (IHTMLBodyElement)
put_background (IHTMLRuleStyle)
put_background (IHTMLStyle)
put_background (IHTMLTable)
put_background (IHTMLTableCell)
put_backgroundAttachment (IHTMLRuleStyle)
put_backgroundAttachment (IHTMLStyle)
put_backgroundColor (IHTMLRuleStyle)
put_backgroundColor (IHTMLStyle)
put_backgroundImage (IHTMLRuleStyle)
put_backgroundImage (IHTMLStyle)
put_backgroundPosition (IHTMLRuleStyle)
put_backgroundPosition (IHTMLStyle)
put_backgroundPositionX (IHTMLRuleStyle)
put_backgroundPositionX (IHTMLStyle)
put_backgroundPositionY (IHTMLRuleStyle)
put_backgroundPositionY (IHTMLStyle)
put_backgroundRepeat (IHTMLRuleStyle)
put_backgroundRepeat (IHTMLStyle)
put_balance (IHTMLBGsound)
put_behavior (IHTMLMarqueeElement)
put_bgColor (IHTMLBodyElement)
put_bgColor (IHTMLDocument2)
put_bgColor (IHTMLMarqueeElement)
put_bgColor (IHTMLTable)
put_bgColor (IHTMLTableCell)
put_bgColor (IHTMLTableRow)
put_bgColor (IHTMLTableSection)
put_bgProperties (IHTMLBodyElement)
put_border (IHTMLFrameBase)
put_border (IHTMLFrameSetElement)
put_border (IHTMLImgElement)
put_border (IHTMLInputImage)
put_border (IHTMLRuleStyle)
put_border (IHTMLStyle)
put_border (IHTMLTable)
put_borderBottom (IHTMLRuleStyle)
put_borderBottom (IHTMLStyle)
put_borderBottomColor (IHTMLRuleStyle)
put_borderBottomColor (IHTMLStyle)
put_borderBottomStyle (IHTMLRuleStyle)
put_borderBottomStyle (IHTMLStyle)
put_borderBottomWidth (IHTMLRuleStyle)
put_borderBottomWidth (IHTMLStyle)
put_borderColor (IHTMLFrameElement)
put_borderColor (IHTMLFrameSetElement)
put_borderColor (IHTMLRuleStyle)
put_borderColor (IHTMLStyle)
put_borderColor (IHTMLTable)
put_borderColor (IHTMLTableCell)
put_borderColor (IHTMLTableRow)
put_borderColorDark (IHTMLTable)
put_borderColorDark (IHTMLTableCell)
put_borderColorDark (IHTMLTableRow)
put_borderColorLight (IHTMLTable)
put_borderColorLight (IHTMLTableCell)
put_borderColorLight (IHTMLTableRow)
put_borderLeft (IHTMLRuleStyle)
put_borderLeft (IHTMLStyle)
put_borderLeftColor (IHTMLRuleStyle)
put_borderLeftColor (IHTMLStyle)
put_borderLeftStyle (IHTMLRuleStyle)
put_borderLeftStyle (IHTMLStyle)
put_borderLeftWidth (IHTMLRuleStyle)
put_borderLeftWidth (IHTMLStyle)
put_borderRight (IHTMLRuleStyle)
put_borderRight (IHTMLStyle)
put_borderRightColor (IHTMLRuleStyle)
put_borderRightColor (IHTMLStyle)
put_borderRightStyle (IHTMLRuleStyle)
put_borderRightStyle (IHTMLStyle)
put_borderRightWidth (IHTMLRuleStyle)
put_borderRightWidth (IHTMLStyle)
put_borderStyle (IHTMLRuleStyle)
put_borderStyle (IHTMLStyle)
put_borderTop (IHTMLRuleStyle)
put_borderTop (IHTMLStyle)
put_borderTopColor (IHTMLRuleStyle)
put_borderTopColor (IHTMLStyle)
put_borderTopStyle (IHTMLRuleStyle)
put_borderTopStyle (IHTMLStyle)
put_borderTopWidth (IHTMLRuleStyle)
put_borderTopWidth (IHTMLStyle)
put_borderWidth (IHTMLRuleStyle)
put_borderWidth (IHTMLStyle)
put_bottomMargin (IHTMLBodyElement)
put_bufferDepth (IHTMLScreen)
put_cancelBubble (IHTMLEventObj)
put_cellPadding (IHTMLTable)
put_cellSpacing (IHTMLTable)
put_charset (IHTMLDocument2)
put_charset (IHTMLMetaElement)
put_checked (IHTMLOptionButtonElement)
put_className (IHTMLElement)
put_clear (IHTMLBlockElement)
put_clear (IHTMLBRElement)
put_clear (IHTMLRuleStyle)
put_clear (IHTMLStyle)
put_clip (IHTMLRuleStyle)
put_clip (IHTMLStyle)
put_code (IHTMLObjectElement)
put_codeBase (IHTMLObjectElement)
put_codeType (IHTMLObjectElement)
put_color (IHTMLBaseFontElement)
put_color (IHTMLFontElement)
put_color (IHTMLHRElement)
put_color (IHTMLRuleStyle)
put_color (IHTMLStyle)
put_cols (IHTMLFrameSetElement)
put_cols (IHTMLTable)
put_cols (IHTMLTextAreaElement)
put_colSpan (IHTMLTableCell)
put_compact (IHTMLDListElement)
put_compact (IHTMLOListElement)
put_compact (IHTMLUListElement)
put_content (IHTMLMetaElement)
put_cookie (IHTMLDocument2)
put_coords (IHTMLAreaElement)
put_cssText (IHTMLRuleStyle)
put_cssText (IHTMLStyle)
put_cursor (IHTMLRuleStyle)
put_cursor (IHTMLStyle)
put_dataFld (IHTMLDatabinding)
put_dataFormatAs (IHTMLDatabinding)
put_dataPageSize (IHTMLTable)
put_dataSrc (IHTMLDatabinding)
put_defaultCharset (IHTMLDocument2)
put_defaultChecked (IHTMLOptionButtonElement)
put_defaultSelected (IHTMLOptionElement)
put_defaultStatus (IHTMLWindow2)
put_defaultValue (IHTMLInputTextElement)
put_defaultValue (IHTMLTextAreaElement)
put_defer (IHTMLScriptElement)
put_dialogHeight (IHTMLDialog)
put_dialogLeft (IHTMLDialog)
put_dialogTop (IHTMLDialog)
put_dialogWidth (IHTMLDialog)
put_dir (IHTMLFormElement)
put_direction (IHTMLMarqueeElement)
put_disabled (IHTMLButtonElement)
put_disabled (IHTMLInputButtonElement)
put_disabled (IHTMLInputFileElement)

* More entries...


Index

SetUrlCacheEntryGroup
SetUrlCacheEntryInfo
SetWallpaper (IActiveDesktop)
SetWallpaperOptions (IActiveDesktop)
SetWindowContextHelpId
SetWindowLong
SetWindowPos
SetWindowText
SetWorkingDirectory (IShellLink)
SetWorkingDirectory (ITask)
SetWorkItemData (IScheduledWorkItem)
SetZoneActionPolicy (IInternetZoneManager)
SetZoneAttributes (IInternetZoneManager)
SetZoneCustomPolicy (IInternetZoneManager)
SetZoneMapping (IInternetSecurityManager)
SHAddToRecentDocs
Shadow Filter Effect
shape
SHAPE=
SHAppBarMessage
SHBrowseForFolder
SHChangeNotify
SHCONTF
SHDeleteEmptyKey
SHDeleteKey
SHDeleteValue
SHDESCRIPTIONID
Shell_NotifyIcon
ShellAbout
ShellExecute
ShellExecuteEx
SHELLEXECUTEINFO
SHELLFLAGSTATE
ShellFolderViewOptions Enumeration
ShellSpecialFolderConstants Enumeration
SHEmptyRecycleBin
SHEnumKeyEx
SHEnumValue
SHFILEINFO
SHFileOperation
SHFILEOPSTRUCT
SHFreeNameMappings
SHGetDataFromIDList
SHGetDesktopFolder
SHGetFileInfo
SHGetInstanceExplorer
SHGetMalloc
SHGetPathFromIDList
SHGetSettings
SHGetSpecialFolderLocation
SHGetSpecialFolderPath
SHGetValue
SHGNO
shiftKey
SHITEMID
SHLoadInProc
SHNAMEMAPPING
SHOpenRegStream
Show (IFileViewer)
Show (IOleDocumentView)
ShowBrowserBar
ShowBrowserBar (IWebBrowser2)
ShowBrowserBar Method
ShowContextMenu (IDocHostUIHandler)
ShowControls Property
ShowCursor
ShowDisplay Property
ShowDW (IDockingWindow)
ShowGroup
showHelp
ShowHelp (IDocHostShowUI)
showHelp (IHTMLWindow2)
ShowHideMenuCtl
ShowHTMLDialog
SHOWHTMLDIALOGFN
ShowInitialize (IFileViewer)
ShowMessage (IDocHostShowUI)
showModalDialog
showModalDialog (IHTMLWindow2)
ShowPositionControls Property
ShowScrollBar
showSecurityInfo (IHTMLOptionsHolder)
ShowSelectionControls Property
ShowSubscriptionProperties (ISubscriptionMgr)
ShowTracker Property
ShowUI (IDocHostUIHandler)
ShowWindow
SHQueryInfoKey
SHQUERYRBINFO
SHQueryRecycleBin
SHQueryValueEx
SHRegCreateUSKey
SHREGDEL_FLAGS
SHRegDeleteEmptyUSKey
SHRegDeleteUSValue
SHREGENUM_FLAGS
SHRegEnumUSKey
SHRegEnumUSValue
SHRegGetUSValue
SHRegOpenUSKey
SHRegQueryInfoUSKey
SHRegQueryUSValue
SHRegSetUSValue
SHRegWriteUSValue
SHSetValue
ShutdownWindows Method
Signing Code
SignOnTime
Silent
Silent Property
single-threaded control <definition>
SIZE (Further Reading)
size (Properties: 1)
size (Properties: 2)
size (Properties: 3)
Size Property
Size Property (ADO)
SIZE= (BASEFONT)
SIZE= (CODEBASE)
SIZE= (FONT)
SIZE= (HR)
SIZE= (INPUT)
SIZE= (SELECT)
sizes (IHTMLOptionsHolder)
Skip (IEnumChannels)
Skip (IEnumIDList)
Skip (IEnumOleDocumentViews)
Skip (IEnumWorkItems)
SMALL (HTML Elements)
SMALL (Objects)
smtError
smtMessageOfTheDay
smtNormal
smtNotice
smtServerInfo
SOANGLE
SOANGLETENTHS
SOARCINFO
SOBailOut
SOBeginTable
SOBITMAPHEADER
SOBORDER
SOCOLORREF
SOCOLUMN
SOCPARCANGLE
SOCPPIEANGLE
SOCPTEXTATPOINT
SODATACELL
SOEMBEDDEDGRAPHIC
SOEMBEDDEDOBJECT
SOEMBEDINFO
SOEndColumnInfo
SOEndFieldInfo
SOEndFontTable
SOEndPalette
SOEndTable
SOEndTabStops
SOFIELD
SOFILTERINFO
SOFTPKG
Software Update Channels, Tasks
SOGetInfo
SOGetScanLineBuffer
SOGROUPINFO
SOLOGBRUSH
SOLOGFONT
SOLOGPEN
SOMAXPOINTS
SOPALETTE
SOPALETTEINDEX
SOPALETTERGB
SOPARAINDENTS
SOPATHINFO
SOPOINT
SOPOLYINFO
SOPutBitmapHeader
SOPutBreak
SOPutChar
SOPutCharAttr
SOPutCharFontById
SOPutCharFontByName
SOPutCharHeight
SOPutCharX
SOPutColumnInfo
SOPutDataCell
SOPutEmbeddedObject
SOPutField
SOPutFieldInfo
SOPutFontTableEntry
SOPutHdrEntry
SOPutMoreText
SOPutMoreVarField
SOPutPaletteEntry
SOPutParaAlign
SOPutParaIndents
SOPutParaMargins
SOPutParaSpacing
SOPutScanLineData
SOPutSectionName
SOPutSectionType
SOPutSpecialCharX
SOPutSubdocInfo
SOPutTableCellInfo
SOPutTableRowFormat
SOPutTabStop
SOPutText
SOPutTextCell
SOPutVarField
SOPutVectorHeader
SORECT
SORGB
Sort
SortColumn Property
SortDirection Property
Sorting and Filtering
SortTable (IABTable)
SOSetDateBase
SOSETRATIO
SOStartColumnInfo
SOStartFieldInfo
SOStartFontTable
SOStartPalette
SOStartTabStops
SOTAB
SOTABLECELLINFO
SOTEXTATARCANGLE
SOTEXTATPOINT
SOTEXTCELL
SOTEXTINRECT
SOTRANSFORM
Source Property (Error - ADO)
Source Property (Recordset - ADO)
Source Property Example (ADO)
sourceIndex
SOVectorAttr
SOVECTORHEADER
SOVectorObject
SPAN (HTML Elements)
SPAN (Objects)
span (Properties)
SPAN= (COL)
SPAN= (COLGROUP)
SPropProblem
SPropProblemArray
SPropTagArray
SPropValue
SQL Property
SQL Property Example
SQLState Property (ADO)
src (Properties: 1)
src (Properties: 2)
src (Properties: 3)
SRC= (APPLET)
SRC= (BGSOUND)
SRC= (EMBED)
SRC= (FRAME)
SRC= (HR)
SRC= (IFRAME)
SRC= (IMG)
SRC= (INPUT)
SRC= (SCRIPT)
srcElement
srcFilter
SRestriction
SRow
SRowSet
SSortOrder
SSortOrderSet
start (Methods)
start (Properties: 1)
start (Properties: 2)
start (IHTMLMarqueeElement)
Start (IInternetProtocolRoot)
START=
STARTDATE=
STARTUPINFO
State
State Property
State Property (ADO)
StateChange Event
status (Methods: open)
status (Properties: 1)
status (Properties: 2)
Status Property
Status Property (ADO)
Status Property Example (ADO)
StatusBar
StatusBar Property
StatusText
StatusText Property

* More entries...


Index

TCHITTESTINFO
TCIS_BUTTONPRESSED
TCIS_HIGHLIGHTED
TCITEM
TCITEMHEADER
TCM_ADJUSTRECT
TCM_DELETEALLITEMS
TCM_DELETEITEM
TCM_DESELECTALL
TCM_GETCURFOCUS
TCM_GETCURSEL
TCM_GETEXTENDEDSTYLE
TCM_GETIMAGELIST
TCM_GETITEM
TCM_GETITEMCOUNT
TCM_GETITEMRECT
TCM_GETROWCOUNT
TCM_GETTOOLTIPS
TCM_GETUNICODEFORMAT
TCM_HIGHLIGHTITEM
TCM_HITTEST
TCM_INSERTITEM
TCM_REMOVEIMAGE
TCM_SETCURFOCUS
TCM_SETCURSEL
TCM_SETEXTENDEDSTYLE
TCM_SETIMAGELIST
TCM_SETITEM
TCM_SETITEMEXTRA
TCM_SETITEMSIZE
TCM_SETMINTABWIDTH
TCM_SETPADDING
TCM_SETTOOLTIPS
TCM_SETUNICODEFORMAT
TCN_GETOBJECT
TCN_KEYDOWN
TCN_SELCHANGE
TCN_SELCHANGING
TCS_BOTTOM
TCS_BUTTONS
TCS_EX_FLATSEPARATORS
TCS_EX_REGISTERDROP
TCS_FIXEDWIDTH
TCS_FLATBUTTONS
TCS_FOCUSNEVER
TCS_FOCUSONBUTTONDOWN
TCS_FORCEICONLEFT
TCS_FORCELABELLEFT
TCS_HOTTRACK
TCS_MULTILINE
TCS_MULTISELECT
TCS_OWNERDRAWFIXED
TCS_RAGGEDRIGHT
TCS_RIGHT
TCS_RIGHTJUSTIFY
TCS_SCROLLOPPOSITE
TCS_SINGLELINE
TCS_TABS
TCS_TOOLTIPS
TCS_VERTICAL
TD (HTML Elements)
TD (Objects)
TDC, Adding to a Page
TDC, Licensing and Distribution
TDC, Relaxing Security
TDC, Understanding the Object Model
TDC, Using
Technical FAQ
Terminate (IInternetProtocolRoot)
Terminate (IScheduledWorkItem)
TerminateProcess
Tested Data-Aware ActiveX Controls
text (Objects)
text (Properties: 1)
text (Properties: 2)
text (Properties: 3)
text (Properties: 4)
text (Properties: type: 5)
TEXT=
textAlign
text-align
TEXTAREA (HTML Elements)
TEXTAREA (Objects)
textarea (type)
textDecoration
text-decoration
textDecorationBlink
textDecorationLineThrough
textDecorationNone
textDecorationOverline
textDecorationUnderline
textIndent
text-indent
TextQualifier
TextRange
textTransform
text-transform
TFOOT (HTML Elements)
TFOOT (Objects)
tfoot (Properties)
TH (HTML Elements)
TH (Objects)
The Microsoft Agent User Interface
The Visual Basic Ocxvb01 Sample
THEAD (HTML Elements)
THEAD (Objects)
thead (Properties)
TheaterMode
TheaterMode Property
THIRD_IPADDRESS
ThisParticipantAlias
ThisParticipantAlias Property
ThisParticipantID
ThisParticipantID Property
ThisParticipantName
ThisParticipantName Property
TileHorizontally Method
TileVertically Method
Timer Event
TIMEZONE=
TITLE (CDF Reference for Active Channels: CDF Elements)
TITLE (HTML Elements)
TITLE (Objects)
title (Properties: 1)
title (Properties: 2)
Title Property
TITLE= (A)
TITLE= (ACRONYM)
TITLE= (ADDRESS)
TITLE= (APPLET)
TITLE= (AREA)
TITLE= (B)
TITLE= (BGSOUND)
TITLE= (BIG)
TITLE= (BLOCKQUOTE)
TITLE= (BODY)
TITLE= (BR)
TITLE= (BUTTON)
TITLE= (CAPTION)
TITLE= (CENTER)
TITLE= (CITE)
TITLE= (CODE)
TITLE= (COL)
TITLE= (COLGROUP)
TITLE= (COMMENT)
TITLE= (DD)
TITLE= (DEL)
TITLE= (DFN)
TITLE= (DIR)
TITLE= (DIV)
TITLE= (DL)
TITLE= (DT)
TITLE= (EM)
TITLE= (EMBED)
TITLE= (FIELDSET)
TITLE= (FONT)
TITLE= (FORM)
TITLE= (FRAME)
TITLE= (FRAMESET)
TITLE= (HEAD)
TITLE= (Hn)
TITLE= (HR)
TITLE= (HTML)
TITLE= (I)
TITLE= (IFRAME)
TITLE= (IMG)
TITLE= (INPUT)
TITLE= (INS)
TITLE= (KBD)
TITLE= (LABEL)
TITLE= (LEGEND)
TITLE= (LI)
TITLE= (LINK)
TITLE= (LISTING)
TITLE= (MAP)
TITLE= (MARQUEE)
TITLE= (MENU)
TITLE= (META)
TITLE= (NOBR)
TITLE= (NOFRAMES)
TITLE= (OBJECT)
TITLE= (OL)
TITLE= (P)
TITLE= (PLAINTEXT)
TITLE= (PRE)
TITLE= (Q)
TITLE= (S)
TITLE= (SAMP)
TITLE= (SCRIPT)
TITLE= (SMALL)
TITLE= (SPAN)
TITLE= (STRIKE)
TITLE= (STRONG)
TITLE= (STYLE)
TITLE= (SUB)
TITLE= (SUP)
TITLE= (TABLE)
TITLE= (TBODY)
TITLE= (TD)
TITLE= (TEXTAREA)
TITLE= (TFOOT)
TITLE= (TH)
TITLE= (THEAD)
TITLE= (TITLE)
TITLE= (TR)
TITLE= (TT)
TITLE= (U)
TITLE= (UL)
TITLE= (VAR)
TITLE= (WBR)
TITLE= (XMP)
TitleChange
TitleChange (DWebBrowserEvents2)
TitleChange Event
toElement
ToolBar
toolbar (open)
ToolBar Property
TOOLINFO
top (CSS Attributes)
top (Methods: open)
top (Properties: 1)
top (Properties: 2)
Top (Reusing the WebBrowser Control: Reference for Visual Basic Developers: Properties)
Top Property
Topic
TopicAgeMax
TopicAgeMin
TopicOp
TopLevelContainer
TopLevelContainer Property
topMargin
TOPMARGIN=
toString (IHTMLDialog)
toString (IHTMLDocument2)
toString (IHTMLElement)
toString (IHTMLElementCollection)
toString (IHTMLLocation)
toString (IHTMLStyle)
toString (IHTMLWindow2)
toString (IOmNavigator)
TR (HTML Elements)
TR (Objects)
Tracking Tooltips
TrackPopupMenu
TrackPopupMenuEx
transaction context object <definition>
Transaction Server object <definition>
Translate (IURLSearchHook)
TranslateAccelerator (IDocHostUIHandler)
TranslateAccelerator (IShellView)
TranslateAcceleratorIO (IInputObject)
TranslateAcceleratorSB (IShellBrowser)
TranslateMessage
TranslateURL
TranslateUrl (IDocHostUIHandler)
TRANSLATEURL_IN_FLAGS
TrayProperties Method
TreeView_CreateDragImage
TreeView_DeleteAllItems
TreeView_DeleteItem
TreeView_EditLabel
TreeView_EndEditLabelNow
TreeView_EnsureVisible
TreeView_Expand
TreeView_GetBkColor
TreeView_GetChild
TreeView_GetCount
TreeView_GetDropHilight
TreeView_GetEditControl
TreeView_GetFirstVisible
TreeView_GetImageList
TreeView_GetIndent
TreeView_GetInsertMarkColor
TreeView_GetISearchString
TreeView_GetItem
TreeView_GetItemHeight
TreeView_GetItemRect
TreeView_GetLastVisible
TreeView_GetNextItem
TreeView_GetNextSibling
TreeView_GetNextVisible
TreeView_GetParent
TreeView_GetPrevSibling
TreeView_GetPrevVisible
TreeView_GetRoot
TreeView_GetScrollTime
TreeView_GetSelection
TreeView_GetTextColor
TreeView_GetToolTips
TreeView_GetUnicodeFormat
TreeView_GetVisibleCount
TreeView_HitTest

* More entries...


Index

CurrentPosition Property
CurrentState Property
cursor (CSS Attributes)
cursor (Properties)
cursor <definition>
CursorLocation Property (ADO)
CursorType Property (ADO)
CursorType, LockType, and EditMode Properties Example (ADO)
Cut
Cut Command
cvsChannelName
cvsNickname
cvsNormal
cvtToUnicode
cvtToUTF8


Index

get_name (IHTMLImgElement)
get_name (IHTMLInputButtonElement)
get_name (IHTMLInputFileElement)
get_name (IHTMLInputHiddenElement)
get_name (IHTMLInputImage)
get_name (IHTMLInputTextElement)
get_name (IHTMLMapElement)
get_name (IHTMLMetaElement)
get_name (IHTMLObjectElement)
get_name (IHTMLOptionButtonElement)
get_name (IHTMLSelectElement)
get_name (IHTMLTextAreaElement)
get_name (IHTMLWindow2)
get_Name (IWebBrowser2)
get_nameProp (IHTMLAnchorElement)
get_nameProp (IHTMLDocument2)
get_nameProp (IHTMLImgElement)
get_navigator (IHTMLWindow2)
get_newEnum (IXMLElementCollection)
get_noHref (IHTMLAreaElement)
get_noResize (IHTMLFrameBase)
get_noShade (IHTMLHRElement)
get_noWrap (IHTMLBodyElement)
get_noWrap (IHTMLDDElement)
get_noWrap (IHTMLDivElement)
get_noWrap (IHTMLDTElement)
get_noWrap (IHTMLTableCell)
get_object (IHTMLObjectElement)
get_Offline (IWebBrowser2)
get_offscreenBuffering (IHTMLWindow2)
get_offsetHeight (IHTMLElement)
get_offsetLeft (IHTMLElement)
get_offsetParent (IHTMLElement)
get_offsetTop (IHTMLElement)
get_offsetWidth (IHTMLElement)
get_offsetX (IHTMLEventObj)
get_offsetY (IHTMLEventObj)
get_onabort (IHTMLImgElement)
get_onabort (IHTMLInputImage)
get_onafterupdate (IHTMLDocument2)
get_onafterupdate (IHTMLElement)
get_onbeforeunload (IHTMLBodyElement)
get_onbeforeunload (IHTMLFrameSetElement)
get_onbeforeunload (IHTMLWindow2)
get_onbeforeupdate (IHTMLDocument2)
get_onbeforeupdate (IHTMLElement)
get_onblur (IHTMLAnchorElement)
get_onblur (IHTMLAreaElement)
get_onblur (IHTMLControlElement)
get_onblur (IHTMLWindow2)
get_onbounce (IHTMLMarqueeElement)
get_onchange (IHTMLInputFileElement)
get_onchange (IHTMLInputTextElement)
get_onchange (IHTMLOptionButtonElement)
get_onchange (IHTMLSelectElement)
get_onchange (IHTMLTextAreaElement)
get_onclick (IHTMLDocument2)
get_onclick (IHTMLElement)
get_ondataavailable (IHTMLElement)
get_ondatasetchanged (IHTMLElement)
get_ondatasetcomplete (IHTMLElement)
get_ondblclick (IHTMLDocument2)
get_ondblclick (IHTMLElement)
get_ondragstart (IHTMLDocument2)
get_ondragstart (IHTMLElement)
get_onerror (IHTMLImgElement)
get_onerror (IHTMLInputImage)
get_onerror (IHTMLLinkElement)
get_onerror (IHTMLObjectElement)
get_onerror (IHTMLScriptElement)
get_onerror (IHTMLStyleElement)
get_onerror (IHTMLWindow2)
get_onerrorupdate (IHTMLDocument2)
get_onerrorupdate (IHTMLElement)
get_onfilterchange (IHTMLElement)
get_onfinish (IHTMLMarqueeElement)
get_onfocus (IHTMLAnchorElement)
get_onfocus (IHTMLAreaElement)
get_onfocus (IHTMLControlElement)
get_onfocus (IHTMLWindow2)
get_onhelp (IHTMLDocument2)
get_onhelp (IHTMLElement)
get_onhelp (IHTMLWindow2)
get_onkeydown (IHTMLDocument2)
get_onkeydown (IHTMLElement)
get_onkeypress (IHTMLDocument2)
get_onkeypress (IHTMLElement)
get_onkeyup (IHTMLDocument2)
get_onkeyup (IHTMLElement)
get_onLine (IOmNavigator)
get_onload (IHTMLBodyElement)
get_onload (IHTMLImgElement)
get_onload (IHTMLInputImage)
get_onload (IHTMLLinkElement)
get_onload (IHTMLStyleElement)
get_onload (IHTMLWindow2)
get_onload (ITMLFrameSetElement)
get_onmousedown (IHTMLDocument2)
get_onmousedown (IHTMLElement)
get_onmousemove (IHTMLDocument2)
get_onmousemove (IHTMLElement)
get_onmouseout (IHTMLDocument2)
get_onmouseout (IHTMLElement)
get_onmouseover (IHTMLDocument2)
get_onmouseover (IHTMLElement)
get_onmouseup (IHTMLDocument2)
get_onmouseup (IHTMLElement)
get_onreadystatechange (IHTMLDocument2)
get_onreadystatechange (IHTMLLinkElement)
get_onreadystatechange (IHTMLObjectElement)
get_onreadystatechange (IHTMLStyleElement)
get_onreadystatechange (IHTMLTable)
get_onreset (IHTMLFormElement)
get_onresize (IHTMLControlElement)
get_onresize (IHTMLWindow2)
get_onrowenter (IHTMLDocument2)
get_onrowenter (IHTMLElement)
get_onrowexit (IHTMLDocument2)
get_onrowexit (IHTMLElement)
get_onscroll (IHTMLTextContainer)
get_onscroll (IHTMLWindow2)
get_onselect (IHTMLBodyElement)
get_onselect (IHTMLInputFileElement)
get_onselect (IHTMLInputTextElement)
get_onselect (IHTMLTextAreaElement)
get_onselectstart (IHTMLDocument2)
get_onselectstart (IHTMLElement)
get_onstart (IHTMLMarqueeElement)
get_onsubmit (IHTMLFormElement)
get_onunload (IHTMLBodyElement)
get_onunload (IHTMLFrameSetElement)
get_onunload (IHTMLWindow2)
get_opener (IHTMLWindow2)
get_opsProfile (IOmNavigator)
get_Option (IHTMLWindow2)
get_options (IHTMLSelectElement)
get_outerHTML (IHTMLElement)
get_outerText (IHTMLElement)
get_overflow (IHTMLRuleStyle)
get_overflow (IHTMLStyle)
get_owningElement (IHTMLStyleSheet)
get_padding (IHTMLRuleStyle)
get_padding (IHTMLStyle)
get_paddingBottom (IHTMLRuleStyle)
get_paddingBottom (IHTMLStyle)
get_paddingLeft (IHTMLRuleStyle)
get_paddingLeft (IHTMLStyle)
get_paddingRight (IHTMLRuleStyle)
get_paddingRight (IHTMLStyle)
get_paddingTop (IHTMLRuleStyle)
get_paddingTop (IHTMLStyle)
get_pageBreakAfter (IHTMLRuleStyle)
get_pageBreakAfter (IHTMLStyle)
get_pageBreakBefore (IHTMLRuleStyle)
get_pageBreakBefore (IHTMLStyle)
get_palette (IHTMLEmbedElement)
get_parent (IHTMLWindow2)
get_Parent (IWebBrowser2)
get_parent (IXMLElement)
get_parentElement (IHTMLElement)
get_parentStyleSheet (IHTMLStyleSheet)
get_parentTextEdit (IHTMLElement)
get_parentWindow (IHTMLDocument2)
get_Path (IWebBrowser2)
get_pathname (IHTMLAnchorElement)
get_pathname (IHTMLAreaElement)
get_pathname (IHTMLLocation)
get_pixelHeight (IHTMLStyle)
get_pixelLeft (IHTMLStyle)
get_pixelTop (IHTMLStyle)
get_pixelWidth (IHTMLStyle)
get_platform (IOmNavigator)
get_plugins (IHTMLDocument2)
get_plugins (IOmNavigator)
get_pluginspage (IHTMLEmbedElement)
get_port (IHTMLAnchorElement)
get_port (IHTMLAreaElement)
get_port (IHTMLLocation)
get_posHeight (IHTMLStyle)
get_position (IHTMLRuleStyle)
get_position (IHTMLStyle)
get_posLeft (IHTMLStyle)
get_posTop (IHTMLStyle)
get_posWidth (IHTMLStyle)
get_productVersion (IHTMLOptionsHolder)
get_prompt (IHTMLIsIndexElement)
get_protocol (IHTMLAnchorElement)
get_protocol (IHTMLAreaElement)
get_protocol (IHTMLDocument2)
get_protocol (IHTMLImgElement)
get_protocol (IHTMLLocation)
get_protocolLong (IHTMLAnchorElement)
get_qualifier (IHTMLEventObj)
get_readOnly (IHTMLInputTextElement)
get_readOnly (IHTMLStyleSheet)
get_readOnly (IHTMLStyleSheetRule)
get_readOnly (IHTMLTextAreaElement)
get_readyState (IHTMLDocument2)
get_readyState (IHTMLImgElement)
get_readyState (IHTMLInputImage)
get_readyState (IHTMLLinkElement)
get_readyState (IHTMLObjectElement)
get_readyState (IHTMLScriptElement)
get_readyState (IHTMLStyleElement)
get_readyState (IHTMLTable)
get_ReadyState (IWebBrowser2)
get_readyState (IXMLDocument)
get_reason (IHTMLEventObj)
get_recordNumber (IHTMLElement)
get_recordset (IHTMLObjectElement)
get_referrer (IHTMLDocument2)
get_RegisterAsBrowser (IWebBrowser2)
get_RegisterAsDropTarget (IWebBrowser2)
get_rel (IHTMLAnchorElement)
get_rel (IHTMLLinkElement)
get_Resizable (IWebBrowser2)
get_returnValue (IHTMLDialog)
get_returnValue (IHTMLEventObj)
get_rev (IHTMLAnchorElement)
get_rev (IHTMLLinkElement)
get_rightMargin (IHTMLBodyElement)

* More entries...


Index

IHTMLAreasCollection::put_length
IHTMLAreasCollection::remove
IHTMLAreasCollection::tags
IHTMLBaseElement::get_href
IHTMLBaseElement::get_target
IHTMLBaseElement::put_href
IHTMLBaseElement::put_target
IHTMLBaseFontElement::get_color
IHTMLBaseFontElement::get_face
IHTMLBaseFontElement::get_size
IHTMLBaseFontElement::put_color
IHTMLBaseFontElement::put_face
IHTMLBaseFontElement::put_size
IHTMLBGsound::get_balance
IHTMLBGsound::get_loop
IHTMLBGsound::get_src
IHTMLBGsound::get_volume
IHTMLBGsound::put_balance
IHTMLBGsound::put_loop
IHTMLBGsound::put_src
IHTMLBGsound::put_volume
IHTMLBlockElement::get_clear
IHTMLBlockElement::put_clear
IHTMLBodyElement::createTextRange
IHTMLBodyElement::get_aLink
IHTMLBodyElement::get_background
IHTMLBodyElement::get_bgColor
IHTMLBodyElement::get_bgProperties
IHTMLBodyElement::get_bottomMargin
IHTMLBodyElement::get_leftMargin
IHTMLBodyElement::get_link
IHTMLBodyElement::get_noWrap
IHTMLBodyElement::get_onbeforeunload
IHTMLBodyElement::get_onload
IHTMLBodyElement::get_onselect
IHTMLBodyElement::get_onunload
IHTMLBodyElement::get_rightMargin
IHTMLBodyElement::get_scroll
IHTMLBodyElement::get_text
IHTMLBodyElement::get_topMargin
IHTMLBodyElement::get_vLink
IHTMLBodyElement::put_aLink
IHTMLBodyElement::put_background
IHTMLBodyElement::put_bgColor
IHTMLBodyElement::put_bgProperties
IHTMLBodyElement::put_bottomMargin
IHTMLBodyElement::put_leftMargin
IHTMLBodyElement::put_link
IHTMLBodyElement::put_noWrap
IHTMLBodyElement::put_onbeforeunload
IHTMLBodyElement::put_onload
IHTMLBodyElement::put_onselect
IHTMLBodyElement::put_onunload
IHTMLBodyElement::put_rightMargin
IHTMLBodyElement::put_scroll
IHTMLBodyElement::put_text
IHTMLBodyElement::put_topMargin
IHTMLBodyElement::put_vLink
IHTMLBRElement::get_clear
IHTMLBRElement::put_clear
IHTMLButtonElement::createTextRange
IHTMLButtonElement::get_disabled
IHTMLButtonElement::get_form
IHTMLButtonElement::get_name
IHTMLButtonElement::get_status
IHTMLButtonElement::get_type
IHTMLButtonElement::get_value
IHTMLButtonElement::put_disabled
IHTMLButtonElement::put_name
IHTMLButtonElement::put_status
IHTMLButtonElement::put_value
IHTMLCommentElement::get_text
IHTMLCommentElement::put_text
IHTMLControlElement::addFilter
IHTMLControlElement::blur
IHTMLControlElement::focus
IHTMLControlElement::get_accessKey
IHTMLControlElement::get_clientHeight
IHTMLControlElement::get_clientLeft
IHTMLControlElement::get_clientTop
IHTMLControlElement::get_clientWidth
IHTMLControlElement::get_onblur
IHTMLControlElement::get_onfocus
IHTMLControlElement::get_onresize
IHTMLControlElement::get_tabIndex
IHTMLControlElement::put_accessKey
IHTMLControlElement::put_onblur
IHTMLControlElement::put_onfocus
IHTMLControlElement::put_onresize
IHTMLControlElement::put_tabIndex
IHTMLControlElement::removeFilter
IHTMLControlRange::add
IHTMLControlRange::commonParentElement
IHTMLControlRange::execCommand
IHTMLControlRange::execCommandShowHelp
IHTMLControlRange::get_length
IHTMLControlRange::item
IHTMLControlRange::queryCommandEnabled
IHTMLControlRange::queryCommandIndeterm
IHTMLControlRange::queryCommandState
IHTMLControlRange::queryCommandSupported
IHTMLControlRange::queryCommandText
IHTMLControlRange::queryCommandValue
IHTMLControlRange::remove
IHTMLControlRange::scrollIntoView
IHTMLControlRange::select
IHTMLDatabinding::get_dataFld
IHTMLDatabinding::get_dataFormatAs
IHTMLDatabinding::get_dataSrc
IHTMLDatabinding::put_dataFld
IHTMLDatabinding::put_dataFormatAs
IHTMLDatabinding::put_dataSrc
IHTMLDDElement::get_noWrap
IHTMLDDElement::put_noWrap
IHTMLDialog::close
IHTMLDialog::get_dialogArguments
IHTMLDialog::get_dialogHeight
IHTMLDialog::get_dialogLeft
IHTMLDialog::get_dialogTop
IHTMLDialog::get_dialogWidth
IHTMLDialog::get_returnValue
IHTMLDialog::put_dialogHeight
IHTMLDialog::put_dialogLeft
IHTMLDialog::put_dialogTop
IHTMLDialog::put_dialogWidth
IHTMLDialog::put_returnValue
IHTMLDialog::toString
IHTMLDivElement::get_align
IHTMLDivElement::get_noWrap
IHTMLDivElement::put_align
IHTMLDivElement::put_noWrap
IHTMLDivPosition::get_align
IHTMLDivPosition::put_align
IHTMLDListElement::get_compact
IHTMLDListElement::put_compact
IHTMLDocument::get_Script
IHTMLDocument2::clear
IHTMLDocument2::close
IHTMLDocument2::createElement
IHTMLDocument2::elementFromPoint
IHTMLDocument2::execCommand
IHTMLDocument2::execCommandShowHelp
IHTMLDocument2::get_activeElement
IHTMLDocument2::get_alinkColor
IHTMLDocument2::get_all
IHTMLDocument2::get_anchors
IHTMLDocument2::get_applets
IHTMLDocument2::get_bgColor
IHTMLDocument2::get_body
IHTMLDocument2::get_charset
IHTMLDocument2::get_cookie
IHTMLDocument2::get_defaultCharset
IHTMLDocument2::get_domain
IHTMLDocument2::get_embeds
IHTMLDocument2::get_expando
IHTMLDocument2::get_fgColor
IHTMLDocument2::get_fileCreatedDate
IHTMLDocument2::get_fileModifiedDate
IHTMLDocument2::get_fileSize
IHTMLDocument2::get_fileUpdatedDate
IHTMLDocument2::get_forms
IHTMLDocument2::get_frames
IHTMLDocument2::get_images
IHTMLDocument2::get_lastModified
IHTMLDocument2::get_linkColor
IHTMLDocument2::get_links
IHTMLDocument2::get_location
IHTMLDocument2::get_mimeType
IHTMLDocument2::get_nameProp
IHTMLDocument2::get_onafterupdate
IHTMLDocument2::get_onbeforeupdate
IHTMLDocument2::get_onclick
IHTMLDocument2::get_ondblclick
IHTMLDocument2::get_ondragstart
IHTMLDocument2::get_onerrorupdate
IHTMLDocument2::get_onhelp
IHTMLDocument2::get_onkeydown
IHTMLDocument2::get_onkeypress
IHTMLDocument2::get_onkeyup
IHTMLDocument2::get_onmousedown
IHTMLDocument2::get_onmousemove
IHTMLDocument2::get_onmouseout
IHTMLDocument2::get_onmouseover
IHTMLDocument2::get_onmouseup
IHTMLDocument2::get_onreadystatechange
IHTMLDocument2::get_onrowenter
IHTMLDocument2::get_onrowexit
IHTMLDocument2::get_onselectstart
IHTMLDocument2::get_parentWindow
IHTMLDocument2::get_plugins
IHTMLDocument2::get_protocol
IHTMLDocument2::get_readyState
IHTMLDocument2::get_referrer
IHTMLDocument2::get_scripts
IHTMLDocument2::get_security
IHTMLDocument2::get_selection
IHTMLDocument2::get_styleSheets
IHTMLDocument2::get_title
IHTMLDocument2::get_URL
IHTMLDocument2::get_vlinkColor
IHTMLDocument2::open
IHTMLDocument2::put_alinkColor
IHTMLDocument2::put_bgColor
IHTMLDocument2::put_charset
IHTMLDocument2::put_cookie
IHTMLDocument2::put_defaultCharset
IHTMLDocument2::put_domain
IHTMLDocument2::put_expando
IHTMLDocument2::put_fgColor
IHTMLDocument2::put_linkColor
IHTMLDocument2::put_onafterupdate
IHTMLDocument2::put_onbeforeupdate
IHTMLDocument2::put_onclick
IHTMLDocument2::put_ondblclick
IHTMLDocument2::put_ondragstart
IHTMLDocument2::put_onerrorupdate
IHTMLDocument2::put_onhelp
IHTMLDocument2::put_onkeydown
IHTMLDocument2::put_onkeypress
IHTMLDocument2::put_onkeyup
IHTMLDocument2::put_onmousedown
IHTMLDocument2::put_onmousemove
IHTMLDocument2::put_onmouseout
IHTMLDocument2::put_onmouseover
IHTMLDocument2::put_onmouseup
IHTMLDocument2::put_onreadystatechange

* More entries...


Index

put_disabled (IHTMLInputHiddenElement)
put_disabled (IHTMLInputImage)
put_disabled (IHTMLInputTextElement)
put_disabled (IHTMLLinkElement)
put_disabled (IHTMLOptionButtonElement)
put_disabled (IHTMLSelectElement)
put_disabled (IHTMLStyleElement)
put_disabled (IHTMLStyleSheet)
put_disabled (IHTMLTextAreaElement)
put_display (IHTMLRuleStyle)
put_display (IHTMLStyle)
put_domain (IHTMLDocument2)
put_dynsrc (IHTMLImgElement)
put_dynsrc (IHTMLInputImage)
put_encoding (IHTMLFormElement)
put_errorCharacter (IHTMLOptionsHolder)
put_errorCode (IHTMLOptionsHolder)
put_errorDebug (IHTMLOptionsHolder)
put_errorLine (IHTMLOptionsHolder)
put_errorMessage (IHTMLOptionsHolder)
put_event (IHTMLScriptElement)
put_execArg (IHTMLOptionsHolder)
put_expando (IHTMLDocument2)
put_face (IHTMLBaseFontElement)
put_face (IHTMLFontElement)
put_fgColor (IHTMLDocument2)
put_filter (IHTMLRuleStyle)
put_filter (IHTMLStyle)
put_findText (IHTMLOptionsHolder)
put_font (IHTMLRuleStyle)
put_font (IHTMLStyle)
put_fontFamily (IHTMLRuleStyle)
put_fontFamily (IHTMLStyle)
put_fontSize (IHTMLRuleStyle)
put_fontSize (IHTMLStyle)
put_fontStyle (IHTMLRuleStyle)
put_fontStyle (IHTMLStyle)
put_fontVariant (IHTMLRuleStyle)
put_fontVariant (IHTMLStyle)
put_fontWeight (IHTMLRuleStyle)
put_fontWeight (IHTMLStyle)
put_frame (IHTMLTable)
put_frameBorder (IHTMLFrameBase)
put_frameBorder (IHTMLFrameSetElement)
put_frameSpacing (IHTMLFrameBase)
put_frameSpacing (IHTMLFrameSetElement)
put_hash (IHTMLAnchorElement)
put_hash (IHTMLAreaElement)
put_hash (IHTMLLocation)
put_height (IHTMLEmbedElement)
put_height (IHTMLImgElement)
put_height (IHTMLInputImage)
put_height (IHTMLMarqueeElement)
put_height (IHTMLObjectElement)
put_height (IHTMLRuleStyle)
put_height (IHTMLStyle)
put_height (IHTMLTable)
put_height (IHTMLTableCell)
put_hidden (IHTMLEmbedElement)
put_host (IHTMLAnchorElement)
put_host (IHTMLAreaElement)
put_host (IHTMLLocation)
put_hostname (IHTMLAnchorElement)
put_hostname (IHTMLAreaElement)
put_hostname (IHTMLLocation)
put_href (IHTMLAnchorElement)
put_href (IHTMLAreaElement)
put_href (IHTMLBaseElement)
put_href (IHTMLLinkElement)
put_href (IHTMLLocation)
put_href (IHTMLStyleSheet)
put_hspace (IHTMLIFrameElement)
put_hspace (IHTMLImgElement)
put_hspace (IHTMLInputImage)
put_hspace (IHTMLMarqueeElement)
put_hspace (IHTMLObjectElement)
put_htmlFor (IHTMLLabelElement)
put_htmlFor (IHTMLScriptElement)
put_httpEquiv (IHTMLMetaElement)
put_id (IHTMLElement)
put_indeterminate (IHTMLOptionButtonElement)
put_index (IHTMLOptionElement)
put_innerHTML (IHTMLElement)
put_innerText (IHTMLElement)
put_isMap (IHTMLImgElement)
put_keyCode (IHTMLEventObj)
put_lang (IHTMLElement)
put_language (IHTMLElement)
put_left (IHTMLRuleStyle)
put_left (IHTMLStyle)
put_leftMargin (IHTMLBodyElement)
put_length (IHTMLAreasCollection)
put_length (IHTMLElementCollection)
put_length (IHTMLFormElement)
put_length (IHTMLSelectElement)
put_letterSpacing (IHTMLRuleStyle)
put_letterSpacing (IHTMLStyle)
put_lineHeight (IHTMLRuleStyle)
put_lineHeight (IHTMLStyle)
put_link (IHTMLBodyElement)
put_linkColor (IHTMLDocument2)
put_listStyle (IHTMLRuleStyle)
put_listStyle (IHTMLStyle)
put_listStyleImage (IHTMLRuleStyle)
put_listStyleImage (IHTMLStyle)
put_listStylePosition (IHTMLRuleStyle)
put_listStylePosition (IHTMLStyle)
put_listStyleType (IHTMLRuleStyle)
put_listStyleType (IHTMLStyle)
put_loop (IHTMLBGsound)
put_loop (IHTMLImgElement)
put_loop (IHTMLInputImage)
put_loop (IHTMLMarqueeElement)
put_lowsrc (IHTMLImgElement)
put_lowsrc (IHTMLInputImage)
put_margin (IHTMLRuleStyle)
put_margin (IHTMLStyle)
put_marginBottom (IHTMLRuleStyle)
put_marginBottom (IHTMLStyle)
put_marginHeight (IHTMLFrameBase)
put_marginLeft (IHTMLRuleStyle)
put_marginLeft (IHTMLStyle)
put_marginRight (IHTMLRuleStyle)
put_marginRight (IHTMLStyle)
put_marginTop (IHTMLRuleStyle)
put_marginTop (IHTMLStyle)
put_marginWidth (IHTMLFrameBase)
put_maxLength (IHTMLInputFileElement)
put_maxLength (IHTMLInputTextElement)
put_media (IHTMLLinkElement)
put_media (IHTMLStyleElement)
put_media (IHTMLStyleSheet)
put_method (IHTMLFormElement)
put_Methods (IHTMLAnchorElement)
put_multiple (IHTMLSelectElement)
put_n (IHTMLNextIdElement)
put_name (IHTMLAnchorElement)
put_name (IHTMLButtonElement)
put_name (IHTMLEmbedElement)
put_name (IHTMLFormElement)
put_name (IHTMLFrameBase)
put_name (IHTMLFrameSetElement)
put_name (IHTMLImgElement)
put_name (IHTMLInputButtonElement)
put_name (IHTMLInputFileElement)
put_name (IHTMLInputHiddenElement)
put_name (IHTMLInputImage)
put_name (IHTMLInputTextElement)
put_name (IHTMLMapElement)
put_name (IHTMLMetaElement)
put_name (IHTMLObjectElement)
put_name (IHTMLOptionButtonElement)
put_name (IHTMLSelectElement)
put_name (IHTMLTextAreaElement)
put_name (IHTMLWindow2)
put_noHref (IHTMLAreaElement)
put_noResize (IHTMLFrameBase)
put_noShade (IHTMLHRElement)
put_noWrap (IHTMLBodyElement)
put_noWrap (IHTMLDDElement)
put_noWrap (IHTMLDivElement)
put_noWrap (IHTMLDTElement)
put_noWrap (IHTMLTableCell)
put_offscreenBuffering (IHTMLWindow2)
put_onabort (IHTMLImgElement)
put_onabort (IHTMLInputImage)
put_onafterupdate (IHTMLDocument2)
put_onafterupdate (IHTMLElement)
put_onbeforeunload (IHTMLBodyElement)
put_onbeforeunload (IHTMLFrameSetElement)
put_onbeforeunload (IHTMLWindow2)
put_onbeforeupdate (IHTMLDocument2)
put_onbeforeupdate (IHTMLElement)
put_onblur (IHTMLAnchorElement)
put_onblur (IHTMLAreaElement)
put_onblur (IHTMLControlElement)
put_onblur (IHTMLWindow2)
put_onbounce (IHTMLMarqueeElement)
put_onchange (IHTMLInputFileElement)
put_onchange (IHTMLInputTextElement)
put_onchange (IHTMLOptionButtonElement)
put_onchange (IHTMLSelectElement)
put_onchange (IHTMLTextAreaElement)
put_onclick (IHTMLDocument2)
put_onclick (IHTMLElement)
put_ondataavailable (IHTMLElement)
put_ondatasetchanged (IHTMLElement)
put_ondatasetcomplete (IHTMLElement)
put_ondblclick (IHTMLDocument2)
put_ondblclick (IHTMLElement)
put_ondragstart (IHTMLDocument2)
put_ondragstart (IHTMLElement)
put_onerror (IHTMLImgElement)
put_onerror (IHTMLInputImage)
put_onerror (IHTMLLinkElement)
put_onerror (IHTMLObjectElement)
put_onerror (IHTMLScriptElement)
put_onerror (IHTMLStyleElement)
put_onerror (IHTMLWindow2)
put_onerrorupdate (IHTMLDocument2)
put_onerrorupdate (IHTMLElement)
put_onfilterchange (IHTMLElement)
put_onfinish (IHTMLMarqueeElement)
put_onfocus (IHTMLAnchorElement)
put_onfocus (IHTMLAreaElement)
put_onfocus (IHTMLControlElement)
put_onfocus (IHTMLWindow2)
put_onhelp (IHTMLDocument2)
put_onhelp (IHTMLElement)
put_onhelp (IHTMLWindow2)
put_onkeydown (IHTMLDocument2)
put_onkeydown (IHTMLElement)
put_onkeypress (IHTMLDocument2)
put_onkeypress (IHTMLElement)
put_onkeyup (IHTMLDocument2)
put_onkeyup (IHTMLElement)
put_onload (IHTMLBodyElement)
put_onload (IHTMLFrameSetElement)

* More entries...


Index

StatusTextChange
StatusTextChange (DWebBrowserEvents2)
StatusTextChange Event
stChannelAccount
stChannelClientData
stChannelHostKey
stChannelKeyword
stChannelLanguage
stChannelName
stChannelOnJoin
stChannelOnPart
stChannelOwnerKey
stChannelRating
stChannelSubject
stChannelTopic
STGM
STGMEDIUM
StgOpenStorage
stop
Stop (Methods)
stop (IHTMLMarqueeElement)
Stop (IWebBrowser2)
Stop Method (Control Methods)
Stop Method (Methods)
Stop Method (Properties, Methods, and Events Reference)
STOPDATE=
StopImage
StopImage Command
StrCatN
StrChr
StrChrI
StrCmpN
StrCmpNI
StrCpyN
StrCSpn
StrCSpnI
StrDup
StrFormatByteSize
StrFromTimeInterval
STRIKE (HTML Elements)
STRIKE (Objects)
StrIntlEqN
StrIntlEqNI
StrIsIntlEqual
StrNCat
StrNCmp
StrNCmpI
StrNCpy
STRONG (HTML Elements)
STRONG (Objects)
StrPBrk
StrRChr
STRRET
StrRStrI
StrSpn
StrStr
StrStrI
StrToInt
StrToIntEx
StrToLong
StrTrim
stServerMessage
stub <definition>
STYLE (HTML Elements)
STYLE (Objects: 1)
style (Objects: 2)
style (Properties)
STYLE= (A)
STYLE= (ACRONYM)
STYLE= (ADDRESS)
STYLE= (APPLET)
STYLE= (AREA)
STYLE= (B)
STYLE= (BIG)
STYLE= (BLOCKQUOTE)
STYLE= (BODY)
STYLE= (BR)
STYLE= (BUTTON)
STYLE= (CAPTION)
STYLE= (CENTER)
STYLE= (CITE)
STYLE= (CODE)
STYLE= (CODEBASE)
STYLE= (COL)
STYLE= (COLGROUP)
STYLE= (DD)
STYLE= (DEL)
STYLE= (DFN)
STYLE= (DIR)
STYLE= (DIV)
STYLE= (DL)
STYLE= (DT)
STYLE= (EM)
STYLE= (EMBED)
STYLE= (FIELDSET)
STYLE= (FONT)
STYLE= (FORM)
STYLE= (Hn)
STYLE= (HR)
STYLE= (I)
STYLE= (IFRAME)
STYLE= (IMG)
STYLE= (INPUT)
STYLE= (INS)
STYLE= (ISINDEX)
STYLE= (KBD)
STYLE= (LABEL)
STYLE= (LEGEND)
STYLE= (LI)
STYLE= (LISTING)
STYLE= (LOGO)
STYLE= (MAP)
STYLE= (MARQUEE)
STYLE= (MENU)
STYLE= (NOBR)
STYLE= (NOFRAMES)
STYLE= (OBJECT)
STYLE= (OL)
STYLE= (P)
STYLE= (PLAINTEXT)
STYLE= (PRE)
STYLE= (Q)
STYLE= (S)
STYLE= (SAMP)
STYLE= (SELECT)
STYLE= (SMALL)
STYLE= (SOFTPKG)
STYLE= (SPAN)
STYLE= (STRIKE)
STYLE= (STRONG)
STYLE= (SUB)
STYLE= (SUP)
STYLE= (TABLE)
STYLE= (TBODY)
STYLE= (TD)
STYLE= (TEXTAREA)
STYLE= (TFOOT)
STYLE= (TH)
STYLE= (THEAD)
STYLE= (TR)
STYLE= (TT)
STYLE= (U)
STYLE= (UL)
STYLE= (VAR)
STYLE= (WBR)
STYLE= (XMP)
styleFloat
styleSheet
styleSheets
SUB (HTML Elements)
SUB (Objects)
Subject
SubjectOp
submit (Methods)
submit (Objects)
submit (type)
submit (IHTMLFormElement)
SubmitChanges Method
SubmitChanges Method Example
Subscription Manager Object
SUBSCRIPTIONINFO
SUBSCRIPTIONINFOFLAGS
SUBSCRIPTIONSCHEDULE
SUBSCRIPTIONSTATE
SUBSCRIPTIONTYPE
SUBSINFO_CHANGESONLY
SUBSINFO_CHANNELFLAGS
SUBSINFO_FRIENDLYNAME
SUBSINFO_GLEAM
SUBSINFO_MAILNOT
SUBSINFO_MAXSIZEKB
SUBSINFO_NEEDPASSWORD
SUBSINFO_PASSWORD
SUBSINFO_RECURSE
SUBSINFO_SCHEDULE
SUBSINFO_TYPE
SUBSINFO_USER
SUBSINFO_WEBCRAWL
SUBSSCHED_AUTO
SUBSSCHED_CUSTOM
SUBSSCHED_DAILY
SUBSSCHED_MANUAL
SUBSSCHED_WEEKLY
SUBSTATE_FULLSUBSCRIPTION
SUBSTATE_NOTSUBSCRIBED
SUBSTATE_PARTIALSUBSCRIPTION
SUBSTYPE_CHANNEL
SUBSTYPE_DESKTOPCOMPONENT
SUBSTYPE_URL
SUP (HTML Elements)
SUP (Objects)
Supporting Tracking Tooltips
Supports Method (ADO)
Supports Method Example (ADO)
Suspend (IBinding)
Suspend (IInternetProtocolRoot)
Suspend Method
SUUserPopData
SUUserPushData
SUUserRetrieveData
SUUserSaveData
SV2CVW2_PARAMS
Switch (IInternetProtocolSink)
SysopCount
SYSTEM
System Requirements for the Address Book Application
systemLanguage
SystemParametersInfo
SYSTEMTIME
SZM_CREATE
SZM_DELETE
SZM_FLAGS


Index

TreeView_InsertItem
TreeView_Select
TreeView_SelectDropTarget
TreeView_SelectItem
TreeView_SelectSetFirstVisible
TreeView_SetBkColor
TreeView_SetImageList
TreeView_SetIndent
TreeView_SetInsertMark
TreeView_SetInsertMarkColor
TreeView_SetItem
TreeView_SetItemHeight
TreeView_SetScrollTime
TreeView_SetTextColor
TreeView_SetToolTips
TreeView_SetUnicodeFormat
TreeView_SortChildren
TreeView_SortChildrenCB
TRIGGER_TYPE_UNION
Troubleshooting Microsoft Agent
Troubleshooting Remote Data Service
trueSpeed
TRUESPEED (MARQUEE)
TT (HTML Elements)
TT (Objects)
TTHITTESTINFO
TTM_ACTIVATE
TTM_ADDTOOL
TTM_DELTOOL
TTM_ENUMTOOLS
TTM_GETCURRENTTOOL
TTM_GETDELAYTIME
TTM_GETMARGIN
TTM_GETMAXTIPWIDTH
TTM_GETTEXT
TTM_GETTIPBKCOLOR
TTM_GETTIPTEXTCOLOR
TTM_GETTOOLCOUNT
TTM_GETTOOLINFO
TTM_HITTEST
TTM_NEWTOOLRECT
TTM_POP
TTM_RELAYEVENT
TTM_SETDELAYTIME
TTM_SETMARGIN
TTM_SETMAXTIPWIDTH
TTM_SETTIPBKCOLOR
TTM_SETTIPTEXTCOLOR
TTM_SETTOOLINFO
TTM_TRACKACTIVATE
TTM_TRACKPOSITION
TTM_UPDATE
TTM_UPDATETIPTEXT
TTM_WINDOWFROMPOINT
TTN_GETDISPINFO
TTN_POP
TTN_SHOW
TTS_ALWAYSTIP
TTS_NOPREFIX
Tutorial: Address Book
TV_DISPINFO
TV_HITTESTINFO
TV_INSERTSTRUCT
TV_ITEM
TV_KEYDOWN
TV_SORTCB
TVHITTESTINFO
TVINSERTSTRUCT
TVITEM
TVITEMEX
TVM_CREATEDRAGIMAGE
TVM_DELETEITEM
TVM_EDITLABEL
TVM_ENDEDITLABELNOW
TVM_ENSUREVISIBLE
TVM_EXPAND
TVM_GETBKCOLOR
TVM_GETCOUNT
TVM_GETEDITCONTROL
TVM_GETIMAGELIST
TVM_GETINDENT
TVM_GETINSERTMARKCOLOR
TVM_GETISEARCHSTRING
TVM_GETITEM
TVM_GETITEMHEIGHT
TVM_GETITEMRECT
TVM_GETNEXTITEM
TVM_GETSCROLLTIME
TVM_GETTEXTCOLOR
TVM_GETTOOLTIPS
TVM_GETUNICODEFORMAT
TVM_GETVISIBLECOUNT
TVM_HITTEST
TVM_INSERTITEM
TVM_SELECTITEM
TVM_SETBKCOLOR
TVM_SETIMAGELIST
TVM_SETINDENT
TVM_SETINSERTMARK
TVM_SETINSERTMARKCOLOR
TVM_SETITEM
TVM_SETITEMHEIGHT
TVM_SETSCROLLTIME
TVM_SETTEXTCOLOR
TVM_SETTOOLTIPS
TVM_SETUNICODEFORMAT
TVM_SORTCHILDREN
TVM_SORTCHILDRENCB
TVN_BEGINDRAG
TVN_BEGINLABELEDIT
TVN_BEGINRDRAG
TVN_DELETEITEM
TVN_ENDLABELEDIT
TVN_GETDISPINFO
TVN_GETINFOTIP
TVN_ITEMEXPANDED
TVN_ITEMEXPANDING
TVN_KEYDOWN
TVN_SELCHANGED
TVN_SELCHANGING
TVN_SETDISPINFO
TVN_SINGLEEXPAND
TVS_CHECKBOXES
TVS_DISABLEDRAGDROP
TVS_EDITLABELS
TVS_FULLROWSELECT
TVS_HASBUTTONS
TVS_HASLINES
TVS_INFOTIP
TVS_LINESATROOT
TVS_NONEVENHEIGHT
TVS_NOSCROLL
TVS_NOTOOLTIPS
TVS_RTLREADING
TVS_SHOWSELALWAYS
TVS_SINGLEEXPAND
TVS_TRACKSELECT
TVSORTCB
type (Properties: 1)
type (Properties: 2)
type (Properties: 3)
type (Properties: 4)
type (Properties: 5)
type (Properties: 6)
type (Properties: 7)
type (Properties: 8)
type (Properties: 9)
Type (Reusing the WebBrowser Control: Reference for Visual Basic Developers: Properties)
Type Property (FolderItem Object)
Type Property (Properties)
Type Property (ADO)
Type Property Example (ADO)
TYPE= (BUTTON)
TYPE= (INPUT)
TYPE= (LI)
TYPE= (LINK)
TYPE= (OBJECT)
TYPE= (OL)
TYPE= (SCRIPT)
TYPE= (STYLE)
TYPE= (UL)
TYPELIB


Index

get_root (IXMLDocument)
get_rowIndex (IHTMLTableRow)
get_rows (IHTMLFrameSetElement)
get_rows (IHTMLTable)
get_rows (IHTMLTableSection)
get_rows (IHTMLTextAreaElement)
get_rowSpan (IHTMLTableCell)
get_rules (IHTMLStyleSheet)
get_rules (IHTMLTable)
get_screen (IHTMLWindow2)
get_screenX (IHTMLEventObj)
get_screenY (IHTMLEventObj)
get_Script
get_Script (IHTMLDocument)
get_scripts (IHTMLDocument2)
get_scroll (IHTMLBodyElement)
get_scrollAmount (IHTMLMarqueeElement)
get_scrollDelay (IHTMLMarqueeElement)
get_scrollHeight (IHTMLTextContainer)
get_scrolling (IHTMLFrameBase)
get_scrollLeft (IHTMLTextContainer)
get_scrollTop (IHTMLTextContainer)
get_scrollWidth (IHTMLTextContainer)
get_search (IHTMLAnchorElement)
get_search (IHTMLAreaElement)
get_search (IHTMLLocation)
get_sectionRowIndex (IHTMLTableRow)
get_security (IHTMLDocument2)
get_selected (IHTMLOptionElement)
get_selectedIndex (IHTMLSelectElement)
get_selection (IHTMLDocument2)
get_selectorText (IHTMLStyleSheetRule)
get_self (IHTMLWindow2)
get_shape (IHTMLAreaElement)
get_shiftKey (IHTMLEventObj)
get_Silent (IWebBrowser2)
get_size (IHTMLBaseFontElement)
get_size (IHTMLFontElement)
get_size (IHTMLHRElement)
get_size (IHTMLInputFileElement)
get_size (IHTMLInputTextElement)
get_size (IHTMLSelectElement)
get_sourceIndex (IHTMLElement)
get_span (IHTMLTableCol)
get_src (IHTMLBGsound)
get_src (IHTMLEmbedElement)
get_src (IHTMLFrameBase)
get_src (IHTMLImgElement)
get_src (IHTMLnputImage)
get_src (IHTMLScriptElement)
get_srcElement (IHTMLEventObj)
get_srcFilter (IHTMLEventObj)
get_start (IHTMLImgElement)
get_start (IHTMLInputImage)
get_start (IHTMLOListElement)
get_status (IHTMLButtonElement)
get_status (IHTMLInputButtonElement)
get_status (IHTMLInputFileElement)
get_status (IHTMLInputHiddenElement)
get_status (IHTMLInputTextElement)
get_status (IHTMLOptionButtonElement)
get_status (IHTMLTextAreaElement)
get_status (IHTMLWindow2)
get_StatusBar (IWebBrowser2)
get_StatusText (IWebBrowser2)
get_style (IHTMLElement)
get_style (IHTMLStyleSheetRule)
get_styleFloat (IHTMLRuleStyle)
get_styleFloat (IHTMLStyle)
get_styleSheet (IHTMLLinkElement)
get_styleSheet (IHTMLStyleElement)
get_styleSheets (IHTMLDocument2)
get_systemLanguage (IOmNavigator)
get_tabIndex (IHTMLAnchorElement)
get_tabIndex (IHTMLAreaElement)
get_tabIndex (IHTMLControlElement)
get_tagName (IHTMLElement)
get_tagName (IXMLElement)
get_target (IHTMLAnchorElement)
get_target (IHTMLAreaElement)
get_target (IHTMLBaseElement)
get_target (IHTMLFormElement)
get_tBodies (IHTMLTable)
get_text (IHTMLBodyElement)
get_text (IHTMLCommentElement)
get_text (IHTMLOptionElement)
get_text (IHTMLScriptElement)
get_text (IHTMLTitleElement)
get_text (IHTMLTxtRange)
get_text (IXMLElement)
get_textAlign (IHTMLRuleStyle)
get_textAlign (IHTMLStyle)
get_textDecoration (IHTMLRuleStyle)
get_textDecoration (IHTMLStyle)
get_textDecorationBlink (IHTMLRuleStyle)
get_textDecorationBlink (IHTMLStyle)
get_textDecorationLineThrough (IHTMLRuleStyle)
get_textDecorationLineThrough (IHTMLStyle)
get_textDecorationNone (IHTMLRuleStyle)
get_textDecorationNone (IHTMLStyle)
get_textDecorationOverline (IHTMLRuleStyle)
get_textDecorationOverline (IHTMLStyle)
get_textDecorationUnderline (IHTMLRuleStyle)
get_textDecorationUnderline (IHTMLStyle)
get_textIndent (IHTMLRuleStyle)
get_textIndent (IHTMLStyle)
get_textTransform (IHTMLRuleStyle)
get_textTransform (IHTMLStyle)
get_tFoot (IHTMLTable)
get_tHead (IHTMLTable)
get_TheaterMode (IWebBrowser2)
get_title (IHTMLDocument2)
get_title (IHTMLElement)
get_title (IHTMLStyleSheet)
get_toElement (IHTMLEventObj)
get_ToolBar (IWebBrowser2)
get_top (IHTMLRuleStyle)
get_top (IHTMLStyle)
get_top (IHTMLWindow2)
get_Top (IWebBrowser2)
get_TopLevelContainer (IWebBrowser2)
get_topMargin (IHTMLBodyElement)
get_trueSpeed (IHTMLMarqueeElement)
get_type (IHTMLButtonElement)
get_type (IHTMLEventObj)
get_type (IHTMLInputButtonElement)
get_type (IHTMLInputFileElement)
get_type (IHTMLInputHiddenElement)
get_type (IHTMLInputImage)
get_type (IHTMLInputTextElement)
get_type (IHTMLLIElement)
get_type (IHTMLLinkElement)
get_type (IHTMLObjectElement)
get_type (IHTMLOListElement)
get_type (IHTMLOptionButtonElement)
get_type (IHTMLScriptElement)
get_type (IHTMLSelectElement)
get_type (IHTMLSelectionObject)
get_type (IHTMLStyleElement)
get_type (IHTMLStyleSheet)
get_type (IHTMLTextAreaElement)
get_type (IHTMLUListElement)
get_Type (IWebBrowser2)
get_type (IXMLElement)
get_units (IHTMLEmbedElement)
get_unsecuredWindowOfDocument (IHTMLOptionsHolder)
get_updateInterval (IHTMLScreen)
get_URL (IHTMLDocument2)
get_url (IHTMLMetaElement)
get_URL (IXMLDocument)
get_urn (IHTMLAnchorElement)
get_useMap (IHTMLImgElement)
get_userAgent (IOmNavigator)
get_userLanguage (IOmNavigator)
get_userProfile (IOmNavigator)
get_vAlign (IHTMLTableCaption)
get_vAlign (IHTMLTableCell)
get_vAlign (IHTMLTableCol)
get_vAlign (IHTMLTableRow)
get_vAlign (IHTMLTableSection)
get_value (IHTMLButtonElement)
get_value (IHTMLInputButtonElement)
get_value (IHTMLInputFileElement)
get_value (IHTMLInputHiddenElement)
get_value (IHTMLInputTextElement)
get_value (IHTMLLIElement)
get_value (IHTMLOptionButtonElement)
get_value (IHTMLOptionElement)
get_value (IHTMLSelectElement)
get_value (IHTMLTextAreaElement)
get_version (IXMLDocument)
get_verticalAlign (IHTMLRuleStyle)
get_verticalAlign (IHTMLStyle)
get_visibility (IHTMLRuleStyle)
get_visibility (IHTMLStyle)
get_Visible (IWebBrowser2)
get_vLink (IHTMLBodyElement)
get_vlinkColor (IHTMLDocument2)
get_volume (IHTMLBGsound)
get_vrml (IHTMLImgElement)
get_vrml (IHTMLInputImage)
get_vspace (IHTMLIFrameElement)
get_vspace (IHTMLImgElement)
get_vspace (IHTMLInputImage)
get_vspace (IHTMLMarqueeElement)
get_vspace (IHTMLObjectElement)
get_whiteSpace (IHTMLRuleStyle)
get_whiteSpace (IHTMLStyle)
get_width (IHTMLEmbedElement)
get_width (IHTMLHRElement)
get_width (IHTMLImgElement)
get_width (IHTMLInputImage)
get_width (IHTMLMarqueeElement)
get_width (IHTMLObjectElement)
get_width (IHTMLRuleStyle)
get_width (IHTMLScreen)
get_width (IHTMLStyle)
get_width (IHTMLTable)
get_width (IHTMLTableCell)
get_width (IHTMLTableCol)
get_Width (IWebBrowser2)
get_window (IHTMLWindow2)
get_wordSpacing (IHTMLRuleStyle)
get_wordSpacing (IHTMLStyle)
get_wrap (IHTMLTextAreaElement)
get_x (IHTMLEventObj)
get_y (IHTMLEventObj)
get_zIndex (IHTMLRuleStyle)
get_zIndex (IHTMLStyle)
GetAccountInformation (IScheduledWorkItem)
GetAdditionalParams
GetAdditionalParams (IHlink)
GetApplicationName (ITask)
GetArguments (IShellLink)
getAttribute (Methods: 1)
getAttribute (Methods: 2)
getAttribute (IHTMLElement)
getAttribute (IHTMLOpsProfile)
getAttribute (IHTMLRuleStyle)
getAttribute (IHTMLStyle)
GetAttributesOf (IShellFolder)
GetBandInfo (IDeskBand)
GetBindInfo (IBindStatusCallback)
GetBindInfo (IInternetBindInfo)
GetBindResult (IBinding)
GetBindString (IInternetBindInfo)
getBookmark
getBookmark (IHTMLTxtRange)

* More entries...


Index

IHTMLDocument2::put_onrowenter
IHTMLDocument2::put_onrowexit
IHTMLDocument2::put_onselectstart
IHTMLDocument2::put_title
IHTMLDocument2::put_URL
IHTMLDocument2::put_vlinkColor
IHTMLDocument2::queryCommandEnabled
IHTMLDocument2::queryCommandIndeterm
IHTMLDocument2::queryCommandState
IHTMLDocument2::queryCommandSupported
IHTMLDocument2::queryCommandText
IHTMLDocument2::queryCommandValue
IHTMLDocument2::toString
IHTMLDocument2::write
IHTMLDocument2::writeln
IHTMLDTElement::get_noWrap
IHTMLDTElement::put_noWrap
IHTMLElement::click
IHTMLElement::contains
IHTMLElement::get_all
IHTMLElement::get_children
IHTMLElement::get_className
IHTMLElement::get_document
IHTMLElement::get_filters
IHTMLElement::get_id
IHTMLElement::get_innerHTML
IHTMLElement::get_innerText
IHTMLElement::get_isTextEdit
IHTMLElement::get_lang
IHTMLElement::get_language
IHTMLElement::get_offsetHeight
IHTMLElement::get_offsetLeft
IHTMLElement::get_offsetParent
IHTMLElement::get_offsetTop
IHTMLElement::get_offsetWidth
IHTMLElement::get_onafterupdate
IHTMLElement::get_onbeforeupdate
IHTMLElement::get_onclick
IHTMLElement::get_ondataavailable
IHTMLElement::get_ondatasetchanged
IHTMLElement::get_ondatasetcomplete
IHTMLElement::get_ondblclick
IHTMLElement::get_ondragstart
IHTMLElement::get_onerrorupdate
IHTMLElement::get_onfilterchange
IHTMLElement::get_onhelp
IHTMLElement::get_onkeydown
IHTMLElement::get_onkeypress
IHTMLElement::get_onkeyup
IHTMLElement::get_onmousedown
IHTMLElement::get_onmousemove
IHTMLElement::get_onmouseout
IHTMLElement::get_onmouseover
IHTMLElement::get_onmouseup
IHTMLElement::get_onrowenter
IHTMLElement::get_onrowexit
IHTMLElement::get_onselectstart
IHTMLElement::get_outerHTML
IHTMLElement::get_outerText
IHTMLElement::get_parentElement
IHTMLElement::get_parentTextEdit
IHTMLElement::get_recordNumber
IHTMLElement::get_sourceIndex
IHTMLElement::get_style
IHTMLElement::get_tagName
IHTMLElement::get_title
IHTMLElement::getAttribute
IHTMLElement::insertAdjacentHTML
IHTMLElement::insertAdjacentText
IHTMLElement::put_className
IHTMLElement::put_id
IHTMLElement::put_innerHTML
IHTMLElement::put_innerText
IHTMLElement::put_lang
IHTMLElement::put_language
IHTMLElement::put_onafterupdate
IHTMLElement::put_onbeforeupdate
IHTMLElement::put_onclick
IHTMLElement::put_ondataavailable
IHTMLElement::put_ondatasetchanged
IHTMLElement::put_ondatasetcomplete
IHTMLElement::put_ondblclick
IHTMLElement::put_ondragstart
IHTMLElement::put_onerrorupdate
IHTMLElement::put_onfilterchange
IHTMLElement::put_onhelp
IHTMLElement::put_onkeydown
IHTMLElement::put_onkeypress
IHTMLElement::put_onkeyup
IHTMLElement::put_onmousedown
IHTMLElement::put_onmousemove
IHTMLElement::put_onmouseout
IHTMLElement::put_onmouseover
IHTMLElement::put_onmouseup
IHTMLElement::put_onrowenter
IHTMLElement::put_onrowexit
IHTMLElement::put_onselectstart
IHTMLElement::put_outerHTML
IHTMLElement::put_outerText
IHTMLElement::put_title
IHTMLElement::removeAttribute
IHTMLElement::scrollIntoView
IHTMLElement::setAttribute
IHTMLElement::toString
IHTMLElementCollection::get__newEnum
IHTMLElementCollection::get_length
IHTMLElementCollection::item
IHTMLElementCollection::put_length
IHTMLElementCollection::tags
IHTMLElementCollection::toString
IHTMLEmbedElement::get_height
IHTMLEmbedElement::get_hidden
IHTMLEmbedElement::get_name
IHTMLEmbedElement::get_palette
IHTMLEmbedElement::get_pluginspage
IHTMLEmbedElement::get_src
IHTMLEmbedElement::get_units
IHTMLEmbedElement::get_width
IHTMLEmbedElement::put_height
IHTMLEmbedElement::put_hidden
IHTMLEmbedElement::put_name
IHTMLEmbedElement::put_src
IHTMLEmbedElement::put_units
IHTMLEmbedElement::put_width
IHTMLEventObj::get_altKey
IHTMLEventObj::get_button
IHTMLEventObj::get_cancelBubble
IHTMLEventObj::get_clientX
IHTMLEventObj::get_clientY
IHTMLEventObj::get_ctrlKey
IHTMLEventObj::get_fromElement
IHTMLEventObj::get_keyCode
IHTMLEventObj::get_offsetX
IHTMLEventObj::get_offsetY
IHTMLEventObj::get_qualifier
IHTMLEventObj::get_reason
IHTMLEventObj::get_returnValue
IHTMLEventObj::get_screenX
IHTMLEventObj::get_screenY
IHTMLEventObj::get_shiftKey
IHTMLEventObj::get_srcElement
IHTMLEventObj::get_srcFilter
IHTMLEventObj::get_toElement
IHTMLEventObj::get_type
IHTMLEventObj::get_x
IHTMLEventObj::get_y
IHTMLEventObj::put_cancelBubble
IHTMLEventObj::put_keyCode
IHTMLEventObj::put_returnValue
IHTMLFieldSetElement::get_align
IHTMLFieldSetElement::put_align
IHTMLFiltersCollection::get__newEnum
IHTMLFiltersCollection::get_length
IHTMLFiltersCollection::item
IHTMLFontElement::get_color
IHTMLFontElement::get_face
IHTMLFontElement::get_size
IHTMLFontElement::put_color
IHTMLFontElement::put_face
IHTMLFontElement::put_size
IHTMLFontNamesCollection::get__newEnum
IHTMLFontNamesCollection::get_length
IHTMLFontNamesCollection::item
IHTMLFontSizesCollection::get__newEnum
IHTMLFontSizesCollection::get_forFont
IHTMLFontSizesCollection::get_length
IHTMLFontSizesCollection::item
IHTMLFormElement::get__newEnum
IHTMLFormElement::get_action
IHTMLFormElement::get_dir
IHTMLFormElement::get_elements
IHTMLFormElement::get_encoding
IHTMLFormElement::get_length
IHTMLFormElement::get_method
IHTMLFormElement::get_name
IHTMLFormElement::get_onreset
IHTMLFormElement::get_onsubmit
IHTMLFormElement::get_target
IHTMLFormElement::item
IHTMLFormElement::put_action
IHTMLFormElement::put_dir
IHTMLFormElement::put_encoding
IHTMLFormElement::put_length
IHTMLFormElement::put_method
IHTMLFormElement::put_name
IHTMLFormElement::put_onreset
IHTMLFormElement::put_onsubmit
IHTMLFormElement::put_target
IHTMLFormElement::reset
IHTMLFormElement::submit
IHTMLFormElement::tags
IHTMLFrameBase::get_border
IHTMLFrameBase::get_frameBorder
IHTMLFrameBase::get_frameSpacing
IHTMLFrameBase::get_marginHeight
IHTMLFrameBase::get_marginWidth
IHTMLFrameBase::get_name
IHTMLFrameBase::get_noResize
IHTMLFrameBase::get_scrolling
IHTMLFrameBase::get_src
IHTMLFrameBase::put_border
IHTMLFrameBase::put_frameBorder
IHTMLFrameBase::put_frameSpacing
IHTMLFrameBase::put_marginHeight
IHTMLFrameBase::put_marginWidth
IHTMLFrameBase::put_name
IHTMLFrameBase::put_noResize
IHTMLFrameBase::put_scrolling
IHTMLFrameBase::put_src
IHTMLFrameElement::get_borderColor
IHTMLFrameElement::put_borderColor
IHTMLFramesCollection2::get_length
IHTMLFramesCollection2::item
IHTMLFrameSetElement::get_border
IHTMLFrameSetElement::get_borderColor
IHTMLFrameSetElement::get_cols
IHTMLFrameSetElement::get_frameBorder
IHTMLFrameSetElement::get_frameSpacing
IHTMLFrameSetElement::get_name
IHTMLFrameSetElement::get_onbeforeunload
IHTMLFrameSetElement::get_onunload
IHTMLFrameSetElement::get_rows
IHTMLFrameSetElement::put_border
IHTMLFrameSetElement::put_borderColor
IHTMLFrameSetElement::put_cols
IHTMLFrameSetElement::put_frameBorder

* More entries...


Index

put_onload (IHTMLImgElement)
put_onload (IHTMLInputImage)
put_onload (IHTMLLinkElement)
put_onload (IHTMLStyleElement)
put_onload (IHTMLWindow2)
put_onmousedown (IHTMLDocument2)
put_onmousedown (IHTMLElement)
put_onmousemove (IHTMLDocument2)
put_onmousemove (IHTMLElement)
put_onmouseout (IHTMLDocument2)
put_onmouseout (IHTMLElement)
put_onmouseover (IHTMLDocument2)
put_onmouseover (IHTMLElement)
put_onmouseup (IHTMLDocument2)
put_onmouseup (IHTMLElement)
put_onreadystatechange (IHTMLDocument2)
put_onreadystatechange (IHTMLLinkElement)
put_onreadystatechange (IHTMLObjectElement)
put_onreadystatechange (IHTMLStyleElement)
put_onreadystatechange (IHTMLTable)
put_onreset (IHTMLFormElement)
put_onresize (IHTMLControlElement)
put_onresize (IHTMLWindow2)
put_onrowenter (IHTMLDocument2)
put_onrowenter (IHTMLElement)
put_onrowexit (IHTMLDocument2)
put_onrowexit (IHTMLElement)
put_onscroll (IHTMLTextContainer)
put_onscroll (IHTMLWindow2)
put_onselect (IHTMLBodyElement)
put_onselect (IHTMLInputFileElement)
put_onselect (IHTMLInputTextElement)
put_onselect (IHTMLTextAreaElement)
put_onselectstart (IHTMLDocument2)
put_onselectstart (IHTMLElement)
put_onstart (IHTMLMarqueeElement)
put_onsubmit (IHTMLFormElement)
put_onunload (IHTMLBodyElement)
put_onunload (IHTMLFrameSetElement)
put_onunload (IHTMLWindow2)
put_opener (IHTMLWindow2)
put_outerHTML (IHTMLElement)
put_outerText (IHTMLElement)
put_overflow (IHTMLRuleStyle)
put_overflow (IHTMLStyle)
put_padding (IHTMLRuleStyle)
put_padding (IHTMLStyle)
put_paddingBottom (IHTMLRuleStyle)
put_paddingBottom (IHTMLStyle)
put_paddingLeft (IHTMLRuleStyle)
put_paddingLeft (IHTMLStyle)
put_paddingRight (IHTMLRuleStyle)
put_paddingRight (IHTMLStyle)
put_paddingTop (IHTMLRuleStyle)
put_paddingTop (IHTMLStyle)
put_pageBreakAfter (IHTMLRuleStyle)
put_pageBreakAfter (IHTMLStyle)
put_pageBreakBefore (IHTMLRuleStyle)
put_pageBreakBefore (IHTMLStyle)
put_pathname (IHTMLAnchorElement)
put_pathname (IHTMLAreaElement)
put_pathname (IHTMLLocation)
put_pixelHeight (IHTMLStyle)
put_pixelLeft (IHTMLStyle)
put_pixelTop (IHTMLStyle)
put_pixelWidth (IHTMLStyle)
put_port (IHTMLAnchorElement)
put_port (IHTMLAreaElement)
put_port (IHTMLLocation)
put_posHeight (IHTMLStyle)
put_posLeft (IHTMLStyle)
put_posTop (IHTMLStyle)
put_posWidth (IHTMLStyle)
put_productVersion (IHTMLOptionsHolder)
put_prompt (IHTMLIsIndexElement)
put_protocol (IHTMLAnchorElement)
put_protocol (IHTMLAreaElement)
put_protocol (IHTMLLocation)
put_readOnly (IHTMLInputTextElement)
put_readOnly (IHTMLTextAreaElement)
put_rel (IHTMLAnchorElement)
put_rel (IHTMLLinkElement)
put_returnValue (IHTMLDialog)
put_returnValue (IHTMLEventObj)
put_rev (IHTMLAnchorElement)
put_rev (IHTMLLinkElement)
put_rightMargin (IHTMLBodyElement)
put_rows (IHTMLFrameSetElement)
put_rows (IHTMLTextAreaElement)
put_rowSpan (IHTMLTableCell)
put_rules (IHTMLTable)
put_scroll (IHTMLBodyElement)
put_scrollAmount (IHTMLMarqueeElement)
put_scrollDelay (IHTMLMarqueeElement)
put_scrolling (IHTMLFrameBase)
put_scrollLeft (IHTMLTextContainer)
put_scrollTop (IHTMLTextContainer)
put_search (IHTMLAnchorElement)
put_search (IHTMLAreaElement)
put_search (IHTMLLocation)
put_selected (IHTMLOptionElement)
put_selectedIndex (IHTMLSelectElement)
put_selectorText (IHTMLStyleSheetRule)
put_shape (IHTMLAreaElement)
put_size (IHTMLBaseFontElement)
put_size (IHTMLFontElement)
put_size (IHTMLHRElement)
put_size (IHTMLInputFileElement)
put_size (IHTMLInputTextElement)
put_size (IHTMLSelectElement)
put_span (IHTMLTableCol)
put_src (IHTMLBGsound)
put_src (IHTMLEmbedElement)
put_src (IHTMLFrameBase)
put_src (IHTMLImgElement)
put_src (IHTMLInputImage)
put_src (IHTMLScriptElement)
put_start (IHTMLImgElement)
put_start (IHTMLInputImage)
put_start (IHTMLOListElement)
put_status (IHTMLButtonElement)
put_status (IHTMLInputButtonElement)
put_status (IHTMLInputFileElement)
put_status (IHTMLInputHiddenElement)
put_status (IHTMLInputTextElement)
put_status (IHTMLOptionButtonElement)
put_status (IHTMLTextAreaElement)
put_status (IHTMLWindow2)
put_styleFloat (IHTMLRuleStyle)
put_styleFloat (IHTMLStyle)
put_tabIndex (IHTMLAnchorElement)
put_tabIndex (IHTMLAreaElement)
put_tabIndex (IHTMLControlElement)
put_target (IHTMLAnchorElement)
put_target (IHTMLAreaElement)
put_target (IHTMLBaseElement)
put_target (IHTMLFormElement)
put_text (IHTMLBodyElement)
put_text (IHTMLCommentElement)
put_text (IHTMLOptionElement)
put_text (IHTMLScriptElement)
put_text (IHTMLTitleElement)
put_text (IHTMLTxtRange)
put_textAlign (IHTMLRuleStyle)
put_textAlign (IHTMLStyle)
put_textDecoration (IHTMLRuleStyle)
put_textDecoration (IHTMLStyle)
put_textDecorationBlink (IHTMLRuleStyle)
put_textDecorationBlink (IHTMLStyle)
put_textDecorationLineThrough (IHTMLRuleStyle)
put_textDecorationLineThrough (IHTMLStyle)
put_textDecorationNone (IHTMLRuleStyle)
put_textDecorationNone (IHTMLStyle)
put_textDecorationOverline (IHTMLRuleStyle)
put_textDecorationOverline (IHTMLStyle)
put_textDecorationUnderline (IHTMLRuleStyle)
put_textDecorationUnderline (IHTMLStyle)
put_textIndent (IHTMLRuleStyle)
put_textIndent (IHTMLStyle)
put_textTransform (IHTMLRuleStyle)
put_textTransform (IHTMLStyle)
put_title (IHTMLDocument2)
put_title (IHTMLElement)
put_title (IHTMLStyleSheet)
put_top (IHTMLRuleStyle)
put_top (IHTMLStyle)
put_topMargin (IHTMLBodyElement)
put_trueSpeed (IHTMLMarqueeElement)
put_type (IHTMLLIElement)
put_type (IHTMLLinkElement)
put_type (IHTMLObjectElement)
put_type (IHTMLOListElement)
put_type (IHTMLScriptElement)
put_type (IHTMLStyleElement)
put_type (IHTMLUListElement)
put_units (IHTMLEmbedElement)
put_updateInterval (IHTMLScreen)
put_URL (IHTMLDocument2)
put_url (IHTMLMetaElement)
put_urn (IHTMLAnchorElement)
put_useMap (IHTMLImgElement)
put_vAlign (IHTMLTableCaption)
put_vAlign (IHTMLTableCell)
put_vAlign (IHTMLTableCol)
put_vAlign (IHTMLTableRow)
put_vAlign (IHTMLTableSection)
put_value (IHTMLButtonElement)
put_value (IHTMLInputButtonElement)
put_value (IHTMLInputFileElement)
put_value (IHTMLInputHiddenElement)
put_value (IHTMLInputTextElement)
put_value (IHTMLLIElement)
put_value (IHTMLOptionButtonElement)
put_value (IHTMLOptionElement)
put_value (IHTMLSelectElement)
put_value (IHTMLTextAreaElement)
put_verticalAlign (IHTMLRuleStyle)
put_verticalAlign (IHTMLStyle)
put_visibility (IHTMLRuleStyle)
put_visibility (IHTMLStyle)
put_vLink (IHTMLBodyElement)
put_vlinkColor (IHTMLDocument2)
put_volume (IHTMLBGsound)
put_vrml (IHTMLImgElement)
put_vrml (IHTMLInputImage)
put_vspace (IHTMLIFrameElement)
put_vspace (IHTMLImgElement)
put_vspace (IHTMLInputImage)
put_vspace (IHTMLMarqueeElement)
put_vspace (IHTMLObjectElement)

* More entries...


Index

GetBorderDW (IDockingWindowSite)
GetBrowseContext
GetBrowseContext (IHlinkFrame)
GetBrowseContext (IHlinkTarget)
GetBrowseWindowInfo
GetBrowseWindowInfo (IHlinkBrowseContext)
GetCache (IInternetSession)
GetChunk Method (ADO)
GetClassFile
GetClassURL
GetCollapseState (IABTable)
GetCommandString (IContextMenu)
GetCommandString (IContextMenu2)
GetComment (IScheduledWorkItem)
GetContentsTable (IABContainer)
GetContentsTable (IDistList)
GetControlWindow (IShellBrowser)
GetCreator (IScheduledWorkItem)
GetCurMoniker (IPersistMoniker)
GetCurrentDirectory
GetCurrentInfo (IShellView)
GetCurrentScriptThreadID (IActiveScript)
GetCursorPos
GetDCEx
GetDefaultDir (IAddrBook)
GetDefaultInfo (ISubscriptionMgr)
GetDescription (IShellLink)
GetDesktopItem (IActiveDesktop)
GetDesktopItemByID (IActiveDesktop)
GetDesktopItemBySource (IActiveDesktop)
GetDesktopItemCount (IActiveDesktop)
GetDesktopItemOptions (IActiveDesktop)
GetDetailsOf Method
GetDispID
GetDispID (IDispatchEx)
GetDisplayNameOf (IShellFolder)
GetDocMiscStatus (IOleDocument)
GetDocument (IOleDocumentView)
GetDocVersionString (IActiveScriptSite)
GetDropTarget (IDocHostUIHandler)
GetEffectiveClientRect
GetElement (ICSSFilterSite)
GetError
GetErrorRetryCount (IScheduledWorkItem)
GetErrorRetryInterval (IScheduledWorkItem)
GetExceptionInfo (IActiveScriptError)
GetExitCode (IScheduledWorkItem)
GetExtension (INewShortcutHook)
GetExternal (IDocHostUIHandler)
GetFileAttributes
GetFlags (IScheduledWorkItem)
GetFolder (INewShortcutHook)
GetFolder Property
GetFriendlyName (IHlink)
GetFriendlyName (IHlinkTarget)
GetHierarchyTable (IABContainer)
GetHierarchyTable (IDistList)
GetHlink
GetHlink (IHlinkBrowseContext)
GetHlinkSite
GetHlinkSite (IHlink)
GetHostInfo (IDocHostUIHandler)
GetHotkey (IShellLink)
GetIconLocation (IExtractIcon)
GetIconLocation (IShellLink)
GetIconOf (IShellIcon)
GetIdleWait (IScheduledWorkItem)
GetIDList (IShellLink)
GetIDsFromNames (IABContainer)
GetIDsFromNames (IAddrBook)
GetIDsFromNames (IDistList)
GetIDsFromNames (IMailUser)
GetInfoFlags (IQueryInfo)
GetInfoOfIndex (IProvideMultipleClassInfo)
GetInfoTip (IQueryInfo)
GetInPlaceSite (IOleDocumentView)
GetInterfaceSafetyOptions
GetInterfaceSafetyOptions (IObjectSafety)
GetItemInfo (IActiveScriptSite)
GetItemObject (IShellView)
GetLastError
GetLastError (IABContainer)
GetLastError (IABTable)
GetLastError (IAddrBook)
GetLastError (IDistList)
GetLastError (IMailUser)
GetLastError (IWABObject)
GetLCID (IActiveScriptSite)
GetLink Property
GetMaxRunTime (ITask)
GetMe (IWABObject)
GetMemberName
GetMemberName (IDispatchEx)
GetMemberProperties
GetMemberProperties (IDispatchEx)
GetMenuContextHelpId
GetMiscStatus
GetMiscStatus (IHlink)
GetModuleHandle
GetMoniker (IHlinkSite)
GetMoniker (IHlinkTarget)
GetMonikerReference
GetMonikerReference (IHlink)
GetMostRecentRunTime (IScheduledWorkItem)
GetMultiTypeInfoCount (IProvideMultipleClassInfo)
GetName (INewShortcutHook)
GetNamesFromIDs (IABContainer)
GetNamesFromIDs (IAddrBook)
GetNamesFromIDs (IDistList)
GetNamesFromIDs (IMailUser)
GetNameSpaceParent
GetNameSpaceParent (IDispatchEx)
GetNextDispID
GetNextDispID (IDispatchEx)
GetNextRunTime (IScheduledWorkItem)
GetObject
GetObject (IHlinkBrowseContext)
GetOptionKeyPath (IDocHostUIHandler)
GetPAB (IAddrBook)
GetPage (IProvideTaskPage)
GetPageInfo (IPrint)
GetParam
GetParameters (ITask)
GetParent
GetParticipantRealName
GetParticipantRealName Method
GetPath (IShellLink)
GetPattern (IActiveDesktop)
GetPinnedWindow (IFileViewerSite)
GetPositionCookie (IPersistHistory)
GetPriority (IBinding)
GetPriority (IBindStatusCallback)
GetPriority (ITask)
GetProcAddress
GetProgressFeedbackMaxEstimate (IReconcilableObject)
GetProperty
GetProperty (IWebBrowser2)
GetProperty Method
GetPropertyInfo (IPropertyBag2)
GetPropList (IABContainer)
GetPropList (IAddrBook)
GetPropList (IDistList)
GetPropList (IMailUser)
GetProps (IABContainer)
GetProps (IAddrBook)
GetProps (IDistList)
GetProps (IMailUser)
GetRect (IOleDocumentView)
GetReferent (INewShortcutHook)
GetRowCount (IABTable)
GetRows Method (ADO)
GetRows Method Example (ADO)
GetRunTimes (IScheduledWorkItem)
GetScriptDispatch (IActiveScript)
GetScriptSite (IActiveScript)
GetScriptState (IActiveScript)
GetScriptThreadID (IActiveScript)
GetScriptThreadState (IActiveScript)
GetScrollInfo
GetScrollPos
GetScrollRange
GetSearchCriteria (IABContainer)
GetSearchCriteria (IDistList)
GetSearchPath (IAddrBook)
GetSecurityId (IInternetHostSecurityManager)
GetSecurityId (IInternetSecurityManager)
GetSecuritySite (IInternetSecurityManager)
GetSessionOption (IInternetSession)
GetShowCmd (IShellLink)
GetSite (IObjectWithSite)
GetSiteInfo
GetSourceLineText (IActiveScriptError)
GetSourcePosition (IActiveScriptError)
GetStatus (IABTable)
GetStatus (IScheduledWorkItem)
GetStringReference
GetStringReference (IHlink)
GetSubMenu
GetSubscriptionInfo (ISubscriptionMgr)
GetSysColor
GetSystemMetrics
GetTargetComputer (ITaskScheduler)
GetTargetFrameName
GetTargetFrameName (IHlink)
GetTaskFlags (ITask)
GetThreadPriority
Getting a Recordset to the Client
Getting Assistance While You Work (Remote Data Service)
Getting Started with Remote Data Service
GetTrigger (IScheduledWorkItem)
GetTrigger (ITaskTrigger)
GetTriggerCount (IScheduledWorkItem)
GetTriggerString (IScheduledWorkItem)
GetTriggerString (ITaskTrigger)
GetUIObjectOf (IShellFolder)
GetURL (IUniformResourceLocator)
GetUrlCacheEntryInfo
GetUrlCacheEntryInfoEx
GetViewStateStream (IShellBrowser)
GetWallpaper (IActiveDesktop)
GetWallpaperOptions (IActiveDesktop)
GetWindow (IActiveScriptSiteWindow)
GetWindow (IInternetSecurityMgrSite)
GetWindow (IWindowForBindingUI)
GetWindowContextHelpId
GetWindowLong
GetWorkingDirectory (IShellLink)
GetWorkingDirectory (ITask)
GetWorkItemData (IScheduledWorkItem)
GetZoneActionPolicy (IInternetZoneManager)
GetZoneAt (IInternetZoneManager)
GetZoneAttributes (IInternetZoneManager)
GetZoneCustomPolicy (IInternetZoneManager)
GetZoneMappings (IInternetSecurityManager)
GlobalAlloc
Glossary
Glow Filter Effect
go
go (IOmHistory)
GoBack
GoBack (IWebBrowser2)
GoBack Method
GoForward
GoForward (IWebBrowser2)
GoForward Method
GoHome
GoHome (IWebBrowser2)
GoHome Method
GOPHER_ATTRIBUTE_TYPE
GOPHER_FIND_DATA
GopherAttributeEnumerator
GopherCreateLocator
GopherFindFirstFile
GopherGetAttribute

* More entries...


Index

IHTMLFrameSetElement::put_frameSpacing
IHTMLFrameSetElement::put_name
IHTMLFrameSetElement::put_onbeforeunload
IHTMLFrameSetElement::put_onload
IHTMLFrameSetElement::put_onunload
IHTMLFrameSetElement::put_rows
IHTMLHeaderElement::get_align
IHTMLHeaderElement::put_align
IHTMLHRElement::get_align
IHTMLHRElement::get_color
IHTMLHRElement::get_noShade
IHTMLHRElement::get_size
IHTMLHRElement::get_width
IHTMLHRElement::put_align
IHTMLHRElement::put_color
IHTMLHRElement::put_noShade
IHTMLHRElement::put_size
IHTMLHRElement::put_width
IHTMLIFrameElement::get_align
IHTMLIFrameElement::get_hspace
IHTMLIFrameElement::get_vspace
IHTMLIFrameElement::put_align
IHTMLIFrameElement::put_hspace
IHTMLIFrameElement::put_vspace
IHTMLImageElementFactory::create
IHTMLImgElement::get_align
IHTMLImgElement::get_alt
IHTMLImgElement::get_border
IHTMLImgElement::get_complete
IHTMLImgElement::get_dynsrc
IHTMLImgElement::get_fileCreatedDate
IHTMLImgElement::get_fileModifiedDate
IHTMLImgElement::get_fileSize
IHTMLImgElement::get_fileUpdatedDate
IHTMLImgElement::get_height
IHTMLImgElement::get_href
IHTMLImgElement::get_hspace
IHTMLImgElement::get_isMap
IHTMLImgElement::get_loop
IHTMLImgElement::get_lowsrc
IHTMLImgElement::get_mimeType
IHTMLImgElement::get_name
IHTMLImgElement::get_nameProp
IHTMLImgElement::get_onabort
IHTMLImgElement::get_onerror
IHTMLImgElement::get_onload
IHTMLImgElement::get_protocol
IHTMLImgElement::get_readyState
IHTMLImgElement::get_src
IHTMLImgElement::get_start
IHTMLImgElement::get_useMap
IHTMLImgElement::get_vrml
IHTMLImgElement::get_vspace
IHTMLImgElement::get_width
IHTMLImgElement::put_align
IHTMLImgElement::put_alt
IHTMLImgElement::put_border
IHTMLImgElement::put_dynsrc
IHTMLImgElement::put_height
IHTMLImgElement::put_hspace
IHTMLImgElement::put_isMap
IHTMLImgElement::put_loop
IHTMLImgElement::put_lowsrc
IHTMLImgElement::put_name
IHTMLImgElement::put_onabort
IHTMLImgElement::put_onerror
IHTMLImgElement::put_onload
IHTMLImgElement::put_src
IHTMLImgElement::put_start
IHTMLImgElement::put_useMap
IHTMLImgElement::put_vrml
IHTMLImgElement::put_vspace
IHTMLImgElement::put_width
IHTMLInputButtonElement::get_disabled
IHTMLInputButtonElement::get_form
IHTMLInputButtonElement::get_name
IHTMLInputButtonElement::get_status
IHTMLInputButtonElement::get_type
IHTMLInputButtonElement::get_value
IHTMLInputButtonElement::put_disabled
IHTMLInputButtonElement::put_name
IHTMLInputButtonElement::put_status
IHTMLInputButtonElement::put_value
IHTMLInputFileElement::get_disabled
IHTMLInputFileElement::get_form
IHTMLInputFileElement::get_maxLength
IHTMLInputFileElement::get_name
IHTMLInputFileElement::get_onchange
IHTMLInputFileElement::get_onselect
IHTMLInputFileElement::get_size
IHTMLInputFileElement::get_status
IHTMLInputFileElement::get_type
IHTMLInputFileElement::get_value
IHTMLInputFileElement::put_disabled
IHTMLInputFileElement::put_maxLength
IHTMLInputFileElement::put_name
IHTMLInputFileElement::put_onchange
IHTMLInputFileElement::put_onselect
IHTMLInputFileElement::put_size
IHTMLInputFileElement::put_status
IHTMLInputFileElement::put_value
IHTMLInputFileElement::select
IHTMLInputHiddenElement::createTextRange
IHTMLInputHiddenElement::get_disabled
IHTMLInputHiddenElement::get_form
IHTMLInputHiddenElement::get_name
IHTMLInputHiddenElement::get_status
IHTMLInputHiddenElement::get_type
IHTMLInputHiddenElement::get_value
IHTMLInputHiddenElement::put_disabled
IHTMLInputHiddenElement::put_name
IHTMLInputHiddenElement::put_status
IHTMLInputHiddenElement::put_value
IHTMLInputImage::get_align
IHTMLInputImage::get_alt
IHTMLInputImage::get_border
IHTMLInputImage::get_complete
IHTMLInputImage::get_disabled
IHTMLInputImage::get_dynsrc
IHTMLInputImage::get_height
IHTMLInputImage::get_hspace
IHTMLInputImage::get_loop
IHTMLInputImage::get_lowsrc
IHTMLInputImage::get_name
IHTMLInputImage::get_onabort
IHTMLInputImage::get_onerror
IHTMLInputImage::get_onload
IHTMLInputImage::get_readyState
IHTMLInputImage::get_start
IHTMLInputImage::get_type
IHTMLInputImage::get_vrml
IHTMLInputImage::get_vspace
IHTMLInputImage::get_width
IHTMLInputImage::put_align
IHTMLInputImage::put_alt
IHTMLInputImage::put_border
IHTMLInputImage::put_disabled
IHTMLInputImage::put_dynsrc
IHTMLInputImage::put_height
IHTMLInputImage::put_hspace
IHTMLInputImage::put_loop
IHTMLInputImage::put_lowsrc
IHTMLInputImage::put_name
IHTMLInputImage::put_onabort
IHTMLInputImage::put_onerror
IHTMLInputImage::put_onload
IHTMLInputImage::put_src
IHTMLInputImage::put_start
IHTMLInputImage::put_vrml
IHTMLInputImage::put_vspace
IHTMLInputImage::put_width
IHTMLInputTextElement::createTextRange
IHTMLInputTextElement::get_defaultValue
IHTMLInputTextElement::get_disabled
IHTMLInputTextElement::get_form
IHTMLInputTextElement::get_maxLength
IHTMLInputTextElement::get_name
IHTMLInputTextElement::get_onchange
IHTMLInputTextElement::get_onselect
IHTMLInputTextElement::get_readOnly
IHTMLInputTextElement::get_size
IHTMLInputTextElement::get_status
IHTMLInputTextElement::get_type
IHTMLInputTextElement::get_value
IHTMLInputTextElement::put_defaultValue
IHTMLInputTextElement::put_disabled
IHTMLInputTextElement::put_maxLength
IHTMLInputTextElement::put_name
IHTMLInputTextElement::put_onchange
IHTMLInputTextElement::put_onselect
IHTMLInputTextElement::put_readOnly
IHTMLInputTextElement::put_size
IHTMLInputTextElement::put_status
IHTMLInputTextElement::put_value
IHTMLInputTextElement::select
IHTMLIsIndexElement::get_action
IHTMLIsIndexElement::get_prompt
IHTMLIsIndexElement::put_action
IHTMLIsIndexElement::put_prompt
IHTMLLabelElement::get_accessKey
IHTMLLabelElement::get_htmlFor
IHTMLLabelElement::put_accessKey
IHTMLLabelElement::put_htmlFor
IHTMLLegendElement::get_align
IHTMLLegendElement::put_align
IHTMLLIElement::get_type
IHTMLLIElement::get_value
IHTMLLIElement::put_type
IHTMLLIElement::put_value
IHTMLLinkElement::get_disabled
IHTMLLinkElement::get_href
IHTMLLinkElement::get_media
IHTMLLinkElement::get_onerror
IHTMLLinkElement::get_onload
IHTMLLinkElement::get_onreadystatechange
IHTMLLinkElement::get_readyState
IHTMLLinkElement::get_rel
IHTMLLinkElement::get_rev
IHTMLLinkElement::get_styleSheet
IHTMLLinkElement::get_type
IHTMLLinkElement::put_disabled
IHTMLLinkElement::put_href
IHTMLLinkElement::put_media
IHTMLLinkElement::put_onerror
IHTMLLinkElement::put_onload
IHTMLLinkElement::put_onreadystatechange
IHTMLLinkElement::put_rel
IHTMLLinkElement::put_rev
IHTMLLinkElement::put_type
IHTMLLocation::assign
IHTMLLocation::get_hash
IHTMLLocation::get_host
IHTMLLocation::get_hostname
IHTMLLocation::get_href
IHTMLLocation::get_pathname
IHTMLLocation::get_port
IHTMLLocation::get_protocol
IHTMLLocation::get_search
IHTMLLocation::put_hash
IHTMLLocation::put_host
IHTMLLocation::put_hostname
IHTMLLocation::put_href
IHTMLLocation::put_pathname
IHTMLLocation::put_port
IHTMLLocation::put_protocol

* More entries...


Index

put_whiteSpace (IHTMLRuleStyle)
put_whiteSpace (IHTMLStyle)
put_width (IHTMLEmbedElement)
put_width (IHTMLHRElement)
put_width (IHTMLImgElement)
put_width (IHTMLInputImage)
put_width (IHTMLMarqueeElement)
put_width (IHTMLObjectElement)
put_width (IHTMLRuleStyle)
put_width (IHTMLStyle)
put_width (IHTMLTable)
put_width (IHTMLTableCell)
put_width (IHTMLTableCol)
put_wordSpacing (IHTMLRuleStyle)
put_wordSpacing (IHTMLStyle)
put_wrap (IHTMLTextAreaElement)
put_zIndex (IHTMLRuleStyle)
put_zIndex (IHTMLStyle)
PutProperty
PutProperty (IWebBrowser2)
PutProperty Method


Index

GopherGetLocatorType
GopherOpenFile
GoSearch
GoSearch (IWebBrowser2)
GoSearch Method
Grayscale Filter Effect

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


Index

IHTMLLocation::put_search
IHTMLLocation::reload
IHTMLLocation::replace
IHTMLLocation::toString
IHTMLMapElement::get_areas
IHTMLMapElement::get_name
IHTMLMapElement::put_name
IHTMLMarqueeElement::get_behavior
IHTMLMarqueeElement::get_bgColor
IHTMLMarqueeElement::get_direction
IHTMLMarqueeElement::get_height
IHTMLMarqueeElement::get_hspace
IHTMLMarqueeElement::get_loop
IHTMLMarqueeElement::get_onbounce
IHTMLMarqueeElement::get_onfinish
IHTMLMarqueeElement::get_onstart
IHTMLMarqueeElement::get_scrollAmount
IHTMLMarqueeElement::get_scrollDelay
IHTMLMarqueeElement::get_trueSpeed
IHTMLMarqueeElement::get_vspace
IHTMLMarqueeElement::get_width
IHTMLMarqueeElement::put_behavior
IHTMLMarqueeElement::put_bgColor
IHTMLMarqueeElement::put_direction
IHTMLMarqueeElement::put_height
IHTMLMarqueeElement::put_hspace
IHTMLMarqueeElement::put_loop
IHTMLMarqueeElement::put_onbounce
IHTMLMarqueeElement::put_onfinish
IHTMLMarqueeElement::put_onstart
IHTMLMarqueeElement::put_scrollAmount
IHTMLMarqueeElement::put_scrollDelay
IHTMLMarqueeElement::put_trueSpeed
IHTMLMarqueeElement::put_vspace
IHTMLMarqueeElement::put_width
IHTMLMarqueeElement::start
IHTMLMarqueeElement::stop
IHTMLMetaElement::get_charset
IHTMLMetaElement::get_content
IHTMLMetaElement::get_httpEquiv
IHTMLMetaElement::get_name
IHTMLMetaElement::get_url
IHTMLMetaElement::put_charset
IHTMLMetaElement::put_content
IHTMLMetaElement::put_httpEquiv
IHTMLMetaElement::put_name
IHTMLMetaElement::put_url
IHTMLMimeTypesCollection::get_length
IHTMLNextIdElement::get_n
IHTMLNextIdElement::put_n
IHTMLnputImage::get_src
IHTMLObjectElement::get_align
IHTMLObjectElement::get_altHtml
IHTMLObjectElement::get_BaseHref
IHTMLObjectElement::get_classid
IHTMLObjectElement::get_code
IHTMLObjectElement::get_codeBase
IHTMLObjectElement::get_codeType
IHTMLObjectElement::get_data
IHTMLObjectElement::get_form
IHTMLObjectElement::get_height
IHTMLObjectElement::get_hspace
IHTMLObjectElement::get_name
IHTMLObjectElement::get_object
IHTMLObjectElement::get_onerror
IHTMLObjectElement::get_onreadystatechange
IHTMLObjectElement::get_readyState
IHTMLObjectElement::get_recordset
IHTMLObjectElement::get_type
IHTMLObjectElement::get_vspace
IHTMLObjectElement::get_width
IHTMLObjectElement::put_align
IHTMLObjectElement::put_altHtml
IHTMLObjectElement::put_code
IHTMLObjectElement::put_codeBase
IHTMLObjectElement::put_codeType
IHTMLObjectElement::put_height
IHTMLObjectElement::put_hspace
IHTMLObjectElement::put_name
IHTMLObjectElement::put_onerror
IHTMLObjectElement::put_onreadystatechange
IHTMLObjectElement::put_type
IHTMLObjectElement::put_vspace
IHTMLObjectElement::put_width
IHTMLOListElement::get_compact
IHTMLOListElement::get_start
IHTMLOListElement::get_type
IHTMLOListElement::put_compact
IHTMLOListElement::put_start
IHTMLOListElement::put_type
IHTMLOpsProfile::addReadRequest
IHTMLOpsProfile::clearRequest
IHTMLOpsProfile::doReadRequest
IHTMLOpsProfile::getAttribute
IHTMLOptionButtonElement::get_checked
IHTMLOptionButtonElement::get_defaultChecked
IHTMLOptionButtonElement::get_disabled
IHTMLOptionButtonElement::get_form
IHTMLOptionButtonElement::get_indeterminate
IHTMLOptionButtonElement::get_name
IHTMLOptionButtonElement::get_onchange
IHTMLOptionButtonElement::get_status
IHTMLOptionButtonElement::get_type
IHTMLOptionButtonElement::get_value
IHTMLOptionButtonElement::put_checked
IHTMLOptionButtonElement::put_defaultChecked
IHTMLOptionButtonElement::put_disabled
IHTMLOptionButtonElement::put_indeterminate
IHTMLOptionButtonElement::put_name
IHTMLOptionButtonElement::put_onchange
IHTMLOptionButtonElement::put_status
IHTMLOptionButtonElement::put_value
IHTMLOptionElement::get_defaultSelected
IHTMLOptionElement::get_form
IHTMLOptionElement::get_index
IHTMLOptionElement::get_selected
IHTMLOptionElement::get_text
IHTMLOptionElement::get_value
IHTMLOptionElement::put_defaultSelected
IHTMLOptionElement::put_index
IHTMLOptionElement::put_selected
IHTMLOptionElement::put_text
IHTMLOptionElement::put_value
IHTMLOptionElementFactory::create
IHTMLOptionsHolder::choosecolordlg
IHTMLOptionsHolder::get_document
IHTMLOptionsHolder::get_errorCharacter
IHTMLOptionsHolder::get_errorCode
IHTMLOptionsHolder::get_errorDebug
IHTMLOptionsHolder::get_errorLine
IHTMLOptionsHolder::get_errorMessage
IHTMLOptionsHolder::get_execArg
IHTMLOptionsHolder::get_findText
IHTMLOptionsHolder::get_fonts
IHTMLOptionsHolder::get_productVersion
IHTMLOptionsHolder::get_unsecuredWindowOfDocument
IHTMLOptionsHolder::openfiledlg
IHTMLOptionsHolder::put_errorCharacter
IHTMLOptionsHolder::put_errorCode
IHTMLOptionsHolder::put_errorDebug
IHTMLOptionsHolder::put_errorLine
IHTMLOptionsHolder::put_errorMessage
IHTMLOptionsHolder::put_execArg
IHTMLOptionsHolder::put_findText
IHTMLOptionsHolder::put_productVersion
IHTMLOptionsHolder::savefiledlg
IHTMLOptionsHolder::showSecurityInfo
IHTMLOptionsHolder::sizes
IHTMLParaElement::get_align
IHTMLParaElement::put_align
IHTMLPluginsCollection::get_length
IHTMLPluginsCollection::refresh
IHTMLRuleStyle::get_background
IHTMLRuleStyle::get_backgroundAttachment
IHTMLRuleStyle::get_backgroundColor
IHTMLRuleStyle::get_backgroundImage
IHTMLRuleStyle::get_backgroundPosition
IHTMLRuleStyle::get_backgroundPositionX
IHTMLRuleStyle::get_backgroundPositionY
IHTMLRuleStyle::get_backgroundRepeat
IHTMLRuleStyle::get_border
IHTMLRuleStyle::get_borderBottom
IHTMLRuleStyle::get_borderBottomColor
IHTMLRuleStyle::get_borderBottomStyle
IHTMLRuleStyle::get_borderBottomWidth
IHTMLRuleStyle::get_borderColor
IHTMLRuleStyle::get_borderLeft
IHTMLRuleStyle::get_borderLeftColor
IHTMLRuleStyle::get_borderLeftStyle
IHTMLRuleStyle::get_borderLeftWidth
IHTMLRuleStyle::get_borderRight
IHTMLRuleStyle::get_borderRightColor
IHTMLRuleStyle::get_borderRightStyle
IHTMLRuleStyle::get_borderRightWidth
IHTMLRuleStyle::get_borderStyle
IHTMLRuleStyle::get_borderTop
IHTMLRuleStyle::get_borderTopColor
IHTMLRuleStyle::get_borderTopStyle
IHTMLRuleStyle::get_borderTopWidth
IHTMLRuleStyle::get_borderWidth
IHTMLRuleStyle::get_clear
IHTMLRuleStyle::get_clip
IHTMLRuleStyle::get_color
IHTMLRuleStyle::get_cssText
IHTMLRuleStyle::get_cursor
IHTMLRuleStyle::get_display
IHTMLRuleStyle::get_filter
IHTMLRuleStyle::get_font
IHTMLRuleStyle::get_fontFamily
IHTMLRuleStyle::get_fontSize
IHTMLRuleStyle::get_fontStyle
IHTMLRuleStyle::get_fontVariant
IHTMLRuleStyle::get_fontWeight
IHTMLRuleStyle::get_height
IHTMLRuleStyle::get_left
IHTMLRuleStyle::get_letterSpacing
IHTMLRuleStyle::get_lineHeight
IHTMLRuleStyle::get_listStyle
IHTMLRuleStyle::get_listStyleImage
IHTMLRuleStyle::get_listStylePosition
IHTMLRuleStyle::get_listStyleType
IHTMLRuleStyle::get_margin
IHTMLRuleStyle::get_marginBottom
IHTMLRuleStyle::get_marginLeft
IHTMLRuleStyle::get_marginRight
IHTMLRuleStyle::get_marginTop
IHTMLRuleStyle::get_overflow
IHTMLRuleStyle::get_padding
IHTMLRuleStyle::get_paddingBottom
IHTMLRuleStyle::get_paddingLeft
IHTMLRuleStyle::get_paddingRight
IHTMLRuleStyle::get_paddingTop
IHTMLRuleStyle::get_pageBreakAfter
IHTMLRuleStyle::get_pageBreakBefore
IHTMLRuleStyle::get_position

* More entries...


Index

IHTMLRuleStyle::get_styleFloat
IHTMLRuleStyle::get_textAlign
IHTMLRuleStyle::get_textDecoration
IHTMLRuleStyle::get_textDecorationBlink
IHTMLRuleStyle::get_textDecorationLineThrough
IHTMLRuleStyle::get_textDecorationNone
IHTMLRuleStyle::get_textDecorationOverline
IHTMLRuleStyle::get_textDecorationUnderline
IHTMLRuleStyle::get_textIndent
IHTMLRuleStyle::get_textTransform
IHTMLRuleStyle::get_top
IHTMLRuleStyle::get_verticalAlign
IHTMLRuleStyle::get_visibility
IHTMLRuleStyle::get_whiteSpace
IHTMLRuleStyle::get_width
IHTMLRuleStyle::get_wordSpacing
IHTMLRuleStyle::get_zIndex
IHTMLRuleStyle::getAttribute
IHTMLRuleStyle::put_background
IHTMLRuleStyle::put_backgroundAttachment
IHTMLRuleStyle::put_backgroundColor
IHTMLRuleStyle::put_backgroundImage
IHTMLRuleStyle::put_backgroundPosition
IHTMLRuleStyle::put_backgroundPositionX
IHTMLRuleStyle::put_backgroundPositionY
IHTMLRuleStyle::put_backgroundRepeat
IHTMLRuleStyle::put_border
IHTMLRuleStyle::put_borderBottom
IHTMLRuleStyle::put_borderBottomColor
IHTMLRuleStyle::put_borderBottomStyle
IHTMLRuleStyle::put_borderBottomWidth
IHTMLRuleStyle::put_borderColor
IHTMLRuleStyle::put_borderLeft
IHTMLRuleStyle::put_borderLeftColor
IHTMLRuleStyle::put_borderLeftStyle
IHTMLRuleStyle::put_borderLeftWidth
IHTMLRuleStyle::put_borderRight
IHTMLRuleStyle::put_borderRightColor
IHTMLRuleStyle::put_borderRightStyle
IHTMLRuleStyle::put_borderRightWidth
IHTMLRuleStyle::put_borderStyle
IHTMLRuleStyle::put_borderTop
IHTMLRuleStyle::put_borderTopColor
IHTMLRuleStyle::put_borderTopStyle
IHTMLRuleStyle::put_borderTopWidth
IHTMLRuleStyle::put_borderWidth
IHTMLRuleStyle::put_clear
IHTMLRuleStyle::put_clip
IHTMLRuleStyle::put_color
IHTMLRuleStyle::put_cssText
IHTMLRuleStyle::put_cursor
IHTMLRuleStyle::put_display
IHTMLRuleStyle::put_filter
IHTMLRuleStyle::put_font
IHTMLRuleStyle::put_fontFamily
IHTMLRuleStyle::put_fontSize
IHTMLRuleStyle::put_fontStyle
IHTMLRuleStyle::put_fontVariant
IHTMLRuleStyle::put_fontWeight
IHTMLRuleStyle::put_height
IHTMLRuleStyle::put_left
IHTMLRuleStyle::put_letterSpacing
IHTMLRuleStyle::put_lineHeight
IHTMLRuleStyle::put_listStyle
IHTMLRuleStyle::put_listStyleImage
IHTMLRuleStyle::put_listStylePosition
IHTMLRuleStyle::put_listStyleType
IHTMLRuleStyle::put_margin
IHTMLRuleStyle::put_marginBottom
IHTMLRuleStyle::put_marginLeft
IHTMLRuleStyle::put_marginRight
IHTMLRuleStyle::put_marginTop
IHTMLRuleStyle::put_overflow
IHTMLRuleStyle::put_padding
IHTMLRuleStyle::put_paddingBottom
IHTMLRuleStyle::put_paddingLeft
IHTMLRuleStyle::put_paddingRight
IHTMLRuleStyle::put_paddingTop
IHTMLRuleStyle::put_pageBreakAfter
IHTMLRuleStyle::put_pageBreakBefore
IHTMLRuleStyle::put_styleFloat
IHTMLRuleStyle::put_textAlign
IHTMLRuleStyle::put_textDecoration
IHTMLRuleStyle::put_textDecorationBlink
IHTMLRuleStyle::put_textDecorationLineThrough
IHTMLRuleStyle::put_textDecorationNone
IHTMLRuleStyle::put_textDecorationOverline
IHTMLRuleStyle::put_textDecorationUnderline
IHTMLRuleStyle::put_textIndent
IHTMLRuleStyle::put_textTransform
IHTMLRuleStyle::put_top
IHTMLRuleStyle::put_verticalAlign
IHTMLRuleStyle::put_visibility
IHTMLRuleStyle::put_whiteSpace
IHTMLRuleStyle::put_width
IHTMLRuleStyle::put_wordSpacing
IHTMLRuleStyle::put_zIndex
IHTMLRuleStyle::removeAttribute
IHTMLRuleStyle::setAttribute
IHTMLScreen::get_availHeight
IHTMLScreen::get_availWidth
IHTMLScreen::get_bufferDepth
IHTMLScreen::get_colorDepth
IHTMLScreen::get_fontSmoothingEnabled
IHTMLScreen::get_height
IHTMLScreen::get_updateInterval
IHTMLScreen::get_width
IHTMLScreen::put_bufferDepth
IHTMLScreen::put_updateInterval
IHTMLScriptElement::get_defer
IHTMLScriptElement::get_event
IHTMLScriptElement::get_htmlFor
IHTMLScriptElement::get_onerror
IHTMLScriptElement::get_readyState
IHTMLScriptElement::get_src
IHTMLScriptElement::get_text
IHTMLScriptElement::get_type
IHTMLScriptElement::put_defer
IHTMLScriptElement::put_event
IHTMLScriptElement::put_htmlFor
IHTMLScriptElement::put_onerror
IHTMLScriptElement::put_src
IHTMLScriptElement::put_text
IHTMLScriptElement::put_type
IHTMLSelectElement::add
IHTMLSelectElement::get__newEnum
IHTMLSelectElement::get_disabled
IHTMLSelectElement::get_form
IHTMLSelectElement::get_length
IHTMLSelectElement::get_multiple
IHTMLSelectElement::get_name
IHTMLSelectElement::get_onchange
IHTMLSelectElement::get_options
IHTMLSelectElement::get_selectedIndex
IHTMLSelectElement::get_size
IHTMLSelectElement::get_type
IHTMLSelectElement::get_value
IHTMLSelectElement::item
IHTMLSelectElement::put_disabled
IHTMLSelectElement::put_length
IHTMLSelectElement::put_multiple
IHTMLSelectElement::put_name
IHTMLSelectElement::put_onchange
IHTMLSelectElement::put_selectedIndex
IHTMLSelectElement::put_size
IHTMLSelectElement::put_value
IHTMLSelectElement::remove
IHTMLSelectElement::tags
IHTMLSelectionObject::clear
IHTMLSelectionObject::createRange
IHTMLSelectionObject::empty
IHTMLSelectionObject::get_type
IHTMLSpanFlow::get_align
IHTMLSpanFlow::put_align
IHTMLStyle::get_background
IHTMLStyle::get_backgroundAttachment
IHTMLStyle::get_backgroundColor
IHTMLStyle::get_backgroundImage
IHTMLStyle::get_backgroundPosition
IHTMLStyle::get_backgroundPositionX
IHTMLStyle::get_backgroundPositionY
IHTMLStyle::get_backgroundRepeat
IHTMLStyle::get_border
IHTMLStyle::get_borderBottom
IHTMLStyle::get_borderBottomColor
IHTMLStyle::get_borderBottomStyle
IHTMLStyle::get_borderBottomWidth
IHTMLStyle::get_borderColor
IHTMLStyle::get_borderLeft
IHTMLStyle::get_borderLeftColor
IHTMLStyle::get_borderLeftStyle
IHTMLStyle::get_borderLeftWidth
IHTMLStyle::get_borderRight
IHTMLStyle::get_borderRightColor
IHTMLStyle::get_borderRightStyle
IHTMLStyle::get_borderRightWidth
IHTMLStyle::get_borderStyle
IHTMLStyle::get_borderTop
IHTMLStyle::get_borderTopColor
IHTMLStyle::get_borderTopStyle
IHTMLStyle::get_borderTopWidth
IHTMLStyle::get_borderWidth
IHTMLStyle::get_clear
IHTMLStyle::get_clip
IHTMLStyle::get_color
IHTMLStyle::get_cssText
IHTMLStyle::get_cursor
IHTMLStyle::get_display
IHTMLStyle::get_filter
IHTMLStyle::get_font
IHTMLStyle::get_fontFamily
IHTMLStyle::get_fontSize
IHTMLStyle::get_fontStyle
IHTMLStyle::get_fontVariant
IHTMLStyle::get_fontWeight
IHTMLStyle::get_height
IHTMLStyle::get_left
IHTMLStyle::get_letterSpacing
IHTMLStyle::get_lineHeight
IHTMLStyle::get_listStyle
IHTMLStyle::get_listStyleImage
IHTMLStyle::get_listStylePosition
IHTMLStyle::get_listStyleType
IHTMLStyle::get_margin
IHTMLStyle::get_marginBottom
IHTMLStyle::get_marginLeft
IHTMLStyle::get_marginRight
IHTMLStyle::get_marginTop
IHTMLStyle::get_overflow
IHTMLStyle::get_padding
IHTMLStyle::get_paddingBottom
IHTMLStyle::get_paddingLeft
IHTMLStyle::get_paddingRight
IHTMLStyle::get_paddingTop
IHTMLStyle::get_pageBreakAfter
IHTMLStyle::get_pageBreakBefore
IHTMLStyle::get_pixelHeight
IHTMLStyle::get_pixelLeft
IHTMLStyle::get_pixelTop

* More entries...


Index

IHTMLStyle::get_pixelWidth
IHTMLStyle::get_posHeight
IHTMLStyle::get_position
IHTMLStyle::get_posLeft
IHTMLStyle::get_posTop
IHTMLStyle::get_posWidth
IHTMLStyle::get_styleFloat
IHTMLStyle::get_textAlign
IHTMLStyle::get_textDecoration
IHTMLStyle::get_textDecorationBlink
IHTMLStyle::get_textDecorationLineThrough
IHTMLStyle::get_textDecorationNone
IHTMLStyle::get_textDecorationOverline
IHTMLStyle::get_textDecorationUnderline
IHTMLStyle::get_textIndent
IHTMLStyle::get_textTransform
IHTMLStyle::get_top
IHTMLStyle::get_verticalAlign
IHTMLStyle::get_visibility
IHTMLStyle::get_whiteSpace
IHTMLStyle::get_width
IHTMLStyle::get_wordSpacing
IHTMLStyle::get_zIndex
IHTMLStyle::getAttribute
IHTMLStyle::put_background
IHTMLStyle::put_backgroundAttachment
IHTMLStyle::put_backgroundColor
IHTMLStyle::put_backgroundImage
IHTMLStyle::put_backgroundPosition
IHTMLStyle::put_backgroundPositionX
IHTMLStyle::put_backgroundPositionY
IHTMLStyle::put_backgroundRepeat
IHTMLStyle::put_border
IHTMLStyle::put_borderBottom
IHTMLStyle::put_borderBottomColor
IHTMLStyle::put_borderBottomStyle
IHTMLStyle::put_borderBottomWidth
IHTMLStyle::put_borderColor
IHTMLStyle::put_borderLeft
IHTMLStyle::put_borderLeftColor
IHTMLStyle::put_borderLeftStyle
IHTMLStyle::put_borderLeftWidth
IHTMLStyle::put_borderRight
IHTMLStyle::put_borderRightColor
IHTMLStyle::put_borderRightStyle
IHTMLStyle::put_borderRightWidth
IHTMLStyle::put_borderStyle
IHTMLStyle::put_borderTop
IHTMLStyle::put_borderTopColor
IHTMLStyle::put_borderTopStyle
IHTMLStyle::put_borderTopWidth
IHTMLStyle::put_borderWidth
IHTMLStyle::put_clear
IHTMLStyle::put_clip
IHTMLStyle::put_color
IHTMLStyle::put_cssText
IHTMLStyle::put_cursor
IHTMLStyle::put_display
IHTMLStyle::put_filter
IHTMLStyle::put_font
IHTMLStyle::put_fontFamily
IHTMLStyle::put_fontSize
IHTMLStyle::put_fontStyle
IHTMLStyle::put_fontVariant
IHTMLStyle::put_fontWeight
IHTMLStyle::put_height
IHTMLStyle::put_left
IHTMLStyle::put_letterSpacing
IHTMLStyle::put_lineHeight
IHTMLStyle::put_listStyle
IHTMLStyle::put_listStyleImage
IHTMLStyle::put_listStylePosition
IHTMLStyle::put_listStyleType
IHTMLStyle::put_margin
IHTMLStyle::put_marginBottom
IHTMLStyle::put_marginLeft
IHTMLStyle::put_marginRight
IHTMLStyle::put_marginTop
IHTMLStyle::put_overflow
IHTMLStyle::put_padding
IHTMLStyle::put_paddingBottom
IHTMLStyle::put_paddingLeft
IHTMLStyle::put_paddingRight
IHTMLStyle::put_paddingTop
IHTMLStyle::put_pageBreakAfter
IHTMLStyle::put_pageBreakBefore
IHTMLStyle::put_pixelHeight
IHTMLStyle::put_pixelLeft
IHTMLStyle::put_pixelTop
IHTMLStyle::put_pixelWidth
IHTMLStyle::put_posHeight
IHTMLStyle::put_posLeft
IHTMLStyle::put_posTop
IHTMLStyle::put_posWidth
IHTMLStyle::put_styleFloat
IHTMLStyle::put_textAlign
IHTMLStyle::put_textDecoration
IHTMLStyle::put_textDecorationBlink
IHTMLStyle::put_textDecorationLineThrough
IHTMLStyle::put_textDecorationNone
IHTMLStyle::put_textDecorationOverline
IHTMLStyle::put_textDecorationUnderline
IHTMLStyle::put_textIndent
IHTMLStyle::put_textTransform
IHTMLStyle::put_top
IHTMLStyle::put_verticalAlign
IHTMLStyle::put_visibility
IHTMLStyle::put_whiteSpace
IHTMLStyle::put_width
IHTMLStyle::put_wordSpacing
IHTMLStyle::put_zIndex
IHTMLStyle::removeAttribute
IHTMLStyle::setAttribute
IHTMLStyle::toString
IHTMLStyleElement::get_disabled
IHTMLStyleElement::get_media
IHTMLStyleElement::get_onerror
IHTMLStyleElement::get_onload
IHTMLStyleElement::get_onreadystatechange
IHTMLStyleElement::get_readyState
IHTMLStyleElement::get_styleSheet
IHTMLStyleElement::get_type
IHTMLStyleElement::put_disabled
IHTMLStyleElement::put_media
IHTMLStyleElement::put_onerror
IHTMLStyleElement::put_onload
IHTMLStyleElement::put_onreadystatechange
IHTMLStyleElement::put_type
IHTMLStyleSheet::addImport
IHTMLStyleSheet::addRule
IHTMLStyleSheet::get_cssText
IHTMLStyleSheet::get_disabled
IHTMLStyleSheet::get_href
IHTMLStyleSheet::get_id
IHTMLStyleSheet::get_imports
IHTMLStyleSheet::get_media
IHTMLStyleSheet::get_owningElement
IHTMLStyleSheet::get_parentStyleSheet
IHTMLStyleSheet::get_readOnly
IHTMLStyleSheet::get_rules
IHTMLStyleSheet::get_title
IHTMLStyleSheet::get_type
IHTMLStyleSheet::put_disabled
IHTMLStyleSheet::put_href
IHTMLStyleSheet::put_media
IHTMLStyleSheet::put_title
IHTMLStyleSheet::removeImport
IHTMLStyleSheet::removeRule
IHTMLStyleSheetRule::get_readOnly
IHTMLStyleSheetRule::get_selectorText
IHTMLStyleSheetRule::get_style
IHTMLStyleSheetRule::put_selectorText
IHTMLStyleSheetRulesCollection::get_length
IHTMLStyleSheetRulesCollection::item
IHTMLStyleSheetsCollection::get__newEnum
IHTMLStyleSheetsCollection::get_length
IHTMLStyleSheetsCollection::item
IHTMLTable::createCaption
IHTMLTable::createTFoot
IHTMLTable::createTHead
IHTMLTable::deleteCaption
IHTMLTable::deleteRow
IHTMLTable::deleteTFoot
IHTMLTable::deleteTHead
IHTMLTable::get_align
IHTMLTable::get_background
IHTMLTable::get_bgColor
IHTMLTable::get_border
IHTMLTable::get_borderColor
IHTMLTable::get_borderColorDark
IHTMLTable::get_borderColorLight
IHTMLTable::get_caption
IHTMLTable::get_cellPadding
IHTMLTable::get_cellSpacing
IHTMLTable::get_cols
IHTMLTable::get_dataPageSize
IHTMLTable::get_frame
IHTMLTable::get_height
IHTMLTable::get_onreadystatechange
IHTMLTable::get_readyState
IHTMLTable::get_rows
IHTMLTable::get_rules
IHTMLTable::get_tBodies
IHTMLTable::get_tFoot
IHTMLTable::get_tHead
IHTMLTable::get_width
IHTMLTable::insertRow
IHTMLTable::nextPage
IHTMLTable::previousPage
IHTMLTable::put_align
IHTMLTable::put_background
IHTMLTable::put_bgColor
IHTMLTable::put_border
IHTMLTable::put_borderColor
IHTMLTable::put_borderColorDark
IHTMLTable::put_borderColorLight
IHTMLTable::put_cellPadding
IHTMLTable::put_cellSpacing
IHTMLTable::put_cols
IHTMLTable::put_dataPageSize
IHTMLTable::put_frame
IHTMLTable::put_height
IHTMLTable::put_onreadystatechange
IHTMLTable::put_rules
IHTMLTable::put_width
IHTMLTable::refresh
IHTMLTableCaption::get_align
IHTMLTableCaption::get_vAlign
IHTMLTableCaption::put_align
IHTMLTableCaption::put_vAlign
IHTMLTableCell::get_align
IHTMLTableCell::get_background
IHTMLTableCell::get_bgColor
IHTMLTableCell::get_borderColor
IHTMLTableCell::get_borderColorDark
IHTMLTableCell::get_borderColorLight
IHTMLTableCell::get_cellIndex
IHTMLTableCell::get_colSpan
IHTMLTableCell::get_height
IHTMLTableCell::get_noWrap
IHTMLTableCell::get_rowSpan
IHTMLTableCell::get_vAlign
IHTMLTableCell::get_width
IHTMLTableCell::put_align
IHTMLTableCell::put_background
IHTMLTableCell::put_bgColor
IHTMLTableCell::put_borderColor
IHTMLTableCell::put_borderColorDark
IHTMLTableCell::put_borderColorLight
IHTMLTableCell::put_colSpan
IHTMLTableCell::put_height

* More entries...


Index

IHTMLTableCell::put_noWrap
IHTMLTableCell::put_rowSpan
IHTMLTableCell::put_vAlign
IHTMLTableCell::put_width
IHTMLTableCol::get_align
IHTMLTableCol::get_span
IHTMLTableCol::get_vAlign
IHTMLTableCol::get_width
IHTMLTableCol::put_align
IHTMLTableCol::put_span
IHTMLTableCol::put_vAlign
IHTMLTableCol::put_width
IHTMLTableRow::deleteCell
IHTMLTableRow::get_align
IHTMLTableRow::get_bgColor
IHTMLTableRow::get_borderColor
IHTMLTableRow::get_borderColorDark
IHTMLTableRow::get_borderColorLight
IHTMLTableRow::get_cells
IHTMLTableRow::get_rowIndex
IHTMLTableRow::get_sectionRowIndex
IHTMLTableRow::get_vAlign
IHTMLTableRow::insertCell
IHTMLTableRow::put_align
IHTMLTableRow::put_bgColor
IHTMLTableRow::put_borderColor
IHTMLTableRow::put_borderColorDark
IHTMLTableRow::put_borderColorLight
IHTMLTableRow::put_vAlign
IHTMLTableSection::deleteRow
IHTMLTableSection::get_align
IHTMLTableSection::get_bgColor
IHTMLTableSection::get_rows
IHTMLTableSection::get_vAlign
IHTMLTableSection::insertRow
IHTMLTableSection::put_align
IHTMLTableSection::put_bgColor
IHTMLTableSection::put_vAlign
IHTMLTextAreaElement::createTextRange
IHTMLTextAreaElement::get_cols
IHTMLTextAreaElement::get_defaultValue
IHTMLTextAreaElement::get_disabled
IHTMLTextAreaElement::get_form
IHTMLTextAreaElement::get_name
IHTMLTextAreaElement::get_onchange
IHTMLTextAreaElement::get_onselect
IHTMLTextAreaElement::get_readOnly
IHTMLTextAreaElement::get_rows
IHTMLTextAreaElement::get_status
IHTMLTextAreaElement::get_type
IHTMLTextAreaElement::get_value
IHTMLTextAreaElement::get_wrap
IHTMLTextAreaElement::put_cols
IHTMLTextAreaElement::put_defaultValue
IHTMLTextAreaElement::put_disabled
IHTMLTextAreaElement::put_name
IHTMLTextAreaElement::put_onchange
IHTMLTextAreaElement::put_onselect
IHTMLTextAreaElement::put_readOnly
IHTMLTextAreaElement::put_rows
IHTMLTextAreaElement::put_status
IHTMLTextAreaElement::put_value
IHTMLTextAreaElement::put_wrap
IHTMLTextAreaElement::select
IHTMLTextContainer::createControlRange
IHTMLTextContainer::get_onscroll
IHTMLTextContainer::get_scrollHeight
IHTMLTextContainer::get_scrollLeft
IHTMLTextContainer::get_scrollTop
IHTMLTextContainer::get_scrollWidth
IHTMLTextContainer::put_onscroll
IHTMLTextContainer::put_scrollLeft
IHTMLTextContainer::put_scrollTop
IHTMLTitleElement::get_text
IHTMLTitleElement::put_text
IHTMLTxtRange::collapse
IHTMLTxtRange::compareEndPoints
IHTMLTxtRange::duplicate
IHTMLTxtRange::execCommand
IHTMLTxtRange::execCommandShowHelp
IHTMLTxtRange::expand
IHTMLTxtRange::findText
IHTMLTxtRange::get_htmlText
IHTMLTxtRange::get_text
IHTMLTxtRange::getBookmark
IHTMLTxtRange::inRange
IHTMLTxtRange::isEqual
IHTMLTxtRange::move
IHTMLTxtRange::moveEnd
IHTMLTxtRange::moveStart
IHTMLTxtRange::moveToBookmark
IHTMLTxtRange::moveToElementText
IHTMLTxtRange::moveToPoint
IHTMLTxtRange::parentElement
IHTMLTxtRange::pasteHTML
IHTMLTxtRange::put_text
IHTMLTxtRange::queryCommandEnabled
IHTMLTxtRange::queryCommandIndeterm
IHTMLTxtRange::queryCommandState
IHTMLTxtRange::queryCommandSupported
IHTMLTxtRange::queryCommandText
IHTMLTxtRange::queryCommandValue
IHTMLTxtRange::scrollIntoView
IHTMLTxtRange::select
IHTMLTxtRange::setEndPoint
IHTMLUListElement::get_compact
IHTMLUListElement::get_type
IHTMLUListElement::put_compact
IHTMLUListElement::put_type
IHTMLWindow2::alert
IHTMLWindow2::blur
IHTMLWindow2::clearInterval
IHTMLWindow2::clearTimeout
IHTMLWindow2::close
IHTMLWindow2::confirm
IHTMLWindow2::execScript
IHTMLWindow2::focus
IHTMLWindow2::get__newEnum
IHTMLWindow2::get_clientInformation
IHTMLWindow2::get_closed
IHTMLWindow2::get_defaultStatus
IHTMLWindow2::get_document
IHTMLWindow2::get_event
IHTMLWindow2::get_external
IHTMLWindow2::get_frames
IHTMLWindow2::get_history
IHTMLWindow2::get_Image
IHTMLWindow2::get_location
IHTMLWindow2::get_name
IHTMLWindow2::get_navigator
IHTMLWindow2::get_offscreenBuffering
IHTMLWindow2::get_onbeforeunload
IHTMLWindow2::get_onblur
IHTMLWindow2::get_onerror
IHTMLWindow2::get_onfocus
IHTMLWindow2::get_onhelp
IHTMLWindow2::get_onload
IHTMLWindow2::get_onresize
IHTMLWindow2::get_onscroll
IHTMLWindow2::get_onunload
IHTMLWindow2::get_opener
IHTMLWindow2::get_Option
IHTMLWindow2::get_parent
IHTMLWindow2::get_screen
IHTMLWindow2::get_self
IHTMLWindow2::get_status
IHTMLWindow2::get_top
IHTMLWindow2::get_window
IHTMLWindow2::moveBy
IHTMLWindow2::moveTo
IHTMLWindow2::navigate
IHTMLWindow2::open
IHTMLWindow2::prompt
IHTMLWindow2::put_defaultStatus
IHTMLWindow2::put_name
IHTMLWindow2::put_offscreenBuffering
IHTMLWindow2::put_onbeforeunload
IHTMLWindow2::put_onblur
IHTMLWindow2::put_onerror
IHTMLWindow2::put_onfocus
IHTMLWindow2::put_onhelp
IHTMLWindow2::put_onload
IHTMLWindow2::put_onresize
IHTMLWindow2::put_onscroll
IHTMLWindow2::put_onunload
IHTMLWindow2::put_opener
IHTMLWindow2::put_status
IHTMLWindow2::resizeBy
IHTMLWindow2::resizeTo
IHTMLWindow2::scroll
IHTMLWindow2::scrollBy
IHTMLWindow2::scrollTo
IHTMLWindow2::setInterval
IHTMLWindow2::setTimeout
IHTMLWindow2::showHelp
IHTMLWindow2::showModalDialog
IHTMLWindow2::toString
IHttpNegotiate
IHttpNegotiate::BeginningTransaction
IHttpNegotiate::OnResponse
IHttpSecurity
IHttpSecurity::OnSecurityProblem
IInputObject
IInputObject::HasFocusIO
IInputObject::TranslateAcceleratorIO
IInputObject::UIActivateIO
IInputObjectSite
IInputObjectSite::OnFocusChangeIS
IInternet
IInternetBindInfo
IInternetBindInfo::GetBindInfo
IInternetBindInfo::GetBindString
IInternetHostSecurityManager
IInternetHostSecurityManager::GetSecurityId
IInternetHostSecurityManager::ProcessUrlAction
IInternetHostSecurityManager::QueryCustomPolicy
IInternetProtocol
IInternetProtocol::LockRequest
IInternetProtocol::Read
IInternetProtocol::Seek
IInternetProtocol::UnlockRequest
IInternetProtocolInfo
IInternetProtocolInfo::CombineUrl
IInternetProtocolInfo::CompareUrl
IInternetProtocolInfo::ParseUrl
IInternetProtocolInfo::QueryInfo
IInternetProtocolRoot
IInternetProtocolRoot::Abort
IInternetProtocolRoot::Continue
IInternetProtocolRoot::Resume
IInternetProtocolRoot::Start
IInternetProtocolRoot::Suspend
IInternetProtocolRoot::Terminate
IInternetProtocolSink
IInternetProtocolSink::ReportData
IInternetProtocolSink::ReportProgress
IInternetProtocolSink::ReportResult
IInternetProtocolSink::Switch
IInternetSecurityManager
IInternetSecurityManager::GetSecurityId
IInternetSecurityManager::GetSecuritySite
IInternetSecurityManager::GetZoneMappings
IInternetSecurityManager::MapUrlToZone
IInternetSecurityManager::ProcessUrlAction
IInternetSecurityManager::QueryCustomPolicy
IInternetSecurityManager::SetSecuritySite
IInternetSecurityManager::SetZoneMapping
IInternetSecurityMgrSite
IInternetSecurityMgrSite::EnableModeless
IInternetSecurityMgrSite::GetWindow
IInternetSession
IInternetSession::CreateBinding
IInternetSession::GetCache
IInternetSession::GetSessionOption
IInternetSession::RegisterMimeFilter
IInternetSession::RegisterNameSpace

* More entries...


Index

IInternetSession::SetCache
IInternetSession::SetSessionOption
IInternetSession::UnregisterMimeFilter
IInternetSession::UnregisterNameSpace
IInternetZoneManager
IInternetZoneManager::CreateZoneEnumerator
IInternetZoneManager::DestroyZoneEnumerator
IInternetZoneManager::GetZoneActionPolicy
IInternetZoneManager::GetZoneAt
IInternetZoneManager::GetZoneAttributes
IInternetZoneManager::GetZoneCustomPolicy
IInternetZoneManager::LogAction
IInternetZoneManager::PromptAction
IInternetZoneManager::SetZoneActionPolicy
IInternetZoneManager::SetZoneAttributes
IInternetZoneManager::SetZoneCustomPolicy
image
image (type)
IMAGEINFO
ImageList_Add
ImageList_AddIcon
ImageList_AddMasked
ImageList_BeginDrag
ImageList_Copy
ImageList_Create
ImageList_Destroy
ImageList_DragEnter
ImageList_DragLeave
ImageList_DragMove
ImageList_DragShowNolock
ImageList_Draw
ImageList_DrawEx
ImageList_DrawIndirect
ImageList_Duplicate
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_RemoveAll
ImageList_Replace
ImageList_ReplaceIcon
ImageList_SetBkColor
ImageList_SetDragCursorImage
ImageList_SetIconSize
ImageList_SetImageCount
ImageList_SetOverlayImage
ImageList_Write
IMAGELISTDRAWPARAMS
images
IMailUser::CopyProps
IMailUser::CopyTo
IMailUser::DeleteProps
IMailUser::GetIDsFromNames
IMailUser::GetLastError
IMailUser::GetNamesFromIDs
IMailUser::GetPropList
IMailUser::GetProps
IMailUser::OpenProperty
IMailUser::SaveChanges
IMailUser::SetProps
IMalloc
IMalloc::Free
IMAPIFolder
IMAPIProp
IMAPITable
IMessage
IMG (HTML Elements)
IMG (Objects)
IMoniker
IMoniker::BindToObject
IMoniker::BindToStorage
IMoniker::GetDisplayName
IMoniker::ParseDisplayName
IMPLEMENTATION
Import (IWABObject)
imports
IncludeObject (ICommDlgBrowser)
Indent
Indent Command
indeterminate
index
Index (Properties)
Index Property
INDEXTOOVERLAYMASK
INDEXTOSTATEIMAGEMASK
INET_E_AGENT_CACHE_SIZE_EXCEEDED
INET_E_AGENT_CONNECTION_FAILED
INET_E_AGENT_MAX_SIZE_EXCEEDED
INET_E_AUTHENTICATION_REQUIRED
INET_E_CANNOT_CONNECT
INET_E_CANNOT_INSTANTIATE_OBJECT
INET_E_CANNOT_LOAD_DATA
INET_E_CANNOT_LOCK_REQUEST
INET_E_CONNECTION_TIMEOUT
INET_E_DATA_NOT_AVAILABLE
INET_E_DEFAULT_ACTION
INET_E_DOWNLOAD_FAILURE
INET_E_INVALID_REQUEST
INET_E_INVALID_URL
INET_E_NO_SESSION
INET_E_NO_VALID_MEDIA
INET_E_OBJECT_NOT_FOUND
INET_E_QUERYOPTION_UNKNOWN
INET_E_REDIRECT)TO_DIR
INET_E_REDIRECTING
INET_E_RESOURCE_NOT_FOUND
INET_E_SECURITY_PROBLEM
INET_E_UNKNOWN_PROTOCOL
INET_E_USE_DEFAULT_PROTOCOLHANDLER
INET_E_USE_DEFAULT_SETTINGS
INET_S_AGENT_PART_FAIL
InetIsOffline
INewShortcutHook
INewShortcutHook::GetExtension
INewShortcutHook::GetFolder
INewShortcutHook::GetName
INewShortcutHook::GetReferent
INewShortcutHook::SetFolder
INewShortcutHook::SetReferent
Info
InitCommonControls
InitCommonControlsEx (Common Control Functions)
INITCOMMONCONTROLSEX (Common Control Structures)
Initialize (IPersistFolder)
Initialize (IShellExtInit)
InitializeFlatSB
InitNew (IActiveScriptParse)
InitNew (IPersistPropertyBag)
InitNew (IPersistPropertyBag2)
innerHTML
innerText
INotifyReplica
INotifyReplica::YouAreAReplica
in-process component <definition>
INPUT (HTML Elements)
INPUT (Objects)
INPUT type=button
INPUT type=checkbox
INPUT type=file
INPUT type=hidden
INPUT type=image
INPUT type=password
INPUT type=radio
INPUT type=reset
INPUT type=submit
INPUT type=text
inRange
inRange (IHTMLTxtRange)
INS (HTML Elements)
INS (Objects)
Insert the Grid and the RDS.DataControl Object
insertAdjacentHTML
insertAdjacentHTML (IHTMLElement)
insertAdjacentText
insertAdjacentText (IHTMLElement)
InsertButton
InsertButton Command
insertCell
insertCell (IHTMLTableRow)
InsertFieldset
InsertFieldset Command
InsertHorizontalRule
InsertHorizontalRule Command
InsertIFrame
InsertIFrame Command
InsertInputButton
InsertInputButton Command
InsertInputCheckbox
InsertInputCheckbox Command
InsertInputFileUpload
InsertInputFileUpload Command
InsertInputHidden
InsertInputHidden Command
InsertInputImage
InsertInputImage Command
InsertInputPassword
InsertInputPassword Command
InsertInputRadio
InsertInputRadio Command
InsertInputReset
InsertInputReset Command
InsertInputSubmit
InsertInputSubmit Command
InsertInputText
InsertInputText Command
InsertMarquee
InsertMarquee Command
InsertMenu
InsertMenusSB (IShellBrowser)
InsertOrderedList
InsertOrderedList Command
InsertParagraph
InsertParagraph Command
insertRow
insertRow (IHTMLTable)
insertRow (IHTMLTableSection)
InsertSelectDropdown
InsertSelectDropdown Command
InsertSelectListbox
InsertSelectListbox Command
InsertTextArea
InsertTextArea Command
InsertUnorderedList
InsertUnorderedList Command
Internet Cache, Tasks
Internet Security Manager
Internet Zone Manager
INTERNET_ASYNC_RESULT
INTERNET_AUTHNOTIFY_DATA
INTERNET_BUFFERS
INTERNET_CACHE_ENTRY_INFO
INTERNET_CERTIFICATE_INFO
INTERNET_CONNECTED_INFO
INTERNET_ERROR_BASE
INTERNET_FLAG_ASYNC
INTERNET_FLAG_CACHE_ASYNC
INTERNET_FLAG_CACHE_IF_NET_FAIL
INTERNET_FLAG_DONT_CACHE
INTERNET_FLAG_EXISTING_CONNECT
INTERNET_FLAG_FORMS_SUBMIT
INTERNET_FLAG_FROM_CACHE
INTERNET_FLAG_HYPERLINK
INTERNET_FLAG_IGNORE_CERT_CN_INVALID
INTERNET_FLAG_IGNORE_CERT_DATE_INVALID
INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP
INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS
INTERNET_FLAG_KEEP_CONNECTION
INTERNET_FLAG_MAKE_PERSISTENT
INTERNET_FLAG_MUST_CACHE_REQUEST
INTERNET_FLAG_NEED_FILE
INTERNET_FLAG_NO_AUTH
INTERNET_FLAG_NO_AUTO_REDIRECT
INTERNET_FLAG_NO_CACHE_WRITE
INTERNET_FLAG_NO_COOKIES
INTERNET_FLAG_NO_UI
INTERNET_FLAG_OFFLINE
INTERNET_FLAG_PASSIVE
INTERNET_FLAG_PRAGMA_NOCACHE
INTERNET_FLAG_RAW_DATA
INTERNET_FLAG_READ_PREFETCH
INTERNET_FLAG_RELOAD
INTERNET_FLAG_RESYNCHRONIZE
INTERNET_FLAG_SECURE
INTERNET_FLAG_TRANSFER_ASCII
INTERNET_FLAG_TRANSFER_BINARY
INTERNET_ONLINE_OFFLINE_INFO
INTERNET_OPTION_ASYNC
INTERNET_OPTION_ASYNC_PRIORITY
INTERNET_OPTION_CACHE_STREAM_HANDLE
INTERNET_OPTION_CALLBACK
INTERNET_OPTION_CALLBACK_FILTER
INTERNET_OPTION_CONNECT_BACKOFF

* More entries...


Index

INTERNET_OPTION_CONNECT_LIMIT
INTERNET_OPTION_CONNECT_RETRIES
INTERNET_OPTION_CONNECT_TIME
INTERNET_OPTION_CONNECT_TIMEOUT
INTERNET_OPTION_CONNECTED_STATE
INTERNET_OPTION_CONTEXT_VALUE
INTERNET_OPTION_CONTROL_RECEIVE_TIMEOUT
INTERNET_OPTION_CONTROL_SEND_TIMEOUT
INTERNET_OPTION_DATA_RECEIVE_TIMEOUT
INTERNET_OPTION_DATA_SEND_TIMEOUT
INTERNET_OPTION_DATAFILE_NAME
INTERNET_OPTION_DISCONNECTED_TIMEOUT
INTERNET_OPTION_END_BROWSER_SESSION
INTERNET_OPTION_ERROR_MASK
INTERNET_OPTION_EXTENDED_ERROR
INTERNET_OPTION_HANDLE_TYPE
INTERNET_OPTION_HTTP_VERSION
INTERNET_OPTION_IDLE_STATE
INTERNET_OPTION_KEEP_CONNECTION
INTERNET_OPTION_LISTEN_TIMEOUT
INTERNET_OPTION_OFFLINE_MODE
INTERNET_OPTION_OFFLINE_SEMANTICS
INTERNET_OPTION_PARENT_HANDLE
INTERNET_OPTION_PASSWORD
INTERNET_OPTION_POLICY
INTERNET_OPTION_PROXY
INTERNET_OPTION_PROXY_PASSWORD
INTERNET_OPTION_PROXY_USERNAME
INTERNET_OPTION_READ_BUFFER_SIZE
INTERNET_OPTION_RECEIVE_THROUGHPUT
INTERNET_OPTION_RECEIVE_TIMEOUT
INTERNET_OPTION_REFRESH
INTERNET_OPTION_REQUEST_FLAGS
INTERNET_OPTION_REQUEST_PRIORITY
INTERNET_OPTION_SECONDARY_CACHE_KEY
INTERNET_OPTION_SECURITY_CERTIFICATE
INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT
INTERNET_OPTION_SECURITY_FLAGS
INTERNET_OPTION_SECURITY_KEY_BITNESS
INTERNET_OPTION_SECURITY_SELECT_CLIENT_CERT
INTERNET_OPTION_SEND_THROUGHPUT
INTERNET_OPTION_SEND_TIMEOUT
INTERNET_OPTION_SETTINGS_CHANGED
INTERNET_OPTION_URL
INTERNET_OPTION_USER_AGENT
INTERNET_OPTION_USERNAME
INTERNET_OPTION_VERSION
INTERNET_OPTION_WRITE_BUFFER_SIZE
INTERNET_PREFETCH_STATUS
INTERNET_PROXY_INFO
INTERNET_SCHEME
INTERNET_STATUS_CALLBACK
INTERNET_VERSION_INFO
InternetAttemptConnect
InternetAutodial
InternetAutodialHangup
InternetCanonicalizeUrl (1)
InternetCanonicalizeUrl (2)
InternetCheckConnection
InternetCloseHandle
InternetCombineUrl (1)
InternetCombineUrl (2)
InternetConfirmZoneCrossing
InternetConnect
InternetConnectUrl
InternetCrackUrl
InternetCreateUrl
InternetDial
InternetErrorDlg
InternetExplorer
InternetExplorer Object
InternetFindNextFile
InternetGetConnectedState
InternetGetCookie
InternetGetLastResponseInfo
InternetGoOnline
InternetHangUp
InternetLockRequestFile
InternetOpen
InternetOpenUrl
InternetQueryDataAvailable
InternetQueryOption
InternetReadFile
InternetReadFileEx
InternetSetCookie
InternetSetDialState
InternetSetFilePointer
InternetSetOption
InternetSetOptionEx
InternetSetStatusCallback
InternetTimeFromSystemTime
InternetTimeToSystemTime
InternetUnlockRequestFile
InternetWriteFile
InterruptScriptThread (IActiveScript)
INTERVALTIME
Introduction to Remote Data Service
InvalidateItem (1)
InvalidateItem (2)
Invert Filter Effect
InviteParticipant
InviteParticipant Method
InvokeCommand (IContextMenu)
InvokeCommand (IContextMenu2)
InvokeCommand (IUniformResourceLocator)
InvokeEx
InvokeEx (IDispatchEx)
InvokeVerb Method
IObjectSafety::GetInterfaceSafetyOptions
IObjectSafety::SetInterfaceSafetyOptions
IObjectWithSite
IObjectWithSite::GetSite
IObjectWithSite::SetSite
IOleClientSite
IOleCommandTarget::Exec
IOleCommandTarget::QueryStatus
IOleControlSite::TranslateAccelerator
IOleDocument::CreateView
IOleDocument::EnumViews
IOleDocument::GetDocMiscStatus
IOleDocumentSite::ActivateMe
IOleDocumentView::ApplyViewState
IOleDocumentView::Clone
IOleDocumentView::CloseView
IOleDocumentView::GetDocument
IOleDocumentView::GetInPlaceSite
IOleDocumentView::GetRect
IOleDocumentView::Open
IOleDocumentView::SaveViewState
IOleDocumentView::SetInPlaceSite
IOleDocumentView::SetRect
IOleDocumentView::SetRectComplex
IOleDocumentView::Show
IOleDocumentView::UIActivate
IOleInPlaceActiveObject
IOleInPlaceActiveObject::EnableModeless
IOleInPlaceActiveObject::OnDocWindowActivate
IOleInPlaceActiveObject::OnFrameWindowActivate
IOleInPlaceActiveObject::ResizeBorder
IOleInPlaceActiveObject::TranslateAccelerator
IOleInPlaceFrame
IOleInPlaceFrame::EnableModeless
IOleInPlaceFrame::InsertMenus
IOleInPlaceFrame::RemoveMenus
IOleInPlaceFrame::SetMenu
IOleInPlaceFrame::SetStatusText
IOleInPlaceObject
IOleInPlaceObject::InPlaceDeactivate
IOleInPlaceSite
IOleInPlaceSite::OnInPlaceActivate
IOleInPlaceSite::OnUIActivate
IOleInPlaceSite::OnUIDeactivate
IOleInPlaceUIWindow
IOleObject
IOleObject::Advise
IOleObject::DoVerb
IOleObject::GetUserClassID
IOleObject::GetUserType
IOleObject::SetClientSite
IOleWindow
IOleWindow::GetWindow
IOmHistory::back
IOmHistory::forward
IOmHistory::get_length
IOmHistory::go
IOmNavigator::get_appCodeName
IOmNavigator::get_appMinorVersion
IOmNavigator::get_appName
IOmNavigator::get_appVersion
IOmNavigator::get_browserLanguage
IOmNavigator::get_connectionSpeed
IOmNavigator::get_cookieEnabled
IOmNavigator::get_cpuClass
IOmNavigator::get_mimeTypes
IOmNavigator::get_onLine
IOmNavigator::get_opsProfile
IOmNavigator::get_platform
IOmNavigator::get_plugins
IOmNavigator::get_systemLanguage
IOmNavigator::get_userAgent
IOmNavigator::get_userLanguage
IOmNavigator::get_userProfile
IOmNavigator::javaEnabled
IOmNavigator::taintEnabled
IOmNavigator::toString
IPAddress (Member Properties)
IPAddress (User Properties)
IPAddressOp (Member Properties)
IPAddressOp (User Properties)
IParseDisplayName
IParseDisplayName::ParseDisplayName
IPersist
IPersist*
IPersist*::InitNew
IPersist*::Load
IPersist*::Save
IPersist::GetClassID
IPersisteMoniker::Load
IPersistFile
IPersistFile::GetCurFile
IPersistFile::IsDirty
IPersistFile::Load
IPersistFile::Save
IPersistFile::SaveCompleted
IPersistFolder
IPersistFolder::Initialize
IPersistHistory::GetPositionCookie
IPersistHistory::LoadHistory
IPersistHistory::SaveHistory
IPersistHistory::SetPositionCookie
IPersistMemory::Load
IPersistMemory::Save
IPersistMoniker
IPersistMoniker::GetCurMoniker
IPersistMoniker::IsDirty
IPersistMoniker::Load
IPersistMoniker::Save
IPersistMoniker::SaveCompleted
IPersistPropertyBag::InitNew
IPersistPropertyBag::Load
IPersistPropertyBag::Save
IPersistPropertyBag2::InitNew
IPersistPropertyBag2::IsDirty
IPersistPropertyBag2::Load
IPersistPropertyBag2::Save
IPersistStorage
IPersistStorage::InitNew
IPersistStorage::Load
IPersistStream
IPersistStreamInit
IPersistStreamInit::InitNew
IPM_CLEARADDRESS
IPM_GETADDRESS
IPM_ISBLANK
IPM_SETADDRESS
IPM_SETFOCUS
IPM_SETRANGE
IPN_FIELDCHANGED
IPrint::GetPageInfo
IPrint::Print
IPrint::SetInitialPageNum
IPropertyBag::Read
IPropertyBag::Write
IPropertyBag2::CountProperties
IPropertyBag2::GetPropertyInfo
IPropertyBag2::LoadObject
IPropertyBag2::Read
IPropertyBag2::Write
IPropertyNotifySink

* More entries...


Index

IProvideMultipleClassInfo::GetInfoOfIndex
IProvideMultipleClassInfo::GetMultiTypeInfoCount
IProvideTaskPage
IProvideTaskPage::GetPage
IQueryInfo
IQueryInfo::GetInfoFlags
IQueryInfo::GetInfoTip
IReconcilableObject
IReconcilableObject::GetProgressFeedbackMaxEstimate
IReconcilableObject::Reconcile
IReconcileInitiator
IReconcileInitiator::SetAbortCallback
IReconcileInitiator::SetProgressFeedback
ISAPI <definition>
IsAsyncMoniker
ISBEAN
IsBrowsable Property
IScheduledWorkItem
IScheduledWorkItem::CreateTrigger
IScheduledWorkItem::DeleteTrigger
IScheduledWorkItem::EditWorkItem
IScheduledWorkItem::GetAccountInformation
IScheduledWorkItem::GetComment
IScheduledWorkItem::GetCreator
IScheduledWorkItem::GetErrorRetryCount
IScheduledWorkItem::GetErrorRetryInterval
IScheduledWorkItem::GetExitCode
IScheduledWorkItem::GetFlags
IScheduledWorkItem::GetIdleWait
IScheduledWorkItem::GetMostRecentRunTime
IScheduledWorkItem::GetNextRunTime
IScheduledWorkItem::GetRunTimes
IScheduledWorkItem::GetStatus
IScheduledWorkItem::GetTrigger
IScheduledWorkItem::GetTriggerCount
IScheduledWorkItem::GetTriggerString
IScheduledWorkItem::GetWorkItemData
IScheduledWorkItem::Run
IScheduledWorkItem::SetAccountInformation
IScheduledWorkItem::SetComment
IScheduledWorkItem::SetCreator
IScheduledWorkItem::SetErrorRetryCount
IScheduledWorkItem::SetErrorRetryInterval
IScheduledWorkItem::SetFlags
IScheduledWorkItem::SetIdleWait
IScheduledWorkItem::SetWorkItemData
IScheduledWorkItem::Terminate
IsDialogMessage
IsDirty (IPersistMoniker)
IsDirty (IPersistPropertyBag2)
isEqual
isEqual (IHTMLTxtRange)
IServiceProvider
IServiceProvider::QueryService
IServiceProvider::QueryService (The IServiceProvider Interface)
IsFileSystem Property
IsFolder Property
IShellBrowser
IShellBrowser::BrowseObject
IShellBrowser::EnableModelessSB
IShellBrowser::GetControlWindow
IShellBrowser::GetViewStateStream
IShellBrowser::InsertMenusSB
IShellBrowser::OnViewWindowActive
IShellBrowser::QueryActiveShellView
IShellBrowser::RemoveMenusSB
IShellBrowser::SendControlMsg
IShellBrowser::SetMenuSB
IShellBrowser::SetStatusTextSB
IShellBrowser::SetToolbarItems
IShellBrowser::TranslateAcceleratorSB
IShellChangeNotify
IShellExecuteHook
IShellExecuteHook::Execute
IShellExtInit
IShellExtInit::Initialize
IShellFolder
IShellFolder::BindToObject
IShellFolder::BindToStorage
IShellFolder::CompareIDs
IShellFolder::CreateViewObject
IShellFolder::EnumObjects
IShellFolder::GetAttributesOf
IShellFolder::GetDisplayNameOf
IShellFolder::GetUIObjectOf
IShellFolder::ParseDisplayName
IShellFolder::SetNameOf
IShellIcon
IShellIcon::GetIconOf
IShellIconOverlay
IShellIconOverlayIdentifier
IShellLink
IShellLink::GetArguments
IShellLink::GetDescription
IShellLink::GetHotkey
IShellLink::GetIconLocation
IShellLink::GetIDList
IShellLink::GetPath
IShellLink::GetShowCmd
IShellLink::GetWorkingDirectory
IShellLink::Resolve
IShellLink::SetArguments
IShellLink::SetDescription
IShellLink::SetHotkey
IShellLink::SetIconLocation
IShellLink::SetIDList
IShellLink::SetPath
IShellLink::SetRelativePath
IShellLink::SetShowCmd
IShellLink::SetWorkingDirectory
IShellPropSheetExt
IShellPropSheetExt::AddPages
IShellPropSheetExt::ReplacePage
IShellView
IShellView::AddPropertySheetPages
IShellView::CreateViewWindow
IShellView::DestroyViewWindow
IShellView::EnableModeless
IShellView::EnableModelessSV
IShellView::GetCurrentInfo
IShellView::GetItemObject
IShellView::Refresh
IShellView::SaveViewState
IShellView::SelectItem
IShellView::TranslateAccelerator
IShellView::UIActivate
IShellView2
ISINDEX
IsLink Property
IsLoggingEnabled
isMap
ISMAP (IMG)
ISoftDistExt
IsOfType (ITaskScheduler)
IsolationLevel and Mode Properties Example (ADO)
IsolationLevel Property (ADO)
IsSoundCardEnabled Method
isSubscribed
IsSubscribed (ISubscriptionMgr)
IsSubscribed Method
isTextEdit
IStorage
IStorage::CreateStorage
IStorage::CreateStream
IStorage::Stat
IStream
IStream::Read
ISubscriptionMgr
ISubscriptionMgr::CreateSubscription
ISubscriptionMgr::DeleteSubscription
ISubscriptionMgr::GetDefaultInfo
ISubscriptionMgr::GetSubscriptionInfo
ISubscriptionMgr::IsSubscribed
ISubscriptionMgr::ShowSubscriptionProperties
ISubscriptionMgr::UpdateAll
ISubscriptionMgr::UpdateSubscription
IsValidURL
Italic
Italic Command
ITask
ITask::GetApplicationName
ITask::GetMaxRunTime
ITask::GetParameters
ITask::GetPriority
ITask::GetTaskFlags
ITask::GetWorkingDirectory
ITask::SetApplicationName
ITask::SetMaxRunTime
ITask::SetParameters
ITask::SetPriority
ITask::SetTaskFlags
ITask::SetWorkingDirectory
ITaskbarList
ITaskbarList::ActivateTab
ITaskbarList::AddTab
ITaskbarList::DeleteTab
ITaskbarList::HrInit
ITaskbarList::SetActiveAlt
ITaskScheduler
ITaskScheduler::Activate
ITaskScheduler::AddWorkItem
ITaskScheduler::Delete
ITaskScheduler::Enum
ITaskScheduler::GetTargetComputer
ITaskScheduler::IsOfType
ITaskScheduler::NewWorkItem
ITaskScheduler::SetTargetComputer
ITaskTrigger
ITaskTrigger::GetTrigger
ITaskTrigger::GetTriggerString
ITaskTrigger::SetTrigger
item
ITEM (CDF Elements)
Item (Channels Collection Object: Properties)
Item (ChatItems Object: Properties)
item (IHTMLAreasCollection)
item (IHTMLControlRange)
item (IHTMLElementCollection)
item (IHTMLFiltersCollection)
item (IHTMLFontNamesCollection)
item (IHTMLFontSizesCollection)
item (IHTMLFormElement)
item (IHTMLFramesCollection2)
item (IHTMLSelectElement)
item (IHTMLStyleSheetRulesCollection)
item (IHTMLStyleSheetsCollection)
item (IXMLElementCollection)
Item Method (FolderItems Object)
Item Method (FolderItemVerbs Object)
Item Method (ShellWindows Object)
Item method (ADO)
Item Property (Channels Collection Object: Properties)
Item Property (ChatItems Object: Properties)
ITEMIDLIST
Items Method
ItemValid
ItemValid Property
ITMLFrameSetElement::get_onload
ITypeInfo
IUniformResourceLocator::GetURL
IUniformResourceLocator::InvokeCommand
IUniformResourceLocator::SetURL
IUnknown
IUnknown::AddRef
IUnknown::QueryInterface
IUnknown::Release
IURL_SETURL_FLAGS
IURL_SETURL_INVOKECOMMAND_FLAGS
IURLSearchHook
IURLSearchHook::Translate
IViewObject::GetColorSet
IWABObject::AllocateBuffer
IWABObject::AllocateMore
IWABObject::Backup
IWABObject::Find
IWABObject::FreeBuffer
IWABObject::GetLastError
IWABObject::GetMe
IWABObject::Import
IWABObject::LDAPUrl
IWABObject::SetMe

* More entries...


Index

IWABObject::VCardCreate
IWABObject::VCardDisplay
IWABObject::VCardRetrieve
IWebBrowser2::ClientToWindow
IWebBrowser2::ExecWB
IWebBrowser2::get_AddressBar
IWebBrowser2::get_Application
IWebBrowser2::get_Busy
IWebBrowser2::get_Container
IWebBrowser2::get_Document
IWebBrowser2::get_FullName
IWebBrowser2::get_FullScreen
IWebBrowser2::get_Height
IWebBrowser2::get_HWND
IWebBrowser2::get_Left
IWebBrowser2::get_LocationName
IWebBrowser2::get_LocationURL
IWebBrowser2::get_MenuBar
IWebBrowser2::get_Name
IWebBrowser2::get_Offline
IWebBrowser2::get_Parent
IWebBrowser2::get_Path
IWebBrowser2::get_ReadyState
IWebBrowser2::get_RegisterAsBrowser
IWebBrowser2::get_RegisterAsDropTarget
IWebBrowser2::get_Resizable
IWebBrowser2::get_Silent
IWebBrowser2::get_StatusBar
IWebBrowser2::get_StatusText
IWebBrowser2::get_TheaterMode
IWebBrowser2::get_ToolBar
IWebBrowser2::get_Top
IWebBrowser2::get_TopLevelContainer
IWebBrowser2::get_Type
IWebBrowser2::get_Visible
IWebBrowser2::get_Width
IWebBrowser2::GetProperty
IWebBrowser2::GoBack
IWebBrowser2::GoForward
IWebBrowser2::GoHome
IWebBrowser2::GoSearch
IWebBrowser2::Navigate
IWebBrowser2::Navigate2
IWebBrowser2::PutProperty
IWebBrowser2::QueryStatusWB
IWebBrowser2::Quit
IWebBrowser2::Refresh
IWebBrowser2::Refresh2
IWebBrowser2::ShowBrowserBar
IWebBrowser2::Stop
IWindowForBindingUI
IWindowForBindingUI::GetWindow
IWinInetHttpInfo
IWinInetHttpInfo::QueryInfo
IWinInetInfo
IWinInetInfo::QueryOption
IXMLDocument
IXMLDocument::createElement
IXMLDocument::get_charset
IXMLDocument::get_doctype
IXMLDocument::get_fileModifiedDate
IXMLDocument::get_fileSize
IXMLDocument::get_fileUpdatedDate
IXMLDocument::get_mimeType
IXMLDocument::get_readyState
IXMLDocument::get_root
IXMLDocument::get_URL
IXMLDocument::get_version
IXMLElement
IXMLElement::addChild
IXMLElement::get_Attribute
IXMLElement::get_children
IXMLElement::get_parent
IXMLElement::get_tagName
IXMLElement::get_text
IXMLElement::get_type
IXMLElement::removeAttribute
IXMLElement::removeChild
IXMLElement::setAttribute
IXMLElementCollection
IXMLElementCollection::get_length
IXMLElementCollection::get_newEnum
IXMLElementCollection::item


Index

!-- --
!DOCTYPE
!important
?XML
@font-face
@import
_NewEnum Method (FolderItems Object)
_NewEnum Method (FolderItemVerbs Object)
_NewEnum Method (ShellWindows Object)

A Button
A (CDF Reference for Active Channels: CDF Elements)
A (HTML Elements)
A (Objects)
ABM_ACTIVATE
ABM_GETAUTOHIDEBAR
ABM_GETSTATE
ABM_GETTASKBARPOS
ABM_NEW
ABM_QUERYPOS
ABM_REMOVE
ABM_SETAUTOHIDEBAR
ABM_SETPOS
ABM_WINDOWPOSCHANGED
ABN_FULLSCREENAPP
ABN_POSCHANGED
ABN_STATECHANGE
ABN_WINDOWARRANGE
Abort (IABTable)
Abort (IBinding)
Abort (IInternetProtocolRoot)
AboutBox (Methods)
AboutBox (MsChatPr Object: Methods)
AboutBox (The File Upload Control Interface)
AboutBox Method (Control Methods)
AboutBox Method (Methods)
AboutBox Method (MsChatPr Object: Methods)
AbsolutePage Property (ADO)
AbsolutePage, PageCount, and PageSize Properties Example (ADO)
AbsolutePosition and CursorLocation Properties Example (ADO)
AbsolutePosition Property (ADO)
ABSTRACT
ACCELERATEABSDI
accessKey
ACCESSKEY= (A)
ACCESSKEY= (BUTTON)
ACCESSKEY= (INPUT)
ACCESSKEY= (LABEL)
ACCESSKEY= (OBJECT)
ACCESSKEY= (SELECT)
ACCESSKEY= (TEXTAREA)
Account
ACM_OPEN
ACM_PLAY
ACM_STOP
ACN_START
ACN_STOP
ACRONYM (HTML Elements)
ACRONYM (Objects)
ACS_AUTOPLAY
ACS_CENTER
ACS_TIMER
ACS_TRANSPARENT
action
ACTION= (DEPENDENCY)
ACTION= (FORM)
Activate (ITaskScheduler)
ActivateMe (IOleDocumentSite)
ActivateTab (ITaskbarList)
active
Active Channels, Tasks
Active Desktop
Active Desktop, Tasks
Active Documents, Tasks
Active Script Debugging API
ActiveConnection Property (ADO)
ActiveConnection, CommandText, CommandTimeout, CommandType, Size, and Direction Properties Example (ADO)
activeElement
ActiveX <definition>
ActiveX control <definition>
ActiveX Controls, Tasks
ActiveX Scripting, Tasks
ActualSize and DefinedSize Properties Example (ADO)
ActualSize Property (ADO)
AD_APPLY_ALL
AD_APPLY_BUFFERED_REFRESH
AD_APPLY_FORCE
AD_APPLY_HTMLGEN
AD_APPLY_REFRESH
AD_APPLY_SAVE
add
Add (Methods)
add (IHTMLAreasCollection)
add (IHTMLControlRange)
add (IHTMLSelectElement)
Add Code to Move through the Displayed Recordset
Add Code to Send a Query to the Database
Add Code to Submit Changes to the Database
Add HTML Controls
Add Method
AddAmbient Method
AddCategory (IChannelMgr)
addChannel
AddChannel Method
AddChannelShortcut (IChannelMgr)
addChild (IXMLElement)
AddCone Method
AddDesktopComponent Method
AddDesktopItem (IActiveDesktop)
AddDesktopItemWithUI (IActiveDesktop)
AddError (IErrorLog)
AddFavorite Method
addFilter (IHTMLControlElement)
addImport
addImport (IHTMLStyleSheet)
Adding Document Content
Adding Scriptlets to Your Application
AddItem
AddNamedItem (IActiveScript)
AddNew Method (ADO)
AddNew Method Example (ADO)
AddPages (IShellPropSheetExt)
AddPoint Method
AddPropertySheetPages (IShellView)
AddPropSheetPageProc
addReadRequest
addReadRequest (IHTMLOpsProfile)
AddRef
ADDRESS (HTML Elements)
ADDRESS (Objects)
Address (IAddrBook)
Address Book Command Buttons
Address Book Data Grid
Address Book Data-Binding Object
Address Book Example: Running the Address Book Sample Application
Address Book Example: Running the Address Book SQL Script
Address Book Example: Setting Up an ODBC Connection for Address Book
Address Book Example: Source Code
Address Book Navigation Buttons
Address Book Sample Application Code Overview
Address Book Text Boxes
Address Book: VBScript Initialization Code
AddressBar
AddressBar Property
addRule
addRule (IHTMLStyleSheet)
AddScriptlet (IActiveScriptParse)
AddTab (ITaskbarList)
AddToolbar (IDockingWindowFrame)
AddTypeLib (IActiveScript)
AddUrl (IActiveDesktop)
AddWizardPages
AddWorkItem (ITaskScheduler)
ADISAPI <definition>
ADO Code Examples
ADO Collections
ADO Error Codes
ADO Methods
ADO Object Model
ADO Objects
ADO Overview
ADO Properties
ADRENTRY
ADRLIST
ADRPARM
Advanced Topics
AdvancedDataControl object <definition>
AdvancedDataFactory object <definition>
AdvancedDataSpace object <definition>
Advise (IABTable)
Advise (IAddrBook)
alert
alert (IHTMLWindow2)
alias <definition>
align (Properties: 1)
align (Properties: 2)
align (Properties: 3)
align (Properties: 4)
ALIGN= (APPLET)
ALIGN= (CAPTION)
ALIGN= (COL)
ALIGN= (COLGROUP)
ALIGN= (DIV)
ALIGN= (EMBED)
ALIGN= (FIELDSET)
ALIGN= (Hn)
ALIGN= (HR)
ALIGN= (IFRAME)
ALIGN= (IMG)
ALIGN= (INPUT)
ALIGN= (LEGEND)
ALIGN= (LISTING)
ALIGN= (OBJECT)
ALIGN= (P)
ALIGN= (SELECT)
ALIGN= (TABLE)
ALIGN= (TBODY)
ALIGN= (TD)
ALIGN= (TEXTAREA)
ALIGN= (TFOOT)
ALIGN= (TH)
ALIGN= (THEAD)
ALIGN= (TR)
aLink
ALINK=
alinkColor
all
AllocateBuffer (IWABObject)
AllocateMore (IWABObject)
AllowChangeDisplayMode Property
AllowHideControls Property
AllowHideDisplay Property
Alpha Filter Effect
alt
ALT= (APPLET)
ALT= (AREA)
ALT= (EMBED)
ALT= (IMG)
ALT= (INPUT)
altHTML
altKey
anchors
Animate_Close
Animate_Create
Animate_Open
Animate_OpenEx
Animate_Play
Animate_Seek
Animate_Stop
AnonymousAllowed
apartment thread <definition>
APPBARDATA
appCodeName
Appearance
Appearance Property (Control Properties)
Appearance Property (Properties)
Append and CreateParameter Methods Example (ADO)
Append Method (ADO)
AppendChunk and GetChunk Methods Example (ADO)
AppendChunk Method (ADO)
AppendData
Appendixes (Remote Data Service Developer's Guide)
Appendixes, Remote Data Service Reference
APPLET (HTML Elements)
APPLET (Objects)
applets
Application
Application Property (Folder Object)
Application Property (FolderItem Object)
Application Property (FolderItems Object)
Application Property (FolderItemVerb Object)
Application Property (FolderItemVerbs Object)
Application Property (Properties)
Application Property (Shell Object)
Application Property (ShellFolderView Object)
Apply Method
ApplyChanges (IActiveDesktop)
ApplyViewState (IOleDocumentView)
appMinorVersion
appName
appVersion
AREA (HTML Elements)
AREA (Objects)
areas
assign
assign (IHTMLLocation)
AssociatedType
AssociatedType Property
Asynchronous Monikers
Attributes and Name Properties Example (ADO)
Attributes Property (ADO)
Authenticate (IAuthenticate)
Authentication, Tasks
Authenticode
AUTOINSTALL=
AutoRewind Property
AutoStart Property
availHeight
availWidth
Away

* More entries...


Index

B Button
B (HTML Elements)
B (Objects)
back
back (IOmHistory)
BackColor (Command Identifiers Reference)
BackColor (Properties)
BackColor Command
BackColor Property
background (CSS Attributes)
background (Properties: 1)
background (Properties: 2)
background (Properties: 3)
BACKGROUND= (BODY)
BACKGROUND= (TABLE)
BACKGROUND= (TD)
BACKGROUND= (TH)
backgroundAttachment
background-attachment
backgroundColor
background-color
backgroundImage
background-image
backgroundPosition
background-position
backgroundPositionX
backgroundPositionY
backgroundRepeat
background-repeat
Backup (IWABObject)
balance
Balance Property
BALANCE=
BanMembers
BanMembers Method
BannedList
BanParticipant
BanParticipant Method
BanUsers
BanUsers Method
BASE (HTML Elements)
BASE (Objects)
BASE=
BASEFONT (HTML Elements)
BASEFONT (Objects)
BeforeNavigate2
BeforeNavigate2 (DWebBrowserEvents2)
BeforeNavigate2 Event
BeginningTransaction (IHttpNegotiate)
BeginTrans, CommitTrans, and RollbackTrans Methods (ADO)
BeginTrans, CommitTrans, and RollbackTrans Methods Example (ADO)
behavior
BEHAVIOR=
bgColor (Properties: 1)
bgColor (Properties: 2)
BGCOLOR= (BODY)
BGCOLOR= (MARQUEE)
BGCOLOR= (TABLE)
BGCOLOR= (TBODY)
BGCOLOR= (TD)
BGCOLOR= (TFOOT)
BGCOLOR= (TH)
BGCOLOR= (THEAD)
BGCOLOR= (TR)
bgProperties
BGPROPERTIES=
BGSOUND (HTML Elements)
BGSOUND (Objects)
BIG (HTML Elements)
BIG (Objects)
BINDF
BINDF_ASYNCHRONOUS
BINDF_ASYNCSTORAGE
BINDF_DIRECT_READ
BINDF_FORMS_SUBMIT
BINDF_FREE_THREADED
BINDF_GETFROMCACHE_IF_NET_FAIL
BINDF_GETNEWESTVERSION
BINDF_HYPERLINK
BINDF_IGNORESECURITYPROBLEM
BINDF_NEEDFILE
BINDF_NO_UI
BINDF_NOPROGRESSIVERENDERING
BINDF_NOWRITECACHE
BINDF_OFFLINEOPERATION
BINDF_PRAGMA_NO_CACHE
BINDF_PULLDATA
BINDF_RESYNCHRONIZE
BINDF_SILENTOPERATION
BINDINFO
BINDINFOF
BINDINFOF_URLENCODEDEXTRAINFO
BINDINFOF_URLENCODESTGMEDDATA
BINDSTATUS
BINDSTATUS_BEGINDOWNLOADCOMPONENTS
BINDSTATUS_BEGINDOWNLOADDATA
BINDSTATUS_BEGINSYNCOPERATION
BINDSTATUS_BEGINUPLOADDATA
BINDSTATUS_CACHEFILENAMEAVAILABLE
BINDSTATUS_CLASSIDAVAILABLE
BINDSTATUS_CLASSINSTALLLOCATION
BINDSTATUS_CONNECTING
BINDSTATUS_DECODING
BINDSTATUS_DOWNLOADINGDATA
BINDSTATUS_ENCODING
BINDSTATUS_ENDDOWNLOADCOMPONENTS
BINDSTATUS_ENDDOWNLOADDATA
BINDSTATUS_ENDSYNCOPERATION
BINDSTATUS_ENDUPLOADINGDATA
BINDSTATUS_FINDINGRESOURCE
BINDSTATUS_INSTALLINGCOMPONENTS
BINDSTATUS_MIMETYPEAVAILABLE
BINDSTATUS_PROTOCOLCLASSID
BINDSTATUS_REDIRECTING
BINDSTATUS_SENDINGREQUEST
BINDSTATUS_UPLOADINGDATA
BINDSTATUS_USINGCACHEDCOPY
BINDSTATUS_VERFIEDMIMETYPEAVAILABLE
BINDSTRING
BINDSTRING_ACCEPT_ENCODINGS
BINDSTRING_ACCEPT_MIMES
BINDSTRING_EXTRA_URL
BINDSTRING_HEADERS
BINDSTRING_LANGUAGE
BINDSTRING_OS
BINDSTRING_PASSWORD
BINDSTRING_POST_COOKIE
BINDSTRING_POST_DATA_MIME
BINDSTRING_UA_COLOR
BINDSTRING_UA_PIXELS
BINDSTRING_URL
BINDSTRING_USERAGENT
BINDSTRING_USERNAME
BindToObject (IShellFolder)
BindToStorage (IShellFolder)
BINDVERB
BINDVERB_CUSTOM
BINDVERB_GET
BINDVERB_POST
BINDVERB_PUT
Blend Transition Filter
BLOCKQUOTE (HTML Elements)
BLOCKQUOTE (Objects)
blur
blur (IHTMLAnchorElement)
blur (IHTMLAreaElement)
blur (IHTMLControlElement)
blur (IHTMLWindow2)
Blur Filter Effect
BODY (HTML Elements)
BODY (Objects)
BOF, EOF Properties (ADO)
BOF, EOF, and Bookmark Properties Example (ADO)
Bold
Bold Command
Bookmark Property (ADO)
border (CSS Attributes)
border (Properties: 1)
border (Properties: 2)
border (Properties: 3)
BORDER= (FRAMESET)
BORDER= (IFRAME)
BORDER= (IMG)
BORDER= (TABLE)
borderBottom
border-bottom
borderBottomColor
border-bottom-color
borderBottomStyle
border-bottom-style
borderBottomWidth
border-bottom-width
borderColor (Properties: 1)
borderColor (Properties: 2)
border-color
BORDERCOLOR= (FRAME)
BORDERCOLOR= (FRAMESET)
BORDERCOLOR= (IFRAME)
BORDERCOLOR= (TABLE)
BORDERCOLOR= (TD)
BORDERCOLOR= (TH)
BORDERCOLOR= (TR)
borderColorDark
BORDERCOLORDARK= (TABLE)
BORDERCOLORDARK= (TD)
BORDERCOLORDARK= (TH)
BORDERCOLORDARK= (TR)
borderColorLight
BORDERCOLORLIGHT= (TABLE)
BORDERCOLORLIGHT= (TD)
BORDERCOLORLIGHT= (TH)
BORDERCOLORLIGHT= (TR)
borderLeft
border-left
borderLeftColor
border-left-color
borderLeftStyle
border-left-style
borderLeftWidth
border-left-width
borderRight
border-right
borderRightColor
border-right-color
borderRightStyle
border-right-style
borderRightWidth
border-right-width
borderStyle
BorderStyle (Properties)
border-style
BorderStyle Property (Control Properties)
BorderStyle Property (Properties)
borderTop
border-top
borderTopColor
border-top-color
borderTopStyle
border-top-style
borderTopWidth
border-top-width
borderWidth
border-width
BORDERWIDTHS
bottomMargin
BOTTOMMARGIN=
boundingHeight
boundingLeft
boundingTop
boundingWidth
BR (HTML Elements)
BR (Objects)
BrowseCallbackProc
BrowseForFolder Method
BROWSEINFO
BrowseObject (IShellBrowser)
browserLanguage
BrowserNavConstants
BSCF
BSCF_AVAILABLEDATASIZEUNKNOWN
BSCF_DATAFULLYAVAILABLE
BSCF_FIRSTDATANOTIFICATION
BSCF_INTERMEDIATEDATANOTIFICATION
BSCF_LASTDATANOTIFICATION
BSTR
bubbleEvent Method
bufferDepth
Building a Simple Remote Data Service Application
business object <definition>
business rule <definition>
Busy
Busy Property
BUTTON (HTML Elements)
BUTTON (Objects: 1)
button (Objects: 2)
button (Properties: 1)
button (Properties: type: 2)

C Button
Cabinet (CAB) Files, Tasks to CloseView (IOleDocumentView)
CLSCTX to ctrlKey
CurrentPosition Property to cvtToUTF8

D Button
DAILY to DTN_CLOSEUP
DTN_DATETIMECHANGE to DYNSRC=

* More entries...


Index

E Button
EARLIESTTIME
EditMode Property (ADO)
EditWorkItem (IScheduledWorkItem)
EjectPC Method
Element Collections
elementFromPoint
elementFromPoint (IHTMLDocument2)
elements
EM (HTML Elements)
EM (Objects)
EM_LIMITTEXT
EM_SETLIMITTEXT
EMBED (HTML Elements)
EMBED (Objects)
embeds
empty
empty (IHTMLSelectionObject)
EN_KILLFOCUS
EN_UPDATE
EnableContextMenu Property
enabled
Enabled Property
EnableModeless (IActiveScriptSiteWindow)
EnableModeless (IDocHostUIHandler)
EnableModeless (IInternetSecurityMgrSite)
EnableModeless (IShellView)
EnableModelessSB (IShellBrowser)
EnableModelessSV (IShellView)
EnablePositionControls Property
EnableScrollBar
EnableSelectionControls Property
EnableTracker Property
encoding
ENCODING=
ENCTYPE=
ENDDATE=
EndDialog
EnterRoom
EnterRoom Method
ENTRYID
ENTRYLIST
Enum (ITaskScheduler)
enumChannelMode
enumChannelMode Enumeration
EnumChannels (IChannelMgr)
enumChannelState
enumChannelState Enumeration
enumConnectionState
enumConnectionState Enumeration
enumConnectionType
enumConnectionType Enumeration
enumConversionSource
enumConversionSource Enumeration
enumConversionType
enumConversionType Enumeration
enumEnumType
enumEnumType Enumeration
enumMemberMode
enumMemberMode Enumeration
enumMessageType
enumMessageType Enumeration
EnumNavigationStack
EnumNavigationStack (IHlinkBrowseContext)
EnumObjects (IShellFolder)
enumPrivateMessageType
enumPrivateMessageType Enumeration
enumServerMessageType
enumServerMessageType Enumeration
enumStringType
enumStringType Enumeration
enumUserMode
enumUserMode Enumeration
EnumViews (IOleDocument)
Error Codes
Error Event
Error Object (ADO)
ERROR_FTP_DROPPED
ERROR_FTP_TRANSFER_IN_PROGRESS
ERROR_GOPHER_ATTRIBUTE_NOT_FOUND
ERROR_GOPHER_DATA_ERROR
ERROR_GOPHER_END_OF_DATA
ERROR_GOPHER_INCORRECT_LOCATOR_TYPE
ERROR_GOPHER_INVALID_LOCATOR
ERROR_GOPHER_NOT_FILE
ERROR_GOPHER_NOT_GOPHER_PLUS
ERROR_GOPHER_PROTOCOL_ERROR
ERROR_GOPHER_UNKNOWN_LOCATOR
ERROR_HTTP_DOWNLEVEL_SERVER
ERROR_HTTP_HEADER_ALREADY_EXISTS
ERROR_HTTP_HEADER_NOT_FOUND
ERROR_HTTP_INVALID_HEADER
ERROR_HTTP_INVALID_QUERY_REQUEST
ERROR_HTTP_INVALID_SERVER_RESPONSE
ERROR_HTTP_REDIRECT_FAILED
ERROR_HTTP_REDIRECT_NEEDS_CONFIRMATION
ERROR_INSUFFICIENT_BUFFER
ERROR_INTERNET_ASYNC_THREAD_FAILED
ERROR_INTERNET_BAD_AUTO_PROXY_SCRIPT
ERROR_INTERNET_BAD_OPTION_LENGTH
ERROR_INTERNET_BAD_REGISTRY_PARAMETER
ERROR_INTERNET_CANNOT_CONNECT
ERROR_INTERNET_CHG_POST_IS_NON_SECURE
ERROR_INTERNET_CLIENT_AUTH_CERT_NEEDED
ERROR_INTERNET_CLIENT_AUTH_NOT_SETUP
ERROR_INTERNET_CONNECTION_ABORTED
ERROR_INTERNET_CONNECTION_RESET
ERROR_INTERNET_DIALOG_PENDING
ERROR_INTERNET_DISCONNECTED
ERROR_INTERNET_EXTENDED_ERROR
ERROR_INTERNET_FAILED_DUETOSECURITYCHECK
ERROR_INTERNET_FORCE_RETRY
ERROR_INTERNET_HANDLE_EXISTS
ERROR_INTERNET_HTTP_TO_HTTPS_ON_REDIR
ERROR_INTERNET_HTTPS_TO_HTTP_ON_REDIR
ERROR_INTERNET_INCORRECT_FORMAT
ERROR_INTERNET_INCORRECT_HANDLE_STATE
ERROR_INTERNET_INCORRECT_HANDLE_TYPE
ERROR_INTERNET_INCORRECT_PASSWORD
ERROR_INTERNET_INCORRECT_USER_NAME
ERROR_INTERNET_INSERT_CDROM
ERROR_INTERNET_INTERNAL_ERROR
ERROR_INTERNET_INVALID_CA
ERROR_INTERNET_INVALID_OPERATION
ERROR_INTERNET_INVALID_OPTION
ERROR_INTERNET_INVALID_PROXY_REQUEST
ERROR_INTERNET_INVALID_URL
ERROR_INTERNET_ITEM_NOT_FOUND
ERROR_INTERNET_LOGIN_FAILURE
ERROR_INTERNET_MIXED_SECURITY
ERROR_INTERNET_NAME_NOT_RESOLVED
ERROR_INTERNET_NEED_UI
ERROR_INTERNET_NO_CALLBACK
ERROR_INTERNET_NO_CONTEXT
ERROR_INTERNET_NO_DIRECT_ACCESS
ERROR_INTERNET_NOT_PROXY_REQUEST
ERROR_INTERNET_OFFLINE
ERROR_INTERNET_OPERATION_CANCELLED
ERROR_INTERNET_OPTION_NOT_SETTABLE
ERROR_INTERNET_OUT_OF_HANDLES
ERROR_INTERNET_POST_IS_NON_SECURE
ERROR_INTERNET_PROTOCOL_NOT_FOUND
ERROR_INTERNET_PROXY_SERVER_UNREACHABLE
ERROR_INTERNET_REDIRECT_SCHEME_CHANGE
ERROR_INTERNET_REGISTRY_VALUE_NOT_FOUND
ERROR_INTERNET_REQUEST_PENDING
ERROR_INTERNET_SEC_CERT_CN_INVALID
ERROR_INTERNET_SEC_CERT_DATE_INVALID
ERROR_INTERNET_SEC_CERT_REVOKED
ERROR_INTERNET_SEC_INVALID_CERT
ERROR_INTERNET_SECURITY_CHANNEL_ERROR
ERROR_INTERNET_SERVER_UNREACHABLE
ERROR_INTERNET_SHUTDOWN
ERROR_INTERNET_TCPIP_NOT_INSTALLED
ERROR_INTERNET_TIMEOUT
ERROR_INTERNET_UNABLE_TO_CACHE_FILE
ERROR_INTERNET_UNABLE_TO_DOWNLOAD_SCRIPT
ERROR_INTERNET_UNRECOGNIZED_SCHEME
ERROR_INVALID_HANDLE
ERROR_NO_MORE_FILES
ERROR_NO_MORE_ITEMS
Errors Collection (ADO)
EscapeChar
etChannels
etChannelsTruncated
etInitialMembers
etMembers
etMessageOfTheDay
etUsers
event (Objects)
event (Properties)
event Property
EVENT=
Example: Building a Table of Contents
EXCEPINFO
Exec (IOleCommandTarget)
execCommand
execCommand (IHTMLControlRange)
execCommand (IHTMLDocument2)
execCommand (IHTMLTxtRange)
execCommandShowHelp (IHTMLControlRange)
execCommandShowHelp (IHTMLDocument2)
execCommandShowHelp (IHTMLTxtRange)
execScript
execScript (IHTMLWindow2)
Execute (IShellExecuteHook)
Execute method (Command - ADO)
Execute method (Connection - ADO)
Execute, Requery, and Clear Methods Example (ADO)
ExecuteOptions and FetchOptions Properties Example
ExecuteOptions Property
ExecWB
ExecWB (IWebBrowser2)
ExecWB Method
ExitProgman
ExitRoom
ExitRoom Method
ExitWindowsEx
expand
expand (IHTMLTxtRange)
expando
ExpandRow (IABTable)
Explore Method
EXT_BUTTON
Extensible Markup Language (XML), Tasks
ExtensionPropSheetPageProc
external
Extract (IExtractIcon)
ExtractAssociatedIcon
ExtractIcon
ExtractIconEx

* More entries...


Index

F Button
face
FACE= (BASEFONT)
FACE= (FONT)
FAILED
FContinue (IContinueCallback)
FContinuePrinting (IContinueCallback)
FD_FLAGS
FetchOptions Property
fgColor
Field Object (ADO)
FieldDelim
Fields Collection (ADO)
FIELDSET (HTML Elements)
FIELDSET (Objects)
file
file (type)
File Transfer Protocol (FTP), Tasks
fileCreatedDate
FILEDESCRIPTOR
FILEGROUPDESCRIPTOR
fileModifiedDate
FileName Property
FILENAME= (CODEBASE)
FILENAME= (ICON)
FileRun Method
fileSize
FILETIME
fileUpdatedDate
filter (CSS Attributes)
Filter (Microsoft Tabular Data Control Reference: Properties)
filter (Properties)
Filter and RecordCount Properties Example (ADO)
Filter Property (ADO)
FilterColumn Property
FilterColumn, FilterCriterion, FilterValue, SortColumn, and SortDirection Properties and Reset Method Example
FilterCriterion Property
FilterDataObject (IDocHostUIHandler)
FilterGraph Property
FilterGraphDispatch Property
filters
Filters and Transitions
FilterValue Property
Find (IWABObject)
FindClose
FindCloseUrlCache
FindComputer Method
FindExecutable
FindFiles Method
FindFirstChangeNotification
FindFirstFile
FindFirstFile (The Web Publishing SPI)
FindFirstUrlCacheEntry
FindFirstUrlCacheEntryEx
FindMediaType
FindMediaTypeClass
FindMimeFromData
FindNextFile
FindNextUrlCacheEntry
FindNextUrlCacheEntryEx
FindResource
FindRow (IABTable)
findText
findText (IHTMLTxtRange)
FindToolbar (IDockingWindowFrame)
FindWindow
FireOnFilterChangeEvent (ICSSFilterSite)
FIRST_IPADDRESS
FlashWindow
FlatSB_EnableScrollBar
FlatSB_GetScrollInfo
FlatSB_GetScrollPos
FlatSB_GetScrollProp
FlatSB_GetScrollRange
FlatSB_SetScrollInfo
FlatSB_SetScrollPos
FlatSB_SetScrollProp
FlatSB_SetScrollRange
FlatSB_ShowScrollBar
Flip Horizontal Filter Effect
Flip Vertical Filter Effect
float
FM_GETDRIVEINFO
FM_GETFILESEL
FM_GETFILESELLFN
FM_GETFOCUS
FM_GETSELCOUNT
FM_GETSELCOUNTLFN
FM_REFRESH_WINDOWS
FM_RELOAD_EXTENSIONS
FMEVENT_HELPMENUITEM
FMEVENT_HELPSTRING
FMEVENT_INITMENU
FMEVENT_LOAD
FMEVENT_SELCHANGE
FMEVENT_TOOLBARLOAD
FMEVENT_UNLOAD
FMEVENT_USER_REFRESH
FMExtensionProc
FMS_GETDRIVEINFO
FMS_GETFILESEL
FMS_LOAD
FMS_TOOLBARLOAD
focus
focus (IHTMLAnchorElement)
focus (IHTMLAreaElement)
focus (IHTMLControlElement)
focus (IHTMLWindow2)
FocusedItem Property
Folder Property
FOLDERFLAGS
FOLDERSETTINGS
FOLDERVIEWMODE
font (CSS Attributes)
FONT (HTML Elements)
FONT (Objects)
font (Properties)
Font Download
fontFamily
font-family
FontName
FontName Command
fontSize
FontSize (Command Identifiers Reference)
font-size
FontSize Command
fontSmoothingEnabled
fontStyle
font-style
fontVariant
font-variant
fontWeight
font-weight
FOR= (LABEL)
FOR= (SCRIPT)
ForeColor
ForeColor Command
FORM (HTML Elements)
FORM (Objects)
form (Properties)
FormatBlock
FormatBlock Command
FORMATETC
FormatMessage
forms
forward
forward (IOmHistory)
FORWARD_WM_NOTIFY
FoundPostInfo
FOURTH_IPADDRESS
FRAME (HTML Elements)
FRAME (Objects)
frame (Properties)
FRAME=
frameBorder
FRAMEBORDER= (FRAME)
FRAMEBORDER= (FRAMESET)
FRAMEBORDER= (IFRAME)
frames
FRAMESET (HTML Elements)
FRAMESET (Objects)
frameSpacing
FRAMESPACING= (FRAMESET)
FRAMESPACING= (IFRAME)
FreeBookmark (IABTable)
FreeBuffer (IWABObject)
FreeLibrary
fromElement
frozen Property
FtpCreateDirectory
FtpDeleteFile
FtpFindFirstFile
FtpGetCurrentDirectory
FtpGetFile
FtpOpenFile
FtpPutFile
FtpRemoveDirectory
FtpRenameFile
FtpSetCurrentDirectory
FullName
FullName Property
FullScreen
fullscreen (open)
FullScreen Property
FullScreenMode Property
FVSHOWINFO

G Button
GenerateDesktopItemHtml (IActiveDesktop) to get_dialogLeft (IHTMLDialog)
get_dialogTop (IHTMLDialog) to get_name (IHTMLFrameSetElement)
get_name (IHTMLImgElement) to get_rightMargin (IHTMLBodyElement)
get_root (IXMLDocument) to getBookmark (IHTMLTxtRange)
GetBorderDW (IDockingWindowSite) to GopherGetAttribute
GopherGetLocatorType to Grayscale Filter Effect

* More entries...


Index

H Button
H1
H2
H3
H4
H5
H6
HANDLE_WM_NOTIFY
HandleMenuMsg (IContextMenu2)
HandleMenuMsg2 (IContextMenu3)
Handling Standard Events
HasFocusIO (IInputObject)
hash
HD_HITTESTINFO
HD_ITEM
HD_LAYOUT
HD_NOTIFY
HDHITTESTINFO
HDITEM
HDLAYOUT
HDM_CREATEDRAGIMAGE
HDM_DELETEITEM
HDM_GETIMAGELIST
HDM_GETITEM
HDM_GETITEMCOUNT
HDM_GETITEMRECT
HDM_GETORDERARRAY
HDM_GETUNICODEFORMAT
HDM_HITTEST
HDM_INSERTITEM
HDM_LAYOUT
HDM_ORDERTOINDEX
HDM_SETHOTDIVIDER
HDM_SETIMAGELIST
HDM_SETITEM
HDM_SETORDERARRAY
HDM_SETUNICODEFORMAT
HDN_BEGINDRAG
HDN_BEGINTRACK
HDN_DIVIDERDBLCLICK
HDN_ENDDRAG
HDN_ENDTRACK
HDN_GETDISPINFO
HDN_ITEMCHANGED
HDN_ITEMCHANGING
HDN_ITEMCLICK
HDN_ITEMDBLCLICK
HDN_TRACK
HDS_BUTTONS
HDS_DRAGDROP
HDS_FULLDRAG
HDS_HIDDEN
HDS_HORZ
HDS_HOTTRACK
HEAD (HTML Elements)
HEAD (Objects)
Header_CreateDragImage
Header_DeleteItem
Header_GetImageList
Header_GetItem
Header_GetItemCount
Header_GetItemRect
Header_GetOrderArray
Header_GetUnicodeFormat
Header_InsertItem
Header_Layout
Header_OrderToIndex
Header_SetHotDivider
Header_SetImageList
Header_SetItem
Header_SetOrderArray
Header_SetUnicodeFormat
HEIGHT (CDF Extensions for Active Desktop Items)
height (CSS Attributes)
height (Methods: open)
Height (Microsoft Chat Control 1.1 Visual Basic Reference: Properties)
height (Properties: 1)
height (Properties: 2)
height (Properties: 3)
Height (Reusing the WebBrowser Control: Reference for Visual Basic Developers: Properties)
Height Property
Height Property (Properties)
HEIGHT= (APPLET)
HEIGHT= (EMBED)
HEIGHT= (FRAME)
HEIGHT= (IFRAME)
HEIGHT= (IMG)
HEIGHT= (MARQUEE)
HEIGHT= (OBJECT)
HEIGHT= (TABLE)
Help Method
HelpContext, HelpFile Properties (ADO)
HELPINFO
HELPWININFO
hidden (Objects)
Hidden (Properties: 1)
hidden (Properties: type: 2)
HideUI (IDocHostUIHandler)
history
History (Properties)
History Property
HIT_LOGGING_INFO
HKEY_TYPE
HKM_GETHOTKEY
HKM_SETHOTKEY
HKM_SETRULES
HLBWIF
HLBWINFO
HLFNAMEF
HLID
HlinkCreateBrowseContext
HlinkCreateFromData
HlinkCreateFromMoniker
HlinkCreateFromString
HLINKGETREF
HlinkGetSpecialReference
HlinkGoBack
HlinkGoForward
HLINKMISC
HlinkNavigate
HlinkNavigateMoniker
HlinkNavigateString
HlinkNavigateToStringReference
HlinkOnNavigate
HlinkQueryCreateFromData
HLINKSETF
HlinkSetSpecialReference
HlinkSimpleNavigateToMoniker
HlinkSimpleNavigateToString
HLINKWHICHMK
HLITEM
HLNF
HLQF
HLSR
Hn
host
HostInChannels
HostKey
hostname
HOUR= (EARLIESTTIME)
HOUR= (INTERVALTIME)
HOUR= (LATESTTIME)
HOUR= (PURGETIME)
hover
HR (HTML Elements)
HR (Objects)
href (Properties: 1)
href (Properties: 2)
href (Properties: 3)
href (Properties: 4)
HREF= (A)
HREF= (AREA)
HREF= (BASE)
HREF= (CDF Extensions for Software Update Channels: CDF Elements: CODEBASE: 1)
HREF= (CDF Extensions for Software Update Channels: CDF Elements: SOFTPKG: 2)
HREF= (CDF Reference for Active Channels: CDF Elements: A: 1)
HREF= (CDF Reference for Active Channels: CDF Elements: CHANNEL: 2)
HREF= (CDF Reference for Active Channels: CDF Elements: ITEM: 3)
HREF= (CDF Reference for Active Channels: CDF Elements: LOGO: 4)
HREF= (CDF Reference for Active Channels: CDF Elements: LOGTARGET: 5)
HREF= (LINK)
HRESULT
HrInit (ITaskbarList)
hspace
HSPACE= (APPLET)
HSPACE= (EMBED)
HSPACE= (IFRAME)
HSPACE= (IMG)
HSPACE= (MARQUEE)
HTML (HTML Elements)
HTML (Objects)
HTML Framework for Address Book
htmlFor (Properties: 1)
htmlFor (Properties: 2)
HTMLHelp API Reference
htmlText
HTTP Status Codes
HTTP_STATUS_ACCEPTED
HTTP_STATUS_AMBIGUOUS
HTTP_STATUS_BAD_GATEWAY
HTTP_STATUS_BAD_METHOD
HTTP_STATUS_BAD_REQUEST
HTTP_STATUS_CONFLICT
HTTP_STATUS_CREATED
HTTP_STATUS_DENIED
HTTP_STATUS_FORBIDDEN
HTTP_STATUS_GATEWAY_TIMEOUT
HTTP_STATUS_GONE
HTTP_STATUS_LENGTH_REQUIRED
HTTP_STATUS_MOVED
HTTP_STATUS_NO_CONTENT
HTTP_STATUS_NONE_ACCEPTABLE
HTTP_STATUS_NOT_FOUND
HTTP_STATUS_NOT_MODIFIED
HTTP_STATUS_NOT_SUPPORTED
HTTP_STATUS_OK
HTTP_STATUS_PARTIAL
HTTP_STATUS_PARTIAL_CONTENT
HTTP_STATUS_PAYMENT_REQ
HTTP_STATUS_PRECOND_FAILED
HTTP_STATUS_PROXY_AUTH_REQ
HTTP_STATUS_REDIRECT
HTTP_STATUS_REDIRECT_KEEP_VERB
HTTP_STATUS_REDIRECT_METHOD
HTTP_STATUS_REQUEST_TIMEOUT
HTTP_STATUS_REQUEST_TOO_LARGE
HTTP_STATUS_RESET_CONTENT
HTTP_STATUS_SERVER_ERROR
HTTP_STATUS_SERVICE_UNAVAIL
HTTP_STATUS_UNSUPPORTED_MEDIA
HTTP_STATUS_URI_TOO_LONG
HTTP_STATUS_USE_PROXY
HTTP_STATUS_VERSION_NOT_SUP
HTTP_VERSION_INFO
HttpAddRequestHeaders
HttpEndRequest
httpEquiv
HTTP-EQUIV
HTTP-EQUIV=
HttpOpenRequest
HttpQueryInfo
HttpSendRequest
HttpSendRequestEx
HWND
HWND Property

I Button
I to ID=
IDataFilter to IHTMLAreasCollection::item
IHTMLAreasCollection::put_length to IHTMLDocument2::put_onreadystatechange
IHTMLDocument2::put_onrowenter to IHTMLFrameSetElement::put_frameBorder
IHTMLFrameSetElement::put_frameSpacing to IHTMLLocation::put_protocol
IHTMLLocation::put_search to IHTMLRuleStyle::get_position
IHTMLRuleStyle::get_styleFloat to IHTMLStyle::get_pixelTop
IHTMLStyle::get_pixelWidth to IHTMLTableCell::put_height
IHTMLTableCell::put_noWrap to IInternetSession::RegisterNameSpace
IInternetSession::SetCache to INTERNET_OPTION_CONNECT_BACKOFF
INTERNET_OPTION_CONNECT_LIMIT to IPropertyNotifySink
IProvideMultipleClassInfo::GetInfoOfIndex to IWABObject::SetMe
IWABObject::VCardCreate to IXMLElementCollection::put_length

J Button
JAVA
javaEnabled
javaEnabled (IOmNavigator)
JoinChannel
JoinChannel Method
JustifyCenter
JustifyCenter Command
JustifyFull
JustifyFull Command
JustifyLeft
JustifyLeft Command
JustifyRight
JustifyRight Command

K Button
KBD (HTML Elements)
KBD (Objects)
keyCode
keyset <definition>
Keyword
KickMember
KickMember Method
KickParticipant
KickParticipant Method
KickUser
KickUser Method
KillChannel
KillChannel Method

L Button
LABEL to ListView_SubItemHitTest
ListView_Update to LVS_TYPESTYLEMASK

* More entries...


Index

M Button
MakeDragList
MAKEINTRESOURCE
MAKEIPADDRESS
MAKEIPRANGE
Managing the User Interface of the ActiveMovie Control
MAP (HTML Elements)
MAP (Objects)
map (Properties)
MAPI
MAPI_PAB_Schema
MAPIAllocateBuffer
MAPIAllocateMore
MAPIFreeBuffer
MAPINAMEID
MapUrlToZone (IInternetSecurityManager)
MapWindowPoints
margin (CSS Attributes)
margin (Properties)
marginBottom
margin-bottom
marginHeight
MARGINHEIGHT= (FRAME)
MARGINHEIGHT= (IFRAME)
marginLeft
margin-left
marginRight
margin-right
marginTop
margin-top
marginWidth
MARGINWIDTH= (FRAME)
MARGINWIDTH= (IFRAME)
MARQUEE (HTML Elements)
MARQUEE (Objects)
marshaling <definition>
MarshalOptions Property (ADO)
MarshalOptions Property Example (ADO)
Mask
Mask Filter
MaskOp
MaxHistoryLength
MaxHistoryLength Property
maxLength
MAXLENGTH=
MaxMemberCount
MaxMembers
MaxMembers Property
MaxMessageLength
MaxMessageLength (Server Properties)
MaxMessageLength Property
MaxRecords Property (ADO)
MaxRecords Property Example (ADO)
MaxStringLength
MaxStringLength Property
MCHITTESTINFO
MCM_GETCOLOR
MCM_GETCURSEL
MCM_GETFIRSTDAYOFWEEK
MCM_GETMAXSELCOUNT
MCM_GETMAXTODAYWIDTH
MCM_GETMINREQRECT
MCM_GETMONTHDELTA
MCM_GETMONTHRANGE
MCM_GETRANGE
MCM_GETSELRANGE
MCM_GETTODAY
MCM_GETUNICODEFORMAT
MCM_HITTEST
MCM_SETCOLOR
MCM_SETCURSEL
MCM_SETDAYSTATE
MCM_SETFIRSTDAYOFWEEK
MCM_SETMAXSELCOUNT
MCM_SETMONTHDELTA
MCM_SETRANGE
MCM_SETSELRANGE
MCM_SETTODAY
MCM_SETUNICODEFORMAT
MCN_GETDAYSTATE
MCN_SELCHANGE
MCN_SELECT
MCS_DAYSTATE
MCS_MULTISELECT
MCS_NOTODAY
MCS_NOTODAYCIRCLE
MCS_WEEKNUMBERS
media
MEDIA= (LINK)
MEDIA= (STYLE)
Member
Member Properties
MemberCount (Object Properties: Channel Properties)
MemberCount (Properties)
MemberCount (Properties)
MemberCount Property
MemberCount Property (Properties)
MemberCountMax
MemberCountMin
MemberIdentity
MemberIdentity Property
MemberModes
MemberModes Property
MemberProperty
MemberProperty Property
MENU (HTML Elements)
MENU (Objects)
MenuBar
menubar (open)
MenuBar Property
MenuHelp
MessageBox
META (HTML Elements)
META (Objects)
method
METHOD= (FORM)
METHOD= (LOGTARGET)
Methods
METHODS=
Microsoft Agent
Microsoft Agent Character Data
Microsoft Agent Component Installation
Microsoft Agent Documentation
Microsoft Agent End-User License Agreement
Microsoft Agent Error Codes
Microsoft Agent Frequently Asked Questions
Microsoft Agent Genie Animation List
Microsoft Agent Introduction
Microsoft Agent Licensing and Redistribution
Microsoft Agent Linguistic Information Sound Editing Tool
Microsoft Agent Merlin Animation List
Microsoft Agent Programming Interface Overview
Microsoft Agent Robby Animation List
Microsoft Agent Samples
Microsoft Agent Speech Output Tags
Microsoft Agent Support
Microsoft CDF Generator
Microsoft Chat Control, Tasks
Microsoft OLE DB Provider for Index Server
Microsoft OLE DB Provider for Microsoft Active Directory Service
Microsoft OLE DB Provider for ODBC
Microsoft Remote Data Service
Microsoft Transaction Server <definition>
middle tier <definition>
MIME <definition>
MIME, Tasks
MIMEAssociationDialog
MIMEASSOCIATIONDIALOG_IN_FLAGS
mimeTypes
MIN= (EARLIESTTIME)
MIN= (INTERVALTIME)
MIN= (LATESTTIME)
MinimizeAll Method
MkParseDisplayName
MkParseDisplayNameEx
mmAuthMember
mmAway
mmClientIgnored
mmHost
mmNone
mmNotAuthMember
mmNotAway
mmNotClientIgnored
mmNotHost
mmNotOwner
mmNotSysop
mmNoVoice
mmOwner
mmSysop
mmVoice
Mode Property (ADO)
Modes (Channel Properties)
Modes (Member Properties)
Modes (User Properties)
ModifyDate Property
ModifyDesktopItem (IActiveDesktop)
MonikerBindToObject (IBindHost)
MonikerBindToObject (IBindHost) (The IBindHost Interface)
MonikerBindToStorage (IBindHost)
MonikerBindToStorage (IBindHost) (The IBindHost Interface)
Monitoring ActiveMovie Control Events
MonthCal_GetColor
MonthCal_GetCurSel
MonthCal_GetFirstDayOfWeek
MonthCal_GetMaxSelCount
MonthCal_GetMaxTodayWidth
MonthCal_GetMinReqRect
MonthCal_GetMonthDelta
MonthCal_GetMonthRange
MonthCal_GetRange
MonthCal_GetSelRange
MonthCal_GetToday
MonthCal_GetUnicodeFormat
MonthCal_HitTest
MonthCal_SetColor
MonthCal_SetCurSel
MonthCal_SetDayState
MonthCal_SetFirstDayOfWeek
MonthCal_SetMaxSelCount
MonthCal_SetMonthDelta
MonthCal_SetRange
MonthCal_SetSelRange
MonthCal_SetToday
MonthCal_SetUnicodeFormat
MONTHLYDATE
MONTHLYDOW
move
move (IHTMLTxtRange)
Move Method (ADO)
Move Method Example (ADO)
moveBy
moveBy (IHTMLWindow2)
moveEnd
moveEnd (IHTMLTxtRange)
MoveFirst, MoveLast, MoveNext, and MovePrevious Methods (ADO)
MoveFirst, MoveLast, MoveNext, and MovePrevious Methods Example (ADO)
MoveFirst, MoveLast, MoveNext, MovePrevious Methods (DataControl)
MoveHere Method
MoveLight Method
MoveSplitBar
MoveSplitBar Method
moveStart
moveStart (IHTMLTxtRange)
moveTo
moveTo (IHTMLWindow2)
moveToBookmark
moveToBookmark (IHTMLTxtRange)
moveToElementText
moveToElementText (IHTMLTxtRange)
moveToPoint
moveToPoint (IHTMLTxtRange)
MoveWindow
MovieWindowSize Property
MSG
msgtAction
msgtCTCP
msgtData
msgtDataRaw
msgtDataReply
msgtDataRequest
msgtInfo
msgtNormal
msgtNotice
msgtSound
msgtThought
msgtWhisper
MULTIKEYHELP
multiple
MULTIPLE (SELECT)

* More entries...


Index

N Button
NAME (HTML Elements: INPUT)
Name (Microsoft Chat Protocol Control 2.0 Visual Basic Reference (Beta1 Release): Object Properties: Channel Properties: 2)
Name (Microsoft Chat Protocol Control 2.0 Visual Basic Reference (Beta1 Release): Object Properties: Server Properties: 1)
name (Properties: 1)
name (Properties: 2)
Name (Reusing the WebBrowser Control: Reference for Visual Basic Developers: Properties)
Name Property (FolderItem Object)
Name Property (FolderItemVerb Object)
Name Property (Properties)
Name Property (ADO)
NAME= (A)
NAME= (APPLET)
NAME= (CLASS)
NAME= (CODE)
NAME= (EMBED)
NAME= (FORM)
NAME= (FRAME)
NAME= (HTTP-EQUIV)
NAME= (IFRAME)
NAME= (IMG)
NAME= (INPUT)
NAME= (MAP)
NAME= (META)
NAME= (OBJECT)
NAME= (PACKAGE)
NAME= (PARAM)
NAME= (SELECT)
NAME= (SOFTPKG)
NAME= (TEXTAREA)
NameOp
NAMESPACE
NameSpace Method
NATIVECODE
NativeError Property (ADO)
navigate
Navigate (Methods)
Navigate (IHlink)
Navigate (IHlinkFrame)
Navigate (IHlinkTarget)
navigate (IHTMLWindow2)
Navigate (IWebBrowser2)
Navigate Method
Navigate2
Navigate2 (IWebBrowser2)
Navigate2 Method
NavigateComplete2
NavigateComplete2 (DWebBrowserEvents2)
NavigateComplete2 Event
navigator
NEEDSTRUSTEDSOURCE
NetInvisibleCount
NETRESOURCE
NetServerCount
NetUserCount
NetworkConnect
NetworkDisconnect
NewChatItems
NewChatItems Property
NEWCPLINFO
NewEntry (IAddrBook)
NewFolder Method
NewWindow2
NewWindow2 (DWebBrowserEvents2)
NewWindow2 Event
NewWorkItem (ITaskScheduler)
Next (IEnumChannels)
Next (IEnumIDList)
Next (IEnumOleDocumentViews)
Next (IEnumWorkItems)
NEXTID
nextPage
nextPage (IHTMLTable)
NextRecordset Method (ADO)
NextRecordset Method Example (ADO)
Nickname
Nickname (Member Properties)
Nickname (User Properties)
Nickname Property
NicknameOp (Member Properties)
NicknameOp (User Properties)
NIM_ADD
NIM_DELETE
NIM_MODIFY
NM_CHAR
NM_CHAR (toolbar)
NM_CLICK
NM_CLICK (list view)
NM_CLICK (status bar)
NM_CLICK (tab)
NM_CLICK (tree view)
NM_CUSTOMDRAW
NM_CUSTOMDRAW (header)
NM_CUSTOMDRAW (list view)
NM_CUSTOMDRAW (rebar)
NM_CUSTOMDRAW (toolbar)
NM_CUSTOMDRAW (tooltip)
NM_CUSTOMDRAW (trackbar)
NM_CUSTOMDRAW (tree view)
NM_DBLCLK
NM_DBLCLK (list view)
NM_DBLCLK (status bar)
NM_DBLCLK (tree view)
NM_HOVER
NM_HOVER (list view)
NM_KEYDOWN
NM_KEYDOWN (toolbar)
NM_KILLFOCUS
NM_KILLFOCUS (date time)
NM_KILLFOCUS (list view)
NM_KILLFOCUS (tree view)
NM_LISTVIEW
NM_NCHITTEST
NM_NCHITTEST (rebar)
NM_OUTOFMEMORY
NM_RCLICK
NM_RCLICK (header)
NM_RCLICK (list view)
NM_RCLICK (tab)
NM_RCLICK (toolbar)
NM_RCLICK (tree view)
NM_RDBLCLK
NM_RDBLCLK (list view)
NM_RDBLCLK (status bar)
NM_RDBLCLK (toolbar)
NM_RELEASEDCAPTURE
NM_RELEASEDCAPTURE (header)
NM_RELEASEDCAPTURE (list view)
NM_RELEASEDCAPTURE (monthcal)
NM_RELEASEDCAPTURE (pager)
NM_RELEASEDCAPTURE (rebar)
NM_RELEASEDCAPTURE (tab)
NM_RELEASEDCAPTURE (toolbar)
NM_RELEASEDCAPTURE (trackbar)
NM_RELEASEDCAPTURE (up-down)
NM_RETURN
NM_RETURN (list view)
NM_RETURN (tree view)
NM_SETCURSOR
NM_SETCURSOR (ComboBoxEx)
NM_SETCURSOR (tree view)
NM_SETFOCUS
NM_SETFOCUS (date time)
NM_SETFOCUS (list view)
NM_SETFOCUS (tree view)
NM_TREEVIEW
NM_UPDOWN
NMCBEDRAGBEGIN
NMCBEENDEDIT
NMCHAR
NMCOMBOBOXEX
NMCUSTOMDRAW
NMDATETIMECHANGE
NMDATETIMEFORMAT
NMDATETIMEFORMATQUERY
NMDATETIMESTRING
NMDATETIMEWMKEYDOWN
NMDAYSTATE
NMHDDISPINFO
NMHDR
NMHEADER
NMIPADDRESS
NMITEMACTIVATE
NMKEY
NMLISTVIEW
NMLVCACHEHINT
NMLVCUSTOMDRAW
NMLVDISPINFO
NMLVFINDITEM
NMLVGETINFOTIP
NMLVKEYDOWN
NMLVODSTATECHANGE
NMMOUSE
NMOBJECTNOTIFY
NMPGCALCSIZE
NMPGSCROLL
NMRBAUTOSIZE
NMREBAR
NMREBARCHILDSIZE
NMSELCHANGE
NMTBCUSTOMDRAW
NMTBDISPINFO
NMTBGETINFOTIP
NMTBHOTITEM
NMTCKEYDOWN
NMTOOLBAR
NMTREEVIEW
NMTTCUSTOMDRAW
NMTTDISPINFO
NMTVCUSTOMDRAW
NMTVDISPINFO
NMTVGETINFOTIP
NMTVKEYDOWN
NMUPDOWN
NOBR
NodeServerCount
NodeUserCount
NOFRAMES
noHref
NOHREF (AREA)
noResize
NORESIZE (FRAME)
NORESIZE (IFRAME)
NOSCRIPT
noShade
NOSHADE (HR)
Note
NOTIFYICONDATA
noWrap
NOWRAP (TD)
NOWRAP (TH)
NRESARRAY
Number Property (ADO)
NumericScale and Precision Properties Example (ADO)
NumericScale Property (ADO)

* More entries...


Index

O Button
OBJECT (HTML Elements)
Object (Microsoft Tabular Data Control Reference: Objects)
OBJECT (Objects)
object (Properties)
object variable <definition>
ObjectId (Channel Properties)
ObjectId (Member Properties)
Objects
ObtainUserAgentString
ODBC <definition>
Offline
Offline Property
offscreenBuffering
offsetHeight
offsetLeft
offsetParent
offsetTop
offsetWidth
offsetX
offsetY
OIBDG_FLAGS
OL (HTML Elements)
OL (Objects)
OLE DB <definition>
OLECMD
OLECMDEXECOPT
OLECMDF
OLECMDID
OLECMDTEXT
OLECMDTEXTF
OleCreateFromData
OleCreateFromFile
OleInitialize
OleRun
OleSave
OleUninitialize
onabort
OnAddMember
OnAddMember Event
onafterupdate
OnAmbientPropertyChange (ICSSFilter)
onbeforeunload
onbeforeupdate
OnBeginEnumeration
OnBeginEnumeration (Events)
OnBeginEnumeration Event
OnBeginEnumeration Event (Events)
onblur
onbounce
onchange
OnChannelError
OnChannelError Event
OnChannelProperty
OnChannelProperty Event
OnChannelPropertyChanged
OnChannelPropertyChanged Event
OnChannelState
OnChannelState Event
onclick
onclick Event
OnConnectionError
OnConnectionError Event
OnConnectionState
OnConnectionState Event
ondataavailable
OnDataAvailable (IBindStatusCallback)
ondatasetchanged
ondatasetcomplete
ondblclick
ondblClick Event
OnDefaultCommand (ICommDlgBrowser)
OnDelMember
OnDelMember Event
OnDocWindowActivate (IDocHostUIHandler)
ondragstart
OnEndEnumeration
OnEndEnumeration (Events)
OnEndEnumeration Event
OnEndEnumeration Event (Events)
OnEnterParticipant
OnEnterParticipant Event
OnEnterScript (IActiveScriptSite)
onerror (Events: 1)
onerror (Events: 2)
OnError (Microsoft Chat Control 1.1 Visual Basic Reference: Events)
OnError Event
onerrorupdate
OnExitParticipant
OnExitParticipant Event
onfilterchange
Onfilterchange Event
onfinish
onfocus
OnFocusChangeIS (IInputObjectSite)
OnFrameWindowActivate (IDocHostUIHandler)
OnFullScreen
OnFullScreen (DWebBrowserEvents2)
OnFullScreen Event
onhelp
OnHistoryFull
OnHistoryFull Event
OnInvitation
OnInvitation Event
OnJoin
onkeydown
onkeyDown Event
onkeypress
onkeyPress Event
onkeyup
onkeyUp Event
OnKnock
OnKnock Event
OnLeaveScript (IActiveScriptSite)
onLine
onload
OnLowResource (IBindStatusCallback)
OnMemberKicked
OnMemberKicked Event
OnMemberProperty
OnMemberProperty Event
OnMemberPropertyChanged
OnMemberPropertyChanged Event
OnMenuBar
OnMenuBar (DWebBrowserEvents2)
OnMenuBar Event
OnMessage
OnMessage (Events)
OnMessage Event
OnMessage Event (Events)
onmousedown
onmousedown Event
onmousemove
onmousemove Event
onmouseout
onmouseover
onmouseup
OnNavigate
OnNavigate (IHlinkFrame)
OnNavigateHlink
OnNavigateHlink (IHlinkBrowseContext)
OnNavigationComplete
OnNavigationComplete (IHlinkSite)
OnObjectAvailable (IBindStatusCallback)
OnPart
OnParticipantAliasChanged
OnParticipantAliasChanged Event
OnParticipantInvited
OnParticipantInvited Event
OnParticipantKicked
OnParticipantKicked Event
OnParticipantRealName
OnParticipantRealName Event
OnParticipantStatusChanged
OnParticipantStatusChanged Event
OnPrivateMessage
OnPrivateMessage Event
OnProgress (IBindStatusCallback)
OnProtocolMessage
OnProtocolMessage Event
OnQuit
OnQuit (DWebBrowserEvents2)
OnQuit Event
onreadystatechange
onreset
onresize
OnResponse (IHttpNegotiate)
OnRoomTopicChanged
OnRoomTopicChanged Event
OnRoomTypeChanged
OnRoomTypeChanged Event
onrowenter
onrowexit
OnScriptError (IActiveScriptSite)
onscriptletevent Event
onscriptletload Event
OnScriptTerminate (IActiveScriptSite)
onscroll
OnSecurityProblem (IHttpSecurity)
onselect
onselectstart
OnServerProperty
OnServerProperty Event
OnServerTextMessage
OnServerTextMessage Event
onstart
OnStartBinding (IBindStatusCallback)
OnStateChange (IActiveScriptSite)
OnStateChange (ICommDlgBrowser)
OnStateChanged
OnStateChanged Event
OnStatusBar
OnStatusBar (DWebBrowserEvents2)
OnStatusBar Event
OnStopBinding (IBindStatusCallback)
onsubmit
OnTextMessageSent
OnTextMessageSent Event
OnTheaterMode
OnTheaterMode (DWebBrowserEvents2)
OnTheaterMode Event
OnToolBar
OnToolBar (DWebBrowserEvents2)
OnToolBar Event
onunload
OnUserProperty
OnUserProperty Event
OnUserPropertyChanged
OnUserPropertyChanged Event
OnViewWindowActive (IShellBrowser)
OnVisible
OnVisible (DWebBrowserEvents2)
OnVisible Event
open (Methods: 1)
open (Methods: 2)
open (IHTMLDocument2)
open (IHTMLWindow2)
Open (IOleDocumentView)
Open and Close Methods Example (ADO)
Open Method
Open Method (Connection - ADO)
Open Method (Recordset - ADO)
Open Software Description (OSD), Tasks
OPENAS
OpenComplete Event
OpenEntry (IABContainer)
OpenEntry (IAddrBook)
OpenEntry (IDistList)
opener
OpenFile
openfiledlg (IHTMLOptionsHolder)
Opening and Running DirectShow Source Files
OpeningChannels
OpeningChannels Property
OpenProperty (IABContainer)
OpenProperty (IAddrBook)
OpenProperty (IDistList)
OpenProperty (IMailUser)
OpenSchema Method (ADO)
OpenSchema Method Example (ADO)
OPTION (HTML Elements)
OPTION (Objects)
options
OriginalValue and UnderlyingValue Properties Example (ADO)
OriginalValue Property (ADO)
OS
OSVERSION
Other Remote Data Service Configuration Information
Outdent
Outdent Command
outerHTML
outerText
overflow (CSS Attributes)
overflow (Properties)
OverWrite
OverWrite Command
OwnerKey
OwnerOfChannels
owningElement

P Button
P to PropSheet_QuerySiblings
PropSheet_RebootSystem to put_disabled (IHTMLInputFileElement)
put_disabled (IHTMLInputHiddenElement) to put_onload (IHTMLFrameSetElement)
put_onload (IHTMLImgElement) to put_vspace (IHTMLObjectElement)
put_whiteSpace (IHTMLRuleStyle) to PutProperty Method

* More entries...


Index

Q Button
Q (HTML Elements)
Q (Objects)
Query Method
QUERY_CAN_NAVIGATE
QUERY_CONTENT_ENCODING
QUERY_CONTENT_TYPE
QUERY_EXPIRATION_DATE
QUERY_IS_CACHED
QUERY_IS_CACHED_OR_MAPPED
QUERY_IS_INSTALLEDENTRY
QUERY_RECOMBINE
QUERY_REFRESH
QUERY_TIME_OF_LAST_CHANGE
QUERY_USES_CACHE
QUERY_USES_NETWORK
QueryActiveShellView (IShellBrowser)
QueryChannelProperty (Channel Object: Methods)
QueryChannelProperty (MsChatPr Object: Methods)
QueryChannelProperty Method (Channel Object: Methods)
QueryChannelProperty Method (MsChatPr Object: Methods)
QueryColumns (IABTable)
queryCommandEnabled
queryCommandEnabled (IHTMLControlRange)
queryCommandEnabled (IHTMLDocument2)
queryCommandEnabled (IHTMLTxtRange)
queryCommandIndeterm
queryCommandIndeterm (IHTMLControlRange)
queryCommandIndeterm (IHTMLDocument2)
queryCommandIndeterm (IHTMLTxtRange)
queryCommandState
queryCommandState (IHTMLControlRange)
queryCommandState (IHTMLDocument2)
queryCommandState (IHTMLTxtRange)
queryCommandSupported
queryCommandSupported (IHTMLControlRange)
queryCommandSupported (IHTMLDocument2)
queryCommandSupported (IHTMLTxtRange)
queryCommandText (IHTMLControlRange)
queryCommandText (IHTMLDocument2)
queryCommandText (IHTMLTxtRange)
queryCommandValue
queryCommandValue (IHTMLControlRange)
queryCommandValue (IHTMLDocument2)
queryCommandValue (IHTMLTxtRange)
QueryContextMenu (IContextMenu)
QueryContextMenu (IContextMenu2)
QueryCustomPolicy (IInternetHostSecurityManager)
QueryCustomPolicy (IInternetSecurityManager)
QueryDefaultRecipOpt (IAddrBook)
QueryHlink
QueryHlink (IHlinkBrowseContext)
QueryInfo (IInternetProtocolInfo)
QueryInfo (IWinInetHttpInfo)
QueryInterface
QueryMemberProperty
QueryMemberProperty Method
QUERYOPTION
QueryOption (IWinInetInfo)
QueryPosition (IABTable)
QueryRows (IABTable)
QueryServerProperty
QueryServerProperty Method
QueryService
QueryService (IHlinkSite)
QueryService (IServiceProvider)
QuerySortOrder (IABTable)
QueryStatus (IOleCommandTarget)
QueryStatusWB
QueryStatusWB (IWebBrowser2)
QueryStatusWB Method
QueryUserProperty
QueryUserProperty Method
Quick Start: Insert and Use the ActiveMovie Control
Quit
Quit (IWebBrowser2)
Quit Method

* More entries...


Index

R Button
radio
radio (type)
raiseEvent Method
Rate Property
Rating
Rating (Channel Properties)
Rating Property
RatingAccessDeniedDialog
RatingAccessDeniedDialog2
RatingCheckUserAccess
RatingEnable
RatingEnabledQuery
RatingFreeDetails
RatingObtainCancel
RatingObtainQuery
RatingSetupUI
RB_BEGINDRAG
RB_DELETEBAND
RB_DRAGMOVE
RB_ENDDRAG
RB_GETBANDBORDERS
RB_GETBANDCOUNT
RB_GETBANDINFO
RB_GETBARHEIGHT
RB_GETBARINFO
RB_GETBKCOLOR
RB_GETCOLORSCHEME
RB_GETDROPTARGET
RB_GETPALETTE
RB_GETRECT
RB_GETROWCOUNT
RB_GETROWHEIGHT
RB_GETTEXTCOLOR
RB_GETTOOLTIPS
RB_GETUNICODEFORMAT
RB_HITTEST
RB_IDTOINDEX
RB_INSERTBAND
RB_MAXIMIZEBAND
RB_MINIMIZEBAND
RB_MOVEBAND
RB_SETBANDINFO
RB_SETBARINFO
RB_SETBKCOLOR
RB_SETCOLORSCHEME
RB_SETPALETTE
RB_SETPARENT
RB_SETTEXTCOLOR
RB_SETTOOLTIPS
RB_SETUNICODEFORMAT
RB_SHOWBAND
RB_SIZETORECT
RBHITTESTINFO
RBN_AUTOSIZE
RBN_BEGINDRAG
RBN_CHILDSIZE
RBN_DELETEDBAND
RBN_DELETINGBAND
RBN_ENDDRAG
RBN_GETOBJECT
RBN_HEIGHTCHANGE
RBN_LAYOUTCHANGED
RBS_AUTOSIZE
RBS_BANDBORDERS
RBS_DBLCLKTOGGLE
RBS_FIXEDORDER
RBS_REGISTERDROP
RBS_TOOLTIPS
RBS_VARHEIGHT
RBS_VERTICALGRIPPER
RDS.DataControl Object Example
RDS.DataSpace Object and CreateObject Method Example
RDSServer.DataFactory Object, Query Method, and CreateObject Method Example
Read (IInternetProtocol)
Read (IPropertyBag)
Read (IPropertyBag2)
ReadFile
READONLY (HTML Elements: INPUT: 1)
READONLY (HTML Elements: TEXTAREA: 2)
readOnly (Properties: 1)
readOnly (Properties: 2)
ReadUrlCacheEntryStream
readyState
READYSTATE (Enumerations)
ReadyState (Properties)
readyState Property (1)
ReadyState Property (2)
ReadyState Property (Control Properties)
ReadyState Property (Properties)
ReadyState Property Example
ReadyStateChange Event
ReadyToNavigate
ReadyToNavigate (IHlinkSite)
RealName
reason
REBARBANDINFO
REBARINFO
RecipOptions (IAddrBook)
Recommended Reading
Reconcile (IReconcilableObject)
RecordCount Property (ADO)
recordNumber
recordset
recordset <definition>
Recordset and SourceRecordset Properties Example
Recordset Object (ADO)
Recordset, SourceRecordset Properties
RECT
Redistribution, Tasks
referrer
refresh
Refresh (Command Identifiers Reference)
Refresh (Reference for Visual Basic Developers: Methods)
refresh (IHTMLPluginsCollection)
refresh (IHTMLTable)
Refresh (IShellView)
Refresh (IWebBrowser2)
Refresh Command
Refresh Method
Refresh Method (Methods)
Refresh Method (ADO)
Refresh Method Example
Refresh Method Example (ADO)
Refresh2
Refresh2 (IWebBrowser2)
Refresh2 Method
RefreshConstants
RefreshMenu Method
RegEnumValue
Register
Register (IHlinkBrowseContext)
RegisterAsBrowser
RegisterAsBrowser Property
RegisterAsDropTarget
RegisterAsDropTarget Property
RegisterBindStatusCallback
RegisterClipboardFormat
RegisterDialogClasses
RegisterDragDrop
Registered
RegisterFormatEnumerator
RegisterHotKey
RegisterMediaTypeClass
RegisterMediaTypes
RegisterMimeFilter (IInternetSession)
RegisterNameSpace (IInternetSession)
RegisterWindowMessage
REGSAM
rel
REL= (A)
REL= (LINK)
Release
ReleaseBindInfo
reload
Reload (Shell DDE Reference)
reload (IHTMLLocation)
Remote Data Service API Reference
Remote Data Service Developer's Guide
Remote Data Service Methods
Remote Data Service Objects
Remote Data Service Properties
Remote Data Service Tutorials
Remote Procedure Call (RPC) <definition>
remove
Remove (Methods)
remove (IHTMLAreasCollection)
remove (IHTMLControlRange)
remove (IHTMLSelectElement)
Remove Method
removeAttribute
removeAttribute (IHTMLElement)
removeAttribute (IHTMLRuleStyle)
removeAttribute (IHTMLStyle)
removeAttribute (IXMLElement)
removeChild (IXMLElement)
RemoveDesktopItem (IActiveDesktop)
removeFilter (IHTMLControlElement)
RemoveFormat
RemoveFormat Command
removeImport (IHTMLStyleSheet)
RemoveMenusSB (IShellBrowser)
removeRule (IHTMLStyleSheet)
RemoveToolbar (IDockingWindowFrame)
replace
replace (IHTMLLocation)
ReplaceItem
ReplacePage (IShellPropSheetExt)
ReportData (IInternetProtocolSink)
ReportProgress (IInternetProtocolSink)
ReportResult (IInternetProtocolSink)
Requery Method (ADO)
RequestBorderSpaceDW (IDockingWindowSite)
res:
reset (Methods)
Reset (Microsoft Tabular Data Control Reference: Methods)
reset (Objects)
reset (type)
Reset (IEnumChannels)
Reset (IEnumIDList)
Reset (IEnumOleDocumentViews)
Reset (IEnumWorkItems)
reset (IHTMLFormElement)
Reset Method
Resizable
resizable (open)
Resizable Property
ResizeBorder (IDocHostUIHandler)
ResizeBorderDW (IDockingWindow)
resizeBy
resizeBy (IHTMLWindow2)
resizeTo
resizeTo (IHTMLWindow2)
Resolve (IShellLink)
ResolveName (IAddrBook)
ResolveNames (IABContainer)
ResolveNames (IDistList)
Restrict (IABTable)
ResultFromScode
Resume (IBinding)
Resume (IInternetProtocolRoot)
Resync Method (ADO)
Resync Method Example (ADO)
RetrieveUrlCacheEntryFile
RetrieveUrlCacheEntryStream
returnValue (Properties: 1)
returnValue (Properties: 2)
rev
REV=
Reveal Transition Filter
Revoke
Revoke (IHlinkBrowseContext)
RevokeBindStatusCallback
RevokeDragDrop
RevokeFormatEnumerator
rightMargin
RIGHTMARGIN=
RoomPath
RoomPath Property
RoomTopic
RoomTopic Property
RowDelim
rowIndex
rows (Collections)
rows (Properties: 1)
rows (Properties: 2)
ROWS= (FRAMESET)
ROWS= (TEXTAREA)
rowset <definition>
rowSpan
ROWSPAN= (TD)
ROWSPAN= (TH)
rules (Collections)
rules (Properties)
RULES=
Run (IScheduledWorkItem)
Run Method
run time <definition>

S Button
S to SetURL (IUniformResourceLocator)
SetUrlCacheEntryGroup to StatusText Property
StatusTextChange to SZM_FLAGS

T Button
Tab Control Extended Styles to TC_KEYDOWN
TCHITTESTINFO to TreeView_HitTest
TreeView_InsertItem to TYPELIB

* More entries...


Index

U Button
U (HTML Elements)
U (Objects)
UDACCEL
UDM_GETACCEL
UDM_GETBASE
UDM_GETBUDDY
UDM_GETPOS
UDM_GETRANGE
UDM_GETRANGE32
UDM_GETUNICODEFORMAT
UDM_SETACCEL
UDM_SETBASE
UDM_SETBUDDY
UDM_SETPOS
UDM_SETRANGE
UDM_SETRANGE32
UDM_SETUNICODEFORMAT
UDN_DELTAPOS
UDS_ALIGNLEFT
UDS_ALIGNRIGHT
UDS_ARROWKEYS
UDS_AUTOBUDDY
UDS_HORZ
UDS_HOTTRACK
UDS_NOTHOUSANDS
UDS_SETBUDDYINT
UDS_WRAP
UIActivate (IOleDocumentView)
UIActivate (IShellView)
UIActivateIO (IInputObject)
UIOption
UIOption Property
UL (HTML Elements)
UL (Objects)
umAdmin
umAuthUser
umAway
umClientIgnored
umInvisible
umNone
umNoNotices
umNotAdmin
umNotAuthUser
umNotAway
umNotClientIgnored
umNotices
umNotInvisible
umNotSysop
umNoWallops
umSysop
umWallops
Unadvise (IABTable)
Unadvise (IAddrBook)
UnBookmark
UnBookmark Command
UndeleteFile
Underline
Underline Command
UnderlyingValue Property (ADO)
Understanding Remote Data Service Applications
UndoMinimizeALL Method
UninitializeFlatSB
units
UNITS=
UnknownConnectionCount
Unlink
Unlink Command
UnlockRequest (IInternetProtocol)
UnlockUrlCacheEntryFile
UnlockUrlCacheEntryStream
UnregisterMimeFilter (IInternetSession)
UnregisterNameSpace (IInternetSession)
Unselect
Unselect Command
Update and CancelUpdate Methods Example (ADO)
Update Method (ADO)
UpdateAll (ISubscriptionMgr)
UpdateBatch and CancelBatch Methods Example (ADO)
UpdateBatch Method (ADO)
UpdateHlink
UpdateHlink (IHlinkFrame)
updateInterval
UpdateSubscription (ISubscriptionMgr)
UpdateUI (IDocHostUIHandler)
UpdateWindow
URL (Properties: 1)
url (Properties: 2)
URL Functions
URL Monikers
URL Property
URL Security Zones, Tasks
URL_COMPONENTS
URL=
URLACTION_ACTIVEX_CONFIRM_NOOBJECTSAFETY
URLACTION_ACTIVEX_CURR_MAX
URLACTION_ACTIVEX_MAX
URLACTION_ACTIVEX_MIN
URLACTION_ACTIVEX_OVERRIDE_DATA_SAFETY
URLACTION_ACTIVEX_OVERRIDE_OBJECT_SAFETY
URLACTION_ACTIVEX_OVERRIDE_SCRIPT_SAFETY
URLACTION_ACTIVEX_RUN
URLACTION_ACTIVEX_TREATSUNTRUSTED
URLACTION_AUTHENTICATE_CLIENT
URLACTION_CHANNEL_SOFTDIST_MAX
URLACTION_CHANNEL_SOFTDIST_MIN
URLACTION_CHANNEL_SOFTDIST_PERMISSIONS
URLACTION_CREDENTIALS_USE
URLACTION_DOWNLOAD_CURR_MAX
URLACTION_DOWNLOAD_MAX
URLACTION_DOWNLOAD_MIN
URLACTION_DOWNLOAD_SIGNED_ACTIVEX
URLACTION_DOWNLOAD_UNSIGNED_ACTIVEX
URLACTION_HTML_CURR_MAX
URLACTION_HTML_FONT_DOWNLOAD
URLACTION_HTML_JAVA_RUN
URLACTION_HTML_MAX
URLACTION_HTML_MIN
URLACTION_HTML_SENDRECV_COOKIE
URLACTION_HTML_SUBMIT_FORMS
URLACTION_HTML_SUBMIT_FORMS_FROM
URLACTION_HTML_SUBMIT_FORMS_TO
URLACTION_INFODELIVERY_CURR_MAX
URLACTION_INFODELIVERY_MAX
URLACTION_INFODELIVERY_MIN
URLACTION_INFODELIVERY_NO_ADDING_CHANNELS
URLACTION_INFODELIVERY_NO_ADDING_SUBSCRIPTIONS
URLACTION_INFODELIVERY_NO_CHANNEL_LOGGING
URLACTION_INFODELIVERY_NO_EDITING_CHANNELS
URLACTION_INFODELIVERY_NO_EDITING_SUBSCRIPTIONS
URLACTION_INFODELIVERY_NO_REMOVING_CHANNELS
URLACTION_INFODELIVERY_NO_REMOVING_SUBSCRIPTIONS
URLACTION_JAVA_CURR_MAX
URLACTION_JAVA_MAX
URLACTION_JAVA_MIN
URLACTION_JAVA_PERMISSIONS
URLACTION_NETWORK_CURR_MAX
URLACTION_NETWORK_MAX
URLACTION_NETWORK_MIN
URLACTION_SCRIPT_CURR_MAX
URLACTION_SCRIPT_JAVA_USE
URLACTION_SCRIPT_MAX
URLACTION_SCRIPT_MIN
URLACTION_SCRIPT_OVERRIDE_SAFETY
URLACTION_SCRIPT_RUN
URLACTION_SCRIPT_SAFE_ACTIVEX
URLACTION_SHELL_CURR_MAX
URLACTION_SHELL_FILE_DOWNLOAD
URLACTION_SHELL_INSTALL_DTITEMS
URLACTION_SHELL_MAX
URLACTION_SHELL_MIN
URLACTION_SHELL_MOVE_OR_COPY
URLACTION_SHELL_VERB
URLACTION_SHELL_WEBVIEW_VERB
URLAssociationDialog
URLASSOCIATIONDIALOG_IN_FLAGS
URLDownloadToCacheFile
URLDownloadToFile
URLINVOKECOMMANDINFO
UrlMkGetSessionOption
UrlMkSetSessionOption
URLOpenBlockingStream
URLOpenPullStream
URLOpenStream
URLPOLICY_ALLOW
URLPOLICY_AUTHENTICATE_CHALLENGE_RESPONSE
URLPOLICY_AUTHENTICATE_CLEARTEXT_OK
URLPOLICY_AUTHENTICATE_MUTUAL_ONLY
URLPOLICY_CHANNEL_SOFTDIST_AUTOINSTALL
URLPOLICY_CHANNEL_SOFTDIST_PRECACHE
URLPOLICY_CHANNEL_SOFTDIST_PROHIBIT
URLPOLICY_CREDENTIALS_ANONYMOUS_ONLY
URLPOLICY_CREDENTIALS_MUST_PROMPT_USER
URLPOLICY_CREDENTIALS_SILENT_LOGON_OK
URLPOLICY_DISALLOW
URLPOLICY_JAVA_CUSTOM
URLPOLICY_JAVA_HIGH
URLPOLICY_JAVA_LOW
URLPOLICY_JAVA_MEDIUM
URLPOLICY_JAVA_PROHIBIT
URLPOLICY_MASK_PERMISSIONS
URLPOLICY_QUERY
URLTEMPLATE
URLTEMPLATE_CUSTOM
URLTEMPLATE_HIGH
URLTEMPLATE_LOW
URLTEMPLATE_MEDIUM
URLTEMPLATE_PREDEFINED_MAX
URLTEMPLATE_PREDEFINED_MIN
URLZONE
URLZONE_INTERNET
URLZONE_INTRANET
URLZONE_LOCAL_MACHINE
URLZONE_PREDEFINED_MAX
URLZONE_PREDEFINED_MIN
URLZONE_TRUSTED
URLZONE_UNTRUSTED
URLZONE_USER_MAX
URLZONE_USER_MIN
URLZONEREG
URLZONEREG_DEFAULT
URLZONEREG_HKCU
URLZONEREG_HKLM
urn
USAGE
UseHeader
useMap
USEMAP=
User
User Properties
userAgent
userLanguage
UserName (Member Properties)
UserName (User Properties)
UserNameOp (Member Properties)
UserNameOp (User Properties)
userProfile
UserProperty
UserProperty Property
Using Default Scriptlets
Using OLE DB Providers with ADO
Using the ActiveMovie Control in Visual Basic
Using the Microsoft Agent Character Editor

* More entries...


Index

V Button
ValidItems
ValidItems Property
vAlign (Properties: 1)
vAlign (Properties: 2)
VALIGN= (CAPTION)
VALIGN= (COL)
VALIGN= (COLGROUP)
VALIGN= (LEGEND)
VALIGN= (TBODY)
VALIGN= (TD)
VALIGN= (TFOOT)
VALIGN= (TH)
VALIGN= (THEAD)
VALIGN= (TR)
VALUE (HTML Elements: INPUT)
value (Properties: 1)
value (Properties: 2)
value (Properties: 3)
Value Property (ADO)
Value Property Example (ADO)
VALUE= (CANRESIZE)
VALUE= (CANRESIZEX)
VALUE= (CANRESIZEY)
VALUE= (HEIGHT)
VALUE= (HTTP-EQUIV)
VALUE= (INPUT)
VALUE= (LANGUAGE)
VALUE= (LI)
VALUE= (LOG)
VALUE= (OPENAS)
VALUE= (OPTION)
VALUE= (OS)
VALUE= (OSVERSION)
VALUE= (PARAM)
VALUE= (PROCESSOR)
VALUE= (USAGE)
VALUE= (WIDTH)
VAR (HTML Elements)
VAR (Objects)
VARIANT
VARIANTARG
VariantInit
VCardCreate (IWABObject)
VCardDisplay (IWABObject)
VCardRetrieve (IWABObject)
Verbs Method
version Property
Version Property (ADO)
Version Property Example (ADO)
VERSION= (?XML)
VERSION= (CODE)
VERSION= (PACKAGE)
VERSION= (SOFTPKG)
verticalAlign
vertical-align
ViewOptions Property
Virtual Table Manager (VTM) <definition>
visibility (CSS Attributes)
visibility (Properties)
Visible
Visible Property
visited
Visual Filter
vLink
VLINK=
vlinkColor
VoiceInChannel
volume
Volume Property
VOLUME=
vspace
VSPACE= (APPLET)
VSPACE= (EMBED)
VSPACE= (IFRAME)
VSPACE= (IMG)
VSPACE= (MARQUEE)
VwStreamCloseFunc
VwStreamDynamicName
VwStreamDynamicType
VwStreamIdCount
VwStreamIdName
VwStreamOpenFunc
VwStreamReadFunc
VwStreamReadRecordFunc
VwStreamSaveName
VwStreamSectionFunc
VwStreamSectionName
VwStreamSeekFunc
VwStreamTellFunc
VwStreamUserSaveType

W Button
WAB_PARAM
WABOpen
WABOpenEx
WaitForCompletion (IABTable)
WALLPAPEROPT
Wave Filter Effect
WBR
Web server <definition>
WebBrowser
WebBrowser Control, Tasks
WebBrowser Object
WEBCRAWL_DONT_MAKE_STICKY
WEBCRAWL_GET_BGSOUNDS
WEBCRAWL_GET_CONTROLS
WEBCRAWL_GET_IMAGES
WEBCRAWL_GET_VIDEOS
WEBCRAWL_IGNORE_ROBOTSTXT
WEBCRAWL_LINKS_ELSEWHERE
WEBCRAWL_RECURSEFLAGS
WEEKLY
Welcome to Scriptlet Technology
What's New in Remote Data Service 1.5
WIDTH (CDF Extensions for Active Desktop Items)
width (CSS Attributes)
width (Methods: open)
Width (Microsoft Chat Control 1.1 Visual Basic Reference: Properties)
width (Properties: 1)
width (Properties: 2)
width (Properties: 3)
Width (Reusing the WebBrowser Control: Reference for Visual Basic Developers: Properties)
Width Property
Width Property (Properties)
WIDTH= (APPLET)
WIDTH= (COL)
WIDTH= (COLGROUP)
WIDTH= (EMBED)
WIDTH= (FRAME)
WIDTH= (HR)
WIDTH= (IFRAME)
WIDTH= (IMG)
WIDTH= (MARQUEE)
WIDTH= (OBJECT)
WIDTH= (TABLE)
WIN32_FIND_DATA
window
WINDOWPOS
Windows Method
Windows Shell, Tasks
WinHelp
WININET_API_FLAG_ASYNC
WININET_API_FLAG_SYNC
WININET_API_FLAG_USE_CONTEXT
WinMain
WIZ_BODYCX
WIZ_BODYX
WIZ_CXBMP
WIZ_CXDLG
WIZ_CYDLG
WM_ACTIVATE
WM_ACTIVATEAPP
WM_CANCELMODE
WM_CHARTOITEM
WM_CLOSE
WM_COMMAND
WM_CONTEXTMENU
WM_CPL_LAUNCH
WM_CPL_LAUNCHED
WM_CREATE
WM_DESTROY
WM_DRAWITEM
WM_DROPFILES
WM_ERASEBKGND
WM_GETHOTKEY
WM_HELP
WM_HOTKEY
WM_HSCROLL
WM_INITMENUPOPUP
WM_KEYDOWN
WM_KEYUP
WM_LBUTTONDBLCLK
WM_LBUTTONDOWN
WM_LBUTTONUP
WM_MBUTTONDOWN
WM_MEASUREITEM
WM_MENUCHAR
WM_MENUSELECT
WM_MOUSEMOVE
WM_NCACTIVATE
WM_NCHITTEST
WM_NCPAINT
WM_NOTIFY
WM_NOTIFYFORMAT
WM_PAINT
WM_RBUTTONDOWN
WM_RBUTTONUP
WM_SETCURSOR
WM_SETHOTKEY
WM_SIZE
WM_SYSCOLORCHANGE
WM_SYSCOMMAND
WM_TCARD
WM_VKEYTOITEM
WM_VSCROLL
WM_WININICHANGE
WpBindToSite
WpCreateSite
WpCreateSiteEx
WpDeleteSite
WpDoesSiteExist
WpEnumProviders
WpGetErrorString
WpListSites
WppBindToSite
WppDeleteSite
WpPost
WpPostEx
WpPostFile
WPPROVINFO
WPSITEINFO
WPSTYLE_CENTER
WPSTYLE_MAX
WPSTYLE_STRETCH
WPSTYLE_TILE
wrap
WRAP=
write
write (IHTMLDocument2)
Write (IPropertyBag)
Write (IPropertyBag2)
WriteHitLogging
writeln
writeln (IHTMLDocument2)
WritePrivateProfileString

X Button
x
XML Document
XML Element
XML-SPACE= (ABSTRACT)
XML-SPACE= (TITLE)
XMP (HTML Elements)
XMP (Objects)
XRay Filter Effect

Y Button
y
YouAreAReplica (INotifyReplica)

Z Button
ZAFLAGS
ZAFLAGS_ADD_SITES
ZAFLAGS_CUSTOM_EDIT
ZAFLAGS_INCLUDE_INTRANET_SITES
ZAFLAGS_INCLUDE_PROXY_OVERRIDE
ZAFLAGS_NO_UI
ZAFLAGS_REQUIRE_VERIFICATION
ZAFLAGS_SUPPORTS_VERIFICATION
ZAFLAGS_UNC_AS_INTRANET
zIndex
z-index
ZONEATTRIBUTES
zOrder


Microsoft Internet Client SDK Overview

Microsoft Internet Client SDK Overview Microsoft Internet Client SDK Overview *
  * Next Topic: Frequently Asked Questions

Internet Client SDK Top Menu

Welcome...

The Microsoft® Internet Client Software Development Kit (SDK), also known as the Internet Explorer 4.0 Author's Toolkit, includes a variety of technologies that Microsoft is introducing to facilitate development of Internet applications and content. You will find a quick overview of what's in the Internet Client SDK below. This is the final release of the Internet Client SDK; it is synched with the final release of Microsoft Internet Explorer 4.0. To use the SDK, you will need to install the latest version of Internet Explorer 4.0. For last-minute issues associated with any given release, be sure to visit the Read Me file.

The SDK is structured to meet the needs of two basic audiences: Web authors who are developing Internet content, and Web ISVs who are writing API-level software. If you are one or the other, you probably don't need to download the entire SDK. From the download site, you can pick and choose those technologies and documentation selections that are of most interest to you. You may find that one set of documentation leads into another. If you haven't downloaded that set, the documentation takes you to a "Comp" file, which leads you back to the download site and invites you to download the needed set of documentation. If you choose to do this, the new set of documentation will be downloaded, and the links between the sets will be resolved. The whole SDK is designed so you can incrementally add to it or upgrade it as your interests require.

If you were to download the entire SDK, you would notice by the table of contents in the left-hand frame that the SDK is divided into five "books": Dynamic HTML, Delivering Content to the Web, Component Development, Internet Tools & Technologies, and Component Library. The first two books are aimed at Web authors. Dynamic HTML talks about developing and manipulating your content using the rich features provided by DHTML, Scripting, and Multimedia Interfaces. Delivering Content to the Web talks about getting information from your site to a client by using Active Channels, Subscriptions, and Active Desktop Items.

If you are an ISV developing components for the Web, you will be interested in the Component Development book. This section talks about ActiveX™ component development (sorry, the SDK for Java™ wasn't quite ready to be included in this release). There are a few things to note if you are an ISV. You will need the latest Win32® development files; these can be installed from the Platform SDK, or the needed subset of these files can be installed from the Internet Client SDK download site (or from the CD, if you are getting this release on a CD). This release supports Intel only; Alpha support is not yet available. This release has been tested with Visual C++® 5.0. Be sure to visit the Read Me file for configuration information. Visual Basic® developers utilizing the Microsoft ActiveX Controls in the SDK should use Visual Basic 5.0. A new entry to the Component Development book is Microsoft Scriptlets Technology.

The last two books, Internet Tools & Technology and Component Library, have a little bit of information for both Web authors and ISVs. The Internet Tools & Technology book contains a vast amount of diverse information, such as Microsoft CryptoAPI, HTMLHelp, WebBrowser Control, Information Delivery API, Internet Ratings, Web Publishing Wizard, WinInet and Urlmon API, Microsoft Script Debugger, and so on. The Component Library has information on controls downloaded with Internet Explorer, or other products that share an association with Internet technology, such as ActiveMovie™ Control, Microsoft Agent, Microsoft NetShow™, Microsoft NetMeeting™, Microsoft Remote Data Service, Tabular Data Control (TDC), and others.

For all the latest information on Internet Explorer 4.0, including downloads, demos, product features, and press releases, visit the Web site at http://www.microsoft.com/ie/ie40/.

Good coding!

Internet Client SDK Program Management


Internet Client SDK Preview Page

 Picture of a computer browsing this channel guide. Internet Client SDK Channel Preview.
Delivering Content to the Web. Internet Tools & Technologies. Click here to add this channel to your list of Active Channels.


=======================================================================

Release notes for the Internet Client Software Development Kit

Copyright (c) Microsoft Corporation, December 1997
=======================================================================

Note: If you did not access this document from <your SDK directory>\help\default.htm,
go to that location because it is a better place to begin reading documentation.
This Readme.txt is the second URL in that document's left-hand frame. If you
are unfamiliar with the Internet Client SDK, you might want to look at
the Overview section. There is a great deal of new material and technologies
available through that section.

-----------------------------------------------------
What's New for Internet Client SDK 4.01 refresh
-----------------------------------------------------
For latest breaking information of the Internet Client SDK 4.01 refresh, please
be sure to read the "What's New" section of the Welcome page from the
Internet Client SDK Download site at: http://www.microsoft.com/msdn/sdk/inetsdk.

-----------------------------------------------------
WELCOME TO THE INTERNET CLIENT SDK 4.0
-----------------------------------------------------

These are the release notes for the Internet Explorer 4.0 version of the SDK.
This release has been tested primarily on Visual C++ 5.0, Windows 95 and Windows NT,
and Internet Explorer 4.0 releases.

Here's a brief description of the contents of this folder, followed by release notes:

BIN       SDK tools, DLLs, and self-extracting .exe files
HELP      HTML documentation (Default.htm) for Web content and software development
INCLUDE   Include files for Internet development
LIB       Libraries for Internet development
SAMPLES   Samples for Web content developers and software developers
COMPLIB	  Internet components (ActiveX Controls, Java applets, and so on)

-----------------------------------------------------
PREREQUISITES OF THIS RELEASE OF THE SDK
-----------------------------------------------------

To do development with this SDK, you need to have installed on your computer:

* Internet Explorer 4.0.
* If you are developing software, the latest Win32 development files. You might
  already have installed these from the latest Platform SDK at
  http://www.microsoft.com/msdn/sdk/. Otherwise, the
  subset you need is available as a download from the Internet Client SDK
  download page under "Win32 SDK Libraries & Headers".
* Windows 95 or Windows NT 4.0 SUR (final version).
* Development tools, if you are building software. This product
  has been tested primarily on Visual C++ 5.0. (See "Configuration Issues"
  below for more information.)

Installing the SDK on Memphis Beta 1 hasn't been fully tested. If you try
this, you must upgrade the Memphis release with the latest Internet Explorer 4.0
release.

-----------------------------------------------------
INSTALLATION ISSUES -- CD AND INTERNET INSTALLS
-----------------------------------------------------

ActiveSetup from the Internet:

Essentially the ActiveSetup from a CD is identical to the ActiveSetup
from the Web. One difference is that the CD will have an image of
a fully installed SDK. If for some reason you are unable to use ActiveSetup,
this should not prevent you from being able to use the documentation and
seeing the samples. Copying those files from the CD to your hard drive
(without using ActiveSetup) is not a supported method of installation.

The new website for installing the SDK is:
http://www.microsoft.com/msdn/sdk/inetsdk/ASetup

The download site is designed to allow you to download the bits that
you're interested in, while ignoring the others for another day. You
can return to the site for incremental downloads that nicely integrate
into your installation. The downloads are targeted at three major
development tasks/audiences: Web and Desktop Content Providers, ActiveX
Component Developers, and Internet Application Developers. There is
also a Component Library with helpful Internet components such
as the Microsoft Chat and NetShow controls. A useful feature of
the documentation is that it integrates well on the client
computer. If you make a jump from the documentation to a set that
you have not yet installed, the documentation will invite you back
to the download site to install that documentation set. When you do this,
the links will be resolved to the new pages.

-----------------------------------------------------
GETTING STARTED ON DOCUMENTATION
-----------------------------------------------------

The documentation has lots of great new content. The entry point is
<your sdk dir.>\help\default.htm. All documentation should be accessed
through this file. Accessing other HTML files directly will cause scripting
errors and break navigation links.

-----------------------------------------------------
CONFIGURATION ISSUES
-----------------------------------------------------

If you have Visual C++ 5.0 and the latest release of the Platform SDK,
you should set your environment variables by executing the following
commands on your command line (note: make exceptions to make sure
you go to the correct directories):

  cd \vc\bin
  vcvars32 x86
  cd c:\mstools
  setenv c:\mstools
  cd c:\inetsdk
  setenv c:\inetsdk

If you have Visual C++ 5.0 and installed the Win32 development files
from the Internet Client SDK, you should set your
environment variables by executing the following commands on your
command line (again note: make exceptions to make sure you use the
correct directories):

  cd \vc\bin
  vcvars32 x86
  cd c:\inetsdk
  setenv c:\inetsdk

If a set of Win32 development files wasn't found in either case,
you will be warned not to pursue development.

If you are developing on a Windows 95 computer, you will want to
increase your environment space. You can do this by changing
"Initial environment" on the "Memory" tab of the "Properties"
menu, which is accessible by clicking in the extreme upper-left
corner of your MS-DOS prompt window.

-----------------------------------------------------
BUILDING/USING SAMPLES
-----------------------------------------------------
For both software and content developers, the samples are located in the
\samples directory, and are often referenced in the documentation as examples.
The Samples.htm file (accessible from Default.htm) provides more detailed
information about each sample.

You will find several new samples targeted at content development. These
are not the traditional type of samples that use compilers or linkers--these
are HTML and CDF samples, and others, that show you how to use or develop content
on Web pages.

For software developers, each sample that produces a binary has a makefile in
its directory. You can execute all of these recursively by executing
...\samples\makeall.bat. All samples should build on Visual C++ 5.0.

Several of the ChatOCX samples are Visual Basic samples. You will need to have
Visual Basic installed to build and execute these samples.

-----------------------------------------------------
WHAT'S IN THE \BIN DIRECTORY
-----------------------------------------------------

Lots of new, good stuff!

Many of the following are self-extracting CAB files; you can read more about them
in the documentation or in the .txt files in the \bin directory.  Upon download,
these file are installed in either the \bin directory of the \complib directory.

* Microsoft Agent files: ACE.exe (a character editor), and Liset.exe (linguistic sound).
* CDCache.exe: A tool that allows you to create a cache container so you can
  reference resources off of a CD-ROM.  (see documentation in the Internet Tools
  and Technology section of the SDK).
* CDFTest.exe, CDFTest.txt: A program that will take a CDF file or OSD file and
  verify its structure and syntax. It will find and report mistakes such as missing
  end tags as well as incorrect or misspelled tags.
* XMLint.*, XMLint.txt: A tool that checks whether an input file (or URL) is a well
  formed XML file.
* StyleT.exe, StyleT.htm: A CSS Style Sheet Validation Tool.  This allows you to:
  Ensure the syntax of CSS Style Sheets (and Inline Styles) is valid, Verify they
  conform to the W3C CSS Specification, Identify the usage of CSS extentions
  supported by Microsoft Internet Explorer.
* Chkjava.exe and Javasign.dll: Tools for signing Java permissions (see notes below).
* Updated MIDL compiler.
* Cdllogvw.exe, Cdllogvw.txt: A useful tool to view error logs during downloads.
* CDFGen.exe: Microsoft CDF Generator (previously known as Liburnia.exe): This
  is a CDF creation wizard.
* Wmfcnv.exe, wmfcnv.txt: Windows metafile converter.
* Cab-sdk.exe: The cabinet development kit components. (self-extracting cab)
* Nm20sdk.exe: The NetMeeting version 2.0 SDK components. (self-extracting cab)
* Ns*.exe: Various NetShow tools and demonstrations. (self-extracting cab)
* Wpsdk.exe: WebPost DLLs to be used if you build the WebPost samples or do Webpost
  development. (self-extracting cab)
* Lpk_tool.exe, Lpk_tool.txt, Lpk_tool.hlp: A tool that generates licensing
  package files for use with licensed ActiveX Controls.
* New code signing tools for Authenticode 2.0 (see Known Issues below): cert2spc.exe,
  certmgr.exe, chktrust.exe, imagehlp.dll, makecert.exe, makectl.exe, msvcrt.dll,
  setreg.exe, signcode.exe, signer.dll.

-----------------------------------------------------
WHAT'S IN THE \CompLib DIRECTORY
-----------------------------------------------------

* Chatcntl.exe, MSChat1j.exe: Microsoft Chat Control and Microsoft Chat Java
  applet.
* Nlaudio.ocx and Nlfile.ocx: NetShow controls.
* Mdac*.exe, Mdac.txt:  The Microsoft Remote Data Access components for the
  server (formerly ADC). (self-extracting cab)
* MSAgent.exe, CGram.exe, Actcnc.exe: Files for Microsoft Agent, including speech files.

-----------------------------------------------------
KNOWN ISSUES OR BUGS
-----------------------------------------------------

MSTASK.H:
  The Task Schedular interface introduced during beta as ISchedulingAgent has been
  renamed to ITaskScheduler in the final release of the product.  This is FYI only,
  no recompile is necessary.

BLEND TRANSITION - CSS:
  Attempting to assign a shape value (for example, Box-In, Wipe-Left) in a script to a
  Blend transition causes Internet Explorer to GPF.  Don't do this.  Setting a shape
  value to a Blend Transition in CSS is ignored.

  This will most likely happen when authors are editing code that changes a Reveal
  Transition to a Blend Transition without taking out any code that sets the
  transition shape.

BINDINFO and ATL:
  The BINDINFO structure has changed size between Internet Explorer 3.x and Internet
  Explorer 4.0.  There are more details in the documentation for BINDINFO that tells
  how to check this structure and how it applies to your code.

  Some of the ATL samples in this SDK -- Glass, IEMime, and TDC for example -- use
  classes based on the ATL CBindStatusCallback class, which implements asynchronous
  moniker downloads. The version of ATL shipping with Visual C++ 5.0 fails to release
  some interfaces and handles the size of the BINDINFO structure incorrectly inside
  CBindStatusCallback. The Glass IEMime and TDC samples are not affected because they
  provide their own revised CBindStatusCallback implementations. However, any customers
  who create projects based on these SDK samples but use CBindStatusCallback directly
  should be aware of these issues. ATL users should also be aware.  Microsoft is
  currently planning to resolve these problems in a future Service Pack for Visual Studio.

OBJBASE.H
  CoCreateStandardMalloc is defined in the objbase.h header file, however this
  function is obsolete and will be removed in a future release.  Attempting
  to use this in your code will generate unresolved symbol errors during
  linking.  CoGetMalloc should be used instead.

-----------------------------------------------------
LATE BREAKING DOCUMENTATION UPDATES
-----------------------------------------------------

AUTHENTICODE RELEASE NOTES:
  The following functionality has been added to the CertMgr program.

  Putting Certificates, CTLs, and CRLs with CertMgr

  The following syntax can be used to invoke CertMgr to put an X509 encoded
  certificate, CTL, or CRL into a file:

    CertMgr -put [options] [-s [-r registryLocation]] SourceStore FileName

  SourceStore is the source certificate store that contains the existing certificates,
  CTLs, and CRLs. FileName is the file to which an X509 encoded certificate, CTL,
  and CRL will be saved. If the -7 option is used, the file will be saved as a PKCS#7.

  CertMgr can put either certificates, CTLs, or CRLs. If there is more than one item
  in one of these categories, the user has two options:

    1.Use the -n and -sha1 options to uniquely identify the item.

    2.Do not specify any options, and CertMgr will prompt the user with a
      list of items to put. The user responds by entering the index of the item to add.

  The options are:

    -c     Put certificates.

    -CTL   Put CTLs.

    -CRL   Put CRLs.

    -7     Save the certificate, CRL, or CTL as a PKCS#7.

    -e encodingType      Certificate encoding type.

    -y storeProviderType Store provider type.

    -f dwFlags           Store open flag. This is the dwFlags parameter
                         passed to CertOpenStore. The default value is
                         CERT_SYSTEM_STORE_CURRENT_USER. Meaningful only if -y is
                         set. For more information see the CryptoAPI 2.0
                         documentation.

    -n commonNameString  The common name of the certificate to
                         put. Can be used only with certificates.

    -s                   Indicates the SourceStore is a system store. If this option
                         is not set, the store is a StoreFile.

    -sha1 sha1Hash       The SHA1 hash of the certificate, CTL, or CRL to add.

    -r registryLocation  Identifies the registry location of the system certificate
                         store. Meaningful only when -s is set. Must be set to
                         either currentUser or localMachine. currentUser is the default.

                         currentUser means that the certificate store is under
                         the registry key HKEY_CURRENT_USER, localMachine means
                         HKEY_LOCAL_MACHINE.

    -?                   Displays all the options.

  The following example puts an X509 encoded certificate, that is located in
  the Root certificate store, to a file called newCert.cer. The certificate's common
  name is "myCert".

    certmgr -put -c -n myCert -s root newCert.cer

UPDATE/CORRECTIONS TO DHTML FILTERS AND TRANSITIONS DOCUMENTATION:

  * When chaining together filters and transitions, it is advised that transitions
    be specified at the end of the list.

  * Under the section titled, "Properties, Methods, and Events" it lists Duration
    and Status as transtion properties. There should also be listed the Enabled
    property, which is present on all visual filters and transtions. A value of FALSE
    will disable the visual filter or transition. A value of TRUE means the visual
    filter or transition is active. The default value is TRUE. This value can be set
    both in the style sheet and through script.

  * The Enabled link on the Filters and Transitions page mistakenly jumps to the Enabled
    property for the Active Move control

  * In the overview for Transitions, the Play  and Stop links mistakenly jump to the Play
    and Stop properties for the NetShow Player Audio control. Jumping to the link will
    also install the control if it hasn't already been installed.

  * In the Creating Multimedia Effect With Visual Filters and Transitions section, the Duration
    link mistakenly jumps to the Duration property for the NetShow Player Audio control.
    Jumping to the link will also install the control if it hasn't already been installed.

  * The first "Show Me" example uses improper syntax.
      <img id=sample src="sample.jpg" style="filter:blur(amount=2) flipv()">
    should be
      <img id=sample src="sample.jpg" style="filter:blur(strength=2) flipv()">

  * The Glow filter's Strength property has a range from 1 to 255, not 0 to 100.

  * The example for the sentence, "Timers create cyclical effects, as in the following
    interactive demonstration." is not a good example. It does not work as intended.

  * The Transition Wizard may produce a scripting error when trying to demonstrate the
    code generated. This is only a problem when showing how the code works within
    the Wizard. The code it generates will work normally when cut-and-copied to an HTML
    document.

  * Disregard the explanitory text after the list of filter names under the Visual
    Filters subheader under Visual Transition Filters Reference.


Internet Client SDK Support

Internet Client SDK Support Internet Client SDK Support *
  * Next Topic: Dynamic HTML

Internet Client SDK Top Menu

  • FAQ
  • KnowledgeBase
  • Public Newsgroups

FAQ

If you have questions about the Internet Client SDK, you'll find our Frequently Asked Questions, available as part of these docs, a great resource. Note that the latest and greatest is available online at http://support.microsoft.com/support/inetsdk/faq/, so be sure to check the online version for more regular updates.

KnowledgeBase

The Microsoft KnowledgeBase, available on http://support.microsoft.com/support/, provides a wealth of information and consists of articles on a wide range of issues on various Microsoft products, including the Internet Client SDK. Always check the KnowledgeBase first to see if an article has already been written on the problem you're currently experiencing.

Public Newsgroups

Accessing the Newsgroups

Peer-to-peer newsgroups are available to help you interact with other Internet Client SDK users and are located on the news server msnews.microsoft.com. The following steps outline the process of using the Internet Connection Wizard to configure Outlook Express to access this news server:

  1. Start Outlook Express.
  2. Go to the Tools menu and select the Accounts... menu item.
  3. In the Internet Accounts dialog, select the Add button and choose the News... popup menu item. The Internet Connection Wizard will be displayed.
  4. Enter the name you want to have displayed on the From field when you post messages in the newsgroups. Select the Next> button to move to the next page of the wizard.
  5. Enter your email name. This can be used by others to send you email messages. Select the Next> button to move to the next page of the wizard.
  6. Enter the following as the name of the news (NNTP) server to use: msnews.microsoft.com.
    Do not select the "My news server requires me to log on" option. You do not need to enter an account name or password. Select the Next> button to move to the next page of the wizard.
  7. Specify a friendly name for this news account. This name is used only by Outlook Express when displaying the news servers you have created accounts for. Select the Next> button to move to the next page of the wizard.
  8. Specify the type of Internet connection to use when acessing the newsgroups. You have the following options:
    • Connnect using my phone line
      Select this option if you already have an account with an Internet Service Provider (ISP) and want to create a connection to that account using your modem and phone line.
    • Connect using my local area network (LAN)
      Select this option if you want to connect to the Internet using a proxy server on your LAN or if your LAN is directly connected to the Internet.
    • I will establish my Internet connection manually
      Select this option if you have an account with an ISP, your computer is already set up to connect to the Internet using this account, and you want to establish the connection to this account yourself. Select the Next> button to move to the next page of the wizard. This will take you to the last page of the wizard. Select the Finish button to exit the wizard.
  9. At this point you will be back in the Internet Accounts dialog and the new account you just created will be listed. Select the Close button. Outlook Express will ask you if you want to download the newsgroups on the news server you just added. Select Yes.
  10. The Newsgroups dialog will be displayed listing the available newsgroups you can choose to subscribe to. The public Internet Client SDK newsgroups are all located under microsoft.public.inetsdk. The section below briefly describes what types of issues go into each of these newsgroups.

Peer-to-Peer Newsgroup Descriptions

The following lists the public Internet Client SDK newsgroups and provides descriptions of the types of issues which should be posted in each:

  • microsoft.public.inetsdk.announcements
    General announcements and newsgroup descriptions

  • microsoft.public.inetsdk.controlpad
    Usage of Control Pad and the HTML Layout control

  • microsoft.public.inetsdk.doc_errors
    Reporting Internet Client SDK documentation errors

  • microsoft.public.inetsdk.html_authoring
    HTML language issues

  • microsoft.public.inetsdk.programming.active_desktop
    Creating folder Web views, authoring HTML pages as desktop components

  • microsoft.public.inetsdk.programming.active_scripting
    Writing Active Scripting hosts and engines

  • microsoft.public.inetsdk.programming.comctl32
    Programming the enhanced common controls (Comctl32.dll: coolbar, rebar, and so forth)

  • microsoft.public.inetsdk.programming.components.design_time
    Development of Design Time components

  • microsoft.public.inetsdk.programming.components.dev
    General Component Development questions

  • microsoft.public.inetsdk.programming.components.packaging
    Marking controls safe for scripting/initializing, using/writing licensed controls, signing code, creating CAB files, downloading code, using IExpress.

  • microsoft.public.inetsdk.programming.components.usage
    Programming IE4 components (netshow, mschat, netmeeting, and so forth)

  • microsoft.public.inetsdk.programming.data_awareness
    Working with data awareness interfaces in IE4; programming the tabular data control (TDC)

  • microsoft.public.inetsdk.programming.docobj
    Creating ActiveX Document servers and containers

  • microsoft.public.inetsdk.programming.html_objectmodel
    Programming the HTML Scripting Object Model via VBScript/JScript, VB, and C/C++

  • microsoft.public.inetsdk.programming.hyperlinking_API
    Using hyperlinking API and interfaces

  • microsoft.public.inetsdk.programming.info_delivery
    Programming the notification manager, IE4 agents; developing agents

  • microsoft.public.inetsdk.programming.mshtml_hosting
    Hosting MSHTML as an Active Document (not the WebBrowser control)

  • microsoft.public.inetsdk.programming.mstask
    Programming the task scheduler Mstask.dll (not InfoDelivery)

  • microsoft.public.inetsdk.programming.scripting.jscript
    JScript language issues

  • microsoft.public.inetsdk.programming.scripting.vbscript
    VBScript language issues

  • microsoft.public.inetsdk.programming.shell_objectmodel
    Programming the Shell via the object model exposed in Shdocvw.dll and Exdisp.h; includes hosting the WebBrowser control and sinking its events

  • microsoft.public.inetsdk.programming.urlmonikers
    Programming UrlMon

  • microsoft.public.inetsdk.sdk_setup
    Reporting problems downloading/setting up the Internet Client SDK--not IE4 setup problems

  • microsoft.public.inetsdk.wininet
    Programming the Win32 Internet API

Expectations of Service

  • Microsoft's Role: Microsoft does not offer any formal support in the public newsgroups. Instead, Microsoft sponsors the newsgroups as a platform for participating in the global community of Microsoft customers and product experts. In addition, Microsoft may monitor the newsgroups to ensure accuracy of information and assist MVPs as needed.
  • Microsoft MVPs: Microsoft MVPs (Most Valuable Professionals) volunteer technical answers and expertise in the newsgroups. The Microsoft MVPs come from a wide range of backgrounds and professions, with a willingness to give their time, expertise, and advice to enhance the technical skills of others within the newsgroups. For more information on the MVP program or how to receive consideration as an MVP, please see the MVP Online Brochure.

Rules of Conduct

  • Appropriate Language: The purpose of the newsgroups is to exchange technical information and expertise on Microsoft products. Please avoid personal attacks, slurs, and excessive profanity in your messages.
  • Message Topics: Please keep the topic of messages relevant to the subject of the newsgroup. It's normal for some message topics to drift from the stated subject. However, to ensure maximum impact and benefit for all involved, please keep your messages close to the newsgroup's subject.
  • Advertising/Solicitation: The newsgroups are for peer-to-peer assistance on Microsoft products. Participants are asked to refrain from posting advertisements or solicitations not pertaining to the intended use and purpose of the newsgroups.


Task List

Task List Task List *
  * Next Topic: Microsoft Internet Client SDK Overview

Internet Client SDK Top Menu

This list contains a number of useful tasks that can be accomplished using the Internet Client SDK. The tasks are divided by subjects and include links to the section it is found in and the actual document. To link to information on a particular task, click the Sample Link to the left of the task. If the specific task you are interested in is not covered in this list, you should investigate the documentation in the sections that have similar questions or that cover the general topic you are interested in.

Active Channels

Task | Location
IChannelMgr::AddChannelShortcut | Adding an Active Channel to the channel pane. | Internet Tools and Technologies, Microsoft Information Delivery API Reference.
IChannelMgr::AddChannelShortcut | Adding an channel category to the channel pane. | Internet Tools and Technologies, Microsoft Information Delivery API Reference.
CDF | Channel Definition Format (CDF) Reference | Delivering Content to the Web, CDF Reference for Active Channels.
Creating a channel | Creating an Active Channel. | Delivering Content to the Web, Creating Active Channels.
See XML | Extensible Markup Language (XML) | See Extensible Markup Language (XML).
Features | Features. | Delivering Content to the Web, Creating Active Channels.
Hit Logging APIs | Hit Logging APIs | Internet Tools and Technologies, Hit Logging API.
CDF Generator | Microsoft CDF Generator | Delivering Content to the Web, Microsoft CDF Generator.

Active Desktop

Task | Location
Adding an Item | Adding an Active Desktop item. | Internet Tools and Technologies, Active Desktop Interface.
Create a Desktop Item | Creating a desktop item | Delivering Content to the Web, Creating Active Desktop Items.
Enumerating Items | Enumerating Active Desktop items. | Internet Tools and Technologies, Active Desktop Interface.
Interface Overview | Overview of the IActiveDesktop interface. | Internet Tools and Technologies, Active Desktop Interface.

Active Documents

Task | Location
Creating an Active Document server | Creating an Active Document server. | Component Development, Programming an Active Document Server.
Hosting | Hosting | Component Development, Programming an Active Document Container.

ActiveX Controls

Task | Location
Access ActiveX control in CAB | Access an ActiveX Control that is stored in a .cab file. | Component Development, Packaging ActiveX Controls.
Identify General Capabilities | Component categories, Using to identify general capabilities. | Component Development, COM Objects for the Internet.
Identify Safety Features | Component categories, Using to identify safety features. | Component Development, Safe Initialization and Scripting for ActiveX Controls.
Initialization | Initialization, identifying the ActiveX Control as safe for. | Component Development, Safe Initialization and Scripting for ActiveX Controls.
Creating a LPK File | License package (.lpk) file, Creating. | Component Development, Licensing ActiveX Controls.
How do I | Licensing, Supporting design-time licensing. | Component Development, Licensing ActiveX Controls.
How do I | Licensing, Supporting run-time licensing. | Component Development, Licensing ActiveX Controls.
How do I | Navigating to a hyperlink target. | Component Developmet, Hyperlinks.
How do I | OLE Automation control (.ocx), Converting to ActiveX. | Component Development, Introduction to ActiveX Controls.
How do I | OLE interfaces that should supported. | Component Development, Introduction to ActiveX Controls.
Efficient Download | Packaging an ActiveX Control for efficient download. | Component Development, Packaging ActiveX Controls.
How do I | Packaging an ActiveX Control in a .cab file. | Component Development, Packaging ActiveX Controls.
How do I | Persistent data, storing. | Component Development, COM Objects for the Internet.
How do I | Progressive data-retrieval, Supporting. | Component Development, COM Objects for the Internet.
Identify Safety Features | Safety features, Identifying safety features using Component categories. | Component Development, Safe Initialization and Scripting for ActiveX Controls.
Identify Safety Features | Safety features, Identifying safety features using IObjectSafety. | Component Development, Safe Initialization and Scripting for ActiveX Controls.
How do I | Scripting, Identify the ActiveX Control as safe for. | Component Development, Safe Initialization and Scripting for ActiveX Controls.
How do I | Test certificate, Creating. | Component Development, Packaging ActiveX Controls.
How do I | Threading, Supporting in an ActiveX Control. | Component Development, Introduction to ActiveX Controls.

ActiveX Scripting

Task | Location
Scripting Host | Scripting host, Creating. | Component Development, ActiveX Scripting Hosts.
Scripting Engine | Scripting engine, Creating. | Component Development, ActiveX Scripting Engines.

Authentication

Task | Location
Using WinInet | Using Win32 Internet functions. | Internet Tools and Technologies, Microsoft Win32 Internet Functions Overview.

Caching

See Internet Cache.

Cabinet (CAB) Files

See the CAB SDK, which is available as a self-extracting executable in the \bin directory of the Internet Client SDK. See Component Packaging for more information.

Channel Definition Format (CDF)

Task | Location
CDF | Channel Definition Format (CDF) Reference | Delivering Content to the Web, CDF Reference for Active Channels.
CDF Generator | Microsoft CDF Generator | Delivering Content to the Web, Microsoft CDF Generator.
See XML | Extensible Markup Language (XML) | See Extensible Markup Language (XML).
See Software Update Channels | Software Update Channels | See Software Update Channels.

Channels

See Active Channels.

Chat Control

See Microsoft Chat Control.

Common Controls

Task | Location
Rebar | Control bar (rebar), Implementing in an application. | Internet Tools and Technologies, Rebar Controls.
Custom Draw | Drawing, Controlling drawing of a common control. | Internet Tools and Technologies, Custom Draw.

Connecting to the Internet

Task | Location
Using WinInet | Using the Win 32 Internet functions. | Internet Tools and Technologies, Microsoft Win32 Internet Functions Overview.

Downloading Internet Resources

Task | Location
Using URLMON | Creating a URL Moniker. | Internet Tools and Technologies, Asynchronous and URL Monikers Overview.
Using WinInet for FTP | Using Win32 Internet functions for a FTP Resource. | Internet Tools and Technologies, Microsoft Win32 Internet Functions Overview.
Using WinInet for HTTP | Using Win32 Internet functions for an HTTP Resource. | Internet Tools and Technologies, Microsoft Win32 Internet Functions Overview.

Dynamic HTML

Task | Location
Creating Multimedia Effects | Creating multimedia effects using Filters. | Dynamic HTML, Filters and Transitions.
Embedding Fonts | Embedding fonts into a Web page. | Dynamic HTML, Font Embedding.
Event Handlers | Event handlers. | Dynamic HTML, Understanding the Event Model.
Manipulating Text | Manipulating text in an HTML document. | Dynamic HTML, Dynamic Content.
Programming with C/C++ | Programming the Document Object Model from C/C++ | Internet Tools and Technologies, Programming the Document Object Model from C/C++.
Publishing Data | Publishing data on an HTML page without using complex server-side scripts. | Dynamic HTML, Data Binding.
How do I | Specifying precise positioning and layering information on HTML elements | Dynamic HTML, Positioning.

Extensible Markup Language (XML)

Task | Location
XML Information | Information and related links. | http://www.microsoft.com/sitebuilder/standards/xml/. External link
XML Object Model | Object model. | Internet Tools and Technologies, XML Object Model.

File Transfer Protocol (FTP)

Task | Location
Overview | Overview of the Win32 Internet API's FTP functions. | Internet Tools and Technologies, Microsoft Win32 Internet Functions Reference.

Internet Cache

Task | Location
Cache Container | Creating a cache container. | Internet Tools and Technologies, Cache Container Tool (Cdcache.exe).
Create Entry | Creating a cache entry. | Internet Tools and Technologies, Microsoft Win32 Internet Functions Overview.
Enumerate Cache | Enumerating the cache. | Internet Tools and Technologies, Microsoft Win32 Internet Functions Overview.
Retrieving information | Retrieving cache entry information. | Internet Tools and Technologies, Microsoft Win32 Internet Functions Overview.

Microsoft Chat Control

Task | Location
Client Web Page | Chat client Web page, Creating. | Component Library, Microsoft Chat Control 1.1 Visual Basic Overview.
Configure UI | User interface, Configuring. | Component Library, Microsoft Chat Control 1.1 Visual Basic Overview.
Send Messages | Sending messages and data in a chat room. | Component Library, Microsoft Chat Control 1.1 Visual Basic Overview.

MIME

Task | Location
MIME Detection | Detection by Internet Explorer 4.0. | Internet Tools and Technologies, Asynchronous and URL Monikers Overview.

Open Software Description (OSD)

Task | Location
See XML | Extensible Markup Language (XML) | See Extensible Markup Language (XML).
OSD External Information | Information and related links. | http://www.microsoft.com/sitebuilder/standards/osd/. External link
See XML | Microsoft Internet Component Download | Internet Tools and Technologies, Microsoft Internet Component Download.
See XML | Overview | Internet Tools and Technologies, Open Software Description (OSD).
See XML | Reference | Internet Tools and Technologies, Open Software Description (OSD).

Profile Assistant

Task | Location
Introduction | Introduction | Delivering Content to the Web, Profile Assistant.
Using | Using the Profile Assistant | Delivering Content to the Web, Profile Assistant.

Redistribution

Task | Location
Redistribution | Redistribution of Microsoft Internet Explorer technologies, such as the WebBrowser control, WININET.DLL, URLMON.DLL, or COMCTL32.DLL. | Internet Tools and Technologies, Licensing and Distribution.
Minimal Install | Using the Minimal Installation Package | Internet Tools and Technologies, Licensing and Distribution.

Security Zones

See URL Security Zones.

Software Update Channels

Task | Location
Creating | Creating a Software Update Channel. | Delivering Content to the Web, Creating Software Update Channels.
OSD Extensions | CDF, Extensions for Software Update Channels. | Delivering Content to the Web, CDF Extensions for Software Update Channels.
OSD | Open Software Description (OSD) | See Open Software Description (OSD).

Tabular Data Control (TDC)

Task | Location
Dynamic Filtering | Dynamic Filtering, Supporting dynamic filtering of tabular data on a Web page. | Component Library, Microsoft Tabular Data Control.
Dynamic Sorting | Dynamic Sorting, Supporting dynamic sorting of tabular data on a Web page. | Component Library, Microsoft Tabular Data Control.
How do I | Using in a Web page? | Component Library, Microsoft Tabular Data Control.

Taskbar

Task | Location
Adding an Icon | Adding an icon. | Internet Tools and Technologies, Taskbar.

Task Scheduler

Task | Location
How do I | add an application to the list of scheduled tasks? | Internet Tools and Techonologies, About the Task Scheduler.

URL Security Zones

Task | Location
Default Zones | Default URL Security Zones | Internet Tools and Technologies, URL Security Zones Overview.
Handling | Handling URL Security Zones | Internet Tools and Technologies, URL Security Zones Overview.
Overview | Overview | Internet Tools and Technologies, URL Security Zones Overview.

Web Browser Control

Task | Location
Use WebBrowser with C/C++ | Adding Internet browsing functionality to an application using C/C++. | Internet Tools and Techonologies, Reusing the WebBrowser Control.
Use WebBrowser with VB | Adding Internet browsing functionality to an application using Visual Basic. | Internet Tools and Techonologies, Reusing the WebBrowser Control
Changing Fonts | Changing fonts. | Internet Tools and Technologies, Reusing the WebBrowser Control.
Controlling | Control an instance of Internet Explorer from my application/ | Internet Tools and Technologies, Reusing the WebBrowser Control.
Printing (C/C++) | Printing Web pages (C/C++). | Internet Tools and Technologies, Reusing the WebBrowser Control.
Printing (VB) | Printing Web pages (Visual Basic). | Internet Tools and Technologies, Reusing the WebBrowser Control.

Windows Shell

Task | Location
How do I | Creating a band that can be viewed on the shell's taskbar. | Internet Tools and Technologies, Band Objects.
Creating a Shell Name Space | Creating a shell name space extension. | Internet Tools and Technologies, Shell Namespace.


ADO Overview

ActiveX™ Data Objects (ADO) enables you to write an application to access and manipulate data in a database server through an OLE DB provider. ADO’s primary benefits are high speed, ease of use, low memory overhead, and a small disk footprint.

ADO Features

ADO supports key features for building client/server and web-based applications, including the following:

  • Independently-created objects. Unlike Data Access Objects (DAO) or Remote Data Objects (RDO), you no longer have to navigate through a hierarchy to create objects because most ADO objects can be independently created. This allows you to create and track only the objects you need, and also results in fewer ADO objects and thus a smaller working set.

  • Batch updating helps improve performance by locally caching changes to data, then writing them all to the server in a single update.

  • Support for stored procedures with in/out parameters and return values.

  • Different cursor types, including the potential for support of back-end–specific cursors.

  • Support for limits on number of returned rows and other query goals for performance tuning.

  • Support for multiple recordsets returned from stored procedures or batch statements.

  • Free-threaded objects for efficient web server applications.

Note While ADO supports these features, the underlying providers and drivers called by ADO may not. Check the topic, Using OLE DB Providers with ADO as well as the documentation for the underlying providers and drivers to determine what functionality they support. Unless otherwise noted in the language reference topics, all of the ADO 1.5 Objects, Methods, and Properties described in this document are available when used with the Microsoft OLE DB Provider for ODBC and Microsoft SQL Server version 6.5.

Remote Data Service

ADO’s Remote Data Service (RDS) allows data remoting, by which you can move data from a server to a client application or Web page, manipulate the data on the client, and return updates to the server in a single round trip. Previously released as Advanced Data Connector 1.0, RDS has been combined with the ADO programming model to simplify client-side data remoting. For more information, see the Remote Data Service documentation.

Installing ADO

As part of the Microsoft Data Access Components, ADO and RDS are automatically installed and registered by a host product, such as Microsoft Internet Information Server. The host product setup program may require that you specifically request the Microsoft Data Access COmponents in order to have ADO and RDS installed.

Programming with ADO

ADO is a dual-interface COM type library. The filename is msado15.dll. The program ID (ProgID) is “ADODB.” In 2 and 3 tier database applications, ADO code that is to execute on the client uses the ProgID “ADOR” instead.

To use ADO with Microsoft Visual Basic or Microsoft Office, you also need to establish a reference to the ADO type library. Select References from the Project menu, check the box for “Microsoft ActiveX Data Objects 1.5 Library,” and then click “OK.” ADO objects, methods, and properties will then be accessible through the VBA Object Browser and the IDE Editor.

To use ADO with Microsoft Visual J++, you also need to create a set of class files using the Java Type Library Wizard. Select the Java Type Library Wizard from the Tools menu, check the box for “Microsoft ActiveX Data Objects 1.5 Library,” and then click “OK.” The wizard will then create the necessary Java class files for ADO.

For some programming languages, you also need to reference (using the #include statement) one or more additional files in your source code, as shown in the table below:
For C++ | For VBScript | For JScript
adoint.h | adovbs.inc | adojavas.inc
adoid.h

Threading

The ADO library is free-threaded, but listed in the Windows Registry as apartment model. The thread safety of ADO depends on the underlying provider and data source. For example, the Microsoft OLE DB Provider for ODBC is free-threaded, but not all ODBC drivers are. You should use ADO as apartment model unless you can verify that all of the underlying components can be used free-threaded.

ADO Objects

Although ADO objects are creatable outside the scope of a hierarchy, the objects exist within hierarchical relationships, as shown in the ADO Object Model.

There are 7 objects in the ADO object model:

Command - Maintains information about a command, such as a query string, parameter definitions, etc. You can execute a command string on a Connecton object or a query string as part of opening a Recordset object, without defining a Command object. The Command object is useful where you want to define query parameters, or execute a stored procedure that returns output parameters.

Connection - Maintains connection information with the data provider.

Error - Contains extended error information about an error condition raised by the provider. Since a single statement can generate two or more errors, the Errors collection can contain more than one Error object at a time, all of which result from the same incident.

Field - Contains information about a single column of data within a Recordset. The Recordset object features a Fields collection to contain all of its Field objects.

Parameter - A single parameter for a parameterized Command. The Command object features a Parameters collection to contain all of its Parameter objects.

Property - A provider-defined characteristic of an ADO object.

Recordset - A set of records returned from a query, and a cursor into those records. You can open a Recordset (i.e., execute a query) without explicitly opening a Connection object. However, if you do first create a Connection object, you can open multiple Recordset objects on the same connection.

Each of these objects features a set of properties and methods with which you can manipulate the object and its contents.

Dynamic Properties Collections

The Connection, Command, and Recordset objects each supports a Properties collection. The properties collection contains any dynamic (or “provider-specific”) properties exposed through ADO by the provider. You use the collection and the Item method to reference the property by it’s name or by it’s ordinal position in the collection, as shown:

Command.Properties.Item(0)
Command.Properties.Item(“Name”)

Since the Item method is a default method on an ADO collection, you can omit it:

Command.Properties(0)
Command.Properties(“Name”)

Further, the Properties collection itself is the default collection for the Connection, Command, andRecordset objects, so you can omit it as well:

Command(0)
Command(“Name”)

All of these syntax forms are identical. Which one you choose depends on your coding style preference.

Working with Data

In ADO, the Recordset object is the main interface to data. While the other objects are useful for managing connections, collecting error information, persisting queries, etc., most of your code’s interaction with ADO will involve one or more Recordset objects.

Here is the minimum code (using Microsoft® Visual Basic® Scripting Edition) needed to generate a Recordset from an ODBC data source:

set rstMain = CreateObject("ADODB.Recordset")
rstMain.Open "SELECT * FROM authors", _
    "DATABASE=pubs;UID=sa;PWD=;DSN=Publishers"

This generates a forward-only, read-only Recordset object. With a few modifications, you can obtain a more functional Recordset:

set rstMain = CreateObject("ADODB.Recordset")
rstMain.Open "SELECT * FROM authors", _
    "DATABASE=pubs;UID=sa;PWD=;DSN=Publishers",
    adOpenKeyset, adLockBatchOptimistic

This creates a fully scrollable and batch-updatable Recordset.

Note In order to reference ADO constants by name (instead of by value) when coding in a scripting language, as shown in these code examples, you must include the appropriate header file. For Microsoft Visual Basic Scripting Edition, include the file adovbs.inc in your code. For Microsoft JScript™, include the file adojavas.inc in your code. You should always refer to constants by name rather than by value since the values may change from one version to the next.

For the latest information on ADO, visit the Microsoft ADO web page.


ADO Object Model

Each of the Connection, Command, Recordset, and Field objects also have a Properties collection.


Using OLE DB Providers with ADO

Much of ADO's power and flexibility is due to the fact that you can use it to connect to any of several different data providers and still expose the same programming model, regardless of the specific features of any given provider.

However, because each provider is unique, how your application interacts with ADO will vary slightly between different providers. The differences you need to be aware of usually fall into one of three categories:

  • Connection parameters in the ConnectionString property.

  • Command object usage.

  • Provider-specific Recordset behavior.

Provider-specific details in each of these three areas are listed for each of the providers currently available from Microsoft, listed as follows.
Area | Topic
ODBC databases | Microsoft OLE DB Provider for ODBC
Microsoft Index Server | Microsoft OLE DB Provider for Microsoft Index Server
Microsoft Active Directory Service | Microsoft OLE DB Provider for Microsoft Active Directory Service

Provider-Specific Dynamic Properties

The Properties collections of the Connection, Command, and Recordset objects include dynamic properties specific to the provider. These properties provide information about functionality specific to the provider beyond the built-in properties ADO supports.

After establishing the connection and creating these objects, use the Refresh method on the object's Properties collection to obtain the provider-specific properties. Refer to the provider documentation and the "OLE DB Programmer's Reference" for detailed information about these dynamic properties.

For more information about OLE DB providers, see the documentation for the Microsoft® OLE DB SDK or visit the Microsoft OLE DB Web page.


Microsoft OLE DB Provider for ODBC

The Microsoft® ODBC Provider allows ADO to connect to any ODBC data source. ODBC drivers are available for every major DBMS in use today, including Microsoft SQL Server, Microsoft Access (Microsoft Jet database engine), and Microsoft FoxPro®, as well as non-Microsoft database products such as Oracle. The provider is free-threaded and unicode enabled.

The provider supports transactions, although different DBMS engines offer different types of transaction support. For example, Microsoft Access supports nested transactions, up to five levels deep.

This is the default provider for ADO and, when used with Microsoft SQL Server 6.5, all provider-dependent ADO 1.5 properties and methods are supported, except as noted in the ADO language reference topics.

Connection String Parameters

To connect to this provider, set the Provider= argument of the ConnectionString property to

MSDASQL

Reading the Provider property will return this string as well.

Because this is the default provider for ADO, if you omit the Provider= parameter from the connection string, ADO will attempt to establish a connection to this provider.

The provider does not support any specific connection parameters in addition to those defined by ADO. However, the provider will pass any non-ADO connection parameters to the ODBC driver manager.

Because you can omit the Provider parameter, you can therefore compose an ADO connection string that is identical to an ODBC connection string for the same data source, using the same parameter names (DRIVER=, DATABASE=, DSN=, and so on), values, and syntax as you would when composing an ODBC connection string. You can connect with or without a predefined data source name (DSN) or FileDSN.

Syntax with a DSN or FileDSN:

"[Provider=MSDASQL;] { DSN=name | FileDSN=filename } ; [DATABASE=database;] UID=user; PWD=password"

Syntax without a DSN (DSN-less connection):

"[Provider=MSDASQL;] DRIVER=driver; SERVER=server; DATABASE=database; UID=user; PWD=password"

If you use a DSN or FileDSN, it must be defined through the ODBC Administrator in the Windows Control Panel. As an alternative to setting a DSN, you can specify the ODBC driver (DRIVER=), such as "SQLServer," the server name (SERVER=), and the database name (DATABASE=).

You can also specify a user account name (UID=), and the password for the user account (PWD=) in the ODBC-specific parameters or in the standard ADO-defined User ID and Password parameters. If you include both the ADO and the ODBC-specific parameters for these values, the ADO parameters take precedence.

Although a DSN definition already specifies a database, you can specify a DATABASE parameter in addition to a DSN to connect to a different database. This also changes the DSN definition to include the specified database. It is a good idea to always include the DATABASE parameter when you use a DSN. This will ensure that you connect to the proper database because another user may have changed the default database parameter since you last checked the DSN definition.

Command Text

How you use the Command object largely depends on the data source, and what type of query or command statement it will accept.

ODBC does provide a specific syntax for calling stored procedures. For the CommandText property of a Command object, the CommandText argument to the Execute method on a Connection object, or the Source argument to the Open method on a Recordset object, pass in a string having this syntax:

"{ [ ? = ] call procedure [ ( ? [, ? [ , … ]] ) ] }"

Where each ? references an object in the Parameters collection. The first ? references Parameters(0), the next ? references Parameters(1), and so on.

The parameter references are optional and depend on the structure of the stored procedure. If calling a stored procedure that defines no parameters, your string would look like this:

"{ call procedure }"

If you have two query parameters, your string would look like this:

"{ call procedure ( ?, ? ) }"

If the stored procedure wants to return a value, the return value is treated as another parameter. If you have no query parameters, but you do have a return value, your string would look like this:

"{ ? = call procedure }"

Finally, if you have a return value and two query parameters, your string would look like this:

"{ ? = call procedure ( ?, ? ) }"

Recordset Behavior

The following tables list the standard ADO methods and properties available on a Recordset object opened with this provider.

For more detailed information on Recordset behavior for your provider configuration, run the Supports method, and enumerate the Properties collection of the Recordset to determine whether provider-specific dynamic properties are present.

Availability of standard ADO Recordset properties:
Property | ForwardOnly | Dynamic | Keyset | Static
AbsolutePage | not available | not available | read/write | read/write
AbsolutePosition | not available | not available | read/write | read/write
ActiveConnection | read/write | read/write | read/write | read/write
BOF | read-only | read-only | read-only | read-only
Bookmark | not available | not available | read/write | read/write
CacheSize | read/write | read/write | read/write | read/write
CursorLocation | read/write | read/write | read/write | read/write
CursorType | read/write | read/write | read/write | read/write
EditMode | read-only | read-only | read-only | read-only
EOF | read-only | read-only | read-only | read-only
Filter | read/write | read/write | read/write | read/write
LockType | read/write | read/write | read/write | read/write
MarshalOptions | read/write | read/write | read/write | read/write
MaxRecords | read/write | read/write | read/write | read/write
PageCount | not available | not available | read-only | read-only
PageSize | read/write | read/write | read/write | read/write
RecordCount | not available | not available | read-only | read-only
Source | read/write | read/write | read/write | read/write
State | read-only | read-only | read-only | read-only
Status | read-only | read-only | read-only | read-only

The AbsolutePosition and AbsolutePage properties are write-only when ADO is used with version 1.0 of the Microsoft OLE DB Provider for ODBC.

Availability of standard ADO Recordset methods:
Method | ForwardOnly | Dynamic | Keyset | Static
AddNew | Yes | Yes | Yes | Yes
CancelBatch | Yes | Yes | Yes | Yes
CancelUpdate | Yes | Yes | Yes | Yes
Clone | No | No | Yes | Yes
Close | Yes | Yes | Yes | Yes
Delete | Yes | Yes | Yes | Yes
GetRows | Yes | Yes | Yes | Yes
Move | Yes | Yes | Yes | Yes
MoveFirst | Yes | Yes | Yes | Yes
MoveLast | No | Yes | Yes | Yes
MoveNext | Yes | Yes | Yes | Yes
MovePrevious | No | Yes | Yes | Yes
NextRecordset* | Yes | Yes | Yes | Yes
Open | Yes | Yes | Yes | Yes
Requery | Yes | Yes | Yes | Yes
Resync | No | No | Yes | Yes
Supports | Yes | Yes | Yes | Yes
Update | Yes | Yes | Yes | Yes
UpdateBatch | Yes | Yes | Yes | Yes

*Not supported for Microsoft Access databases.

For specific implementation details and functional information about the Microsoft OLE DB Provider for ODBC, consult the documents "Microsoft OLE DB Provider for ODBC" and the "Microsoft OLE DB Programmer's Reference," available in the OLE DB SDK, which you can review or download at Microsoft OLE DB Web page. The "Microsoft ODBC Programmer's Reference" is available on the Microsoft ODBC Web page.


Microsoft OLE DB Provider for Index Server

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Microsoft OLE DB Provider for Microsoft Index Server

The Microsoft OLE DB Provider for Microsoft Index Server provides programmatic read-only access to file system and Web data indexed by Microsoft Index Server 2.0. ADO applications can issue SQL queries to retrieve content and file property information. Microsoft Index Server and its OLE DB provider are included in the Microsoft Windows NT 4.0 Option Pack.

The provider is free-threaded and unicode enabled.

Connection String Parameters

To connect to this provider, set the Provider= argument to the ConnectionString property to

MSIDXS

Reading the Provider property will return this string as well.

Command Text

The Index Server SQL query syntax consists of extensions to the SQL-92 SELECT statement and its FROM and WHERE clauses. The results of the query are returned via OLE DB rowsets which can be consumed by ADO and manipulated as Recordset objects.

You can search for exact words or phrases, or use wildcards to search for patterns or stems of words. The search logic can be based on boolean decisions, weighted terms' proximity to other words. You can also search by "free text," which find matches based on meaning, rather than exact words.

The specific command dialect is fully documented in the "Microsoft Index Server Reference" under "SQL Access to Index Server Data."

The provider does not accept stored procedure calls or simple table names (for example, the CommandType property will always be adCmdText).

Recordset Behavior

The following tables list the features available with a Recordset object opened with this provider. Only the Static cursor type (adOpenStatic) is available.

For more detailed information on Recordset behavior for your provider configuration, run the Supports method, and enumerate the Properties collection of the Recordset to determine whether provider-specific dynamic properties are present.

Availability of standard ADO Recordset properties:
AbsolutePage | read/write
AbsolutePosition | read/write
ActiveConnection | read-only
BOF | read-only
Bookmark* | read/write
CacheSize | read/write
CursorLocation | always adUseServer
CursorType | always adOpenStatic
EditMode | always adEditNone
EOF | read-only
Filter | read/write
LockType | read/write
MarshalOptions | not available
MaxRecords | read/write
PageCount | read-only
PageSize | read/write
RecordCount | read-only
Source | read/write
State | read-only
Status | read-only

*Bookmarks must be enabled on the provider in order for this feature to exist on the Recordset.

Availability of standard ADO Recordset methods:
AddNew | No
CancelBatch | No
CancelUpdate | No
Clone | Yes
Close | Yes
Delete | No
GetRows | Yes
Move | Yes
MoveFirst | Yes
MoveLast | Yes
MoveNext | Yes
MovePrevious | Yes
NextRecordset | Yes
Open | Yes
Requery | Yes
Resync | Yes
Supports | Yes
Update | No
UpdateBatch | No

For specific implementation details and functional information about the Microsoft OLE DB Provider for Microsoft Index Server, consult the "Microsoft OLE DB Programmer's Reference" and "Microsoft Index Server" documentation, or visit the Microsoft Index Server Web page.


Microsoft OLE DB Provider for Microsoft Active Directory Service

The Microsoft® Active Directory Service Interfaces (ADSI) Provider Version 1.0 allows ADO to access heterogeneous directory services through ADSI. This gives ADO applications read-only access to the Microsoft Windows NT® 4.0 directory services, as well as to any LDAP compliant directory service and Novell Directory Services. ADSI itself is based on a provider model, so if there is a new provider giving access to another directory, the ADO application will be able to access it seamlessly. The ADSI provider is free-threaded and unicode-enabled.

Connection String Parameters

To connect to this provider, set the Provider argument of the ConnectionString property to

ADSDSOObject

Reading the Provider property will return this string as well.

Command Text

The provider recognizes a four-part command text string in the following syntax:

"Root; Filter; Attributes[; Scope]"
Value | Description
Root | The ADsPath object from which the search is to be started (that is, the root of the search).
Filter | The search filter in the RFC 960 format.
Attributes | A comma-delimited list of attributes to be returned.
Scope Optional. A String that specifies the scope of the search. Can be one of the following:
  • Base — Search only the base object (Root of the search)

  • OneLevel — Search only one level

  • Subtree — Search the entire subtree.

The provider does not accept stored procedure calls or simple table names (for example, the CommandType property will always be adCmdText). See the ADSI documentation for a more complete description of the command text elements.

Recordset Behavior

The following tables list the features available with on a Recordset object opened with this provider. Only the Static cursor type (adOpenStatic) is available.

For more detailed information about Recordset behavior for your provider configuration, run the Supports method, and enumerate the Properties collection of the Recordset to determine whether provider-specific dynamic properties are present.

Availability of standard ADO Recordset properties:
AbsolutePage | read/write
AbsolutePosition | read/write
ActiveConnection | read-only
BOF | read-only
Bookmark | read/write
CacheSize | read/write
CursorLocation | always adUseServer
CursorType | always adOpenStatic
EditMode | always adEditNone
EOF | read-only
Filter | read/write
LockType | read/write
MarshalOptions | not available
MaxRecords | read/write
PageCount | read-only
PageSize | read/write
RecordCount | read-only
Source | read/write
State | read-only
Status | read-only

Availability of standard ADO Recordset methods:
AddNew | No
CancelBatch | No
CancelUpdate | No
Clone | Yes
Close | Yes
Delete | No
GetRows | Yes
Move | Yes
MoveFirst | Yes
MoveLast | Yes
MoveNext | Yes
MovePrevious | Yes
NextRecordset | Yes
Open | Yes
Requery | Yes
Resync | Yes
Supports | Yes
Update | No
UpdateBatch | No

For more information about ADSI in general and the specifics of the provider, please refer to the documentation provided in the ADSI SDK. The SDK can be installed from the ADSI Web Page.


ADO Error Codes

In addition to the provider errors that are described in the Error object and Errors collection, ADO itself can return errors to the exception-handling mechanism of your run-time environment. Use your programming language's error trapping mechanism, such as the On Error statement in Microsoft® Visual Basic®, to trap and handle the following errors. Both decimal and hexadecimal error code values are shown.
Constant Name Number Description
adErrInvalidArgument 3001

0x800A0BB9

The application is using arguments that are of the wrong type, are out of acceptable range, or are in conflict with one another.
adErrNoCurrentRecord 3021

0x800A0BCD

Either BOF or EOF is True, or the current record has been deleted; the operation requested by the application requires a current record.
adErrIllegalOperation 3219

0x800A0C93

The operation requested by the application is not allowed in this context.
adErrInTransaction 3246

0x800A0CAE

The application may not explicitly close a Connection object while in the middle of a transaction.
adErrFeatureNotAvailable 3251

0x800A0CB3

The operation requested by the application is not supported by the provider.
adErrItemNotFound 3265

0x800A0CC1

ADO could not find the object in the collection corresponding to the name or ordinal reference requested by the application.
adErrObjectInCollection 3367

0x800A0D27

Can't append. Object already in collection.
adErrObjectNotSet 3420

0x800A0D5C

The object referenced by the application no longer points to a valid object.
adErrDataConversion 3421

0x800A0D5D

The application is using a value of the wrong type for the current operation.
adErrObjectClosed 3704

0x800A0E78

The operation requested by the application is not allowed if the object is closed.
adErrObjectOpen 3705

0x800A0E79

The operation requested by the application is not allowed if the object is open.
adErrProviderNotFound 3706

0x800A0E7A

ADO could not find the specified provider.
adErrBoundToCommand 3707

0x800A0E7B

The application cannot change the ActiveConnection property of a Recordset object with a Command object as its source.
adErrInvalidParamInfo 3708

0x800A0E7C

The application has improperly defined a Parameter object.
adErrInvalidConnection 3709

0x800A0E7D

The application requested an operation on an object with a reference to a closed or invalid Connection object.


(Untitled)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

ADO Objects

Use these reference topics to learn how to use all of the ADO objects.


(Untitled)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

ADO Collections

Use these reference topics to learn how to use all of the ADO collections.


(Untitled)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

ADO Methods

Use these reference topics to learn how to use all of the ADO methods.


(Untitled)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

ADO Properties

Use these reference topics to learn how to use all of the ADO properties.


(Untitled)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

ADO Code Examples

Use these code examples to learn how ADO features are used in both Microsoft Visual Basic and in Microsoft Visual Basic, Scripting Edition. You can run these examples by copying and pasting them into your own source files.


AddNew Method (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

AddNew Method - ADO

Creates a new record for an updatable Recordset object.

Applies To

Recordset

Syntax

recordset.AddNew Fields, Values

Parameters

Fields Optional. A single name or an array of names or ordinal positions of the fields in the new record.

Values Optional. A single value or an array of values for the fields in the new record. If Fields is an array, Values must also be an array with the same number of members; otherwise, an error occurs. The order of field names must match the order of field values in each array.

Remarks

Use the AddNew method to create and initialize a new record. Use the Supports method with adAddNew to verify whether you can add records to the current Recordset object.

After you call the AddNew method, the new record becomes the current record and remains current after you call the Update method. If the Recordset object does not support bookmarks, you may not be able to access the new record once you move to another record. Depending on your cursor type, you may need to call the Requery method to make the new record accessible.

If you call AddNew while editing the current record or while adding a new record, ADO calls the Update method to save any changes and then creates the new record.

The behavior of the AddNew method depends on the updating mode of the Recordset object and whether or not you pass the Fields and Values arguments.

In immediate update mode (the provider writes changes to the underlying data source once you call the Update method), calling the AddNew method without arguments sets the EditMode property to adEditAdd. The provider caches any field value changes locally. Calling the Update method posts the new record to the database and resets the EditMode property to adEditNone. If you pass the Fields and Values arguments, ADO immediately posts the new record to the database (no Update call is necessary); the EditMode property value does not change (adEditNone).

In batch update mode (the provider caches multiple changes and writes them to the underlying data source only when you call the UpdateBatch method), calling the AddNew method without arguments sets the EditMode property to adEditAdd. The provider caches any field value changes locally. Calling the Update method adds the new record to the current recordset and resets the EditMode property to adEditNone, but the provider does not post the changes to the underlying database until you call the UpdateBatch method. If you pass the Fields and Values arguments, ADO sends the new record to the provider for storage in a cache; you need to call the UpdateBatch method to post the new record to the underlying database.

Examples

AddNew Method Example (VB)


Append Method (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Append Method - ADO

Appends an object to a collection.

Applies To

Parameters

Syntax

collection.Append object

Parameters

object An object variable representing the object to be appended.

Remarks

Use the Append method on a collection to add an object to that collection. This method is available only on the Parameters collection of a Command object. You must set the Type property of a Parameter object before appending it to the Parameters collection. If you select a variable-length data type, you must also set the Size property to a value greater than zero.

By describing the parameter yourself, you can minimize calls to the provider and consequently improve performance when using stored procedures or parameterized queries. However, you must know the properties of the parameters associated with the stored procedure or parameterized query you wish to call. Use the CreateParameter method to create Parameter objects with the appropriate property settings and use the Append method to add them to the Parameters collection. This lets you set and return parameter values without having to call the provider for the parameter information. If you are writing to a provider that does not supply parameter information, you must manually populate the Parameters collection using this method to be able to use parameters at all.

Examples

Append and CreateParameter Methods Example (VB)


AppendChunk Method (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

AppendChunk Method - ADO

Appends data to a large text or binary data Field or Parameter object.

Applies To

Field, Parameter

Syntax

object.AppendChunk Data

Parameters

object A Field or Parameter object.

Data A Variant containing the data you want to append to the object.

Remarks

Use the AppendChunk method on a Field or Parameter object to fill it with long binary or character data. In situations where system memory is limited, you can use the AppendChunk method to manipulate long values in portions rather than in their entirety.

Field

If the adFldLong bit in the Attributes property of a Field object is set to true, you can use the AppendChunk method for that field.

The first AppendChunk call on a Field object writes data to the field, overwriting any existing data. Subsequent AppendChunk calls add to existing data. If you are appending data to one field and then you set or read the value of another field in the current record, ADO assumes that you are done appending data to the first field. If you call the AppendChunk method on the first field again, ADO interprets the call as a new AppendChunk operation and overwrites the existing data. Accessing fields in other Recordset objects (that are not clones of the first Recordset object) will not disrupt AppendChunk operations.

If there is no current record when you call AppendChunk on a Field object, an error occurs.

Parameter

If the adFldLong bit in the Attributes property of a Parameter object is set to true, you can use the AppendChunk method for that parameter.

The first AppendChunk call on a Parameter object writes data to the parameter, overwriting any existing data. Subsequent AppendChunk calls on a Parameter object add to existing parameter data. An AppendChunk call that passes a Null value generates an error; you must manually set the Value property of the Parameter object to a zero-length string ("") in order to clear its value.

Examples

AppendChunk and GetChunk Methods Example (VB)


BeginTrans, CommitTrans, and RollbackTrans Methods (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

BeginTrans, CommitTrans, and RollbackTrans Methods - ADO

The transaction methods manage transaction processing within a Connection object as follows:

  • BeginTrans begins a new transaction.

  • CommitTrans saves any changes and ends the current transaction. It may also start a new transaction.

  • RollbackTrans cancels any changes made during the current transaction and ends the transaction. It may also start a new transaction.

Applies To

Connection

Syntax

level = connection.BeginTrans()

connection.BeginTrans

connection.CommitTrans

connection.RollbackTrans

Return Value

BeginTrans can be called as a function that returns a Long variable indicating the nesting level of the transaction.

Remarks

Use these methods with a Connection object when you want to save or cancel a series of changes made to the source data as a single unit. For example, to transfer money between accounts, you subtract an amount from one and add the same amount to the other. If either update fails, the accounts no longer balance. Making these changes within an open transaction ensures either all or none of the changes goes through.

Note Not all providers support transactions. Check that the provider-defined property "Transaction DDL" appears in the Connection object's Properties collection, indicating that the provider supports transactions. If the provider does not support transactions, calling one of these methods will return an error.

Once you call the BeginTrans method, the provider will no longer instantaneously commit any changes you make until you call CommitTrans or RollbackTrans to end the transaction.

For providers that support nested transactions, calling the BeginTrans method within an open transaction starts a new, nested transaction. The return value indicates the level of nesting: a return value of "1" indicates you have opened a top-level transaction (that is, the transaction is not nested within another transaction), "2" indicates that you have opened a second-level transaction (a transaction nested within a top-level transaction), and so forth. Calling CommitTrans or RollbackTrans affects only the most recently opened transaction; you must close or rollback the current transaction before you can resolve any higher level transactions.

Calling the CommitTrans method saves changes made within an open transaction on the connection and ends the transaction. Calling the RollbackTrans method reverses any changes made within an open transaction and ends the transaction. Calling either method when there is no open transaction generates an error.

Depending on the Connection object's Attributes property, calling either the CommitTrans or RollbackTrans methods may automatically start a new transaction. If the Attributes property is set to adXactCommitRetaining, the provider automatically starts a new transaction after a CommitTrans call. If the Attributes property is set to adXactAbortRetaining, the provider automatically starts a new transaction after a RollbackTrans call.

Remote Data Service Usage The BeginTrans, CommitTrans, and RollbackTrans methods are not available on a client-side Connection object.

Examples

BeginTrans, CommitTrans, and RollbackTrans Methods Example (VB)


CancelBatch Method (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

CancelBatch Method - ADO

Cancels a pending batch update.

Applies To

Recordset

Syntax

recordset.CancelBatch AffectRecords

Parameters

AffectRecords Optional. An AffectEnum value that determines how many records the CancelBatch method will affect. Can be one of the following constants:
adAffectCurrent | Cancel pending updates only for the current record.
adAffectGroup | Cancel pending updates for records that satisfy the current Filter property setting. You must set the Filter property to one of the valid predefined constants in order to use this option.
adAffectAll | Default. Cancel pending updates for all the records in the Recordset object, including any hidden by the current Filter property setting.

Remarks

Use the CancelBatch method to cancel any pending updates in a recordset in batch update mode. If the recordset is in immediate update mode, calling CancelBatch without adAffectCurrent generates an error.

If you are editing the current record or are adding a new record when you call CancelBatch, ADO first calls the CancelUpdate method to cancel any cached changes; after that, all pending changes in the recordset are canceled.

It's possible that the current record will be indeterminable after a CancelBatch call, especially if you were in the process of adding a new record. For this reason, it is prudent to set the current record position to a known location in the recordset after the CancelBatch call. For example, call the MoveFirst method.

If the attempt to cancel the pending updates fails because of a conflict with the underlying data (for example, a record has been deleted by another user), the provider returns warnings to the Errors collection but does not halt program execution. A run-time error occurs only if there are conflicts on all the requested records. Use the Filter property (adFilterAffectedRecords) and the Status property to locate records with conflicts.

Examples

UpdateBatch and CancelBatch Methods Example (VB)


CancelUpdate Method (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

CancelUpdate Method - ADO

Cancels any changes made to the current record or to a new record prior to calling the Update method.

Applies To

Recordset

Syntax

recordset.CancelUpdate

Remarks

Use the CancelUpdate method to cancel any changes made to the current record or to discard a newly added record. You cannot undo changes to the current record or to a new record after you call the Update method unless the changes are either part of a transaction that you can roll back with the RollbackTrans method or part of a batch update that you can cancel with the CancelBatch method.

If you are adding a new record when you call the CancelUpdate method, the record that was current prior to the AddNew call becomes the current record again.

If you have not changed the current record or added a new record, calling the CancelUpdate method generates an error.

Examples

Update and CancelUpdate Methods Example (VB)


Clear Method (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Clear Method - ADO

Removes all of the objects in a collection.

Applies To

Errors

Syntax

Errors.Clear

Remarks

Use the Clear method on the Errors collection to remove all existing Error objects from the collection. When an error occurs, ADO automatically clears the Errors collection and fills it with Error objects based on the new error. However, some properties and methods return warnings that appear as Error objects in the Errors collection but do not halt a program's execution. Before you call the Resync, UpdateBatch, or CancelBatch methods on a Recordset object or before you set the Filter property on a Recordset object, call the Clear method on the Errors collection. Doing so enables you to read the Count property of the Errors collection to test for returned warnings as a result of these specific calls.

Examples

Execute, Requery, and Clear Method Example (VB)


Clone Method (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Clone Method - ADO

Creates a duplicate Recordset object from an existing Recordset object.

Applies To

Recordset

Syntax

Set rstDuplicate = rstOriginal.Clone ()

Return Values

Returns a Recordset object reference.

Parameters

rstDuplicate An object variable identifying the duplicate Recordset object you're creating.

rstOriginal An object variable identifying the Recordset object you want to duplicate.

Remarks

Use the Clone method to create multiple, duplicate Recordset objects, particularly if you want to be able to maintain more than one current record in a given set of records. Using the Clone method is more efficient than creating and opening a new Recordset object with the same definition as the original.

The current record of a newly created clone is set to the first record.

Changes you make to one Recordset object are visible in all of its clones regardless of cursor type. However, once you execute Requery on the original Recordset, the clones will no longer be synchronized to the original.

Closing the original Recordset does not close its copies; closing a copy does not close the original or any of the other copies.

You can only clone a Recordset object that supports bookmarks. Bookmark values are interchangeable; that is, a bookmark reference from one Recordset object refers to the same record in any of its clones.

Examples

Clone Method Example (VB)


Close Method (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Close Method - ADO

Closes an open object and any dependent objects.

Applies To

Connection, Recordset

Syntax

object.Close

Remarks

Use the Close method to close either a Connection object or a Recordset object to free any associated system resources. Closing an object does not remove it from memory; you may change its property settings and open it again later. To completely eliminate an object from memory, set the object variable to Nothing.

Connection

Using the Close method to close a Connection object also closes any active Recordset objects associated with the connection. A Command object associated with the Connection object you are closing will persist, but it will no longer be associated with a Connection object, that is, its ActiveConnection property will be set to Nothing. Also, the Command object's Parameters collection will be cleared of any provider-defined parameters.

You can later call the Open method to reestablish the connection to the same or another data source. While the Connection object is closed, calling any methods that require an open connection to the data source generates an error.

Closing a Connection object while there are open Recordset objects on the connection rolls back any pending changes in all of the Recordset objects. Explicitly closing a Connection object (calling the Close method) while a transaction is in progress generates an error. If a Connection object falls out of scope while a transaction is in progress, ADO automatically rolls back the transaction.

Recordset

Using the Close method to close a Recordset object releases the associated data and any exclusive access you may have had to the data through this particular Recordset object. You can later call the Open method to reopen the Recordset with the same or modified attributes. While the Recordset object is closed, calling any methods that require a live cursor generates an error.

If an edit is in progress while in immediate update mode, calling the Close method generates an error; call the Update or CancelUpdate method first. If you close the Recordset object during batch updating, all changes since the last UpdateBatch call are lost.

If you use the Clone method to create copies of an open Recordset object, closing the original or a clone does not affect any of the other copies.

Examples

Open and Close Methods Example (VB)


CreateParameter Method (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

CreateParameter Method - ADO

Creates a new Parameter object with the specified properties.

Applies To

Command

Syntax

Set parameter = command.CreateParameter (Name, Type, Direction, Size, Value)

Return Value

Returns a Parameter object.

Parameters

Name Optional. A String representing the name of the Parameter object.

Type Optional. A Long value specifying the data type of the Parameter object. See the Type property for valid settings.

Direction Optional. A Long value specifying the type of Parameter object. See the Direction property for valid settings.

Size Optional. A Long value specifying the maximum length for the parameter value in characters or bytes.

Value, varValue Optional. A Variant specifying the value for the Parameter object.

Remarks

Use the CreateParameter method to create a new Parameter object with the specified name, type, direction, size, and value. Any values you pass in the arguments are written to the corresponding Parameter properties.

This method does not automatically append the Parameter object to the Parameters collection of a Command object. This lets you set additional properties whose values ADO will validate when you append the Parameter object to the collection.

If you specify a variable-length data type in the Type argument, you must either pass a Size argument or set the Size property of the Parameter object before appending it to the Parameters collection; otherwise, an error occurs.

Examples

Append and CreateParameter Methods Example (VB)


Delete Method (Collection - ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Delete Method (Parameters Collection) ADO

Deletes an object from the Parameters collection.

Applies To

Parameters

Syntax

Parameters.Delete Index

Parameters

Index A String representing the name of the object you wish to delete, or the object’s ordinal position (index) in the collection.

Remarks

Using the Delete method on a collection lets you remove one of the objects in the collection. This method is available only on the Parameters collection of a Command object. You must use the Parameter object's Name property or it's collection index when calling the Delete method — an object variable is not a valid argument.


Delete Method (Recordset - ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Delete Method (Recordset) ADO

Deletes the current record or a group of records.

Applies To

Recordset

Syntax

recordset.Delete AffectRecords

Parameters

AffectRecords Optional. An AffectEnum value that determines how many records the Delete method will affect. Can be one of the following constants:
adAffectCurrent | Default. Delete only the current record.
adAffectGroup | Delete the records that satisfy the current Filter property setting. You must set the Filter property to one of the valid predefined constants in order to use this option.

Remarks

Using the Delete method marks the current record or a group of records in a Recordset object for deletion. If the Recordset object doesn't allow record deletion, an error occurs. If you are in immediate update mode, deletions occur in the database immediately. Otherwise, the records are marked for deletion from the cache and the actual deletion happens when you call the UpdateBatch method. (Use the Filter property to view the deleted records.)

Retrieving field values from the deleted record generates an error. After deleting the current record, the deleted record remains current until you move to a different record. Once you move away from the deleted record, it is no longer accessible.

If you nest deletions in a transaction, you can recover deleted records with the RollbackTrans method. If you are in batch update mode, you can cancel a pending deletion or group of pending deletions with the CancelBatch method.

If the attempt to delete records fails because of a conflict with the underlying data (for example, a record has already been deleted by another user), the provider returns warnings to the Errors collection but does not halt program execution. A run-time error occurs only if there are conflicts on all the requested records.

Examples

Delete Method Example (VB)


Execute method (Command - ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Execute Method (Command) ADO

Executes the query, SQL statement, or stored procedure specified in the CommandText property.

Applies To

Command

Syntax

For a row-returning Command:

Set recordset = command.Execute( RecordsAffected, Parameters, Options )

For a non row-returning Command:

command.Execute RecordsAffected, Parameters, Options

Return Values

Returns a Recordset object reference.

Parameters

RecordsAffected Optional. A Long variable to which the provider returns the number of records that the operation affected.

Parameters Optional. A Variant array of parameter values passed with an SQL statement. (Output parameters will not return correct values when passed in this argument.)

Options Optional. A Long value that indicates how the provider should evaluate the CommandText property of the Command object:
adCmdText | Indicates that the provider should evaluate CommandText as a textual definition of a command, such as an SQL statement.
adCmdTable | Indicates that the provider should evaluate CommandText as a table name.
adCmdStoredProc | Indicates that the provider should evaluate CommandText as a stored procedure.
adCmdUnknown | Indicates that the type of command in CommandText is not known.

See the CommandType property for a more detailed explanation of the first four constants in this list.

Remarks

Using the Execute method on a Command object executes the query specified in the CommandText property of the object. If the CommandText property specifies a row-returning query, any results the execution generates are stored in a new Recordset object. If the command is not a row-returning query, the provider returns a closed Recordset object. Some application languages allow you to ignore this return value if no Recordset is desired.

If the query has parameters, the current values for the Command object's parameters are used unless you override these with parameter values passed with the Execute call. You can override a subset of the parameters by omitting new values for some of the parameters when calling the Execute method. The order in which you specify the parameters is the same order in which the method passes them. For example, if there were four (or more) parameters and you wanted to pass new values for only the first and fourth parameters, you would pass Array(var1,,,var4) as the Parameters argument.

Note Output parameters will not return correct values when passed in the Parameters argument.

Examples

Execute, Requery, and Clear Methods Example (VB)


Execute method (Connection - ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Execute Method (Connection) ADO

Executes the specified query, SQL statement, stored procedure, or provider-specific text.

Applies To

Connection

Syntax

For a non row-returning command string:

connection.Execute CommandText, RecordsAffected, Options

For a row-returning command string:

Set recordset = connection.Execute (CommandText, RecordsAffected, Options)

Return Values

Returns a Recordset object reference.

Parameters

CommandText A String containing the SQL statement, table name, stored procedure, or provider-specific text to execute.

RecordsAffected Optional. A Long variable to which the provider returns the number of records that the operation affected.

Options Optional. A Long value that indicates how the provider should evaluate the CommandText argument:
adCmdText | Indicates that the provider should evaluate CommandText as a textual definition of a command.
adCmdTable | Indicates that the provider should evaluate CommandText as a table name.
adCmdStoredProc | Indicates that the provider should evaluate CommandText as a stored procedure.
adCmdUnknown | Indicates that the type of command in the CommandText argument is not known.

See the CommandType property for a more detailed explanation of the first four constants in this list.

Remarks

Using the Execute method on a Connection object executes whatever query you pass to the method in the CommandText argument on the specified connection. If the CommandText argument specifies a row-returning query, any results the execution generates are stored in a new Recordset object. If the command is not a row-returning query, the provider returns a closed Recordset object.

The returned Recordset object is always a read-only, forward-only cursor. If you need a Recordset object with more functionality, first create a Recordset object with the desired property settings, then use the Recordset object’s Open method to execute the query and return the desired cursor type.

The contents of the CommandText argument are specific to the provider and can be standard SQL syntax or any special command format that the provider supports.

Examples

Execute, Requery, and Clear Methods Example (VB)


GetChunk Method (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

GetChunk Method - ADO

Returns all or a portion of the contents of a large text or binary data Field object.

Applies To

Field

Syntax

variable = field.GetChunk( Size )

Return Values

Returns a Variant.

Parameters

Size A Long expression equal to the number of bytes or characters you want to retrieve.

Remarks

Use the GetChunk method on a Field object to retrieve part or all of its long binary or character data. In situations where system memory is limited, you can use the GetChunk method to manipulate long values in portions rather than in their entirety.

The data a GetChunk call returns is assigned to variable. If Size is greater than the remaining data, the GetChunk method returns only the remaining data without padding variable with empty spaces. If the field is empty, the GetChunk method returns Null.

Each subsequent GetChunk call retrieves data starting from where the previous GetChunk call left off. However, if you are retrieving data from one field and then you set or read the value of another field in the current record, ADO assumes you are done retrieving data from the first field. If you call the GetChunk method on the first field again, ADO interprets the call as a new GetChunk operation and starts reading from the beginning of the data. Accessing fields in other Recordset objects (that are not clones of the first Recordset object) will not disrupt GetChunk operations.

If the adFldLong bit in the Attributes property of a Field object is set to true, you can use the GetChunk method for that field.

If there is no current record when you use the GetChunk method on a Field object, error 3021 (no current record) occurs.

Examples

AppendChunk and GetChunk Methods Example (VB)


GetRows Method (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

GetRows Method - ADO

Retrieves multiple records of a Recordset into an array.

Applies To

Recordset

Syntax

array = recordset.GetRows( Rows, Start, Fields )

Return Values

Returns a two-dimensional array.

Parameters

Rows Optional. A Long expression indicating the number of records to retrieve. Default is adGetRowsRest (-1).

Start Optional. A String or Variant that evaluates to the bookmark for the record from which the GetRows operation should begin. You can also use one of the following BookmarkEnum values:
adBookmarkCurrent | Start at the current record.
adBookmarkFirst | Start at the first record.
adBookmarkLast | Start at the last record.

Fields Optional. A Variant representing a single field name or ordinal position or an array of field names or ordinal position numbers. ADO returns only the data in these fields.

Remarks

Use the GetRows method to copy records from a Recordset into a two-dimensional array. The first subscript identifies the field and the second identifies the record number. The array variable is automatically dimensioned to the correct size when the GetRows method returns the data.

If you do not specify a value for the Rows argument, the GetRows method automatically retrieves all the records in the Recordset object. If you request more records than are available, GetRows returns only the number of available records.

If the Recordset object supports bookmarks, you can specify at which record the GetRows method should begin retrieving data by passing the value of that record's Bookmark property.

If you want to restrict the fields the GetRows call returns, you can pass either a single field name/number or an array of field names/numbers in the Fields argument.

After you call GetRows, the next unread record becomes the current record, or the EOF property is set to True if there are no more records.

Examples

GetRows Method Example (VB)


Move Method (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Move Method - ADO

Moves the position of the current record in a Recordset object.

Applies To

Recordset

Syntax

recordset.Move NumRecords, Start

Parameters

NumRecords A signed Long expression specifying the number of records the current record position moves.

Start Optional. A String or Variant that evaluates to a bookmark. You can also use one of the following BookmarkEnum values:
adBookmarkCurrent | Default. Start at the current record.
adBookmarkFirst | Start at the first record.
adBookmarkLast | Start at the last record.

Remarks

The Move method is supported on all Recordset objects.

If the NumRecords argument is greater than zero, the current record position moves forward (toward the end of the recordset). If NumRecords is less than zero, the current record position moves backward (toward the beginning of the recordset).

If the Move call would move the current record position to a point before the first record, ADO sets the current record to the position before the first record in the recordset (BOF is True). An attempt to move backward when the BOF property is already True generates an error.

If the Move call would move the current record position to a point after the last record, ADO sets the current record to the position after the last record in the recordset (EOF is True). An attempt to move forward when the EOF property is already True generates an error.

Calling the Move method from an empty Recordset object generates an error.

If you pass the Start argument, the move is relative to the record with this bookmark assuming the Recordset object supports bookmarks. If not specified, the move is relative to the current record.

If you are using the CacheSize property to locally cache records from the provider, passing a NumRecords that moves the current record position outside of the current group of cached records forces ADO to retrieve a new group of records starting from the destination record. The CacheSize property determines the size of the newly retrieved group, and the destination record is the first record retrieved.

If the Recordset object is forward-only, a user can still pass a NumRecords less than zero as long as the destination is within the current set of cached records. If the Move call would move the current record position to a record before the first cached record, an error will occur. Thus, you can use a record cache that supports full scrolling over a provider that only supports forward scrolling. Because cached records are loaded into memory, you should avoid caching more records than is necessary. Even if a forward-only Recordset object supports backward moves in this way, calling the MovePrevious method on any forward-only Recordset object still generates an error.

Examples

Move Method Example (VB)


MoveFirst, MoveLast, MoveNext, and MovePrevious Methods (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

MoveFirst, MoveLast, MoveNext, and MovePrevious Methods - ADO

Moves to the first, last, next, or previous record in a specified Recordset object and makes that record the current record.

Applies To

Recordset

Syntax

recordset.{MoveFirst | MoveLast | MoveNext | MovePrevious}

Remarks

Use the MoveFirst method to move the current record position to the first record in the recordset.

Use the MoveLast method to move the current record position to the last record in the recordset. The Recordset object must support bookmarks or backward cursor movement; otherwise, the method call will generate an error.

Use the MoveNext method to move the current record position one record forward (toward the bottom of the Recordset). If the last record is the current record and you call the MoveNext method, ADO sets the current record to the position after the last record in the Recordset (EOF is True). An attempt to move forward when the EOF property is already True generates an error.

Use the MovePrevious method to move the current record position one record backward (toward the top of the Recordset). The Recordset object must support bookmarks or backward cursor movement; otherwise, the method call will generate an error. If the first record is the current record and you call the MovePrevious method, ADO sets the current record to the position before the first record in the Recordset (BOF is True). An attempt to move backward when the BOF property is already True generates an error. If the Recordset object does not support either bookmarks or backward cursor movement, the MovePrevious method will generate an error.

If the recordset is forward-only and you want to support both forward and backward scrolling, you can use the CacheSize property to create a record cache that will support backward cursor movement through the Move method. Because cached records are loaded into memory, you should avoid caching more records than is necessary. You can call the MoveFirst method in a forward-only Recordset object; doing so may cause the provider to re-execute the command that generated the Recordset object.

Examples

MoveFirst, MoveLast, MoveNext, and MovePrevious Methods Example (VB)


NextRecordset Method (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

NextRecordset Method - ADO

Clears the current Recordset object and returns the next recordset by advancing through a series of commands.

Applies To

Recordset

Syntax

Set recordset2 = recordset1.NextRecordset( RecordsAffected )

Return Values

Returns a Recordset object. In the syntax model, recordset1 and recordset2 can be the same Recordset object, or you can use separate objects.

Parameters

RecordsAffected Optional. A Long variable to which the provider returns the number of records that the current operation affected.

Remarks

Use the NextRecordset method to return the results of the next command in a compound command statement or of a stored procedure that returns multiple results. If you open a Recordset object based on a compound command statement (for example, "SELECT * FROM table1;SELECT * FROM table2") using the Execute method on a Command or the Open method on a Recordset, ADO executes only the first command and returns the results to recordset. To access the results of subsequent commands in the statement, call the NextRecordset method.

As long as there are additional results, the NextRecordset method will continue to return Recordset objects. If a row-returning command returns no records, the returned Recordset object will be empty; test for this case by verifying that the BOF and EOF properties are both True. If a non row-returning command executes successfully, the returned Recordset object will be closed, which you can verify by testing the State property on the Recordset. When there are no more results, recordset will be set to Nothing.

If an edit is in progress while in immediate update mode, calling the NextRecordset method generates an error; call the Update or CancelUpdate method first.

If you need to pass parameters for more than one command in the compound statement by filling the Parameters collection or by passing an array with the original Open or Execute call, the parameters must be in the same order in the collection or array as their respective commands in the command series. You must finish reading all the results before reading output parameter values.

When you call the NextRecordset method, ADO executes only the next command in the statement. If you explicitly close the Recordset object before stepping through the entire command statement, ADO never executes the remaining commands.

Remote Data Service Usage The NextRecordset method is not available on a client-side (ADOR) Recordset object.

Examples

NextRecordset Method Example (VB)


Open Method (Connection - ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Open Method (Connection) ADO

Opens a connection to a data source.

Applies To

Connection

Syntax

connection.Open ConnectionString, UserID, Password

Parameters

ConnectionString Optional. A String containing connection information. See the ConnectionString property for details on valid settings.

UserID Optional. A String containing a user name to use when establishing the connection.

Password Optional. A String containing a password to use when establishing the connection.

Remarks

Using the Open method on a Connection object establishes the physical connection to a data source. After this method successfully completes, the connection is live and you can issue commands against it and process results.

Use the optional ConnectionString argument to specify a connection string containing a series of argument = value statements separated by semicolons. The ConnectionString property automatically inherits the value used for the ConnectionString argument. Therefore, you can either set the ConnectionString property of the Connection object before opening it, or use the ConnectionString argument to set or override the current connection parameters during the Open method call.

If you pass user and password information both in the ConnectionString argument and in the optional UserID and Password arguments, the results may be unpredictable; you should only pass such information in either the ConnectionString argument or the UserID and Password arguments.

When you have concluded your operations over an open Connection, use the Close method to free any associated system resources. Closing an object does not remove it from memory; you may change its property settings and use the Open method to open it again later. To completely eliminate an object from memory, set the object variable to Nothing.

Remote Data Service Usage When used on a client-side Connection object, the Open method doesn’t actually establish a connection to the server until a Recordset is opened on the Connection object.

Examples

Open and Close Methods Example (VB)


Open Method (Recordset - ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Open Method (Recordset) ADO

Opens a cursor.

Applies To

Recordset

Syntax

recordset.Open Source, ActiveConnection, CursorType, LockType, Options

Parameters

Source Optional. A Variant that evaluates to a valid Command object variable name, an SQL statement, a table name, or a stored procedure call.

ActiveConnection Optional. Either a Variant that evaluates to a valid Connection object variable name, or a String containing ConnectionString parameters.

CursorType Optional. A CursorTypeEnum value that determines the type of cursor that the provider should use when opening the Recordset. Can be one of the following constants (See the CursorType property for definitions of these settings.):
adOpenForwardOnly | (Default) Opens a forward-only-type cursor.
adOpenKeyset | Opens a keyset-type cursor.
adOpenDynamic | Opens a dynamic-type cursor.
adOpenStatic | Opens a static type cursor.

LockType Optional. A LockTypeEnum value that determines what type of locking (concurrency) the provider should use when opening the Recordset. Can be one of the following constants (See the LockType property for more information.):
adLockReadOnly | (Default) Read-only — you cannot alter the data.
adLockPessimistic | Pessimistic locking, record by record — the provider does what is necessary to ensure successful editing of the records, usually by locking records at the data source immediately upon editing.
adLockOptimistic | Optimistic locking, record by record — the provider uses optimistic locking, locking records only when you call the Update method.
adLockBatchOptimistic | Optimistic batch updates — required for batch update mode as opposed to immediate update mode.

Options Optional. A Long value that indicates how the provider should evaluate the Source argument if it represents something other than a Command object. Can be one of the following constants (See the CommandType property for a more detailed explanation of these constants.):
adCmdText | Indicates that the provider should evaluate Source as a textual definition of a command.
adCmdTable | Indicates that the provider should evaluate Source as a table name.
adCmdStoredProc | Indicates that the provider should evaluate Source as a stored procedure.
adCmdUnknown | Indicates that the type of command in the Source argument is not known.

See the CommandType property for a more detailed explanation of the first four constants in this list.

Remarks

Using the Open method on a Recordset object opens a cursor that represents records from a base table or the results of a query.

Use the optional Source argument to specify a data source using one of the following: a Command object variable, an SQL statement, a stored procedure, or a table name.

The ActiveConnection argument corresponds to the ActiveConnection property and specifies in which connection to open the Recordset object. If you pass a connection definition for this argument, ADO opens a new connection using the specified parameters. You can change the value of this property after opening the Recordset to send updates to another provider. Or, you can set this property to Nothing (in Microsoft Visual Basic) to disconnect the Recordset from any provider.

For the other arguments that correspond directly to properties of a Recordset object (Source, CursorType, and LockType), the relationship of the arguments to the properties is as follows:

  • The property is read/write before the Recordset object is opened.

  • The property settings are used unless you pass the corresponding arguments when executing the Open method. If you pass an argument, it overrides the corresponding property setting, and the property setting is updated with the argument value.

  • After you open the Recordset object, these properties become read-only.

Note For Recordset objects whose Source property is set to a valid Command object, the ActiveConnection property is read-only, even if the Recordset object isn't open.

If you pass a Command object in the Source argument and also pass an ActiveConnection argument, an error occurs. The ActiveConnection property of the Command object must already be set to a valid Connection object or connection string.

If you pass something other than a Command object in the Source argument, you can use the Options argument to optimize evaluation of the Source argument. If the Options argument is not defined, you may experience diminished performance because ADO must make calls to the provider to determine if the argument is an SQL statement, a stored procedure, or a table name. If you know what Source type you're using, setting the Options argument instructs ADO to jump directly to the relevant code. If the Options argument does not match the Source type, an error occurs.

If the data source returns no records, the provider sets both the BOF and EOF properties to True, and the current record position is undefined. You can still add new data to this empty Recordset object if the cursor type allows it.

When you have concluded your operations over an open Recordset object, use the Close method to free any associated system resources. Closing an object does not remove it from memory; you may change its property settings and use the Open method to open it again later. To completely eliminate an object from memory, set the object variable to Nothing.

Examples

Open and Close Methods Example (VB)


Refresh Method (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Refresh Method - ADO

Updates the objects in a collection to reflect objects available from and specific to the provider.

Applies To

Fields, Parameters, Properties

Syntax

collection.Refresh

Remarks

The Refresh method accomplishes different tasks depending on the collection from which you call it.

Parameters

Using the Refresh method on a Command object's Parameters collection retrieves provider-side parameter information for the stored procedure or parameterized query specified in the Command object. The collection will be empty for providers that do not support stored procedure calls or parameterized queries.

You should set the ActiveConnection property of the Command object to a valid Connection object, the CommandText property to a valid command, and the CommandType property to adCmdStoredProc before calling the Refresh method.

If you access the Parameters collection before calling the Refresh method, ADO will automatically call the method and populate the collection for you.

Note If you use the Refresh method to obtain parameter information from the provider and it returns one or more variable-length data type Parameter objects, ADO may allocate memory for the parameters based on their maximum potential size which will cause an error during execution. You should explicitly set the Size property for these parameters before calling the Execute method to prevent errors.

Fields

Using the Refresh method on the Fields collection has no visible effect. To retrieve changes from the underlying database structure, you must use either the Requery method or, if the Recordset object does not support bookmarks, the MoveFirst method.

Properties

Using the Refresh method on a Properties collection of some objects populates the collection with the dynamic properties the provider exposes. These properties provide information about functionality specific to the provider beyond the built-in properties ADO supports.

Examples

Refresh Method Example (VB)


Requery Method (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Requery Method - ADO

Updates the data in a Recordset object by re-executing the query on which the object is based.

Applies To

Recordset

Syntax

recordset.Requery

Remarks

Use the Requery method to refresh the entire contents of a Recordset object from the data source by reissuing the original command and retrieving the data a second time. Calling this method is equivalent to calling the Close and Open methods in succession. If you are editing the current record or adding a new record, an error occurs.

While the Recordset object is open, the properties that define the nature of the cursor (CursorType, LockType, MaxRecords, and so forth) are read-only. Thus, the Requery method can only refresh the current cursor. To change any of the cursor properties and view the results, you must use the Close method so that the properties become read/write again. You can then change the property settings and call the Open method to reopen the cursor.

Examples

Execute, Requery, and Clear Methods Example (VB)


Resync Method (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Resync Method - ADO

Refreshes the data in the current Recordset object from the underlying database.

Applies To

Recordset

Syntax

recordset.Resync AffectRecords

Parameters

AffectRecords Optional. An AffectEnum value that determines how many records the Resync method will affect. Can be one of the following constants:
adAffectCurrent | Refresh only the current record.
adAffectGroup | Refresh the records that satisfy the current Filter property setting. You must set the Filter property to one of the valid predefined constants in order to use this option.
adAffectAll | Default. Refresh all the records in the Recordset object, including any hidden by the current Filter property setting.

Remarks

Use the Resync method to re-synchronize records in the current Recordset with the underlying database. This is useful if you are using either a static or forward-only cursor but you want to see any changes in the underlying database. Calling the Resync method cancels any pending batch updates.

Unlike the Refresh method, the Resync method does not re-execute the Recordset object's underlying command; new records in the underlying database will not be visible.

If the attempt to resynchronize fails because of a conflict with the underlying data (for example, a record has been deleted by another user), the provider returns warnings to the Errors collection but does not halt program execution. A run-time error occurs only if there are conflicts on all the requested records. Use the Filter property (adFilterAffectedRecords) and the Status property to locate records with conflicts.

Remote Data Service Usage The Resync method is not available on a client-side (ADOR) Recordset.

Examples

Resync Method Example (VB)


Supports Method (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Supports Method - ADO

Determines whether a specified Recordset object supports a particular type of functionality.

Applies To

Recordset

Syntax

boolean = recordset.Supports( CursorOptions )

Return Values

Returns a Boolean value that indicates whether all of the features identified by the CursorOptions argument are supported by the provider.

Parameters

CursorOptions A Long expression that consists of one or more of the following CursorOptionEnum values:
adAddNew | You can use the AddNew method to add new records.
adApproxPosition | You can read and set the AbsolutePosition and AbsolutePage properties.
adBookmark | You can use the Bookmark property to access specific records.
adDelete | You can use the Delete method to delete records.
adHoldRecords | You can retrieve more records or change the next retrieve position without committing all pending changes.
adMovePrevious | You can use the MoveFirst and MovePrevious methods, and Move or GetRows methods to move the current record position backward without requiring bookmarks.
adResync | You can update the cursor with the data visible in the underlying database, using the Resync method.
adUpdate | You can use the Update method to modify existing data.
adUpdateBatch | You can use batch updating (UpdateBatch and CancelBatch methods) to transmit changes to the provider in groups.

Remarks

Use the Supports method to determine what types of functionality a Recordset object supports. If the Recordset object supports the features whose corresponding constants are in CursorOptions, the Supports method returns True. Otherwise, it returns False.

Note Although the Supports method may return True for a given functionality, it does not guarantee that the provider can make the feature available under all circumstances. The Supports method simply returns whether or not the provider can support the specified functionality assuming certain conditions are met. For example, the Supports method may indicate that a Recordset object supports updates even though the cursor is based on a multi-table join, some columns of which are not updatable.

Examples

Supports Method Example (VB)


Update Method (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Update Method - ADO

Saves any changes you make to the current record of a Recordset object.

Applies To

Recordset

Syntax

recordset.Update Fields, Values

Parameters

Fields Optional. A Variant representing a single name or a Variant array representing names or ordinal positions of the field or fields you wish to modify.

Values Optional. A Variant representing a single value or a Variant array representing values for the field or fields in the new record.

Remarks

Use the Update method to save any changes you make to the current record of a Recordset object since calling the AddNew method or since changing any field values in an existing record. The Recordset object must support updates.

To set field values, do one of the following:

  • Assign values to a Field object's Value property and call the Update method.

  • Pass a field name and a value as arguments with the Update call.

  • Pass an array of field names and an array of values with the Update call.

When you use arrays of fields and values, there must be an equal number of elements in both arrays. Also, the order of field names must match the order of field values. If the number and order of fields and values do not match, an error occurs.

If the Recordset object supports batch updating, then you can cache multiple changes to one or more records locally until you call the UpdateBatch method. If you are editing the current record or adding a new record when you call the UpdateBatch method, ADO will automatically call the Update method to save any pending changes to the current record before transmitting the batched changes to the provider.

If you move from the record you are adding or editing before calling the Update method, ADO will automatically call Update to save the changes. You must call the CancelUpdate method if you want to cancel any changes made to the current record or to discard a newly added record.

The current record remains current after you call the Update method.

Examples

Update and CancelUpdate Methods Example (VB)


UpdateBatch Method (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

UpdateBatch Method - ADO

Writes all pending batch updates to disk.

Applies To

Recordset

Syntax

recordset.UpdateBatch AffectRecords

Parameters

AffectRecords Optional. An AffectEnum value that determines how many records the UpdateBatch method will affect. Can be one of the following constants:
adAffectCurrent | Write pending changes only for the current record.
adAffectGroup | Write pending changes for the records that satisfy the current Filter property setting. You must set the Filter property to one of the valid predefined constants in order to use this option.
adAffectAll | (Default) Write pending changes for all the records in the Recordset object, including any hidden by the current Filter property setting.

Remarks

Use the UpdateBatch method when modifying a Recordset object in batch update mode to transmit all changes made in a Recordset object to the underlying database.

If the Recordset object supports batch updating, then you can cache multiple changes to one or more records locally until you call the UpdateBatch method. If you are editing the current record or adding a new record when you call the UpdateBatch method, ADO will automatically call the Update method to save any pending changes to the current record before transmitting the batched changes to the provider.

Note You should use batch updating only with either a keyset or static cursor.

If the attempt to transmit changes fails because of a conflict with the underlying data (for example, a record has already been deleted by another user), the provider returns warnings to the Errors collection but does not halt program execution. A run-time error occurs only if there are conflicts on all the requested records. Use the Filter property (adFilterAffectedRecords) and the Status property to locate records with conflicts.

To cancel all pending batch updates, use the CancelBatch method.

Examples

UpdateBatch and CancelBatch Methods Example (VB)


Item method (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Item Method - ADO

Returns a specific member of a collection by name or ordinal number.

Applies To

Errors, Fields, Parameters, Properties

Syntax

Set object = collection.Item ( Index )

Return Values

Returns an object reference.

Parameters

Index A Variant that evaluates either to the name or to the ordinal number of an object in a collection.

Remarks

Use the Item method to return a specific object in a collection. If the method cannot find an object in the collection corresponding to the Index argument, an error occurs. Also, some collections don't support named objects; for these collections, you must use ordinal number references.

The Item method is the default method for all collections; therefore, the following syntax forms are interchangeable:

collection.Item (Index)

collection (Index)


OpenSchema Method (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

OpenSchema Method - ADO

Obtains database schema information from the provider.

Applies To

Connection

Syntax

Set recordset = connection.OpenSchema (QueryType, Criteria, SchemaID)

Return Values

Returns a Recordset object that contains schema information.

Parameters

QueryType The type of schema query to run. Can be any of the constants listed below.

Criteria Optional. An array of query constraints for each QueryType option, as listed below.
QueryType values | Criteria values
adSchemaAsserts CONSTRAINT_CATALOG
CONSTRAINT_SCHEMA
CONSTRAINT_NAME
adSchemaCatalogs | CATALOG_NAME
adSchemaCharacterSets CHARACTER_SET_CATALOG
CHARACTER_SET_SCHEMA
CHARACTER_SET_NAME
adSchemaCheckConstraints CONSTRAINT_CATALOG
CONSTRAINT_SCHEMA
CONSTRAINT_NAME
adSchemaCollations COLLATION_CATALOG
COLLATION_SCHEMA
COLLATION_NAME
adSchemaColumnDomainUsage DOMAIN_CATALOG
DOMAIN_SCHEMA
DOMAIN_NAME
COLUMN_NAME
adSchemaColumnPrivileges TABLE_CATALOG
TABLE_SCHEMA
TABLE_NAME
COLUMN_NAME
GRANTOR
GRANTEE
adSchemaColumns TABLE_CATALOG
TABLE_SCHEMA
TABLE_NAME
COLUMN_NAME
adSchemaConstraintColumnUsage TABLE_CATALOG
TABLE_SCHEMA
TABLE_NAME
COLUMN_NAME
adSchemaConstraintTableUsage TABLE_CATALOG
TABLE_SCHEMA
TABLE_NAME
adSchemaForeignKeys PK_TABLE_CATALOG
PK_TABLE_SCHEMA
PK_TABLE_NAME
FK_TABLE_CATALOG
FK_TABLE_SCHEMA
FK_TABLE_NAME
adSchemaIndexes TABLE_CATALOG
TABLE_SCHEMA
INDEX_NAME
TYPE
TABLE_NAME
adSchemaKeyColumnUsage CONSTRAINT_CATALOG
CONSTRAINT_SCHEMA
CONSTRAINT_NAME
TABLE_CATALOG
TABLE_SCHEMA
TABLE_NAME
COLUMN_NAME
adSchemaPrimaryKeys PK_TABLE_CATALOG
PK_TABLE_SCHEMA
PK_TABLE_NAME
adSchemaProcedureColumns PROCEDURE_CATALOG
PROCEDURE_SCHEMA
PROCEDURE_NAME
COLUMN_NAME
adSchemaProcedureParameters PROCEDURE_CATALOG
PROCEDURE_SCHEMA
PROCEDURE_NAME
PARAMTER_NAME
adSchemaProcedures PROCEDURE_CATALOG
PROCEDURE_SCHEMA
PROCEDURE_NAME
PARAMTER_TYPE
adSchemaProviderSpecific | See Remarks
adSchemaProviderTypes DATA_TYPE
BEST_MATCH
adSchemaReferentialConstraints CONSTRAINT_CATALOG
CONSTRAINT_SCHEMA
CONSTRAINT_NAME
adSchemaSchemata CATALOG_NAME
SCHEMA_NAME
SCHEMA_OWNER
adSchemaSQLLanguages | <none>
adSchemaStatistics TABLE_CATALOG
TABLE_SCHEMA
TABLE_NAME
adSchemaTableConstraints CONSTRAINT_CATALOG
CONSTRAINT_SCHEMA
CONSTRAINT_NAME
TABLE_CATALOG
TABLE_SCHEMA
TABLE_NAME
CONSTRAINT_TYPE
adSchemaTablePrivileges TABLE_CATALOG
TABLE_SCHEMA
TABLE_NAME
GRANTOR
GRANTEE
adSchemaTables TABLE_CATALOG
TABLE_SCHEMA
TABLE_NAME
TABLE_TYPE
adSchemaTranslations TRANSLATION_CATALOG
TRANSLATION_SCHEMA
TRANSLATION_NAME
adSchemaUsagePrivileges OBJECT_CATALOG
OBJECT_SCHEMA
OBJECT_NAME
OBJECT_TYPE
GRANTOR
GRANTEE
adSchemaViewColumnUsage VIEW_CATALOG
VIEW_SCHEMA
VIEW_NAME
adSchemaViewTableUsage VIEW_CATALOG
VIEW_SCHEMA
VIEW_NAME
adSchemaViews TABLE_CATALOG
TABLE_SCHEMA
TABLE_NAME

SchemaID The GUID for a provider-schema schema query not defined by the OLE DB 1.1 specification. This parameter is required if QueryType is set to adSchemaProviderSpecific; otherwise, it is not used.

Remarks

The OpenSchema method returns information about the data source, such as information about the tables on the server and the columns in the tables.

The Criteria argument is an array of values that can be used to limit the results of a schema query. Each schema query has a different set of parameters that it supports. The actual schemas are defined by the OLE DB specification under the "IDBSchemaRowset" interface. The ones supported in ADO 1.5 are listed above.

The constant adSchemaProviderSpecific is used for the QueryType argument if the provider defines its own non-standard schema queries outside those listed above. When this constant is used, the SchemaID argument is required to pass the GUID of the schema query to execute. If QueryType is set to adSchemaProviderSpecific but SchemaID is not provided, an error will result.

Providers are not required to support all of the OLE DB standard schema queries. Specifically, only adSchemaTables, adSchemaColumns and adSchemaProviderTypes are required by the OLE DB specification. However, the provider is not required to support the Criteria constraints listed above for those schema queries.

Remote Data Service Usage The OpenSchema method is not available on a client-side (ADOR) Connection object.

Examples

OpenSchema Method Example (VB)

See Also

Using OLE DB Providers with ADO


AddNew Method Example (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

AddNew Method Example

This example uses the AddNew method to create a new record with the specified name.

Public Sub AddNewX()

    Dim cnn1 As ADODB.Connection
    Dim rstEmployees As ADODB.Recordset
    Dim strCnn As String
    Dim strID As String
    Dim strFirstName As String
    Dim strLastName As String
    Dim booRecordAdded As Boolean

    ' Open a connection.
    Set cnn1 = New ADODB.Connection
    strCnn = "driver={SQL Server};server=srv;" & _
        "uid=sa;pwd=;database=pubs"
    cnn1.Open strCnn

    ' Open Employee table.
    Set rstEmployees = New ADODB.Recordset
    rstEmployees.CursorType = adOpenKeyset
    rstEmployees.LockType = adLockOptimistic
    rstEmployees.Open "employee", cnn1, , , adCmdTable

    ' Get data from the user.
    strID = Trim(InputBox("Enter employee ID:"))
    strFirstName = Trim(InputBox("Enter first name:"))
    strLastName = Trim(InputBox("Enter last name:"))

    ' Proceed only if the user actually entered something
    ' for both the first and last names.
    If (strID <> "") And (strFirstName <> "") _
        And (strLastName <> "") Then

        rstEmployees.AddNew
        rstEmployees!emp_id = strID
        rstEmployees!fname = strFirstName
        rstEmployees!lname = strLastName
        rstEmployees.Update
        booRecordAdded = True

        ' Show the newly added data.
        MsgBox "New record: " & rstEmployees!emp_id & " " & _
            rstEmployees!fname & " " & rstEmployees!lname

    Else
        MsgBox "Please enter an employee ID, " & _
            "first name, and last name."
    End If

    ' Delete the new record because this is a demonstration.
    cnn1.Execute "DELETE FROM employee WHERE emp_id = '" & strID & "'"

    rstEmployees.Close
    cnn1.Close

End Sub

VBScript Version

The following is the same example written in VBScript to be used in an Active Server Page (ASP). To view this example, you need to create a system Data Source Name (DSN) called AdvWorks for the Microsoft Access database file AdvWorks.mdb, which is installed with Microsoft Internet Information Server and located at C:\InetPub\ASPSamp\AdvWorks. Locate the file adovbs.inc and place it in the directory you plan to use. Cut and paste the following code to Notepad or another text editor and save it as AddNew.asp. You can view the result in any client browser.

To exercise the example, add a new fictional record in the HTML Form. Click the Add New Button. See the Delete method example to remove unwanted records.

<!-- #Include file="ADOVBS.INC" -->
<% Language = VBScript %>
<HTML><HEAD><TITLE>ADO 1.5 Open Method</TITLE>
</HEAD><BODY>
<FONT FACE="MS SANS SERIF" SIZE=2>
<Center><H3>ADO AddNew Method</H3>
<!-- ADO Connection Object used to create recordset-->
<%
'Create and Open Connection Object
Set OBJdbConnection = Server.CreateObject("ADODB.Connection")
OBJdbConnection.Open "AdvWorks"
'Create and Open Recordset Object
Set RsCustomerList = Server.CreateObject("ADODB.Recordset")
RsCustomerList.ActiveConnection = OBJdbConnection
RsCustomerList.CursorType = adOpenKeyset
RsCustomerList.LockType = adLockOptimistic
RsCustomerList.Source = "Customers"
RsCustomerList.Open

%>
<!-- If this is the first time the page is opened, the Form collection will be empty when data is entered

run AddNew method-->
<% If Not IsEmpty(Request.Form) Then
    If Not Request.Form("CompanyName") = "" Then
        RsCustomerList.AddNew
        RsCustomerList("CompanyName") = Request.Form("CompanyName")
        RsCustomerList("ContactLastName") = Request.Form("LastName")
        RsCustomerList("ContactFirstName") = Request.Form("FirstName")
        RsCustomerList("PhoneNumber") = Request.Form("PhoneNumber")
        RsCustomerList("City") = Request.Form("City")
        RsCustomerList("StateOrProvince") = Request.Form("State")
        RsCustomerList.Update
        RsCustomerList.MoveFirst

    End If
End If
%>

<TABLE COLSPAN=8 CELLPADDING=5 BORDER=0>

<!-- BEGIN column header row for Customer Table-->

<TR><TD ALIGN=CENTER BGCOLOR="#008080">
<FONT STYLE="ARIAL NARROW" COLOR="#ffffff" SIZE=1>Company Name</FONT></TD>
<TD ALIGN=CENTER BGCOLOR="#008080">
<FONT STYLE="ARIAL NARROW" COLOR="#ffffff" SIZE=1>Contact Name</FONT></TD>
<TD ALIGN=CENTER WIDTH=150 BGCOLOR="#008080">
<FONT STYLE="ARIAL NARROW" COLOR="#ffffff" SIZE=1>Phone Number</FONT></TD>
<TD ALIGN=CENTER BGCOLOR="#008080">
<FONT STYLE="ARIAL NARROW" COLOR="#ffffff" SIZE=1>City</FONT></TD>
<TD ALIGN=CENTER BGCOLOR="#008080">
<FONT STYLE="ARIAL NARROW" COLOR="#ffffff" SIZE=1>State/Province</FONT></TD></TR>
<!--Display ADO Data from Customer Table One row on each pass through recordset-->
<% Do While Not RsCustomerList.EOF %>
  <TR><TD BGCOLOR="f7efde" ALIGN=CENTER>
    <FONT STYLE="ARIAL NARROW" SIZE=1>
      <%= RSCustomerList("CompanyName")%>
    </FONT></TD>
  <TD BGCOLOR="f7efde" ALIGN=CENTER>
    <FONT STYLE="ARIAL NARROW" SIZE=1>
      <%= RScustomerList("ContactLastName") & ", " %>
      <%= RScustomerList("ContactFirstName") %>
    </FONT></TD>
  <TD BGCOLOR="f7efde" ALIGN=CENTER>
    <FONT STYLE="ARIAL NARROW" SIZE=1>
     <%= RScustomerList("PhoneNumber")%>
   </FONT></TD>
  <TD BGCOLOR="f7efde" ALIGN=CENTER>
    <FONT STYLE="ARIAL NARROW" SIZE=1>
      <%= RScustomerList("City")%>
    </FONT></TD>
  <TD BGCOLOR="f7efde" ALIGN=CENTER>
    <FONT STYLE="ARIAL NARROW" SIZE=1>
      <%= RScustomerList("StateOrProvince")%>
    </FONT></TD></TR>
<!-- Next Row = Record Loop and add to row html table-->
<%
RScustomerList.MoveNext
Loop
%>

</TABLE><HR>
<!-- Form to enter new record posts variables back to this page -->
<Table>
<Form Method = Post Action="AddNew.asp" Name=Form>
<TR><TD><P>Company Name:</TD>
<TD><Input Type="Text" Size="50" Name="CompanyName" Value = ""></P></TD>
<TR><TD><P>Contact First Name:</TD>
<TD><Input Type="Text" Size="50" Name="FirstName" Value = ""></P></TD>
<TR><TD><P>Contact Last Name:</TD>
<TD><Input Type="Text" Size="50" Name="LastName" Value = ""></P></TD>
<TR><TD><P>Contact Phone:</TD>
<TD><Input Type="Text" Size="50" Name="PhoneNumber" Value = ""></P></TD>
<TR><TD><P>City:</TD>
<TD><Input Type="Text" Size="50" Name="City" Value = ""></P></TD>
<TR><TD><P>State / Province:</TD>
<TD><Input Type="Text" Size="5" Name="State" Value = ""></P></TD>
<TR><TD><Input Type="Submit" Value="Add New "><Input Type="Reset" Value="Reset Form">
</Form></Table></Center></FONT>
<%'Show location of DSN data source
Response.Write(OBJdbConnection)
%>
<Script Language = "VBScript">
Sub Form_OnSubmit
    MsgBox "Sending New Record to Server",,"ADO-ASP _Example"
End Sub
</Script>
</BODY></HTML>


Append and CreateParameter Methods Example (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Append and CreateParameter Methods Example

This example uses the Append and CreateParameter methods to execute a stored procedure with an input parameter.

Public Sub AppendX()

    Dim cnn1 As ADODB.Connection
    Dim cmdByRoyalty As ADODB.Command
    Dim prmByRoyalty As ADODB.Parameter
    Dim rstByRoyalty As ADODB.Recordset
    Dim rstAuthors As ADODB.Recordset
    Dim intRoyalty As Integer
    Dim strAuthorID As String
    Dim strCnn As String

    ' Open connection.
    Set cnn1 = New ADODB.Connection
    strCnn = "driver={SQL Server};server=srv;" & _
        "uid=sa;pwd=;database=pubs"
    cnn1.Open strCnn
    cnn1.CursorLocation = adUseClient

    ' Open command object with one parameter.
    Set cmdByRoyalty = New ADODB.Command
    cmdByRoyalty.CommandText = "byroyalty"
    cmdByRoyalty.CommandType = adCmdStoredProc

    ' Get parameter value and append parameter.
    intRoyalty = Trim(InputBox("Enter royalty:"))
    Set prmByRoyalty = cmdByRoyalty.CreateParameter("percentage", _
        adInteger, adParamInput)
    cmdByRoyalty.Parameters.Append prmByRoyalty
    prmByRoyalty.Value = intRoyalty

    ' Create recordset by executing the command.
    Set cmdByRoyalty.ActiveConnection = cnn1
    Set rstByRoyalty = cmdByRoyalty.Execute

    ' Open the Authors table to get author names for display.
    Set rstAuthors = New ADODB.Recordset
    rstAuthors.Open "authors", cnn1, , , adCmdTable

    ' Print current data in the recordset, adding
    ' author names from Authors table.
    Debug.Print "Authors with " & intRoyalty & " percent royalty"
    Do While Not rstByRoyalty.EOF
        strAuthorID = rstByRoyalty!au_id
        Debug.Print "	" & rstByRoyalty!au_id & ", ";
        rstAuthors.Filter = "au_id = '" & strAuthorID & "'"
        Debug.Print rstAuthors!au_fname & " " & rstAuthors!au_lname
        rstByRoyalty.MoveNext
    Loop

    rstByRoyalty.Close
    rstAuthors.Close
    cnn1.Close

End Sub


AppendChunk and GetChunk Methods Example (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

AppendChunk and GetChunk Methods Example

This example uses the AppendChunk and GetChunk methods to fill an image field with data from another record, 32K at a time. In a real application, one might use a procedure like this to copy a record containing a photo or graphic image field from one table to another. In this example, the record is simply being copied back to same table. Note that all the chunk manipulation takes place within a single AddNew-Update sequence.

Public Sub AppendChunkX()

    Dim cnn1 As ADODB.Connection
    Dim rstPubInfo As ADODB.Recordset
    Dim strCnn As String
    Dim strPubID As String
    Dim strPRInfo As String
    Dim lngOffset As Long
    Dim lngLogoSize As Long
    Dim varLogo As Variant
    Dim varChunk As Variant

    Const conChunkSize = 100

    ' Open a connection.
    Set cnn1 = New ADODB.Connection
    strCnn = "driver={SQL Server};server=srv;" & _
        "uid=sa;pwd=;database=pubs"
    cnn1.Open strCnn

    ' Open the pub_info table.
    Set rstPubInfo = New ADODB.Recordset
    rstPubInfo.CursorType = adOpenKeyset
    rstPubInfo.LockType = adLockOptimistic
    rstPubInfo.Open "pub_info", cnn1, , , adCmdTable

    ' Prompt for a logo to copy.
    strMsg = "Available logos are : " & vbCr & vbCr
    Do While Not rstPubInfo.EOF
        strMsg = strMsg & rstPubInfo!pub_id & vbCr & _
            Left(rstPubInfo!pr_info, InStr(rstPubInfo!pr_info, ",") - 1) & _
            vbCr & vbCr
        rstPubInfo.MoveNext
    Loop
    strMsg = strMsg & "Enter the ID of a logo to copy:"
    strPubID = InputBox(strMsg)

    ' Copy the logo to a variable in chunks.
    rstPubInfo.Filter = "pub_id = '" & strPubID & "'"
    lngLogoSize = rstPubInfo!logo.ActualSize
    Do While lngOffset < lngLogoSize
        varChunk = rstPubInfo!logo.GetChunk(conChunkSize)
        varLogo = varLogo & varChunk
        lngOffset = lngOffset + conChunkSize
    Loop

    ' Get data from the user.
    strPubID = Trim(InputBox("Enter a new pub ID:"))
    strPRInfo = Trim(InputBox("Enter descriptive text:"))

    ' Add a new record, copying the logo in chunks.
    rstPubInfo.AddNew
    rstPubInfo!pub_id = strPubID
    rstPubInfo!pr_info = strPRInfo

    lngOffset = 0   ' Reset offset.
    Do While lngOffset < lngLogoSize
        varChunk = LeftB(RightB(varLogo, lngLogoSize - lngOffset), _
            conChunkSize)
        rstPubInfo!logo.AppendChunk varChunk
        lngOffset = lngOffset + conChunkSize
    Loop
    rstPubInfo.Update

     ' Show the newly added data.
    MsgBox "New record: " & rstPubInfo!pub_id & vbCr & _
        "Description: " & rstPubInfo!pr_info & vbCr & _
        "Logo size: " & rstPubInfo!logo.ActualSize

    ' Delete new record because this is a demonstration.
    rstPubInfo.Requery
    cnn1.Execute "DELETE FROM pub_info " & _
        "WHERE pub_id = '" & strPubID & "'"

    rstPubInfo.Close
    cnn1.Close

End Sub


BeginTrans, CommitTrans, and RollbackTrans Methods Example (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

BeginTrans, CommitTrans, and RollbackTrans Methods Example

This example changes the book type of all psychology books in the Titles table of the database. After the BeginTrans method starts a transaction that isolates all the changes made to the Titles table, the CommitTrans method saves the changes. Notice that you can use the Rollback method to undo changes that you saved using the Update method.

Public Sub BeginTransX()

    Dim cnn1 As ADODB.Connection
    Dim rstTitles As ADODB.Recordset
    Dim strCnn As String
    Dim strTitle As String
    Dim strMessage As String

    ' Open connection.
    strCnn = "driver={SQL Server};server=srv;" & _
        "uid=sa;pwd=;database=pubs"
    Set cnn1 = New ADODB.Connection
    cnn1.Open strCnn

    ' Open titles table.
    Set rstTitles = New ADODB.Recordset
    rstTitles.CursorType = adOpenDynamic
    rstTitles.LockType = adLockPessimistic
    rstTitles.Open "titles", cnn1, , , adCmdTable

    rstTitles.MoveFirst
    cnn1.BeginTrans

    ' Loop through recordset and ask user if she wants
    ' to change the type for a specified title.
    Do Until rstTitles.EOF
        If Trim(rstTitles!Type) = "psychology" Then
            strTitle = rstTitles!Title
            strMessage = "Title: " & strTitle & vbCr & _
            "Change type to self help?"

            ' Change the title for the specified
            ' employee.
            If MsgBox(strMessage, vbYesNo) = vbYes Then
                rstTitles!Type = "self_help"
                rstTitles.Update
            End If
        End If

            rstTitles.MoveNext
    Loop

    ' Ask if the user wants to commit to all the
    ' changes made above.
    If MsgBox("Save all changes?", vbYesNo) = vbYes Then
        cnn1.CommitTrans
    Else
        cnn1.RollbackTrans
    End If

    ' Print current data in recordset.
    rstTitles.Requery
    rstTitles.MoveFirst
    Do While Not rstTitles.EOF
        Debug.Print rstTitles!Title & " - " & rstTitles!Type
        rstTitles.MoveNext
    Loop

    ' Restore original data because this
    ' is a demonstration.
    rstTitles.MoveFirst
    Do Until rstTitles.EOF
        If Trim(rstTitles!Type) = "self_help" Then
            rstTitles!Type = "psychology"
            rstTitles.Update
        End If
        rstTitles.MoveNext
    Loop

    rstTitles.Close
    cnn1.Close

End Sub


Clone Method Example (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Clone Method Example

This example uses the Clone method to create copies of a Recordset and then lets the user position the record pointer of each copy independently.

Public Sub CloneX()

    Dim arstStores(1 To 3) As ADODB.Recordset
    Dim intLoop As Integer
    Dim strSQL As String
    Dim strCnn As String
    Dim strMessage As String
    Dim strFind As String

    ' Assign SQL statement and connection string to variables.
    strSQL = "SELECT stor_name FROM Stores " & _
        "ORDER BY stor_name"
    strCnn = "driver={SQL Server};server=srv;" & _
        "uid=sa;pwd=;database=pubs"

    ' Open recordset as a static cursor type recordset.
    Set arstStores(1) = New ADODB.Recordset
    arstStores(1).CursorType = adOpenStatic
    arstStores(1).LockType = adLockBatchOptimistic
    arstStores(1).Open strSQL, strCnn, , , adCmdText

    ' Create two clones of the original Recordset.
    Set arstStores(2) = arstStores(1).Clone
    Set arstStores(3) = arstStores(1).Clone

    Do While True

        ' Loop through the array so that on each pass,
        ' the user is searching a different copy of the
        ' same Recordset.
        For intLoop = 1 To 3

            ' Ask for search string while showing where
            ' the current record pointer is for each Recordset.
            strMessage = _
                "Recordsets from stores table:" & vbCr & _
                "  1 - Original - Record pointer at " & _
                arstStores(1)!stor_name & vbCr & _
                "  2 - Clone - Record pointer at " & _
                arstStores(2)!stor_name & vbCr & _
                "  3 - Clone - Record pointer at " & _
                arstStores(3)!stor_name & vbCr & _
                "Enter search string for #" & intLoop & ":"
            strFind = Trim(InputBox(strMessage))
            If strFind = "" Then Exit Do

            ' Find the search string; if there's no
            ' match, jump to the last record.
            arstStores(intLoop).Filter = "stor_name >= '" & strFind & "'"
            If arstStores(intLoop).EOF Then
                arstStores(intLoop).Filter = adFilterNone
                arstStores(intLoop).MoveLast
            End If

        Next intLoop

    Loop

    arstStores(1).Close
    arstStores(2).Close
    arstStores(3).Close

End Sub

VBScript Version

The following is the same example written in VBScript to be used in an Active Server Page (ASP). To view this example, you need to create a system Data Source Name (DSN) called AdvWorks for the Microsoft Access database file AdvWorks.mdb, which is installed with Microsoft Internet Information Server and located at C:\InetPub\ASPSamp\AdvWorks. Locate the file adovbs.inc and place it in the directory you plan to use. Cut and paste the following code to Notepad or another text editor and save it as Clone.asp. You can view the result in any client browser.

To exercise the example, change the line RsCustomerList.Source = "Customers" to RsCustomerList.Source = "Products" to count a larger table.

<!-- #Include file="ADOVBS.INC" -->
<% Language = VBScript %>
<HTML><HEAD>
<TITLE>ADO 1.5 Clone Method</TITLE>
</HEAD><BODY> <Center>
<H3>ADO Clone Method</H3>
<!--- ADO Connection Object used to create recordset-->
<%
'Create and open Connection object
Set OBJdbConnection = Server.CreateObject("ADODB.Connection")
OBJdbConnection.Open "AdvWorks"
'Create and open Recordset object
Set RsCustomerList = Server.CreateObject("ADODB.Recordset")
RsCustomerList.ActiveConnection = OBJdbConnection
RsCustomerList.CursorType = adOpenKeyset
RsCustomerList.LockType = adLockOptimistic
RsCustomerList.Source = "Customers"
RsCustomerList.Open
%>
<HR>
<!-- Loop through Customers Table adding 1 to the Counter variable each pass -->
<%
    Set MyRecordset = RSCustomerList.Clone
    Counter = 0
    Do Until MyRecordset.EOF
        Counter = Counter + 1
        MyRecordset.MoveNext
    Loop
%>
<!-- Display Results -->
<H3>There Are <%=Counter %> Records in the Customers Table</H3>
<BR><HR>
<H4>Location of DSN Datbase</H4>
<%' Show location of DSN data source
Response.Write(OBJdbConnection)
%>
<HR></Center></BODY></HTML>


Delete Method Example (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Delete Method Example

This example uses the Delete method to remove a specified record from a Recordset. The DeleteRecord procedure is required for this procedure to run.

Public Sub DeleteX()

    Dim rstRoySched As ADODB.Recordset
    Dim strCnn As String
    Dim strMsg As String
    Dim strTitleID As String
    Dim intLoRange As Integer
    Dim intHiRange As Integer
    Dim intRoyalty As Integer

    ' Open RoySched table.
    strCnn = "driver={SQL Server};server=srv;" & _
        "uid=sa;pwd=;database=pubs"
    Set rstRoySched = New ADODB.Recordset
    Set rstRoySched.CursorLocation = adUseClient
    rstRoySched.CursorType = adOpenKeyset
    rstRoySched.LockType = adLockBatchOptimistic
    rstRoySched.Open "SELECT * FROM roysched " & _
        "WHERE royalty = 20", strCnn, , , adCmdText

    ' Prompt for a record to delete.
    strMsg = "Before delete there are " & _
        rstRoySched.RecordCount & _
        " titles with 20 percent royalty:" & vbCr & vbCr
    Do While Not rstRoySched.EOF
        strMsg = strMsg & rstRoySched!title_id & vbCr
        rstRoySched.MoveNext
    Loop
    strMsg = strMsg & vbCr & vbCr & _
        "Enter the ID of a record to delete:"
    strTitleID = UCase(InputBox(strMsg))

    ' Move to the record and save data so it can be restored.
    rstRoySched.Filter = "title_id = '" & strTitleID & "'"
    intLoRange = rstRoySched!lorange
    intHiRange = rstRoySched!hirange
    intRoyalty = rstRoySched!royalty

    ' Delete the record.
    rstRoySched.Delete
    rstRoySched.UpdateBatch

    ' Show the results.
    rstRoySched.Filter = adFilterNone
    rstRoySched.Requery
    strMsg = ""
    strMsg = "After delete there are " & _
        rstRoySched.RecordCount & _
        " titles with 20 percent royalty:" & vbCr & vbCr
    Do While Not rstRoySched.EOF
        strMsg = strMsg & rstRoySched!title_id & vbCr
        rstRoySched.MoveNext
    Loop
    MsgBox strMsg

    ' Restore the data because this is a demonstration.
    rstRoySched.AddNew
    rstRoySched!title_id = strTitleID
    rstRoySched!lorange = intLoRange
    rstRoySched!hirange = intHiRange
    rstRoySched!royalty = intRoyalty
    rstRoySched.UpdateBatch

    rstRoySched.Close

End Sub

VBScript Version

The following is the same example written in VBScript to be used in an Active Server Page (ASP). To view this example, you need to create a system Data Source Name (DSN) called AdvWorks for the Microsoft Access database file AdvWorks.mdb, which is installed with Microsoft Internet Information Server and located at C:\InetPub\ASPSamp\AdvWorks. Locate the file adovbs.inc and place it in the directory you plan to use. Cut and paste the following code to Notepad or another text editor and save it as Delete.asp. You can view the result in any client browser.

To exercise the example, try using the AddNew example first, to add some records. Then try to delete them.

<!-- #Include file="ADOVBS.INC" -->
<% Language = VBScript %>

<HTML>

<HEAD><TITLE>ADO 1.5 Delete Method</TITLE>
</HEAD><BODY>
<FONT FACE="MS SANS SERIF" SIZE=2>
<Center><H3>ADO Delete Method</H3>

<!--- ADO Connection Object used to create recordset-->
<%
'Create and Open Connection Object
Set OBJdbConnection = Server.CreateObject("ADODB.Connection")
OBJdbConnection.Open "AdvWorks"
'Create and Open Recordset Object
Set RsCustomerList = Server.CreateObject("ADODB.Recordset")
RsCustomerList.ActiveConnection = OBJdbConnection
RsCustomerList.CursorType = adOpenKeyset
RsCustomerList.LockType = adLockOptimistic
RsCustomerList.Source = "Customers"
RsCustomerList.Open
%>
<!-- Move to designated Record and Delete It -->
<%

If Not IsEmpty(Request.Form("WhichRecord")) Then
    'Get value to move from Form Post method
    Moves = Request.Form("WhichRecord")

    RsCustomerList.Move CInt(Moves)
    If Not RsCustomerList.EOF or RsCustomerList.BOF Then
        RsCustomerList.Delete 1
        RsCustomerList.MoveFirst

    Else
        Response.Write "Not a Valid Record Number"
        RsCustomerList.MoveFirst
    End If
End If

%>
<!-- BEGIN column header row for Customer Table-->

<TABLE COLSPAN=8 CELLPADDING=5 BORDER=0><TR>
<TD ALIGN=CENTER BGCOLOR="#008080">
<FONT STYLE="ARIAL NARROW" COLOR="#ffffff" SIZE=1>Company Name</FONT>
</TD>
<TD ALIGN=CENTER BGCOLOR="#008080">
<FONT STYLE="ARIAL NARROW" COLOR="#ffffff" SIZE=1>Contact Name</FONT>
</TD>
<TD ALIGN=CENTER WIDTH=150 BGCOLOR="#008080">
<FONT STYLE="ARIAL NARROW" COLOR="#ffffff" SIZE=1>Phone Number</FONT>
</TD>
<TD ALIGN=CENTER BGCOLOR="#008080">
<FONT STYLE="ARIAL NARROW" COLOR="#ffffff" SIZE=1>City</FONT>
</TD>
<TD ALIGN=CENTER BGCOLOR="#008080">
<FONT STYLE="ARIAL NARROW" COLOR="#ffffff" SIZE=1>State/Province</FONT>
</TD></TR>

<!--Display ADO Data from Customer Table Loop through Recordset adding
One Row to HTML Table each pass-->
<% Do While Not RsCustomerList.EOF %>
  <TR><TD BGCOLOR="f7efde" ALIGN=CENTER>
    <FONT STYLE="ARIAL NARROW" SIZE=1>
      <%= RSCustomerList("CompanyName")%>
    </FONT></TD>
  <TD BGCOLOR="f7efde" ALIGN=CENTER>
    <FONT STYLE="ARIAL NARROW" SIZE=1>
      <%= RScustomerList("ContactLastName") & ", " %>
      <%= RScustomerList("ContactFirstName") %>
    </FONT></TD>
  <TD BGCOLOR="f7efde" ALIGN=CENTER>
    <FONT STYLE="ARIAL NARROW" SIZE=1>
      <%= RScustomerList("PhoneNumber")%>
   </FONT></TD>
  <TD BGCOLOR="f7efde" ALIGN=CENTER>
    <FONT STYLE="ARIAL NARROW" SIZE=1>
      <%= RScustomerList("City")%>
    </FONT></TD>
  <TD BGCOLOR="f7efde" ALIGN=CENTER>
    <FONT STYLE="ARIAL NARROW" SIZE=1>
      <%= RScustomerList("StateOrProvince")%>
    </FONT></TD>
  </TR>
<!-Next Row = Record Loop and add to html table-->
<%
RScustomerList.MoveNext
Loop
%>
</Table></Center></FONT>
<!-- Do Client side Input Data Validation Move to named record and Delete it -->

<Center>
<H4>Clicking Button Will Remove Designated Record</H4>
<H5>There are <%=RsCustomerList.RecordCount - 1%> Records in this Set</H5>
<Form Method = Post Action = "Delete.asp" Name = Form>
<Input Type = Text Name = "WhichRecord" Size = 3></Form>
<Input Type = Button Name = cmdDelete Value = "Delete Record"></Center>

</BODY>

<Script Language = "VBScript">

Sub cmdDelete_OnClick
If IsNumeric(Document.Form.WhichRecord.Value) Then
    Document.Form.WhichRecord.Value = CInt(Document.Form.WhichRecord.Value)
Dim Response
    Response = MsgBox("Are You Sure About Deleting This Record?", vbYesNo,  "ADO-ASP

Example")

    If Response = vbYes Then

    Document.Form.Submit

    End If
Else
    MsgBox "You Must Enter a Valid Record Number",,"ADO-ASP Example"
End If
End Sub

</Script>
</HTML>


Execute, Requery, and Clear Methods Example (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Execute, Requery, and Clear Methods Example

This example demonstrates the Execute method when run from both a Command object and a Connection object. It also uses the Requery method to retrieve current data in a recordset, and the Clear method to clear the contents of the Errors collection. The ExecuteCommand and PrintOutput procedures are required for this procedure to run.

Public Sub ExecuteX()

    Dim strSQLChange As String
    Dim strSQLRestore As String
    Dim strCnn As String
    Dim cnn1 As ADODB.Connection
    Dim cmdChange As ADODB.Command
    Dim rstTitles As ADODB.Recordset
    Dim errLoop As ADODB.Error

    ' Define two SQL statements to execute as command text.
    strSQLChange = "UPDATE Titles SET Type = " & _
        "'self_help' WHERE Type = 'psychology'"
    strSQLRestore = "UPDATE Titles SET Type = " & _
        "'psychology' WHERE Type = 'self_help'"

    ' Open connection.
    strCnn = "driver={SQL Server};server=srv;" & _
        "uid=sa;pwd=;database=pubs"
    Set cnn1 = New ADODB.Connection
    cnn1.Open strCnn

    ' Create command object.
    Set cmdChange = New ADODB.Command
    Set cmdChange.ActiveConnection = cnn1
    cmdChange.CommandText = strSQLChange

    ' Open titles table.
    Set rstTitles = New ADODB.Recordset
    rstTitles.Open "titles", cnn1, , , adCmdTable

    ' Print report of original data.
    Debug.Print _
        "Data in Titles table before executing the query"
    PrintOutput rstTitles

    ' Clear extraneous errors from the Errors collection.
    cnn1.Errors.Clear

    ' Call the ExecuteCommand subroutine to execute cmdChange command.
    ExecuteCommand cmdChange, rstTitles

    ' Print report of new data.
    Debug.Print _
        "Data in Titles table after executing the query"
    PrintOutput rstTitles

    ' Use the Connection object's execute method to
    ' execute SQL statement to restore data. Trap for
    ' errors, checking the Errors collection if necessary.
    On Error GoTo Err_Execute
    cnn1.Execute strSQLRestore
    On Error GoTo 0

    ' Retrieve the current data by requerying the recordset.
    rstTitles.Requery

    ' Print report of restored data.
    Debug.Print "Data after executing the query " & _
        "to restore the original information"
    PrintOutput rstTitles

    rstTitles.Close
    cnn1.Close

    Exit Sub

Err_Execute:

    ' Notify user of any errors that result from
    ' executing the query.
    If Errors.Count > 0 Then
        For Each errLoop In Errors
            MsgBox "Error number: " & errLoop.Number & vbCr & _
                errLoop.Description
        Next errLoop
    End If

    Resume Next

End Sub

Public Sub ExecuteCommand(cmdTemp As ADODB.Command, _
    rstTemp As ADODB.Recordset)

    Dim errLoop As Error

    ' Run the specified Command object. Trap for
    ' errors, checking the Errors collection if necessary.
    On Error GoTo Err_Execute
    cmdTemp.Execute
    On Error GoTo 0

    ' Retrieve the current data by requerying the recordset.
    rstTemp.Requery

    Exit Sub

Err_Execute:

    ' Notify user of any errors that result from
    ' executing the query.
    If Errors.Count > 0 Then
        For Each errLoop In Errors
            MsgBox "Error number: " & errLoop.Number & vbCr & _
                errLoop.Description
        Next errLoop
    End If

    Resume Next

End Sub

Public Sub PrintOutput(rstTemp As ADODB.Recordset)

    ' Enumerate Recordset.
    Do While Not rstTemp.EOF
        Debug.Print "    " & rstTemp!Title & _
            ", " & rstTemp!Type
        rstTemp.MoveNext
    Loop

End Sub

VBScript Version

The following is the same example written in VBScript to be used in an Active Server Page (ASP). To view this example, you need to create a system Data Source Name (DSN) called AdvWorks using the data source AdvWorks.mdb installed with IIS and located at C:\InetPub\ASPSamp\AdvWorks. This is a Microsoft Access database file. Use Find to locate the file adovbs.inc and place it in the directory you plan to use. Cut and paste the following code to Notepad or another text editor and save it as Execute.asp. You can view the result in any client browser.

<!-- #Include file="ADOVBS.INC" -->
<HTML><HEAD>
<TITLE>ADO 1.5 Execute Method</TITLE></HEAD>

<BODY>
<FONT FACE="MS SANS SERIF" SIZE=2>
<Center><H3>ADO Execute Method</H3><H4>Recordset Retrieved Using Connection Object</H4>
<TABLE WIDTH=600 BORDER=0>
<TD VALIGN=TOP ALIGN=LEFT COLSPAN=3><FONT SIZE=2>

<!--- Recordsets retrieved using Execute method of Connection and Command Objects-->
<%
Set OBJdbConnection = Server.CreateObject("ADODB.Connection")
OBJdbConnection.Open "AdvWorks"
SQLQuery = "SELECT * FROM Customers"
'First Recordset RSCustomerList
Set RSCustomerList = OBJdbConnection.Execute(SQLQuery)

Set OBJdbCommand = Server.CreateObject("ADODB.Command")
OBJdbCommand.ActiveConnection = OBJdbConnection
SQLQuery2 = "SELECT * From Products"
OBJdbCommand.CommandText = SQLQuery2
Set RsProductList = OBJdbCommand.Execute

%>
<TABLE COLSPAN=8 CELLPADDING=5 BORDER=0>

<!-- BEGIN column header row for Customer Table-->

<TR><TD ALIGN=CENTER BGCOLOR="#008080">
<FONT STYLE="ARIAL NARROW" COLOR="#ffffff" SIZE=1>Company Name</FONT>
</TD>
<TD ALIGN=CENTER BGCOLOR="#008080">
<FONT STYLE="ARIAL NARROW" COLOR="#ffffff" SIZE=1>Contact Name</FONT>
</TD>
<TD ALIGN=CENTER WIDTH=150 BGCOLOR="#008080">
<FONT STYLE="ARIAL NARROW" COLOR="#ffffff" SIZE=1>E-mail address</FONT>
</TD>
<TD ALIGN=CENTER BGCOLOR="#008080">
<FONT STYLE="ARIAL NARROW" COLOR="#ffffff" SIZE=1>City</FONT>
</TD>
<TD ALIGN=CENTER BGCOLOR="#008080">
<FONT STYLE="ARIAL NARROW" COLOR="#ffffff" SIZE=1>State/Province</FONT>
</TD></TR>

<!--Display ADO Data from Customer Table-->
<% Do While Not RScustomerList.EOF %>
  <TR>
  <TD BGCOLOR="f7efde" ALIGN=CENTER>
    <FONT STYLE="ARIAL NARROW" SIZE=1>
      <%= RSCustomerList("CompanyName")%>
    </FONT></TD>
  <TD BGCOLOR="f7efde" ALIGN=CENTER>
    <FONT STYLE="ARIAL NARROW" SIZE=1>
      <%= RScustomerList("ContactLastName") & ", " %>
      <%= RScustomerList("ContactFirstName") %>
    </FONT></TD>
  <TD BGCOLOR="f7efde" ALIGN=CENTER>
    <FONT STYLE="ARIAL NARROW" SIZE=1>

      <%= RScustomerList("ContactLastName")%>
   </FONT></TD>
  <TD BGCOLOR="f7efde" ALIGN=CENTER>
    <FONT STYLE="ARIAL NARROW" SIZE=1>
      <%= RScustomerList("City")%>
    </FONT></TD>
  <TD BGCOLOR="f7efde" ALIGN=CENTER>
    <FONT STYLE="ARIAL NARROW" SIZE=1>
      <%= RScustomerList("StateOrProvince")%>
    </FONT></TD>
  </TR>
<!-Next Row = Record Loop and add to html table-->
<%
RScustomerList.MoveNext
Loop
RScustomerList.Close

%>

</TABLE><HR>
<H4>Recordset Retrieved Using Command Object</H4>
<TABLE COLSPAN=8 CELLPADDING=5 BORDER=0>

<!-- BEGIN column header row for Product List Table-->

<TR><TD ALIGN=CENTER BGCOLOR="#800000">
<FONT STYLE="ARIAL NARROW" COLOR="#ffffff" SIZE=1>Product Type</FONT>
</TD>
<TD ALIGN=CENTER BGCOLOR="#800000">
<FONT STYLE="ARIAL NARROW" COLOR="#ffffff" SIZE=1>Product Name</FONT>
</TD>
<TD ALIGN=CENTER WIDTH=350 BGCOLOR="#800000">
<FONT STYLE="ARIAL NARROW" COLOR="#ffffff" SIZE=1>Product Description</FONT>
</TD>
<TD ALIGN=CENTER BGCOLOR="#800000">
<FONT STYLE="ARIAL NARROW" COLOR="#ffffff" SIZE=1>Unit Price</FONT>
</TD></TR>

<!-- Display ADO Data Product List-->
<% Do While Not RsProductList.EOF %>
  <TR>
  <TD BGCOLOR="f7efde" ALIGN=CENTER>
    <FONT STYLE="ARIAL NARROW" SIZE=1>
      <%= RsProductList("ProductType")%>
    </FONT></TD>
  <TD BGCOLOR="f7efde" ALIGN=CENTER>
    <FONT STYLE="ARIAL NARROW" SIZE=1>
      <%= RsProductList("ProductName")%>
    </FONT></TD>
  <TD BGCOLOR="f7efde" ALIGN=CENTER>
    <FONT STYLE="ARIAL NARROW" SIZE=1>
     <%= RsProductList("ProductDescription")%>
   </FONT></TD>

  <TD BGCOLOR="f7efde" ALIGN=CENTER>
    <FONT STYLE="ARIAL NARROW" SIZE=1>
      <%= RsProductList("UnitPrice")%>
    </FONT></TD>

<!--  Next Row = Record -->
<%
RsProductList.MoveNext
Loop
'Remove objects from memory to free resources
RsProductList.Close
OBJdbConnection.Close
Set ObJdbCommand = Nothing
Set RsProductList = Nothing
Set OBJdbConnection = Nothing
%>
</TABLE></FONT></Center></BODY></HTML>


GetRows Method Example (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

GetRows Method Example

This example uses the GetRows method to retrieve a specified number of rows from a Recordset and to fill an array with the resulting data. The GetRows method will return fewer than the desired number of rows in two cases: either if EOF has been reached, or if GetRows tried to retrieve a record that was deleted by another user. The function returns False only if the second case occurs. The GetRowsOK function is required for this procedure to run.

Public Sub GetRowsX()

    Dim rstEmployees As ADODB.Recordset
    Dim strCnn As String
    Dim strMessage As String
    Dim intRows As Integer
    Dim avarRecords As Variant
    Dim intRecord As Integer

    ' Open recordset with names and hire dates from employee table.
    strCnn = "driver={SQL Server};server=srv;" & _
        "uid=sa;pwd=;database=pubs"
    Set rstEmployees = New ADODB.Recordset
    rstEmployees.Open "SELECT fName, lName, hire_date " & _
        "FROM Employee ORDER BY lName", strCnn, , , adCmdText

    Do While True
        ' Get user input for number of rows.
        strMessage = "Enter number of rows to retrieve."
        intRows = Val(InputBox(strMessage))

        If intRows <= 0 Then Exit Do

        ' If GetRowsOK is successful, print the results,
        ' noting if the end of the file was reached.
        If GetRowsOK(rstEmployees, intRows, _
                avarRecords) Then
            If intRows > UBound(avarRecords, 2) + 1 Then
                Debug.Print "(Not enough records in " & _
                    "Recordset to retrieve " & intRows & _
                    " rows.)"
            End If
            Debug.Print UBound(avarRecords, 2) + 1 & _
                " records found."

            ' Print the retrieved data.
            For intRecord = 0 To UBound(avarRecords, 2)
                Debug.Print "    " & _
                    avarRecords(0, intRecord) & " " & _
                    avarRecords(1, intRecord) & ", " & _
                    avarRecords(2, intRecord)
            Next intRecord
        Else
            ' Assuming the GetRows error was due to data
            ' changes by another user, use Requery to
            ' refresh the Recordset and start over.
            If MsgBox("GetRows failed--retry?", _
                    vbYesNo) = vbYes Then
                rstEmployees.Requery
            Else
                Debug.Print "GetRows failed!"
                Exit Do
            End If
        End If

        ' Because using GetRows leaves the current
        ' record pointer at the last record accessed,
        ' move the pointer back to the beginning of the
        ' Recordset before looping back for another search.
        rstEmployees.MoveFirst
    Loop

    rstEmployees.Close

End Sub

Public Function GetRowsOK(rstTemp As ADODB.Recordset, _
    intNumber As Integer, avarData As Variant) As Boolean

    ' Store results of GetRows method in array.
    avarData = rstTemp.GetRows(intNumber)
    ' Return False only if fewer than the desired
    ' number of rows were returned, but not because the
    ' end of the Recordset was reached.
    If intNumber > UBound(avarData, 2) + 1 And _
            Not rstTemp.EOF Then
        GetRowsOK = False
    Else
        GetRowsOK = True
    End If

End Function


Move Method Example (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Move Method Example

This example uses the Move method to position the record pointer based on user input.

Public Sub MoveX()

    Dim rstAuthors As ADODB.Recordset
    Dim strCnn As String
    Dim varBookmark As Variant
    Dim strCommand As String
    Dim lngMove As Long

    ' Open recordset from Authors table.
    strCnn = "driver={SQL Server};server=srv;" & _
        "uid=sa;pwd=;database=pubs"
    Set rstAuthors = New ADODB.Recordset
    rstAuthors.CursorType = adOpenStatic
    ' Use client cursor to allow use of
    ' AbsolutePosition property.
    rstAuthors.CursorLocation = adUseClient
    rstAuthors.Open "SELECT au_id, au_fname, au_lname, city, state " & _
        "FROM Authors ORDER BY au_lname", strCnn, , , adCmdText

    rstAuthors.MoveFirst

    Do While True
        ' Display information about current record and
        ' ask how many records to move.

        strCommand = InputBox( _
            "Record " & rstAuthors.AbsolutePosition & _
            " of " & rstAuthors.RecordCount & vbCr & _
            "Author: " & rstAuthors!au_fname & _
            " " & rstAuthors!au_lname & vbCr & _
            "Location: " & rstAuthors!City & _
            ", " & rstAuthors!State & vbCr & vbCr & _
            "Enter number of records to Move " & _
            "(positive or negative).")

        If strCommand = "" Then Exit Do

        ' Store bookmark in case the Move goes too far
        ' forward or backward.
        varBookmark = rstAuthors.Bookmark

        ' Move method requires parameter of data type Long.
        lngMove = CLng(strCommand)
        rstAuthors.Move lngMove

        ' Trap for BOF or EOF.
        If rstAuthors.BOF Then
            MsgBox "Too far backward! " & _
                "Returning to current record."
            rstAuthors.Bookmark = varBookmark
        End If
        If rstAuthors.EOF Then
            MsgBox "Too far forward! " & _
                "Returning to current record."
            rstAuthors.Bookmark = varBookmark
        End If
    Loop
    rstAuthors.Close

End Sub

VBScript Version

The following is the same example written in VBScript to be used in an Active Server Page (ASP). To view this example, you need to create a system Data Source Name (DSN) called AdvWorks for the Microsoft Access database file AdvWorks.mdb, which is installed with Microsoft Internet Information Server and located at C:\InetPub\ASPSamp\AdvWorks. Locate the file adovbs.inc and place it in the directory you plan to use. Cut and paste the following code to Notepad or another text editor and save it as Move.asp. You can view the result in any client browser.

Try entering a letter or non integer to see the error handling work.

<!-- #Include file="ADOVBS.INC" -->
<% Language = VBScript %>
<HTML><HEAD>
<TITLE>ADO 1.5 Move Methods</TITLE></HEAD>
<BODY>
<FONT FACE="MS SANS SERIF" SIZE=2>
<Center>
<H3>ADO Move Methods</H3>

<%
 'Create and Open Connection Object
Set OBJdbConnection = Server.CreateObject("ADODB.Connection")
OBJdbConnection.Open "AdvWorks"
'Create and Open Recordset Object
Set RsCustomerList = Server.CreateObject("ADODB.Recordset")
RsCustomerList.ActiveConnection = OBJdbConnection
RsCustomerList.CursorType = adOpenKeyset
RsCustomerList.LockType = adLockOptimistic
RsCustomerList.Source = "Customers"

RsCustomerList.Open

'Check number of user moves this session
'Increment by amount in Form
Session("Clicks") = Session("Clicks") + Request.Form("MoveAmount")
Clicks = Session("Clicks")
'Move to last known recordset position plus amount passed
'by Form Post method
RsCustomerList.Move CInt(Clicks)

'Error Handling
    If RsCustomerList.EOF Then
            Session("Clicks") = RsCustomerList.RecordCount
            Response.Write "This is the Last Record"
            RsCustomerList.MoveLast
        Else If RsCustomerList.BOF Then
            Session("Clicks") = 1
            RsCustomerList.MoveFirst
            Response.Write "This is the First Record"
        End If
    End If

%>

<H3>Current Record Number is <BR>
<% If Session("Clicks") = 0 Then
Session("Clicks") = 1
End If
Response.Write(Session("Clicks") )%> of <%=RsCustomerList.RecordCount%></H3>
<HR>

<Center><TABLE COLSPAN=8 CELLPADDING=5 BORDER=0>

<!-- BEGIN column header row for Customer Table-->

<TR>

<TD ALIGN=CENTER BGCOLOR="#008080">
<FONT STYLE="ARIAL NARROW" COLOR="#ffffff" SIZE=1>Company Name</FONT>
</TD>
<TD ALIGN=CENTER BGCOLOR="#008080">
<FONT STYLE="ARIAL NARROW" COLOR="#ffffff" SIZE=1>Contact Name</FONT>
</TD>
<TD ALIGN=CENTER WIDTH=150 BGCOLOR="#008080">
<FONT STYLE="ARIAL NARROW" COLOR="#ffffff" SIZE=1>Phone Number</FONT>
</TD>
<TD ALIGN=CENTER BGCOLOR="#008080">
<FONT STYLE="ARIAL NARROW" COLOR="#ffffff" SIZE=1>City</FONT>
</TD>
<TD ALIGN=CENTER BGCOLOR="#008080">
<FONT STYLE="ARIAL NARROW" COLOR="#ffffff" SIZE=1>State/Province</FONT>
</TD>

</TR>

<!--Display ADO Data from Customer Table-->

  <TR>
  <TD BGCOLOR="f7efde" ALIGN=CENTER>
    <FONT STYLE="ARIAL NARROW" SIZE=1>
      <%= RSCustomerList("CompanyName")%>
    </FONT></TD>
  <TD BGCOLOR="f7efde" ALIGN=CENTER>
    <FONT STYLE="ARIAL NARROW" SIZE=1>
      <%= RScustomerList("ContactLastName") & ", " %>
      <%= RScustomerList("ContactFirstName") %>
    </FONT></TD>
  <TD BGCOLOR="f7efde" ALIGN=CENTER>
    <FONT STYLE="ARIAL NARROW" SIZE=1>

      <%= RScustomerList("PhoneNumber")%>
   </FONT></TD>
  <TD BGCOLOR="f7efde" ALIGN=CENTER>
    <FONT STYLE="ARIAL NARROW" SIZE=1>
      <%= RScustomerList("City")%>
    </FONT></TD>
  <TD BGCOLOR="f7efde" ALIGN=CENTER>
    <FONT STYLE="ARIAL NARROW" SIZE=1>
      <%= RScustomerList("StateOrProvince")%>
    </FONT></TD>
  </TR> </Table></FONT>

<HR>
<Input Type = Button Name = cmdDown  Value = "<    ">
<Input Type = Button Name = cmdUp Value = "   >">
<H5>Click Direction Arrows for Previous or Next Record
<BR> Click Move Amount to use Move Method
Enter Number of Records to Move + or - </H5>

<Table>

<Form Method = Post Action="Move.asp" Name=Form>

<TR><TD><Input Type="Button" Name = Move Value="Move Amount "></TD><TD></TD><TD>
<Input Type="Text" Size="4" Name="MoveAmount" Value = 0></TD><TR>
</Form></Table></Center>

</BODY>

<Script Language = "VBScript">

Sub Move_OnClick
' Make sure move value entered is an integer
If IsNumeric(Document.Form.MoveAmount.Value)Then
    Document.Form.MoveAmount.Value = CInt(Document.Form.MoveAmount.Value)
    Document.Form.Submit
Else
    MsgBox "You Must Enter a Number", ,"ADO-ASP Example"
    Document.Form.MoveAmount.Value = 0
End If

End Sub

Sub cmdDown_OnClick

Document.Form.MoveAmount.Value = -1
Document.Form.Submit

End Sub

Sub cmdUp_OnClick

Document.Form.MoveAmount.Value = 1
Document.Form.Submit

End Sub

</Script>
</HTML>


MoveFirst, MoveLast, MoveNext, and MovePrevious Methods Example (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

MoveFirst, MoveLast, MoveNext, and MovePrevious Methods Example

This example uses the MoveFirst, MoveLast, MoveNext, and MovePrevious methods to move the record pointer of a Recordset based on the supplied command. The MoveAny procedure is required for this procedure to run.

Public Sub MoveFirstX()

    Dim rstAuthors As ADODB.Recordset
    Dim strCnn As String
    Dim strMessage As String
    Dim intCommand As Integer

    ' Open recordset from Authors table.
    strCnn = "driver={SQL Server};server=srv;" & _
        "uid=sa;pwd=;database=pubs"
    Set rstAuthors = New ADODB.Recordset
    rstAuthors.CursorType = adOpenStatic
    ' Use client cursor to enable AbsolutePosition property.
    rstAuthors.CursorLocation = adUseClient
    rstAuthors.Open "authors", strCnn, , , adCmdTable

    ' Show current record information and get user's method choice.
    Do While True

        strMessage = "Name: " & rstAuthors!au_fName & " " & _
            rstAuthors!au_lName & vbCr & "Record " & _
            rstAuthors.AbsolutePosition & " of " & _
            rstAuthors.RecordCount & vbCr & vbCr & _
            "[1 - MoveFirst, 2 - MoveLast, " & vbCr & _
            "3 - MoveNext, 4 - MovePrevious]"
        intCommand = Val(Left(InputBox(strMessage), 1))
        If intCommand < 1 Or intCommand > 4 Then Exit Do

        ' Call method based on user's input.
        MoveAny intCommand, rstAuthors
    Loop
    rstAuthors.Close

End Sub

Public Sub MoveAny(intChoice As Integer, _
    rstTemp As Recordset)

    ' Use specified method, trapping for BOF and EOF.
    Select Case intChoice
        Case 1
            rstTemp.MoveFirst
        Case 2
            rstTemp.MoveLast
        Case 3
            rstTemp.MoveNext
            If rstTemp.EOF Then
                MsgBox "Already at end of recordset!"
                rstTemp.MoveLast
            End If
        Case 4
            rstTemp.MovePrevious
            If rstTemp.BOF Then
                MsgBox "Already at beginning of recordset!"
                rstTemp.MoveFirst
            End If
    End Select

End Sub

VBScript Version

The following is the same example written in VBScript to be used in an Active Server Page (ASP). To view this example, you need to create a system Data Source Name (DSN) called AdvWorks for the Microsoft Access database file AdvWorks.mdb, which is installed with Microsoft Internet Information Server and located at C:\InetPub\ASPSamp\AdvWorks. Locate the file adovbs.inc and place it in the directory you plan to use. Cut and paste the following code to Notepad or another text editor and save it as MoveOne.asp. You can view the result in any client browser.

Try moving beyond the upper or lower limits of the recordset to see error handling work.

<!-- #Include file="ADOVBS.INC" -->
<% Language = VBScript %>
<HTML><HEAD>
<TITLE>ADO 1.5 MoveNext MovePrevious MoveLast MoveFirst Methods</TITLE></HEAD>
<BODY>
<FONT FACE="MS SANS SERIF" SIZE=2>
<Center>
<H3>ADO Methods<BR>MoveNext MovePrevious MoveLast MoveFirst</H3>
<!-- Create Connection and Recordset Objects on Server -->
<%
 'Create and Open Connection Object
Set OBJdbConnection = Server.CreateObject("ADODB.Connection")
OBJdbConnection.Open "AdvWorks"
'Create and Open Recordset Object
Set RsCustomerList = Server.CreateObject("ADODB.Recordset")
RsCustomerList.ActiveConnection = OBJdbConnection
RsCustomerList.CursorType = adOpenKeyset
RsCustomerList.LockType = adLockOptimistic
RsCustomerList.Source = "Customers"

RsCustomerList.Open

' Check Request.Form collection to see if any moves are recorded

If Not IsEmpty(Request.Form("MoveAmount")) Then
'Keep track of the number and direction of moves this session

    Session("Moves") = Session("Moves") + Request.Form("MoveAmount")

    Clicks = Session("Moves")
'Move to last known position
    RsCustomerList.Move CInt(Clicks)
'Check if move is + or - and do error checking
        If CInt(Request.Form("MoveAmount")) = 1 Then

            If RsCustomerList.EOF Then
                Session("Moves") = RsCustomerList.RecordCount
                RsCustomerList.MoveLast
            End If

            RsCustomerList.MoveNext
        End If

        If Request.Form("MoveAmount") < 1 Then

            RsCustomerList.MovePrevious
        End If
'Check if First Record or Last Record Command Buttons Clicked
        If Request.Form("MoveLast") = 3 Then
            RsCustomerList.MoveLast
            Session("Moves") = RsCustomerList.RecordCount
        End If
        If Request.Form("MoveFirst") = 2 Then
            RsCustomerList.MoveFirst
            Session("Moves") = 1
        End If

End If
' Do Error checking for combination of Move Button clicks
        If RsCustomerList.EOF Then
            Session("Moves") = RsCustomerList.RecordCount
            RsCustomerList.MoveLast
            Response.Write "This is the Last Record"
            End If

        If RsCustomerList.BOF Then
            Session("Moves") = 1
            RsCustomerList.MoveFirst
            Response.Write "This is the First Record"
        End If

%>

<H3>Current Record Number is <BR>
<!-- Display Current Record Number and Recordset Size -->
<% If IsEmpty(Session("Moves"))  Then
Session("Moves") = 1
End If
%>

<%Response.Write(Session("Moves") )%> of <%=RsCustomerList.RecordCount%></H3>
<HR>

<Center><TABLE COLSPAN=8 CELLPADDING=5 BORDER=0>

<!-- BEGIN column header row for Customer Table-->

<TR><TD ALIGN=CENTER BGCOLOR="#008080">
<FONT STYLE="ARIAL NARROW" COLOR="#ffffff" SIZE=1>Company Name</FONT>
</TD>
<TD ALIGN=CENTER BGCOLOR="#008080">
<FONT STYLE="ARIAL NARROW" COLOR="#ffffff" SIZE=1>Contact Name</FONT>
</TD>
<TD ALIGN=CENTER WIDTH=150 BGCOLOR="#008080">
<FONT STYLE="ARIAL NARROW" COLOR="#ffffff" SIZE=1>Phone Number</FONT>
</TD>
<TD ALIGN=CENTER BGCOLOR="#008080">
<FONT STYLE="ARIAL NARROW" COLOR="#ffffff" SIZE=1>City</FONT>
</TD>
<TD ALIGN=CENTER BGCOLOR="#008080">
<FONT STYLE="ARIAL NARROW" COLOR="#ffffff" SIZE=1>State/Province</FONT>
</TD></TR>

<!--Display ADO Data from Customer Table-->

  <TR>
  <TD BGCOLOR="f7efde" ALIGN=CENTER>
    <FONT STYLE="ARIAL NARROW" SIZE=1>
      <%= RSCustomerList("CompanyName")%>
    </FONT></TD>
  <TD BGCOLOR="f7efde" ALIGN=CENTER>
    <FONT STYLE="ARIAL NARROW" SIZE=1>
      <%= RScustomerList("ContactLastName") & ", " %>
      <%= RScustomerList("ContactFirstName") %>
    </FONT></TD>
  <TD BGCOLOR="f7efde" ALIGN=CENTER>
    <FONT STYLE="ARIAL NARROW" SIZE=1>

      <%= RScustomerList("PhoneNumber")%>
   </FONT></TD>
  <TD BGCOLOR="f7efde" ALIGN=CENTER>
    <FONT STYLE="ARIAL NARROW" SIZE=1>
      <%= RScustomerList("City")%>
    </FONT></TD>
  <TD BGCOLOR="f7efde" ALIGN=CENTER>
    <FONT STYLE="ARIAL NARROW" SIZE=1>
      <%= RScustomerList("StateOrProvince")%>
    </FONT></TD>
  </TR> </Table></FONT>

<HR>
<Input Type = Button Name = cmdDown  Value = "<    ">
<Input Type = Button Name = cmdUp Value = "    >">
<BR>
<Input Type = Button Name = cmdFirst Value = "First Record">

<Input Type = Button Name = cmdLast Value = "Last Record">
<H5>Click Direction Arrows to Use MovePrevious or MoveNext
<BR> </H5>

<!-- Use Hidden Form Fields to send values to Server -->

<Form Method = Post Action="MoveOne.asp" Name=Form>
<Input Type="Hidden" Size="4" Name="MoveAmount" Value = 0>
<Input Type="Hidden" Size="4" Name="MoveLast" Value = 0>
<Input Type="Hidden" Size="4" Name="MoveFirst" Value = 0>
</Form></BODY>

<Script Language = "VBScript">

Sub cmdDown_OnClick
'Set Values in Form Input Boxes and Submit Form
    Document.Form.MoveAmount.Value = -1
    Document.Form.Submit
End Sub

Sub cmdUp_OnClick

    Document.Form.MoveAmount.Value = 1
    Document.Form.Submit

End Sub

Sub cmdFirst_OnClick

    Document.Form.MoveFirst.Value = 2
    Document.Form.Submit

End Sub

Sub cmdLast_OnClick

    Document.Form.MoveLast.Value = 3
    Document.Form.Submit

End Sub
</Script></HTML>


NextRecordset Method Example (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

NextRecordset Method Example

This example uses the NextRecordset method to view the data in a recordset that uses a compound command statement made up of three separate SELECT statements.

Public Sub NextRecordsetX()

    Dim rstCompound As ADODB.Recordset
    Dim strCnn As String
    Dim intCount As Integer

    ' Open compound recordset.
    strCnn = "driver={SQL Server};server=srv;" & _
        "uid=sa;pwd=;database=pubs"

    Set rstCompound = New ADODB.Recordset
    rstCompound.Open "SELECT * FROM authors; " & _
        "SELECT * FROM stores; " & _
        "SELECT * FROM jobs", strCnn, , , adCmdText

    ' Display results from each SELECT statement.
    intCount = 1
    Do Until rstCompound Is Nothing
        Debug.Print "Contents of recordset #" & intCount
        Do While Not rstCompound.EOF
            Debug.Print , rstCompound.Fields(0), _
                rstCompound.Fields(1)
            rstCompound.MoveNext
        Loop

        Set rstCompound = rstCompound.NextRecordset
        intCount = intCount + 1
    Loop

End Sub


Open and Close Methods Example (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Open and Close Methods Example

This example uses the Open and Close methods on both Recordset and Connection objects that have been opened.

Public Sub OpenX()

    Dim cnn1 As ADODB.Connection
    Dim rstEmployees As ADODB.Recordset
    Dim strCnn As String
    Dim varDate As Variant

    ' Open connection.
    strCnn = "driver={SQL Server};server=srv;" & _
        "uid=sa;pwd=;database=pubs"
    Set cnn1 = New ADODB.Connection
    cnn1.Open strCnn

    ' Open employee table.
    Set rstEmployees = New ADODB.Recordset
    rstEmployees.CursorType = adOpenKeyset
    rstEmployees.LockType = adLockOptimistic
    rstEmployees.Open "employee", cnn1, , , adCmdTable

    ' Assign the first employee record's hire date
    ' to a variable, then change the hire date.
    varDate = rstEmployees!hire_date
    Debug.Print "Original data"
    Debug.Print "    Name - Hire Date"
    Debug.Print "    " & rstEmployees!fName & " " & _
        rstEmployees!lName & " - " & rstEmployees!hire_date
    rstEmployees!hire_date = #1/1/1900#
    rstEmployees.Update
    Debug.Print "Changed data"
    Debug.Print "    Name - Hire Date"
    Debug.Print "    " & rstEmployees!fName & " " & _
        rstEmployees!lName & " - " & rstEmployees!hire_date

    ' Requery Recordset and reset the hire date.
    rstEmployees.Requery
    rstEmployees!hire_date = varDate
    rstEmployees.Update
    Debug.Print "Data after reset"
    Debug.Print "    Name - Hire Date"
    Debug.Print "    " & rstEmployees!fName & " " & _
        rstEmployees!lName & " - " & rstEmployees!hire_date

    rstEmployees.Close
    cnn1.Close

End Sub

VBScript Version

The following is the same example written in VBScript to be used in an Active Server Page (ASP). To view this example, you need to create a system Data Source Name (DSN) called AdvWorks for the Microsoft Access database file AdvWorks.mdb, which is installed with Microsoft Internet Information Server and located at C:\InetPub\ASPSamp\AdvWorks. Locate the file adovbs.inc and place it in the directory you plan to use. Cut and paste the following code to Notepad or another text editor and save it as ADOOpen.asp. You can view the result in any client browser.

<!-- #Include file="ADOVBS.INC" -->
<HTML><HEAD>
<TITLE>ADO 1.5 Open Method</TITLE>
</HEAD><BODY>
<FONT FACE="MS SANS SERIF" SIZE=2>
<Center><H3>ADO Open Method</H3>
<TABLE WIDTH=600 BORDER=0>
<TD VALIGN=TOP ALIGN=LEFT COLSPAN=3><FONT SIZE=2>
<!--- ADO Connection used to create 2 recordsets-->
<%
Set OBJdbConnection = Server.CreateObject("ADODB.Connection")
OBJdbConnection.Open "AdvWorks"
SQLQuery = "SELECT * FROM Customers"
'First Recordset RSCustomerList
Set RSCustomerList = OBJdbConnection.Execute(SQLQuery)
'Second Recordset RsProductist
Set RsProductList = Server.CreateObject("ADODB.Recordset")
RsProductList.CursorType = adOpenDynamic
RsProductList.LockType = adLockOptimistic
RsProductList.Open "Products", OBJdbConnection
%>
<TABLE COLSPAN=8 CELLPADDING=5 BORDER=0>

<!-- BEGIN column header row for Customer Table-->

<TR><TD ALIGN=CENTER BGCOLOR="#008080">
<FONT STYLE="ARIAL NARROW" COLOR="#ffffff" SIZE=1>Company Name</FONT></TD>
<TD ALIGN=CENTER BGCOLOR="#008080">
<FONT STYLE="ARIAL NARROW" COLOR="#ffffff" SIZE=1>Contact Name</FONT></TD>
<TD ALIGN=CENTER WIDTH=150 BGCOLOR="#008080">
<FONT STYLE="ARIAL NARROW" COLOR="#ffffff" SIZE=1>E-mail address</FONT></TD>
<TD ALIGN=CENTER BGCOLOR="#008080">
<FONT STYLE="ARIAL NARROW" COLOR="#ffffff" SIZE=1>City</FONT></TD>
<TD ALIGN=CENTER BGCOLOR="#008080">
<FONT STYLE="ARIAL NARROW" COLOR="#ffffff" SIZE=1>State/Province</FONT></TD></TR>

<!--Display ADO Data from Customer Table-->
<% Do While Not RScustomerList.EOF %>
  <TR><TD BGCOLOR="f7efde" ALIGN=CENTER>
    <FONT STYLE="ARIAL NARROW" SIZE=1>
      <%= RSCustomerList("CompanyName")%>
    </FONT></TD>
  <TD BGCOLOR="f7efde" ALIGN=CENTER>
    <FONT STYLE="ARIAL NARROW" SIZE=1>
      <%= RScustomerList("ContactLastName") & ", " %>
      <%= RScustomerList("ContactFirstName") %>
    </FONT></TD>
  <TD BGCOLOR="f7efde" ALIGN=CENTER>
    <FONT STYLE="ARIAL NARROW" SIZE=1>
    <%= RScustomerList("ContactLastName")%>
   </FONT></TD>
  <TD BGCOLOR="f7efde" ALIGN=CENTER>
    <FONT STYLE="ARIAL NARROW" SIZE=1>
      <%= RScustomerList("City")%>
    </FONT></TD>
  <TD BGCOLOR="f7efde" ALIGN=CENTER>
    <FONT STYLE="ARIAL NARROW" SIZE=1>
      <%= RScustomerList("StateOrProvince")%>
    </FONT></TD></TR>
<!-Next Row = Record Loop and add to html table-->
<%
RScustomerList.MoveNext
Loop
RScustomerList.Close
OBJdbConnection.Close
%>
</TABLE>
<HR>
<TABLE COLSPAN=8 CELLPADDING=5 BORDER=0>

<!-- BEGIN column header row for Product List Table-->

<TR><TD ALIGN=CENTER BGCOLOR="#800000">
<FONT STYLE="ARIAL NARROW" COLOR="#ffffff" SIZE=1>Product Type</FONT></TD>
<TD ALIGN=CENTER BGCOLOR="#800000">
<FONT STYLE="ARIAL NARROW" COLOR="#ffffff" SIZE=1>Product Name</FONT></TD>
<TD ALIGN=CENTER WIDTH=350 BGCOLOR="#800000">
<FONT STYLE="ARIAL NARROW" COLOR="#ffffff" SIZE=1>Product Description</FONT></TD>
<TD ALIGN=CENTER BGCOLOR="#800000">
<FONT STYLE="ARIAL NARROW" COLOR="#ffffff" SIZE=1>Unit Price</FONT></TD></TR>
<!-- Display ADO Data Product List-->
<% Do While Not RsProductList.EOF %>
  <TR>  <TD BGCOLOR="f7efde" ALIGN=CENTER>
    <FONT STYLE="ARIAL NARROW" SIZE=1>
      <%= RsProductList("ProductType")%>
    </FONT></TD>
  <TD BGCOLOR="f7efde" ALIGN=CENTER>
    <FONT STYLE="ARIAL NARROW" SIZE=1>
      <%= RsProductList("ProductName")%>
    </FONT></TD>
  <TD BGCOLOR="f7efde" ALIGN=CENTER>
    <FONT STYLE="ARIAL NARROW" SIZE=1>
     <%= RsProductList("ProductDescription")%>
   </FONT></TD>
  <TD BGCOLOR="f7efde" ALIGN=CENTER>
    <FONT STYLE="ARIAL NARROW" SIZE=1>
      <%= RsProductList("UnitPrice")%>
    </FONT></TD>

<!--  Next Row = Record -->
<%
RsProductList.MoveNext
Loop
'Remove Objects from Memory Freeing
Set RsProductList = Nothing
Set OBJdbConnection = Nothing
%>
</TABLE></FONT></Center></BODY></HTML>


OpenSchema Method Example (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

OpenSchema Method Example

This example uses the OpenSchema method to display the name and type of each table in the Pubs database.

Public Sub OpenSchemaX()

    Dim cnn1 As ADODB.Connection
    Dim rstSchema As ADODB.Recordset
    Dim strCnn As String

    Set cnn1 = New ADODB.Connection
    strCnn = "driver={SQL Server};server=srv;" & _
        "uid=sa;pwd=;database=pubs"
    cnn1.Open strCnn

    Set rstSchema = cnn1.OpenSchema(adSchemaTables)

    Do Until rstSchema.EOF
        Debug.Print "Table name: " & _
            rstSchema!TABLE_NAME & vbCr & _
            "Table type: " & rstSchema!TABLE_TYPE & vbCr
        rstSchema.MoveNext
    Loop
    rstSchema.Close

    cnn1.Close

End Sub


Refresh Method Example (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Refresh Method Example

This example demonstrates using the Refresh method to refresh the Parameters collection for a stored procedure Command object.

Public Sub RefreshX()

    Dim cnn1 As ADODB.Connection
    Dim cmdByRoyalty As ADODB.Command
    Dim rstByRoyalty As ADODB.Recordset
    Dim rstAuthors As ADODB.Recordset
    Dim intRoyalty As Integer
    Dim strAuthorID As String
    Dim strCnn As String

    ' Open connection.
    Set cnn1 = New ADODB.Connection
    strCnn = "driver={SQL Server};server=srv;" & _
        "uid=sa;pwd=;database=pubs"
    cnn1.Open strCnn

    ' Open a command object for a stored procedure
    ' with one parameter.
    Set cmdByRoyalty = New ADODB.Command
    Set cmdByRoyalty.ActiveConnection = cnn1
    cmdByRoyalty.CommandText = "byroyalty"
    cmdByRoyalty.CommandType = adCmdStoredProc
    cmdByRoyalty.Parameters.Refresh

    ' Get paramater value and execute the command,
    ' storing the results in a recordset.
    intRoyalty = Trim(InputBox("Enter royalty:"))
    cmdByRoyalty.Parameters(1) = intRoyalty
    Set rstByRoyalty = cmdByRoyalty.Execute()

    ' Open the Authors table to get author names for display.
    Set rstAuthors = New ADODB.Recordset
    rstAuthors.Open "authors", cnn1, , , adCmdTable

    ' Print current data in the recordset, adding
    ' author names from Authors table.
    Debug.Print "Authors with " & intRoyalty & " percent royalty"
    Do While Not rstByRoyalty.EOF
        strAuthorID = rstByRoyalty!au_id
        Debug.Print "	" & rstByRoyalty!au_id & ", ";
        rstAuthors.Filter = "au_id = '" & strAuthorID & "'"
        Debug.Print rstAuthors!au_fname & " " & _
            rstAuthors!au_lname
        rstByRoyalty.MoveNext
    Loop

    rstByRoyalty.Close
    rstAuthors.Close
    cnn1.Close

End Sub


Resync Method Example (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Resync Method Example

This example demonstrates using the Resync method to refresh data in a static recordset.

Public Sub ResyncX()

    Dim strCnn As String
    Dim rstTitles As ADODB.Recordset

    ' Open connections.
    strCnn = "driver={SQL Server};server=srv;" & _
        "uid=sa;pwd=;database=pubs"

    ' Open recordset for titles table.
    Set rstTitles = New ADODB.Recordset
    rstTitles.CursorType = adOpenStatic
    rstTitles.LockType = adLockBatchOptimistic
    rstTitles.Open "titles", strCnn, , , adCmdTable

    ' Change the type of the first title in the recordset.
    rstTitles!Type = "database"

    ' Display the results of the change.
    MsgBox "Before resync: " & vbCr & vbCr & _
        "Title - " & rstTitles!Title & vbCr & _
        "Type - " & rstTitles!Type

    ' Resync with database and redisplay results.
    rstTitles.Resync
    MsgBox "After resync: " & vbCr & vbCr & _
        "Title - " & rstTitles!Title & vbCr & _
        "Type - " & rstTitles!Type

    rstTitles.CancelBatch
    rstTitles.Close

End Sub


Supports Method Example (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Supports Method Example

This example uses the Supports method to display the options supported by a recordset opened with different cursor types. The DisplaySupport procedure is required for this procedure to run.

Public Sub SupportsX()

    Dim aintCursorType(4) As Integer
    Dim rstTitles As ADODB.Recordset
    Dim strCnn As String
    Dim intIndex As Integer

    ' Open connections.
    strCnn = "driver={SQL Server};server=srv;" & _
        "uid=sa;pwd=;database=pubs"

    ' Fill array with CursorType constants.
    aintCursorType(0) = adOpenForwardOnly
    aintCursorType(1) = adOpenKeyset
    aintCursorType(2) = adOpenDynamic
    aintCursorType(3) = adOpenStatic

    ' Open recordset using each CursorType and
    ' optimitic locking. Then call the DisplaySupport
    ' procedure to display the supported options.
    For intIndex = 0 To 3
        Set rstTitles = New ADODB.Recordset
        rstTitles.CursorType = aintCursorType(intIndex)
        rstTitles.LockType = adLockOptimistic
        rstTitles.Open "titles", strCnn, , , adCmdTable

        Select Case aintCursorType(intIndex)
            Case adOpenForwardOnly
                Debug.Print "ForwardOnly cursor supports:"
            Case adOpenKeyset
                Debug.Print "Keyset cursor supports:"
            Case adOpenDynamic
                Debug.Print "Dynamic cursor supports:"
            Case adOpenStatic
                Debug.Print "Static cursor supports:"
        End Select

        DisplaySupport rstTitles
        rstTitles.Close
    Next intIndex

End Sub

Public Sub DisplaySupport(rstTemp As ADODB.Recordset)

    Dim alngConstants(9) As Long
    Dim booSupports As Boolean
    Dim intIndex As Integer

    ' Fill array with cursor option constants.
    alngConstants(0) = adAddNew
    alngConstants(1) = adApproxPosition
    alngConstants(2) = adBookmark
    alngConstants(3) = adDelete
    alngConstants(4) = adHoldRecords
    alngConstants(5) = adMovePrevious
    alngConstants(6) = adResync
    alngConstants(7) = adUpdate
    alngConstants(8) = adUpdateBatch

    For intIndex = 0 To 8
        booSupports = _
            rstTemp.Supports(alngConstants(intIndex))
        If booSupports Then
            Select Case alngConstants(intIndex)
                Case adAddNew
                    Debug.Print "	AddNew"
                Case adApproxPosition
                    Debug.Print "	AbsolutePosition and AbsolutePage"
                Case adBookmark
                    Debug.Print "	Bookmark"
                Case adDelete
                    Debug.Print "	Delete"
                Case adHoldRecords
                    Debug.Print "	holding records"
                Case adMovePrevious
                    Debug.Print "	MovePrevious and Move"
                Case adResync
                    Debug.Print "	resyncing data"
                Case adUpdate
                    Debug.Print "	Update"
                Case adUpdateBatch
                    Debug.Print "	batch updating"
            End Select
        End If
    Next intIndex

End Sub


Update and CancelUpdate Methods Example (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Update and CancelUpdate Methods Example

This example demonstrates the Update method in conjunction with CancelUpdate method.

Public Sub UpdateX()

    Dim rstEmployees As ADODB.Recordset
    Dim strOldFirst As String
    Dim strOldLast As String
    Dim strMessage As String

    ' Open recordset with names from Employee table.
    strCnn = "driver={SQL Server};server=srv;" & _
        "uid=sa;pwd=;database=pubs"
    Set rstEmployees = New ADODB.Recordset
    rstEmployees.CursorType = adOpenKeyset
    rstEmployees.LockType = adLockOptimistic
    rstEmployees.Open "SELECT fname, lname " & _
        "FROM Employee ORDER BY lname", strCnn, , , adCmdText

    ' Store original data.
    strOldFirst = rstEmployees!fname
    strOldLast = rstEmployees!lname
    ' Change data in edit buffer.
    rstEmployees!fname = "Linda"
    rstEmployees!lname = "Kobara"

    ' Show contents of buffer and get user input.
    strMessage = "Edit in progress:" & vbCr & _
        "  Original data = " & strOldFirst & " " & _
        strOldLast & vbCr & "  Data in buffer = " & _
        rstEmployees!fname & " " & rstEmployees!lname & vbCr & vbCr & _
        "Use Update to replace the original data with " & _
        "the buffered data in the Recordset?"

    If MsgBox(strMessage, vbYesNo) = vbYes Then
        rstEmployees.Update
    Else
        rstEmployees.CancelUpdate
    End If

    ' Show the resulting data.
    MsgBox "Data in recordset = " & rstEmployees!fname & " " & _
        rstEmployees!lname

    ' Restore original data because this is a demonstration.
    If Not (strOldFirst = rstEmployees!fname And _
            strOldLast = rstEmployees!lname) Then
        rstEmployees!fname = strOldFirst
        rstEmployees!lname = strOldLast
        rstEmployees.Update
    End If

    rstEmployees.Close

End Sub

This example demonstrates the Update method in conjunction with the AddNew method.

Public Sub UpdateX2()

    Dim cnn1 As ADODB.Connection
    Dim rstEmployees As ADODB.Recordset
    Dim strEmpID As String
    Dim strOldFirst As String
    Dim strOldLast As String
    Dim strMessage As String

    ' Open a connection.
    Set cnn1 = New ADODB.Connection
    strCnn = "driver={SQL Server};server=srv;" & _
        "uid=sa;pwd=;database=pubs"
    cnn1.Open strCnn

    ' Open recordset with data from Employee table.
    Set rstEmployees = New ADODB.Recordset
    rstEmployees.CursorType = adOpenKeyset
    rstEmployees.LockType = adLockOptimistic
    rstEmployees.Open "employee", cnn1, , , adCmdTable

    rstEmployees.AddNew
    strEmpID = "B-S55555M"
    rstEmployees!emp_id = strEmpID
    rstEmployees!fname = "Bill"
    rstEmployees!lname = "Sornsin"

    ' Show contents of buffer and get user input.
    strMessage = "AddNew in progress:" & vbCr & _
        "Data in buffer = " & rstEmployees!emp_id & ", " & _
        rstEmployees!fname & " " & rstEmployees!lname & vbCr & vbCr & _
        "Use Update to save buffer to recordset?"

    If MsgBox(strMessage, vbYesNoCancel) = vbYes Then
        rstEmployees.Update
        ' Go to the new record and show the resulting data.
        MsgBox "Data in recordset = " & rstEmployees!emp_id & ", " & _
             rstEmployees!fname & " " & rstEmployees!lname
    Else
        rstEmployees.CancelUpdate
        MsgBox "No new record added."
    End If

    ' Delete new data because this is a demonstration.
    cnn1.Execute "DELETE FROM employee WHERE emp_id = '" & strEmpID & "'"

    rstEmployees.Close

End Sub


UpdateBatch and CancelBatch Methods Example (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

UpdateBatch and CancelBatch Methods Example

This example demonstrates the UpdateBatch method in conjunction with CancelBatch method.

Public Sub UpdateBatchX()

    Dim rstTitles As ADODB.Recordset
    Dim strCnn As String
    Dim strTitle As String
    Dim strMessage As String

    ' Assign connection string to variable.
    strCnn = "driver={SQL Server};server=srv;" & _
        "uid=sa;pwd=;database=pubs"

    Set rstTitles = New ADODB.Recordset
    rstTitles.CursorType = adOpenKeyset
    rstTitles.LockType = adLockBatchOptimistic
    rstTitles.Open "titles", strCnn, , , adCmdTable

    rstTitles.MoveFirst

    ' Loop through recordset and ask user if she wants
    ' to change the type for a specified title.
    Do Until rstTitles.EOF
        If Trim(rstTitles!Type) = "psychology" Then
            strTitle = rstTitles!Title
            strMessage = "Title: " & strTitle & vbCr & _
                "Change type to self help?"

            If MsgBox(strMessage, vbYesNo) = vbYes Then
                rstTitles!Type = "self_help"
            End If
        End If

        rstTitles.MoveNext
    Loop

    ' Ask if the user wants to commit to all the
    ' changes made above.
    If MsgBox("Save all changes?", vbYesNo) = vbYes Then
        rstTitles.UpdateBatch
    Else
        rstTitles.CancelBatch
    End If

    ' Print current data in recordset.
    rstTitles.Requery
    rstTitles.MoveFirst
    Do While Not rstTitles.EOF
        Debug.Print rstTitles!Title & " - " & rstTitles!Type
        rstTitles.MoveNext
    Loop

    ' Restore original values because this is a demonstration.
    rstTitles.MoveFirst
    Do Until rstTitles.EOF
        If Trim(rstTitles!Type) = "self_help" Then
            rstTitles!Type = "psychology"
        End If
        rstTitles.MoveNext
    Loop
    rstTitles.UpdateBatch

    rstTitles.Close

End Sub


Command Object (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Command Object

A Command object is a definition of a specific command that you intend to execute against a data source.

Collections

Parameters, Properties

Methods

CreateParameter, Execute

Properties

ActiveConnection, CommandText, CommandTimeout, CommandType, Name, Prepared, State

Remarks

Use a Command object to query a database and return records in a Recordset object, to execute a bulk operation, or to manipulate the structure of a database. Depending on the functionality of the provider, some Command collections, methods, or properties may generate an error when referenced.

With the collections, methods, and properties of a Command object, you can do the following:

  • Define the executable text of the command (for example, an SQL statement) with the CommandText property.

  • Define parameterized queries or stored-procedure arguments with Parameter objects and the Parameters collection.

  • Execute a command and return a Recordset object if appropriate with the Execute method.

  • Specify the type of command with the CommandType property prior to execution to optimize performance.

  • Control whether or not the provider saves a prepared (or compiled) version of the command prior to execution with the Prepared property.

  • Set the number of seconds a provider will wait for a command to execute with the CommandTimeout property.

  • Associate an open connection with a Command object by setting its ActiveConnection property.

  • Set the Name property to identify the Command object as a method on the associated Connection object.

  • Pass a Command object to the Source property of a Recordset in order to obtain data.

Note To execute a query without using a Command object, pass a query string to the Execute method of a Connection object or to the Open method of a Recordset object. However, a Command object is required when you want to persist the command text and re-execute it, or use query parameters.

To create a Command object independently of a previously defined Connection object, set its ActiveConnection property to a valid connection string. ADO still creates a Connection object, but it doesn't assign that object to an object variable. However, if you are associating multiple Command objects with the same connection, you should explicitly create and open a Connection object; this assigns the Connection object to an object variable. If you do not set the Command objects' ActiveConnection property to this object variable, ADO creates a new Connection object for each Command object, even if you use the same connection string.

To execute a Command, simply call it by its Name property on the associated Connection object. The Command must have its ActiveConnection property set to the Connection object. If the Command has parameters, pass values for them as arguments to the method.

See Also

Using OLE DB Providers with ADO


Connection Object (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Connection Object

A Connection object represents an open connection to a data source.

Collections

Errors, Properties

Methods

BeginTrans, Close, CommitTrans, Execute, Open, OpenSchema, RollbackTrans

Properties

Attributes, CommandTimeout, ConnectionString, ConnectionTimeout, CursorLocation, DefaultDatabase, IsolationLevel, Mode, Provider, State, Version

Remarks

A Connection object represents a unique session with a data source. In the case of a client/server database system, it may be equivalent to an actual network connection to the server. Depending on the functionality supported by the provider, some collections, methods, or properties of a Connection object may not be available.

Using the collections, methods, and properties of a Connection object, you can do the following:

  • Configure the connection before opening it with the ConnectionString, ConnectionTimeout, and Mode properties.

  • Set the CursorLocation property to invoke the Client Cursor Provider, which supports batch updates.

  • Set the default database for the connection with the DefaultDatabase property.

  • Set the level of isolation for the transactions opened on the connection with the IsolationLevel property.

  • Specify an OLE DB provider with the Provider property.

  • Establish, and later break, the physical connection to the data source with the Open and Close methods.

  • Execute a command on the connection with the Execute method and configure the execution with the CommandTimeout property.

  • Manage transactions on the open connection, including nested transactions if the provider supports them, with the BeginTrans, CommitTrans, and RollbackTrans methods and the Attributes property.

  • Examine errors returned from the data source with the Errors collection.

  • Read the version from the ADO implementation in use with the Version property.

  • Obtain schema information about your database with the OpenSchema method.

Note To execute a query without using a Command object, pass a query string to the Execute method of a Connection object. However, a Command object is required when you want to persist the command text and re-execute it, or use query parameters.

You can create Connection objects independently of any other previously defined object.

See Also

Using OLE DB Providers with ADO


Error Object (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Error Object

An Error object contains details about data access errors pertaining to a single operation involving the provider.

Properties

Description, HelpContext, HelpFile, NativeError, Number, Source, SQLState

Remarks

Any operation involving ADO objects can generate one or more provider errors. As each error occurs, one or more Error objects are placed in the Errors collection of the Connection object. When another ADO operation generates an error, the Errors collection is cleared, and the new set of Error objects are placed in the Errors collection.

Note Each Error object represents a specific provider error, not an ADO error. ADO errors are exposed to the run-time exception handling mechanism. For example, in Microsoft Visual Basic, the occurrence of an ADO-specific error will trigger an On Error event and appear in the Err object. For a complete list of ADO errors, see the ADO Error Codes topic.

You can read an Error object’s properties to obtain specific details about each error, including the following:

  • The Description property, which contains the text of the error.

  • The Number property, which contains the Long integer value of the error constant.

  • The Source property, which identifies the object that raised the error. This is particularly useful when you have several Error objects in the Errors collection following a request to a data source.

  • The HelpFile and HelpContext properties, which indicate the appropriate Microsoft Windows Help file and Help topic, respectively, (if any exist) for the error.

  • The SQLState and NativeError properties, which provide information from SQL data sources.

When a provider error occurs, it is placed in the Errors collection of the Connection object. ADO supports the return of multiple errors by a single ADO operation to allow for error information specific to the provider. To obtain this rich error information in an error handler, use the appropriate error-trapping features of the language or environment you are working with, then use nested loops to enumerate the properties of each Error object in the Errors collection.

Microsoft Visual Basic and VBScript If there is no valid Connection object, you will need to retrieve error information from the Err object.

Just as providers do, ADO clears the OLE Error Info object before making a call that could potentially generate a new provider error. However, the Errors collection on the Connection object is cleared and populated only when the provider generates a new error, or when the Clear method is called.

Some properties and methods return warnings that appear as Error objects in the Errors collection but do not halt a program's execution. Before you call the Resync, UpdateBatch, or CancelBatch methods on a Recordset object, or before you set the Filter property on a Recordset object, call the Clear method on the Errors collection so that you can read the Count property of the Errors collection to test for returned warnings.

See Also

Using OLE DB Providers with ADO


Field Object (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Field Object

A Field object represents a column of data with a common data type.

Collections

Properties

Methods

AppendChunk, GetChunk

Properties

ActualSize, Attributes, DefinedSize, Name, NumericScale, OriginalValue, Precision, Type, UnderlyingValue, Value

Remarks

A Recordset object has a Fields collection made up of Field objects. Each Field object corresponds to a column in the Recordset. You use the Value property of Field objects to set or return data for the current record. Depending on the functionality the provider exposes, some collections, methods, or properties of a Field object may not be available.

With the collections, methods, and properties of a Field object, you can do the following:

  • Return the name of a field with the Name property.

  • View or change the data in the Field with the Value property.

  • Return the basic characteristics of a field with the Type, Precision, and NumericScale properties.

  • Return the declared size of a field with the DefinedSize property.

  • Return the actual size of the data in a given field with the ActualSize property.

  • Determine what types of functionality are supported for a given field with the Attributes property and Properties collection.

  • Manipulate the values of fields containing long binary or long character data with the AppendChunk and GetChunk methods.

  • If the provider supports batch updates, resolve discrepancies in field values during batch updating with the OriginalValue and UnderlyingValue properties.

All of the metadata properties (Name, Type, DefinedSize, Precision, and NumericScale) are available before opening the Field object’s Recordset. Setting them at that time is useful for dynamically constructing forms.


Parameter Object (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Parameter Object

A Parameter object represents a parameter or argument associated with a Command object based on a parameterized query or stored procedure.

Collections

Properties

Methods

AppendChunk

Properties

Attributes, Direction, Name, NumericScale, Precision, Size, Type, Value

Remarks

Many providers support parameterized commands. These are commands where the desired action is defined once, but variables (or parameters) are used to alter some details of the command. For example, an SQL SELECT statement could use a parameter to define the matching criteria of a WHERE clause, and another to define the column name for a SORT BY clause.

Parameter objects represent parameters associated with parameterized queries, or the in/out arguments and the return values of stored procedures. Depending on the functionality of the provider, some collections, methods, or properties of a Parameter object may not be available.

With the collections, methods, and properties of a Parameter object, you can do the following:

  • Set or return the name of a parameter with the Name property.

  • Set or return the value of a parameter with the Value property.

  • Set or return parameter characteristics with the Attributes and Direction, Precision, NumericScale, Size, and Type properties.

  • Pass long binary or character data to a parameter with the AppendChunk method.

If you know the names and properties of the parameters associated with the stored procedure or parameterized query you wish to call, you can use the CreateParameter method to create Parameter objects with the appropriate property settings and use the Append method to add them to the Parameters collection. This lets you set and return parameter values without having to call the Refresh method on the Parameters collection to retrieve the parameter information from the provider, a potentially resource-intensive operation.


Property Object (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Property Object

A Property object represents a dynamic characteristic of an ADO object that is defined by the provider.

Properties

Attributes, Name, Type, Value

Remarks

ADO objects have two types of properties: built-in and dynamic. Built-in properties are those properties implemented in ADO and immediately available to any new object, using the familiar MyObject.Property syntax.

Built-in properties do not appear as Property objects in an object’s Properties collection, so while you can change their values, you cannot modify their characteristics or delete them.

Dynamic properties are defined by the underlying data provider, and appear in the Properties collection for the appropriate ADO object. For example, a property specific to the provider may indicate if a Recordset object supports transactions or updating. These additional properties will appear as Property objects in that Recordset object’s Properties collection. Dynamic properties can be referenced only through the collection, using the MyObject.Properties(0) or MyObject.Properties("Name") syntax.

A dynamic Property object has four built-in properties of its own:

  • The Name property is a string that identifies the property.

  • The Type property is an integer that specifies the property data type.

  • The Value property is a variant that contains the property setting.

  • The Attributes property is a long value that indicates characteristics of the property specific to the provider.

See Also

Using OLE DB Providers with ADO


Recordset Object (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Recordset Object

A Recordset object represents the entire set of records from a base table or the results of an executed command. At any time, the Recordset object only refers to a single record within the set as the current record.

Collections

Fields, Properties

Methods

AddNew, CancelBatch, CancelUpdate, Clone, Close, Delete, GetRows, Move, MoveFirst, MoveLast, MoveNext, MovePrevious, NextRecordset, Open, Requery, Resync, Supports, Update, UpdateBatch

Properties

AbsolutePage, AbsolutePosition, ActiveConnection, BOF, Bookmark, CacheSize, CursorLocation, CursorType, EditMode, EOF, Filter, LockType, MarshalOptions, MaxRecords, PageCount, PageSize, RecordCount, Source, State, Status

Remarks

You use Recordset objects to manipulate data from a provider. When you use ADO, you manipulate data almost entirely using Recordset objects. All Recordset objects are constructed using records (rows) and fields (columns). Depending on the functionality supported by the provider, some Recordset methods or properties may not be available.

Recordset objects can also be remoted. For example, in a web-based application, you can open a Recordset on the client, using the progID "ADOR." The Remote Data Service provides a mechanism for local data caching and local cursoring of remoted Recordset data. A client-side Recordset can be used in the same way as a server-side Recordset, and supports almost all of the Recordset normal methods and properties. Recordset methods and properties that are not supported on a client-side Recordset, or that behave differently, are noted in the Help topics for those properties and methods.

There are four different cursor types defined in ADO:

  • Dynamic cursor — allows you to view additions, changes, and deletions by other users, and allows all types of movement through the Recordset that don't rely on bookmarks; allows bookmarks if the provider supports them.

  • Keyset cursor — behaves like a dynamic cursor, except that it prevents you from seeing records that other users add, and prevents access to records that other users delete. Data changes by other users will still be visible. It always supports bookmarks and therefore allows all types of movement through the Recordset.

  • Static cursor — provides a static copy of a set of records for you to use to find data or generate reports; always allows bookmarks and therefore allows all types of movement through the Recordset. Additions, changes, or deletions by other users will not be visible. This is the only type of cursor allowed when you open a client-side (ADOR) Recordset object.

  • Forward-only cursor — behaves identically to a dynamic cursor except that it allows you to scroll only forward through records. This improves performance in situations where you need to make only a single pass through a recordset.

Set the CursorType property prior to opening the Recordset to choose the cursor type, or pass a CursorType argument with the Open method. Some providers don’t support all cursor types. Check the documentation for the provider. If you don't specify a cursor type, ADO opens a forward-only cursor by default.

When used with some providers (such as the Microsoft ODBC Provider for OLE DB in conjunction with Microsoft SQL Server), you can create Recordset objects independently of a previously defined Connection object by passing a connection string with the Open method. ADO still creates a Connection object, but it doesn't assign that object to an object variable. However, if you are opening multiple Recordset objects over the same connection, you should explicitly create and open a Connection object; this assigns the Connection object to an object variable. If you do not use this object variable when opening your Recordset objects, ADO creates a new Connection object for each new Recordset, even if you pass the same connection string.

You can create as many Recordset objects as needed.

When you open a Recordset, the current record is positioned to the first record (if any) and the BOF and EOF properties are set to False. If there are no records, the BOF and EOF property settings are True.

You can use the MoveFirst, MoveLast, MoveNext, and MovePrevious methods, as well as the Move method, and the AbsolutePosition, AbsolutePage, and Filter properties to reposition the current record, assuming the provider supports the relevant functionality. Forward-only Recordset objects support only the MoveNext method. When you use the Move methods to visit each record (or enumerate the Recordset), you can use the BOF and EOF properties to see if you've moved beyond the beginning or end of the Recordset.

Recordset objects may support two types of updating: immediate and batched. In immediate updating, all changes to data are written immediately to the underlying data source once you call the Update method. You can also pass arrays of values as parameters with the AddNew and Update methods and simultaneously update several fields in a record.

If a provider supports batch updating, you can have the provider cache changes to more than one record and then transmit them in a single call to the database with the UpdateBatch method. This applies to changes made with the AddNew, Update, and Delete methods. After you call the UpdateBatch method, you can use the Status property to check for any data conflicts in order to resolve them.

Note To execute a query without using a Command object, pass a query string to the Open method of a Recordset object. However, a Command object is required when you want to persist the command text and re-execute it, or use query parameters.

See Also

Using OLE DB Providers with ADO


Errors Collection (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Errors Collection

The Errors collection contains all the Error objects created in response to a single failure involving the provider.

Methods

Clear, Item

Properties

Count

Remarks

Any operation involving ADO objects can generate one or more provider errors. As each error occurs, one or more Error objects may be placed in the Errors collection of the Connection object. When another ADO operation generates an error, the Errors collection is cleared, and the new set of Error objects may be placed in the Errors collection.

Each Error object represents a specific provider error, not an ADO error. ADO errors are exposed to the run-time exception handling mechanism. For example, in Microsoft Visual Basic, the occurrence of an ADO-specific error will trigger an On Error event and appear in the Err object.

ADO operations that don't generate an error have no effect on the Errors collection. Use the Clear method to manually clear the Errors collection.

The set of Error objects in the Errors collection describes all errors that occurred in response to a single statement. Enumerating the specific errors in the Errors collection enables your error-handling routines to more precisely determine the cause and origin of an error, and take appropriate steps to recover.

Some properties and methods return warnings that appear as Error objects in the Errors collection but do not halt a program's execution. Before you call the Resync, UpdateBatch, or CancelBatch methods on a Recordset object, or before you set the Filter property on a Recordset object, call the Clear method on the Errors collection so that you can read the Count property of the Errors collection to test for returned warnings.

Note See the Error object topic for a more detailed explanation of the way a single ADO operation can generate multiple errors.

See Also

Using OLE DB Providers with ADO


Fields Collection (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Fields Collection

A Fields collection contains all the Field objects of a Recordset object.

Methods

Item, Refresh

Properties

Count

Remarks

A Recordset object has a Fields collection made up of Field objects. Each Field object corresponds to a column in the Recordset. You can populate the Fields collection before opening the Recordset by calling the Refresh method on the collection.

Note See the Field object topic for a more detailed explanation of how to use Field objects.


Parameters Collection (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Parameters Collection

A Parameters collection contains all the Parameter objects of a Command object.

Methods

Append, Delete, Item, Refresh

Properties

Count

Remarks

A Command object has a Parameters collection made up of Parameter objects.

Using the Refresh method on a Command object's Parameters collection retrieves provider parameter information for the stored procedure or parameterized query specified in the Command object. Some providers do not support stored procedure calls or parameterized queries; calling the Refresh method on the Parameters collection when using such a provider will return an error.

If you have not defined your own Parameter objects and you access the Parameters collection before calling the Refresh method, ADO will automatically call the method and populate the collection for you.

You can minimize calls to the provider to improve performance if you know the properties of the parameters associated with the stored procedure or parameterized query you wish to call. Use the CreateParameter method to create Parameter objects with the appropriate property settings and use the Append method to add them to the Parameters collection. This lets you set and return parameter values without having to call the provider for the parameter information. If you are writing to a provider that does not supply parameter information, you must manually populate the Parameters collection using this method to be able to use parameters at all. Use the Delete method to remove Parameter objects from the Parameters collection if necessary.


Properties Collection (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Properties Collection

A Properties collection contains all the Property objects for a specific instance of an object.

Methods

Item, Refresh

Properties

Count

Remarks

Some ADO objects have a Properties collection made up of Property objects. Each Property object corresponds to a characteristic of the ADO object specific to the provider.

Note See the Property object topic for a more detailed explanation of how to use Property objects.

See Also

Using OLE DB Providers with ADO


AbsolutePage Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

AbsolutePage Property - ADO

Specifies in which page the current record resides.

Applies To

Recordset

Settings and Return Values

Sets or returns a Long value from 1 to the number of pages in the Recordset object (PageCount), or returns one of the following constants.
Constant | Description
adPosUnknown | The Recordset is empty, the current position is unknown, or the provider does not support the AbsolutePage property.
adPosBOF | The current record pointer is at BOF (that is, the BOF property is True.)
adPosEOF | The current record pointer is at EOF (that is, the EOF property is True.)

Remarks

Use the AbsolutePage property to identify the page number on which the current record is located. Use the PageSize property to logically divide the Recordset object into a series of pages, each of which has the number of records equal to PageSize (except for the last page which may have fewer records). The provider must support the appropriate functionality for this property to be available.

Like the AbsolutePosition property, AbsolutePage is 1-based and equals 1 when the current record is the first record in the Recordset. Set this property to move to the first record of a particular page. Obtain the total number of pages from the PageCount property.

Examples

AbsolutePage, PageCount, and PageSize Properties Example (VB)


AbsolutePosition Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

AbsolutePosition Property - ADO

Specifies the ordinal position of a Recordset object's current record.

Applies To

Recordset

Settings and Return Values

Sets or returns a Long value from 1 to the number of records in the Recordset object (RecordCount), or returns one of the following constants.
Constant | Description
adPosUnknown | The Recordset is empty, the current position is unknown, or the provider does not support the AbsolutePosition property.
adPosBOF | The current record pointer is at BOF (that is, the BOF property is True.)
adPosEOF | The current record pointer is at EOF (that is, the EOF property is True.)

Remarks

Use the AbsolutePosition property to move to a record based on its ordinal position in the Recordset object, or to determine the ordinal position of the current record. The provider must support the appropriate functionality for this property to be available.

Like the AbsolutePage property, AbsolutePosition is 1-based and equals 1 when the current record is the first record in the Recordset. You can obtain the total number of records in the Recordset object from the RecordCount property.

When you set the AbsolutePosition property, even if it is to a record in the current cache, ADO reloads the cache with a new group of records starting with the record you specified. The CacheSize property determines the size of this group.

Note You should not use the AbsolutePosition property as a surrogate record number. The position of a given record changes when you delete a preceding record. There is also no assurance that a given record will have the same AbsolutePosition if the Recordset object is requeried or reopened. Bookmarks are still the recommended way of retaining and returning to a given position and are the only way of positioning across all types of Recordset objects.

Examples

AbsolutePosition and CursorLocation Properties Example (VB)


ActiveConnection Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

ActiveConnection Property - ADO

Indicates to which Connection object the specified Command or Recordset object currently belongs.

Applies To

Command, Recordset

Settings and Return Values

Sets or returns a String containing the definition for a connection or a Connection object. Default is a Null object reference.

Remarks

Use the ActiveConnection property to determine the Connection object over which the specified Command object will execute or the specified Recordset will be opened.

Command

For Command objects, the ActiveConnection property is read/write.

If you attempt to call the Execute method on a Command object before setting this property to an open Connection object or valid connection string, an error occurs.

Microsoft Visual Basic Setting the ActiveConnection property to Nothing disassociates the Command object from the current Connection and causes the provider to release any associated resources on the data source. You can then associate the Command object with the same or another Connection object. Some providers allow you to change the property setting from one Connection to another, without having to first set the property to Nothing.

If the Parameters collection of the Command object contains parameters supplied by the provider, the collection is cleared if you set the ActiveConnection property to Nothing or to another Connection object. If you manually create Parameter objects and use them to fill the Parameters collection of the Command object, setting the ActiveConnection property to Nothing or to another Connection object leaves the Parameters collection intact.

Closing the Connection object with which a Command object is associated sets the ActiveConnection property to Nothing. Setting this property to a closed Connection object generates an error.

Recordset

For open Recordset objects or for Recordset objects whose Source property is set to a valid Command object, the ActiveConnection property is read-only. Otherwise, it is read/write.

You can set this property to a valid Connection object or to a valid connection string. In this case, the provider creates a new Connection object using this definition and opens the connection. Additionally, the provider may set this property to the new Connection object to give you a way to access the Connection object for extended error information or to execute other commands.

If you use the ActiveConnection argument of the Open method to open a Recordset object, the ActiveConnection property will inherit the value of the argument.

If you set the Source property of the Recordset object to a valid Command object variable, the ActiveConnection property of the Recordset inherits the setting of the Command object's ActiveConnection property.

Remote Data Service Usage When used on a client-side (ADOR) Recordset object, this property can only be set to a connection string or (In Microsoft Visual Basic or VBScript) to Nothing.

Examples

ActiveConnection, CommandText, CommandTimeout, CommandType, Size, and Direction Properties Example (VB)


ActualSize Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

ActualSize Property - ADO

Indicates the actual length of a field's value.

Applies To

Field, Recordset

Settings and Return Values

Returns a Long value. Some providers may allow this property to be set to reserve space for BLOB data, in which case the default value is 0.

Remarks

Use the ActualSize property to return the actual length of a Field object's value. For all fields, the ActualSize property is read-only. If ADO cannot determine the length of the Field object's value, the ActualSize property returns adUnknown.

The ActualSize and DefinedSize properties are different as shown in the following example: a Field object with a declared type of adVarChar and a maximum length of 50 characters returns a DefinedSize property value of 50, but the ActualSize property value it returns is the length of the data stored in the field for the current record.

Examples

ActualSize and DefinedSize Properties Example (VB)


Attributes Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Attributes Property - ADO

Indicates one or more characteristics of an object.

Applies To

Connection, Field, Parameter, Property

Settings and Return Values

Sets or returns a Long value.

For a Connection object, the Attributes property is read/write, and its value can be the sum of any one or more of these XactAttributeEnum values (default is zero):
Constant | Description
adXactCommitRetaining | Performs retaining commits, that is, calling CommitTrans automatically starts a new transaction. Not all providers support this.
adXactAbortRetaining | Performs retaining aborts, that is, calling RollbackTrans automatically starts a new transaction. Not all providers support this.

For a Parameter object, the Attributes property is read/write, and its value can be the sum of any one or more of these ParameterAttributesEnum values:
Constant | Description
adParamSigned | Default. Indicates that the parameter accepts signed values.
adParamNullable | Indicates that the parameter accepts Null values.
adParamLong | Indicates that the parameter accepts long binary data.

For a Field object, the Attributes property is read-only, and its value can be the sum of any one or more of these FieldAttributeEnum values:
Constant | Description
adFldMayDefer | Indicates that the field is deferred, that is, the field values are not retrieved from the data source with the whole record, but only when you explicitly access them.
adFldUpdatable | Indicates that you can write to the field.
adFldUnknownUpdatable | Indicates that the provider cannot determine if you can write to the field.
adFldFixed | Indicates that the field contains fixed-length data.
adFldIsNullable | Indicates that the field accepts Null values.
adFldMayBeNull | Indicates that you can read Null values from the field.
adFldLong | Indicates that the field is a long binary field. Also indicates that you can use the AppendChunk and GetChunk methods.
adFldRowID | Indicates that the field contains some kind of record ID (record number, unique identifier, and so forth).
adFldRowVersion | Indicates that the field contains some kind of time or date stamp used to track updates.
adFldCacheDeferred | Indicates that the provider caches field values and that subsequent reads are done from the cache.

For a Property object, the Attributes property is read-only, and its value can be the sum of any one or more of these PropertyAttributesEnum values:
Constant | Description
adPropNotSupported | Indicates that the property is not supported by the provider.
adPropRequired | Indicates that the user must specify a value for this property before the data source is initialized.
adPropOptional | Indicates that the user does not need to specify a value for this property before the data source is initialized.
adPropRead | Indicates that the user can read the property.
adPropWrite | Indicates that the user can set the property.

Remarks

Use the Attributes property to set or return characteristics of Connection objects, Parameter objects, Field objects, or Property objects.

When you set multiple attributes, you can sum the appropriate constants. If you set the property value to a sum including incompatible constants, an error occurs.

Remote Data Service Usage This property is not available on a client-side Connection object.

Examples

Attributes and Name Properties Example (VB)


BOF, EOF Properties (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

BOF, EOF Properties - ADO

  • BOF indicates that the current record position is before the first record in a Recordset object.

  • EOF indicates that the current record position is after the last record in a Recordset object.

Applies To

Recordset

Return Values

The BOF and EOF properties return Boolean values.

Remarks

Use the BOF and EOF properties to determine whether a Recordset object contains records or whether you've gone beyond the limits of a Recordset object when you move from record to record.

The BOF property returns True (-1) if the current record position is before the first record and False (0) if the current record position is on or after the first record.

The EOF property returns True if the current record position is after the last record and False if the current record position is on or before the last record.

If either the BOF or EOF property is True, there is no current record.

If you open a Recordset object containing no records, the BOF and EOF properties are set to True, and the Recordset object's RecordCount property setting is zero. When you open a Recordset object that contains at least one record, the first record is the current record and the BOF and EOF properties are False.

If you delete the last remaining record in the Recordset object, the BOF and EOF properties may remain False until you attempt to reposition the current record.

This table shows which Move methods are allowed with different combinations of the BOF and EOF properties.
MoveFirst,
MoveLast 		MovePrevious,
Move < 0
Move 0 		MoveNext,
Move > 0
BOF=True,
EOF=False 		Allowed Error Error Allowed
BOF=False,
EOF=True 		Allowed Allowed Error Error
Both True | Error | Error | Error | Error
Both False | Allowed | Allowed | Allowed | Allowed

Allowing a Move method doesn't guarantee that the method will successfully locate a record; it only means that calling the specified Move method won't generate an error.

The following table shows what happens to the BOF and EOF property settings when you call various Move methods but are unable to successfully locate a record.
BOF | EOF
MoveFirst, MoveLast | Set to True | Set to True
Move 0 | No change | No change
MovePrevious, Move < 0 | Set to True | No change
MoveNext, Move > 0 | No change | Set to True

Examples

BOF, EOF, and Bookmark Properties Example (VB)


Bookmark Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Bookmark Property - ADO

Returns a bookmark that uniquely identifies the current record in a Recordset object or sets the current record in a Recordset object to the record identified by a valid bookmark.

Applies To

Recordset

Settings and Return Values

Sets or returns a Variant expression that evaluates to a valid bookmark.

Remarks

Use the Bookmark property to save the position of the current record and return to that record at any time. Bookmarks are available only in Recordset objects that support bookmark functionality.

When you open a Recordset object, each of its records has a unique bookmark. To save the bookmark for the current record, assign the value of the Bookmark property to a variable. To quickly return to that record at any time after moving to a different record, set the Recordset object's Bookmark property to the value of that variable.

The user may not be able to view the value of the bookmark. Also, users should not expect bookmarks to be directly comparable—two bookmarks that refer to the same record may have different values.

If you use the Clone method to create a copy of a Recordset object, the Bookmark property settings for the original and the duplicate Recordset objects are identical and you can use them interchangeably. However, you can't use bookmarks from different Recordset objects interchangeably, even if they were created from the same source or command.

Remote Data Service Usage When used on a client-side (ADOR) Recordset object, the Bookmark property is always available.

Examples

BOF, EOF, and Bookmark Properties Example (VB)

See Also

Supports Method


CacheSize Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

CacheSize Property - ADO

Indicates the number of records from a Recordset object that are cached locally in memory.

Applies To

Recordset

Settings and Return Values

Sets or returns a Long value that must be greater than 0. Default is 1.

Remarks

Use the CacheSize property to control how many records the provider keeps in its buffer and how many to retrieve at one time into local memory. For example, if the CacheSize is 10, after first opening the Recordset object, the provider retrieves the first 10 records into local memory. As you move through the Recordset object, the provider returns the data from the local memory buffer. As soon as you move past the last record in the cache, the provider retrieves the next 10 records from the data source into the cache.

The value of this property can be adjusted during the life of the Recordset object, but changing this value only affects the number of records in the cache after subsequent retrievals from the data source. Changing the property value alone will not change the current contents of the cache.

If there are fewer records to retrieve than CacheSize specifies, the provider returns the remaining records; no error occurs.

A CacheSize setting of zero is not allowed and returns an error.

Records retrieved from the cache don't reflect concurrent changes that other users made to the source data. To force an update of all the cached data, use the Resync method.

Examples

CacheSize Property Example (VB)


CommandText Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

CommandText Property - ADO

Contains the text of a command that you want to issue against a provider.

Applies To

Command

Settings and Return Values

Sets or returns a String value containing a provider command, such as an SQL statement, a table name, or a stored procedure call. Default is "" (zero-length string).

Remarks

Use the CommandText property to set or return the text of a Command object. Usually, this will be an SQL statement, but can also be any other type of command statement recognized by the provider, such as a stored procedure call. An SQL statement must be of the particular dialect or version supported by the provider’s query processor.

If the Prepared property of the Command object is set to True and the Command object is bound to an open connection when you set the CommandText property, ADO prepares the query (that is, a compiled form of the query is stored by the provider) when you call the Execute or Open methods.

Depending on the CommandType property setting, ADO may alter the CommandText property. You can read the CommandText property at any time to see the actual command text that ADO will use during execution.

Examples

ActiveConnection, CommandText, CommandTimeout, CommandType, Size, and Direction Properties Example (VB)


CommandTimeout Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

CommandTimeout Property - ADO

Indicates how long to wait while executing a command before terminating the attempt and generating an error.

Applies To

Command, Connection

Settings and Return Values

Sets or returns a Long value that indicates, in seconds, how long to wait for a command to execute. Default is 30.

Remarks

Use the CommandTimeout property on a Connection object or Command object to allow the cancellation of an Execute method call, due to delays from network traffic or heavy server use. If the interval set in the CommandTimeout property elapses before the command completes execution, an error occurs and ADO cancels the command. If you set the property to zero, ADO will wait indefinitely until the execution is complete. Make sure the provider and data source to which you are writing code supports the CommandTimeout functionality.

The CommandTimeout setting on a Connection object has no effect on the CommandTimeout setting on a Command object on the same Connection; that is, the Command object’s CommandTimeout property does not inherit the value of the Connection object’s CommandTimeout value.

On a Connection object, the CommandTimeout property remains read/write after the Connection is opened.

Examples

ActiveConnection, CommandText, CommandTimeout, CommandType, Size, and Direction Properties Example (VB)


CommandType Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

CommandType Property - ADO

Indicates the type of a Command object.

Applies To

Command

Settings and Return Values

Sets or returns one of the following CommandTypeEnum values:
Constant | Description
adCmdText | Evaluates CommandText as a textual definition of a command.
adCmdTable | Evaluates CommandText as a table name.
adCmdStoredProc | Evaluates CommandText as a stored procedure.
adCmdUnknown | Default. The type of command in the CommandText property is not known.

Remarks

Use the CommandType property to optimize evaluation of the CommandText property.

If the CommandType property value equals adCmdUnknown (the default value), you may experience diminished performance because ADO must make calls to the provider to determine if the CommandText property is an SQL statement, a stored procedure, or a table name. If you know what type of command you're using, setting the CommandType property instructs ADO to go directly to the relevant code. If the CommandType property does not match the type of command in the CommandText property, an error occurs when you call the Execute method.

Examples

ActiveConnection, CommandText, CommandTimeout, CommandType, Size, and Direction Properties Example (VB)


ConnectionString Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

ConnectionString Property - ADO

Contains the information used to establish a connection to a data source.

Applies To

Connection

Settings and Return Values

Sets or returns a String value.

Remarks

Use the ConnectionString property to specify a data source by passing a detailed connection string containing a series of argument = value statements separated by semicolons.

ADO supports seven arguments for the ConnectionString property; any other arguments pass directly to the provider without any processing by ADO. The arguments ADO supports are as follows:
Argument | Description
Provider= | Specifies the name of a provider to use for the connection.
Data Source= | Specifies the name of a data source for the connection, for example, a SQL Server database registered as an ODBC data source.
User ID= | Specifies the user name to use when opening the connection.
Password= | Specifies the password to use when opening the connection.
File Name= | Specifies the name of a provider-specific file (for example, a persisted data source object) containing preset connection information.
Remote Provider= | Specifies the name of a provider to use when opening a client-side connection. (Remote Data Service only.)
Remote Server= | Specifies the path name of the sever to use when opening a client-side connection. (Remote Data Service only.)

After you set the ConnectionString property and open the Connection object, the provider may alter the contents of the property, for example, by mapping the ADO-defined argument names to their provider equivalents.

The ConnectionString property automatically inherits the value used for the ConnectionString argument of the Open method, so you can override the current ConnectionString property during the Open method call.

Because the File Name argument causes ADO to load the associated provider, you cannot pass both the Provider and File Name arguments.

The ConnectionString property is read/write when the connection is closed and read-only when it is open.

Remote Data Service Usage When used on a client-side Connection object, the ConnectionString property can only include the Remote Provider and Remote Server parameters.

Examples

ConnectionString, ConnectionTimeout, and State Properties Example (VB)

See Also

Using OLE DB Providers with ADO


ConnectionTimeout Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

ConnectionTimeout Property - ADO

Indicates how long to wait while establishing a connection before terminating the attempt and generating an error.

Applies To

Connection

Settings and Return Values

Sets or returns a Long value that indicates, in seconds, how long to wait for the connection to open. Default is 15.

Remarks

Use the ConnectionTimeout property on a Connection object if delays from network traffic or heavy server use make it necessary to abandon a connection attempt. If the time from the ConnectionTimeout property setting elapses prior to the opening of the connection, an error occurs and ADO cancels the attempt. If you set the property to zero, ADO will wait indefinitely until the connection is opened. Make sure the provider to which you are writing code supports the ConnectionTimeout functionality.

The ConnectionTimeout property is read/write when the connection is closed and read-only when it is open.

Examples

ConnectionString, ConnectionTimeout, and State Properties Example (VB)


Count Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Count Property - ADO

Indicates the number of objects in a collection.

Applies To

Errors, Fields, Parameters, Properties

Return Values

Returns a Long value.

Remarks

Use the Count property to determine how many objects are in a given collection.

Because numbering for members of a collection begins with zero, you should always code loops starting with the zero member and ending with the value of the Count property minus one. If you are using Microsoft® Visual Basic® and want to loop through the members of a collection without checking the Count property, use the For Each...Next command.

If the Count property is zero, there are no objects in the collection.

Examples

Count Property Example (VB)


CursorType Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

CursorType Property - ADO

Indicates the type of cursor used in a Recordset object.

Applies To

Recordset

Settings and Return Values

Sets or returns one of the following CursorTypeEnum values:
Constant | Description
adOpenForwardOnly | Forward-only cursor. Default. Identical to a static cursor except that you can only scroll forward through records. This improves performance in situations when you only need to make a single pass through a recordset.
adOpenKeyset | Keyset cursor. Like a dynamic cursor, except that you can't see records that other users add, although records that other users delete are inaccessible from your recordset. Data changes by other users are still visible.
adOpenDynamic | Dynamic cursor. Additions, changes, and deletions by other users are visible, and all types of movement through the recordset are allowed, except for bookmarks if the provider doesn't support them.
adOpenStatic | Static cursor. A static copy of a set of records that you can use to find data or generate reports. Additions, changes, or deletions by other users are not visible.

Remarks

Use the CursorType property to specify the type of cursor that should be used when opening the Recordset object. The CursorType property is read/write when the Recordset is closed and read-only when it is open.

If a provider does not support the requested cursor type, the provider may return another cursor type. The CursorType property will change to match the actual cursor type in use when the Recordset object is open. To verify specific functionality of the returned cursor, use the Supports method. After you close the Recordset, the CursorType property reverts to its original setting.

The following chart shows the provider functionality (identified by Supports method constants) required for each cursor type.
For a Recordset of this CursorType | The Supports method must return True for all of these constants:
adOpenForwardOnly | none
adOpenKeyset | adBookmark, adHoldRecords, adMovePrevious, adResync
adOpenDynamic | adMovePrevious
adOpenStatic | adBookmark, adHoldRecords, adMovePrevious, adResync

Note Although Supports(adUpdateBatch) may be true for dynamic and forward-only cursors, for batch updates you should use either a keyset or static cursor, set the LockType property to adLockBatchOptimistic, and set the CursorLocation property to adUseClient (or its synonym adUseClientBatch) to enable the Microsoft Client Cursor Engine, which is required for batch updates.

Remote Data Service Usage When used on a client-side (ADOR) Recordset object, the CursorType property can only be set to adOpenStatic.

Examples

CursorType, LockType, and EditMode Properties Example (VB)


DefaultDatabase Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

DefaultDatabase Property - ADO

Indicates the default database for a Connection object.

Applies To

Connection

Settings and Return Values

Sets or returns a String that evaluates to the name of a database available from the provider.

Remarks

Use the DefaultDatabase property to set or return the name of the default database on a specific Connection object.

If there is a default database, SQL strings may use an unqualified syntax to access objects in that database. To access objects in a database other than the one specified in the DefaultDatabase property, you must qualify object names with the desired database name. Upon connection, the provider will write default database information to the DefaultDatabase property. Some providers allow only one database per connection in which case you cannot change the DefaultDatabase property.

Some data sources and providers may not support this feature, and may return an error or an empty string.

Remote Data Service Usage This property is not available on a client-side Connection object.

Examples

Provider and DefaultDatabase Properties Example (VB)


DefinedSize Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

DefinedSize Property - ADO

Indicates the defined size of a Field object.

Applies To

Field

Return Values

Returns a Long value that reflects the defined size of a field as a number of bytes.

Remarks

Use the DefinedSize property to determine the data capacity of a Field object.

The DefinedSize and ActualSize properties are different. For example, consider a Field object with a declared type of adVarChar and a DefinedSize property value of 50, containing a single character. The ActualSize property value it returns is the length in bytes of the single character.

Examples

ActualSize and DefinedSize Properties Example (VB)


Description Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Description Property - ADO

A descriptive string associated with an Error object.

Applies To

Error

Return Values

Returns a String value.

Remarks

Use the Description property to obtain a short description of the error. Display this property to alert the user to an error that you cannot or do not want to handle. The string will come from either ADO or a provider.

Providers are responsible for passing specific error text to ADO. ADO adds an Error object to the Errors collection for each provider error or warning it receives. Enumerate the Errors collection to trace the errors that the provider passes.

Examples

Description, HelpContext, HelpFile, NativeError, Number, Source, and SQLState Properties Example (VB)


Direction Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Direction Property - ADO

Indicates whether the Parameter represents an input parameter, an output parameter, or both, or if the parameter is the return value from a stored procedure.

Applies To

Parameter

Settings and Return Values

Sets or returns one of the following ParameterDirectionEnum values:
Constant | Description
adParamInput | Default. Indicates an input parameter.
adParamOutput | Indicates an output parameter.
adParamInputOutput | Indicates both an input and output parameter.
adParamReturnValue | Indicates a return value.

Remarks

Use the Direction property to specify how a parameter is passed to or from a procedure. The Direction property is read/write; this allows you to work with providers that don't return this information or to set this information when you don't want ADO to make an extra call to the provider to retrieve parameter information.

Not all providers can determine the direction of parameters in their stored procedures. In these cases, you must set the Direction property prior to executing the query.

Examples

ActiveConnection, CommandText, CommandTimeout, CommandType, Size, and Direction Properties Example (VB)


EditMode Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

EditMode Property - ADO

Indicates the editing status of the current record.

Applies To

Recordset

Return Values

Returns one of the following EditModeEnum values:
Constant | Description
adEditNone | Indicates that no editing operation is in progress.
adEditInProgress | Indicates that data in the current record has been modified but not yet saved.
adEditAdd | Indicates that the AddNew method has been invoked, and the current record in the copy buffer is a new record that hasn't been saved in the database.

Remarks

ADO maintains an editing buffer associated with the current record. This property indicates whether changes have been made to this buffer, or whether a new record has been created. Use the EditMode property to determine the editing status of the current record. You can test for pending changes if an editing process has been interrupted and determine whether you need to use the Update or CancelUpdate method.

See the AddNew method for a more detailed description of the EditMode property under different editing conditions.

Examples

CursorType, LockType, and EditMode Properties Example (VB)


Filter Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Filter Property - ADO

Indicates a filter for data in a Recordset.

Applies To

Recordset

Settings and Return Values

Sets or returns a Variant value, which can contain one of the following:

  • Criteria string — a string made up of one or more individual clauses concatenated with AND or OR operators.

  • Array of bookmarks — an array of unique bookmark values that point to records in the Recordset object.

  • One of the following FilterGroupEnum values:
    Constant | Description
    adFilterNone | Removes the current filter and restores all records to view.
    adFilterPendingRecords | Allows you to view only records that have changed but have not yet been sent to the server. Only applicable for batch update mode.
    adFilterAffectedRecords | Allows you to view only records affected by the last Delete, Resync, UpdateBatch, or CancelBatch call.
    adFilterFetchedRecords | Allows you to view records in the current cache, that is, the results of the last call to retrieve records from the database.

Remarks

Use the Filter property to selectively screen out records in a Recordset object. The filtered Recordset becomes the current cursor. This affects other properties such as AbsolutePosition, AbsolutePage, RecordCount, and PageCount that return values based on the current cursor, since setting the Filter property to a specific value will move the current record to the first record that satisfies the new value.

The criteria string is made up of clauses in the form FieldName-Operator-Value (for example, "LastName = 'Smith'"). You can create compound clauses by concatenating individual clauses with AND (for example, "LastName = 'Smith' AND FirstName = 'John'") or OR (for example, "LastName = 'Smith' OR LastName = 'Jones'"). Use the following guidelines for criteria strings:

  • FieldName must be a valid field name from the Recordset. If the field name contains spaces, you must enclose the name in square brackets.

  • Operator must be one of the following: <, >, <=, >=, <>, =, LIKE.

  • Value is the value with which you will compare the field values (for example, 'Smith', #8/24/95#, 12.345 or $50.00). Use single quotes with strings and pound signs (#) with dates. For numbers, you can use decimal points, dollar signs, and scientific notation. If Operator is LIKE, Value can use wildcards. Only the asterisk (*) and percent sign (%) wild cards are allowed, and they must be the last character in the string. Value may not be Null.

  • There is no precedence between AND and OR. Clauses can be grouped within parentheses. However, you cannot group clauses joined by an OR and then join the group to another clause with an AND, like this
    (LastName = 'Smith' OR LastName = 'Jones') AND FirstName = 'John'

    Instead, you would construct this filter as

    (LastName = 'Smith' AND FirstName = 'John') OR (LastName = 'Jones' AND FirstName = 'John')
  • In a LIKE clause, you can use a wildcard at the beginning and end of the pattern (for example, LastName Like '*mit*'), or only at the end of the pattern (for example, LastName Like 'Smit*').

The filter constants make it easier to resolve individual record conflicts during batch update mode by allowing you to view, for example, only those records that were affected during the last UpdateBatch method call.

Setting the Filter property itself may fail because of a conflict with the underlying data (for example, a record has already been deleted by another user); in such a case, the provider returns warnings to the Errors collection but does not halt program execution. A run-time error occurs only if there are conflicts on all the requested records. Use the Status property to locate records with conflicts.

Setting the Filter property to a zero-length string ("") has the same effect as using the adFilterNone constant.

Whenever the Filter property is set, the current record position moves to the first record in the filtered subset of records in the Recordset. Similarly, when the Filter property is cleared, the current record position moves to the first record in the Recordset.

See the Bookmark property for an explanation of bookmark values from which you can build an array to use with the Filter property.

Examples

Filter and RecordCount Properties Example (VB)


HelpContext, HelpFile Properties (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

HelpContext, HelpFile Properties - ADO

Indicates the help file and topic associated with an Error object.

Applies To

Error

Return Values

  • HelpContextID — returns a context ID, as a Long value, for a topic in a Microsoft Windows Help file.

  • HelpFile — returns a String that evaluates to a fully resolved path to a Help file.

Remarks

If a Windows Help (.hlp) file is specified in the HelpFile property, the HelpContext property is used to automatically display the Help topic it identifies. If there is no relevant help topic available, the HelpContext property returns zero and the HelpFile property returns a zero-length string ("").

Examples

Description, HelpContext, HelpFile, NativeError, Number, Source, and SQLState Properties Example (VB)


IsolationLevel Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

IsolationLevel Property - ADO

Indicates the level of isolation for a Connection object.

Applies To

Connection

Settings and Return Values

Sets or returns one of the following IsolationLevelEnum values:
Constant | Description
adXactUnspecified | Indicates that the provider is using a different IsolationLevel than specified, but that the level cannot be determined.
adXactChaos | Indicates that you cannot overwrite pending changes from more highly isolated transactions.
adXactBrowse | Indicates that from one transaction you can view uncommitted changes in other transactions.
adXactReadUncommitted | Same as adXactBrowse.
adXactCursorStability | Default. Indicates that from one transaction you can view changes in other transactions only after they've been committed.
adXactReadCommitted | Same as adXactCursorStability.
adXactRepeatableRead | Indicates that from one transaction you cannot see changes made in other transactions, but that requerying can bring new recordsets.
adXactIsolated | Indicates that transactions are conducted in isolation of other transactions.
adXactSerializable | Same as adXactIsolated.

Remarks

Use the IsolationLevel property to set the isolation level of a Connection object. The IsolationLevel property is read/write. The setting does not take effect until the next time you call the BeginTrans method. If the level of isolation you request is unavailable, the provider may return the next greater level of isolation.

Remote Data Service Usage When used on a client-side Connection object, the IsolationLevel property can only be set to adXactUnspecified.

Examples

IsolationLevel and Mode Properties Example (VB)


LockType Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

LockType Property - ADO

Indicates the type of locks placed on records during editing.

Applies To

Recordset

Settings and Return Values

Sets or returns one of the following LockTypeEnum values:
Constant | Description
adLockReadOnly | Default. Read-only — you cannot alter the data.
adLockPessimistic | Pessimistic locking, record by record — the provider does what is necessary to ensure successful editing of the records, usually by locking records at the data source immediately upon editing.
adLockOptimistic | Optimistic locking, record by record — the provider uses optimistic locking, locking records only when you call the Update method.
adLockBatchOptimistic | Optimistic batch updates — required for batch update mode as opposed to immediate update mode.

Remarks

Set the LockType property before opening a Recordset to specify what type of locking the provider should use when opening it. Read the property to return the type of locking in use on an open Recordset object. The LockType property is read/write when the Recordset is closed and read-only when it is open.

Providers may not support all lock types. If a provider cannot support the requested LockType setting, it will substitute another type of locking. To determine the actual locking functionality available in a Recordset object, use the Supports method with adUpdate and adUpdateBatch.

Remote Data Service Usage When used on a client-side (ADOR) Recordset object, the LockType property can only be set to adLockOptimisticBatch.

Examples

CursorType, LockType, and EditMode Properties Example (VB)


MaxRecords Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

MaxRecords Property - ADO

Indicates the maximum number of records to return to a Recordset from a query.

Applies To

Recordset

Settings and Return Values

Sets or returns a Long value. Default is zero (no limit).

Remarks

Use the MaxRecords property to limit the number of records the provider returns from the data source. The default setting of this property is zero, which means the provider returns all requested records. The MaxRecords property is read/write when the Recordset is closed and read-only when it is open.

Examples

MaxRecords Property Example (VB)


Mode Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Mode Property - ADO

Indicates the available permissions for modifying data in a Connection.

Applies To

Connection

Settings and Return Values

Sets or returns one of the following ConnectModeEnum values:
Constant | Description
adModeUnknown | Default. Indicates that the permissions have not yet been set or cannot be determined.
adModeRead | Indicates read-only permissions.
adModeWrite | Indicates write-only permissions.
adModeReadWrite | Indicates read/write permissions.
adModeShareDenyRead | Prevents others from opening connection with read permissions.
adModeShareDenyWrite | Prevents others from opening connection with write permissions.
adModeShareExclusive | Prevents others from opening connection.
adModeShareDenyNone | Prevents others from opening connection with any permissions.

Remarks

Use the Mode property to set or return the access permissions in use by the provider on the current connection. You can set the Mode property only when the Connection object is closed.

Remote Data Service Usage When used on a client-side Connection object, the Mode property can only be set to adModeUnknown.

Examples

IsolationLevel and Mode Properties Example (VB)


Name Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Name Property - ADO

Indicates the name of an object.

Applies To

Command, Field, Parameter, Property

Settings and Return Values

Sets or returns a String value. The value is read/write on a Command or Parameter object and read-only on a Property or Field object.

Remarks

Use the Name property to assign a name to or retrieve the name of a Command, Field, Parameter, or Property object.

For Parameter objects not yet appended to the Parameters collection, the Name property is read/write. For appended Parameter objects and all other objects, the Name property is read-only. Names do not have to be unique within a collection.

You can retrieve the Name property of an object by an ordinal reference, after which you can refer to the object directly by name. For example, if rstMain.Properties(20).Name yields Updatability, you can subsequently refer to this property as rstMain.Properties("Updatability").

Examples

Attributes and Name Properties Example (VB)


NativeError Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

NativeError Property - ADO

Indicates the provider-specific error code for a given Error object.

Applies To

Error

Return Values

Returns a Long value.

Remarks

Use the NativeError property to retrieve the database-specific error information for a particular Error object. For example, when using the Microsoft ODBC Provider for OLE DB with a Microsoft® SQL Server™ database, native error codes that originate from SQL Server pass through ODBC and the ODBC Provider to the ADO NativeError property.

Examples

Description, HelpContext, HelpFile, NativeError, Number, Source, and SQLState Properties Example (VB)


Number Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Number Property - ADO

Indicates the number that uniquely identifies an Error object.

Applies To

Error

Return Values

Returns a Long value.

Remarks

Use the Number property to determine which error occurred. The value of the property is a unique number that corresponds to the error condition.

Examples

Description, HelpContext, HelpFile, NativeError, Number, Source, and SQLState Properties Example (VB)


NumericScale Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

NumericScale Property - ADO

Indicates the scale of Numeric values in a Parameter or Field object.

Applies To

Field, Parameter

Settings and Return Values

Sets or returns a Byte value, indicating the number of decimal places to which numeric values will be resolved.

Remarks

Use the NumericScale property to determine how many digits to the right of the decimal point will be used to represent values for a numeric Parameter or Field object.

For Parameter objects, the NumericScale property is read/write. For Field objects, the NumericScale property is read-only.

Examples

NumericScale and Precision Properties Example (VB)


OriginalValue Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

OriginalValue Property - ADO

Indicates the value of a Field that existed in the record before any changes were made.

Applies To

Field

Return Values

Returns a Variant value.

Remarks

Use the OriginalValue property to return the original field value for a field from the current record.

In immediate update mode (the provider writes changes to the underlying data source once you call the Update method), the OriginalValue property returns the field value that existed prior to any changes (that is, since the last Update method call). This is the same value that the CancelUpdate method uses to replace the Value property.

In batch update mode (the provider caches multiple changes and writes them to the underlying data source only when you call the UpdateBatch method), the OriginalValue property returns the field value that existed prior to any changes (that is, since the last UpdateBatch method call). This is the same value that the CancelBatch method uses to replace the Value property. When you use this property with the UnderlyingValue property, you can resolve conflicts that arise from batch updates.

Examples

OriginalValue and UnderlyingValue Properties Example (VB)


PageCount Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

PageCount Property - ADO

Indicates how many pages of data the Recordset object contains.

Applies To

Recordset

Return Values

Returns a Long value.

Remarks

Use the PageCount property to determine how many pages of data are in the Recordset object. Pages are groups of records whose size equals the PageSize property setting. Even if the last page is incomplete, because there are fewer records than the PageSize value, it counts as an additional page in the PageCount value. If the Recordset object does not support this property, the value will be -1 to indicate that the PageCount is indeterminable.

See the PageSize and AbsolutePage properties for more on page functionality.

Examples

AbsolutePage, PageCount, and PageSize Properties Example (VB)


PageSize Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

PageSize Property - ADO

Indicates how many records constitute one page in the Recordset.

Applies To

Recordset

Settings and Return Values

Sets or returns a Long value, indicating how many records are on a page. Default is 10.

Remarks

Use the PageSize property to determine how many records make up a logical page of data. Establishing a page size allows you to use the AbsolutePage property to move to the first record of a particular page. This is useful in web-server scenarios when you want to allow the user to page through data, viewing a certain number of records at a time.

This property can be set at any time, and its value will be used for calculating where the first record of a particular page is.

Examples

AbsolutePage, PageCount, and PageSize Properties Example (VB)


Precision Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Precision Property - ADO

Indicates the degree of precision for Numeric values in a Parameter object or for numeric Field objects.

Applies To

Field, Parameter

Settings and Return Values

Sets or returns a Byte value, indicating the maximum total number of digits used to represent values. The value is read/write on a Parameter object and read-only on a Field object.

Remarks

Use the Precision property to determine the maximum number of digits used to represent values for a numeric Parameter or Field object.

Examples

NumericScale and Precision Properties Example (VB)


Prepared Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Prepared Property - ADO

Indicates whether or not to save a compiled version of a command before execution.

Applies To

Command

Settings and Return Values

Sets or returns a Boolean value.

Remarks

Use the Prepared property to have the provider save a prepared (or compiled) version of the query specified in the CommandText property before a Command object's first execution. This may slow a command's first execution, but once the provider compiles a command, the provider will use the compiled version of the command for any subsequent executions, which will result in improved performance.

If the property is False, the provider will execute the Command object directly without creating a compiled version.

If the provider does not support command preparation, it may return an error as soon as this property is set to True. If it does not return an error, it simply ignores the request to prepare the command and sets the Prepared property to False.

Examples

Prepared Property Example (VB)


Provider Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Provider Property - ADO

Indicates the name of the provider for a Connection object.

Applies To

Connection

Settings and Return Values

Sets or returns a String value.

Remarks

Use the Provider property to set or return the name of the provider for a connection. This property can also be set by the contents of ConnectionString property or the ConnectionString argument of the Open method; however, specifying a provider in more than one place while calling the Open method can have unpredictable results. If no provider is specified, the property will default to MSDASQL (Microsoft OLE DB Provider for ODBC).

The Provider property is read/write when the connection is closed and read-only when it is open. The setting does not take effect until you either open the Connection object or access the Properties collection of the Connection object. If the setting is invalid, an error occurs.

Examples

Provider and DefaultDatabase Properties Example (VB)

See Also

Using OLE DB Providers with ADO

Microsoft OLE DB Provider for ODBC


RecordCount Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

RecordCount Property - ADO

Indicates the current number of records in a Recordset object.

Applies To

Recordset

Return Values

Returns a Long value.

Remarks

Use the RecordCount property to find out how many records are in a Recordset object. The property returns -1 when ADO cannot determine the number of records. Reading the RecordCount property on a closed Recordset causes an error.

If the Recordset object supports approximate positioning or bookmarks — that is, Supports (adApproxPosition) or Supports (adBookmark), respectively, returns True — this value will be the exact number of records in the Recordset regardless of whether it has been fully populated. If the Recordset object does not support approximate positioning, this property may be a significant drain on resources because all records will have to be retrieved and counted to return an accurate RecordCount value.

Examples

Filter and RecordCount Properties Example (VB)


Size Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Size Property - ADO

Indicates the maximum size, in bytes or characters, of a Parameter object.

Applies To

Parameter

Settings and Return Values

Sets or returns a Long value that indicates the maximum size in bytes or characters of a value in a Parameter object.

Remarks

Use the Size property to determine the maximum size for values written to or read from the Value property of a Parameter object. The Size property is read/write.

If you specify a variable-length data type for a Parameter object, you must set the object's Size property before appending it to the Parameters collection; otherwise an error occurs. If you have already appended the Parameter object to the Parameters collection of a Command object and you change its type to a variable-length data type, you must set the Parameter object's Size property before executing the Command object; otherwise an error occurs.

If you use the Refresh method to obtain parameter information from the provider and it returns one or more variable-length data type Parameter objects, ADO may allocate memory for the parameters based on their maximum potential size which could cause an error during execution. To prevent an error, you should explicitly set the Size property for these parameters before executing the command.

Examples

ActiveConnection, CommandText, CommandTimeout, CommandType, Size, and Direction Properties Example (VB)


Source Property (Error - ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Source Property (Error) ADO

Indicates the name of the object or application that originally generated an error.

Applies To

Error

Return Values

Returns a String value.

Remarks

Use the Source property on an Error object to determine the name of the object or application that originally generated an error. This could be the object's class name or programmatic ID. For errors in ADODB, the property value will be ADODB.ObjectName where ObjectName is the name of the object that triggered the error. The Source property is read-only for Error objects.

Based on the error documentation from the Source, Number, and Description properties of Error objects, you can write code that will handle the error appropriately.

Examples

Description, HelpContext, HelpFile, NativeError, Number, Source, and SQLState Properties Example (VB)


Source Property (Recordset - ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Source Property (Recordset) ADO

Indicates the source for the data in a Recordset object (Command object, SQL statement, table name, or stored procedure).

Applies To

Recordset

Settings and Return Values

Sets a String value or Command object reference; returns only a String value.

Remarks

Use the Source property to specify a data source for a Recordset object using one of the following: a Command object variable, an SQL statement, a stored procedure, or a table name. The Source property is read/write for closed Recordset objects and read-only for open Recordset objects.

If you set the Source property to a Command object, the ActiveConnection property of the Recordset object will inherit the value of the ActiveConnection property for the specified Command object. However, reading the Source property does not return a Command object; instead, it returns the CommandText property of the Command object to which you set the Source property.

If the Source property is an SQL statement, a stored procedure, or a table name, you can optimize performance by passing the appropriate Options argument with the Open method call.

Examples

Source Property Example (VB)


SQLState Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

SQLState Property - ADO

Indicates the SQL state for a given Error object.

Applies To

Error

Return Values

Returns a five-character String that follows the ANSI SQL standard.

Remarks

Use the SQLState property to read the five-character error code that the provider returns when an error occurs during the processing of a SQL statement. For example, when using the Microsoft OLE DB Provider for ODBC with a Microsoft® SQL Server™ database, SQL state error codes originate from ODBC based either on errors specific to ODBC or on errors that originate from Microsoft SQL Server and are then mapped to ODBC errors. These error codes are documented in the ANSI SQL standard, but may be implemented differently by different data sources.

Examples

Description, HelpContext, HelpFile, NativeError, Number, Source, and SQLState Properties Example (VB)


Status Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Status Property - ADO

Indicates the status of the current record with respect to batch updates or other bulk operations.

Applies To

Recordset

Return Values

Returns a sum of one or more of the following RecordStatusEnum values:
Constant | Description
adRecOK | The record was successfully updated.
adRecNew | The record is new.
adRecModified | The record was modified.
adRecDeleted | The record was deleted.
adRecUnmodified | The record was not modified.
adRecInvalid | The record was not saved because its bookmark is invalid.
adRecMultipleChanges | The record was not saved because it would have affected multiple records.
adRecPendingChanges | The record was not saved because it refers to a pending insert.
adRecCanceled | The record was not saved because the operation was canceled.
adRecCantRelease | The new record was not saved because of existing record locks.
adRecConcurrencyViolation | The record was not saved because optimistic concurrency was in use.
adRecIntegrityViolation | The record was not saved because the user violated integrity constraints.
adRecMaxChangesExceeded | The record was not saved because there were too many pending changes.
adRecObjectOpen | The record was not saved because of a conflict with an open storage object.
adRecOutOfMemory | The record was not saved because the computer has run out of memory.
adRecPermissionDenied | The record was not saved because the user has insufficient permissions.
adRecSchemaViolation | The record was not saved because it violates the structure of the underlying database.
adRecDBDeleted | The record has already been deleted from the data source.

Remarks

Use the Status property to see what changes are pending for records modified during batch updating. You can also use the Status property to view the status of records that fail during bulk operations such as when you call the Resync, UpdateBatch, or CancelBatch methods on a Recordset object, or set the Filter property on a Recordset object to an array of bookmarks. With this property, you can determine how a given record failed and resolve it accordingly.

Examples

Status Property Example (VB)


Type Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Type Property - ADO

Indicates the operational type or data type of a Parameter, Field, or Property object.

Applies To

Field, Parameter, Property

Settings and Return Values

Sets or returns one of the following DataTypeEnum values. The corresponding OLE DB type indicator is shown in parentheses in the description column of the following table. For more information on OLE DB data types, see Chapter 10 and Appendix A of the OLE DB 1.1 Programmer's Reference.
Constant | Description
adArray | Or'd together with another type to indicate that the data is a safe-array of that type (DBTYPE_ARRAY).
adBigInt | An 8-byte signed integer (DBTYPE_I8).
adBinary | A binary value (DBTYPE_BYTES).
adBoolean | A Boolean value (DBTYPE_BOOL).
adByRef | Or'd together with another type to indicate that the data is a pointer to data of the other type (DBTYPE_BYREF).
adBSTR | A null-terminated character string (Unicode) (DBTYPE_BSTR).
adChar | A String value (DBTYPE_STR).
adCurrency | A currency value (DBTYPE_CY). Currency is a fixed-point number with 4 digits to the right of the decimal point. It is stored in an 8-byte signed integer scaled by 10,000.
adDate | A Date value (DBTYPE_DATE). A date is stored as a Double, the whole part of which is the number of days since December 30, 1899, and the fractional part of which is the fraction of a day.
adDBDate | A date value (yyyymmdd) (DBTYPE_DBDATE).
adDBTime | A time value (hhmmss) (DBTYPE_DBTIME).
adDBTimeStamp | A date-time stamp (yyyymmddhhmmss plus a fraction in billionths) (DBTYPE_DBTIMESTAMP).
adDecimal | An exact numeric value with a fixed precision and scale (DBTYPE_DECIMAL).
adDouble | A double-precision floating point value (DBTYPE_R8).
adEmpty | No value was specified (DBTYPE_EMPTY).
adError | A 32-bit error code (DBTYPE_ERROR).
adGUID | A globally unique identifier (GUID) (DBTYPE_GUID).
adIDispatch | A pointer to an IDispatch interface on an OLE object (DBTYPE_IDISPATCH).
adInteger | A 4-byte signed integer (DBTYPE_I4).
adIUnknown | A pointer to an IUnknown interface on an OLE object (DBTYPE_IUNKNOWN).
adLongVarBinary | A long binary value (Parameter object only).
adLongVarChar | A long String value (Parameter object only).
adLongVarWChar | A long null-terminated string value (Parameter object only).
adNumeric | An exact numeric value with a fixed precision and scale (DBTYPE_NUMERIC).
adSingle | A single-precision floating point value (DBTYPE_R4).
adSmallInt | A 2-byte signed integer (DBTYPE_I2).
adTinyInt | A 1-byte signed integer (DBTYPE_I1).
adUnsignedBigInt | An 8-byte unsigned integer (DBTYPE_UI8).
adUnsignedInt | A 4-byte unsigned integer (DBTYPE_UI4).
adUnsignedSmallInt | A 2-byte unsigned integer (DBTYPE_UI2).
adUnsignedTinyInt | A 1-byte unsigned integer (DBTYPE_UI1).
adUserDefined | A user-defined variable (DBTYPE_UDT).
adVarBinary | A binary value (Parameter object only).
adVarChar | A String value (Parameter object only).
adVariant | An Automation Variant (DBTYPE_VARIANT).
adVector | Or'd together with another type to indicate that the data is a DBVECTOR structure, as defined by OLE DB, that contains a count of elements and a pointer to data of the other type (DBTYPE_VECTOR).
adVarWChar | A null-terminated Unicode character string (Parameter object only).
adWChar | A null-terminated Unicode character string (DBTYPE_WSTR).

Remarks

For Parameter objects, the Type property is read/write. For all other objects, the Type property is read-only.

Examples

Tye Property Example (VB)


UnderlyingValue Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

UnderlyingValue Property - ADO

Indicates a Field object's current value in the database.

Applies To

Field

Return Values

Returns a Variant value.

Remarks

Use the UnderlyingValue property to return the current field value from the database. The field value in the UnderlyingValue property is the value that is visible to your transaction and may be the result of a recent update by another transaction. This may differ from the OriginalValue property, which reflects the value that was originally returned to the Recordset.

This is similar to using the Resync method, but the UnderlyingValue property returns only the value for a specific field from the current record. This is the same value that the Resync method uses to replace the Value property.

When you use this property with the OriginalValue property, you can resolve conflicts that arise from batch updates.

Examples

OriginalValue and UnderlyingValue Properties Example (VB)


Value Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Value Property - ADO

Indicates the value assigned to a Field, Parameter, or Property object.

Applies To

Field, Parameter, Property

Settings and Return Values

Sets or returns a Variant value. Default value depends on the Type property.

Remarks

Use the Value property to set or return data from Field objects, to set or return parameter values with Parameter objects, or to set or return property settings with Property objects. Whether the Value property is read/write or read-only depends upon numerous factors — see the topics for the respective objects for more information.

ADO allows setting and returning long binary data with the Value property.

Examples

Value Property Example (VB)


Version Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Version Property - ADO

Indicates the ADO version number.

Applies To

Connection

Return Values

Returns a String value.

Remarks

Use the Version property to return the version number of the ADO implementation.

The version of the provider will be available as a dynamic property in the Properties collection.

Examples

Version Property Example (VB)


CursorLocation Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

CursorLocation Property - ADO

Sets or returns the location of the cursor engine.

Applies To

Connection, Recordset

Settings And Return Values

Sets or returns a Long value that can be set to one of the following constants:
Constant | Description
adUseClient | Uses client-side cursors supplied by a local cursor library. Local cursor engines will often allow many features that driver-supplied cursors may not, so using this setting may provide an advantage with respect to features that will be enabled. For backward-compatibility, the synonym adUseClientBatch is also supported.
adUseServer | Default. Uses data provider or driver-supplied cursors. These cursors are sometimes very flexible and allow for some additional sensitivity to reflecting changes that others make to the actual data source. However, some features of the Microsoft Client Cursor Provider (such as disassociated recordsets) cannot be simulated with server-side cursors and these features will then become unavailable with this setting.

Remarks

This property allows you to choose between various cursor libraries accessible to the provider. Usually, you can choose between using a client-side cursor library or one that is located on the server.

This property setting only affects connections established after the property has been set. Changing the CursorLocation property has no effect on existing connections.

This property is read/write on a Connection or a closed Recordset, and read-only on an open Recordset.

Remote Data Service Usage When used on a client-side (ADOR) Recordset or Connection object, the CursorLocation property can only be set to adUseClient.

Examples

AbsolutePosition and CursorLocation Properties Example (VB)

See Also

Using OLE DB Providers with ADO


MarshalOptions Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

MarshalOptions Property - ADO

Indicates which records are to be marshaled back to the server.

Applies To

Recordset

Settings And Return Values

Sets or returns a Long value that can be one of the following constants:
Constant | Description
adMarshalAll | Default. Indicates that all rows are returned to the server.
adMarshalModifiedOnly | Indicates that only modified rows are returned to the server.

Remarks

When using a client-side (ADOR) Recordset, records that have been modified on the client are written back to the middle-tier or web server through a technique called marshaling, the process of packaging and sending interface method parameters across thread or process boundaries.Setting the MarshalOptions property can improve performance when modified remote data is marshaled for updating back to the middle-tier or web server.

Remote Data Service Usage This property is only used on a client-side (ADOR) Recordset.

Examples

MarshalOptions Property Example (VB)


State Property (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

State Property - ADO

Describes the current state of an object.

Applies To

Command, Connection, Recordset

Return Values

Sets or returns a Long value that can be one of the following constants:
Constant | Description
adStateClosed | Default. Indicates that the object is closed.
adStateOpen | Indicates that the object is open.

Remarks

You can use the State property to determine the current state of a given object at any time.

Examples

ConnectionString, ConnectionTimeout, and State Properties Example (VB)


AbsolutePage, PageCount, and PageSize Properties Example (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

AbsolutePage, PageCount, and PageSize Properties Example

This example uses the AbsolutePage, PageCount, and PageSize properties to display names and hire dates from the Employee table five records at a time.

Public Sub AbsolutePageX()

    Dim rstEmployees As ADODB.Recordset
    Dim strCnn As String
    Dim strMessage As String
    Dim intPage As Integer
    Dim intPageCount As Integer
    Dim intRecord As Integer

    ' Open a recordset using a client cursor
    ' for the employee table.
    strCnn = "driver={SQL Server};server=srv;" & _
        "uid=sa;pwd=;database=pubs"
    Set rstEmployees = New ADODB.Recordset
    ' Use client cursor to enable AbsolutePosition property.
    rstEmployees.CursorLocation = adUseClient
    rstEmployees.Open "employee", strCnn, , , adCmdTable

    ' Display names and hire dates, five records
    ' at a time.
    rstEmployees.PageSize = 5
    intPageCount = rstEmployees.PageCount
    For intPage = 1 To intPageCount
        rstEmployees.AbsolutePage = intPage
        strMessage = ""
        For intRecord = 1 To rstEmployees.PageSize
            strMessage = strMessage & _
                rstEmployees!fname & " " & _
                rstEmployees!lname & " " & _
                rstEmployees!hire_date & vbCr
            rstEmployees.MoveNext
            If rstEmployees.EOF Then Exit For
        Next intRecord
        MsgBox strMessage
    Next intPage
    rstEmployees.Close

End Sub


AbsolutePosition and CursorLocation Properties Example (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

AbsolutePosition and CursorLocation Properties Example

This example demonstrates how the AbsolutePosition property can track the progress of a loop that enumerates all the records of a Recordset. It uses the CursorLocation property to enable the AbsolutePosition property by setting the cursor to a client cursor.

Public Sub AbsolutePositionX()

    Dim rstEmployees As ADODB.Recordset
    Dim strCnn As String
    Dim strMessage As String

    ' Open a recordset for the Employee table
    ' using a client cursor.
    strCnn = "driver={SQL Server};server=srv;" & _
        "uid=sa;pwd=;database=pubs"
    Set rstEmployees = New ADODB.Recordset
    ' Use client cursor to enable AbsolutePosition property.
    rstEmployees.CursorLocation = adUseClient
    rstEmployees.Open "employee", strCnn, , , adCmdTable

    ' Enumerate Recordset.
    Do While Not rstEmployees.EOF
        ' Display current record information.
        strMessage = "Employee: " & rstEmployees!lName & vbCr & _
            "(record " & rstEmployees.AbsolutePosition & _
            " of " & rstEmployees.RecordCount & ")"
        If MsgBox(strMessage, vbOKCancel) = vbCancel _
            Then Exit Do
        rstEmployees.MoveNext
    Loop

    rstEmployees.Close

End Sub


ActiveConnection, CommandText, CommandTimeout, CommandType, Size, and Direction Properties Example (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

ActiveConnection, CommandText, CommandTimeout, CommandType, Size, and Direction Properties Example

This example uses the ActiveConnection, CommandText, CommandTimeout, CommandType, Size, and Direction properties to execute a stored procedure.

Public Sub ActiveConnectionX()

    Dim cnn1 As ADODB.Connection
    Dim cmdByRoyalty As ADODB.Command
    Dim prmByRoyalty As ADODB.Parameter
    Dim rstByRoyalty As ADODB.Recordset
    Dim rstAuthors As ADODB.Recordset
    Dim intRoyalty As Integer
    Dim strAuthorID As String
    Dim strCnn As String

    ' Define a command object for a stored procedure.
    Set cnn1 = New ADODB.Connection
    strCnn = "driver={SQL Server};server=srv;" & _
        "uid=sa;pwd=;database=pubs"
    cnn1.Open strCnn
    Set cmdByRoyalty = New ADODB.Command
    Set cmdByRoyalty.ActiveConnection = cnn1
    cmdByRoyalty.CommandText = "byroyalty"
    cmdByRoyalty.CommandType = adCmdStoredProc
    cmdByRoyalty.CommandTimeout = 15

    ' Define the stored procedure's input parameter.
    intRoyalty = Trim(InputBox( _
        "Enter royalty:"))
    Set prmByRoyalty = New ADODB.Parameter
    prmByRoyalty.Type = adInteger
    prmByRoyalty.Size = 3
    prmByRoyalty.Direction = adParamInput
    prmByRoyalty.Value = intRoyalty
    cmdByRoyalty.Parameters.Append prmByRoyalty

    ' Create a recordset by executing the command.
    Set rstByRoyalty = cmdByRoyalty.Execute()

    ' Open the Authors table to get author names for display.
    Set rstAuthors = New ADODB.Recordset
    rstAuthors.Open "authors", strCnn, , , adCmdTable

    ' Print current data in the recordset, adding
    ' author names from Authors table.
    Debug.Print "Authors with " & intRoyalty & _
        " percent royalty"
    Do While Not rstByRoyalty.EOF
        strAuthorID = rstByRoyalty!au_id
        Debug.Print , rstByRoyalty!au_id & ", ";
        rstAuthors.Filter = "au_id = '" & strAuthorID & "'"
        Debug.Print rstAuthors!au_fname & " " & _
            rstAuthors!au_lname
        rstByRoyalty.MoveNext
    Loop

    rstByRoyalty.Close
    rstAuthors.Close
    cnn1.Close

End Sub


ActualSize and DefinedSize Properties Example (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

ActualSize and DefinedSize Properties Example

This example uses the ActualSize and DefinedSize properties to display the defined size and actual size of a field.

Public Sub ActualSizeX()

    Dim rstStores As ADODB.Recordset
    Dim strCnn As String

    ' Open a recordset for the Stores table.
    strCnn = "driver={SQL Server};server=srv;" & _
        "uid=sa;pwd=;database=pubs"
    Set rstStores = New ADODB.Recordset
    rstStores.Open "stores", strCnn, , , adCmdTable

    ' Loop through the recordset displaying the contents
    ' of the stor_name field, the field's defined size,
    ' and its actual size.
    rstStores.MoveFirst

    Do Until rstStores.EOF
        MsgBox "Store name: " & rstStores!stor_name & _
        vbCr & "Defined size: " & _
        rstStores!stor_name.DefinedSize & _
        vbCr & "Actual size: " & _
        rstStores!stor_name.ActualSize & vbCr
        rstStores.MoveNext
    Loop

    rstStores.Close

End Sub


Attributes and Name Properties Example (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Attributes and Name Properties Example

This examples displays the value of the Attributes property for Connection, Field, and Property objects. It uses the Name property to display the name of each Field and Property object.

Public Sub AttributesX

    Dim cnn1 As ADODB.Connection
    Dim rstEmployees As ADODB.Recordset
    Dim fldLoop As ADODB.Field
    Dim proLoop As ADODB.Property
    Dim strCnn As String

    ' Open connection and recordset.
    strCnn = "driver={SQL Server};server=srv;" & _
        "uid=sa;pwd=;database=pubs"
    Set cnn1 = New ADODB.Connection
    cnn1.Open strCnn
    Set rstEmployees = New ADODB.Recordset
    rstEmployees.Open "employee", cnn1, , , adCmdTable

    ' Display the attributes of the connection.
    Debug.Print "Connection attributes = " & _
        cnn1.Attributes

    ' Display the attributes of the Employee table's
    ' fields.
    Debug.Print "Field attributes:"
    For Each fldLoop In rstEmployees.Fields
        Debug.Print "	" & fldLoop.Name & " = " & _
            fldLoop.Attributes
    Next fldLoop

    ' Display the attributes of the Employee table's
    ' properties.
    Debug.Print "Property attributes:"
    For Each proLoop In rstEmployees.Properties
        Debug.Print "	" & proLoop.Name & " = " & _
            proLoop.Attributes
    Next proLoop

    rstEmployees.Close
    cnn1.Close

End Sub


BOF, EOF, and Bookmark Properties Example (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

BOF, EOF, and Bookmark Properties Example

This example uses the BOF and EOF properties to display a message if a user tries to move past the first or last record of a Recordset. It uses the Bookmark property to let the user flag a record in a Recordset and return to it later.

Public Sub BOFX()

    Dim rstPublishers As ADODB.Recordset
    Dim strCnn As String
    Dim strMessage As String
    Dim intCommand As Integer
    Dim varBookmark As Variant

    ' Open recordset with data from Publishers table.
    strCnn = "driver={SQL Server};server=srv;" & _
        "uid=sa;pwd=;database=pubs"
    Set rstPublishers = New ADODB.Recordset
    rstPublishers.CursorType = adOpenStatic
    ' Use client cursor to enable AbsolutePosition property.
    rstPublishers.CursorLocation = adUseClient
    rstPublishers.Open "SELECT pub_id, pub_name FROM publishers " & _
        "ORDER BY pub_name", strCnn, , , adCmdText

    rstPublishers.MoveFirst

    Do While True
        ' Display information about current record
        ' and get user input.
        strMessage = "Publisher: " & rstPublishers!pub_name & _
            vbCr & "(record " & rstPublishers.AbsolutePosition & _
            " of " & rstPublishers.RecordCount & ")" & vbCr & vbCr & _
            "Enter command:" & vbCr & _
            "[1 - next / 2 - previous /" & vbCr & _
            "3 - set bookmark / 4 - go to bookmark]"
        intCommand = Val(InputBox(strMessage))

        Select Case intCommand
            ' Move forward or backward, trapping for BOF
            ' or EOF.
            Case 1
                rstPublishers.MoveNext
                If rstPublishers.EOF Then
                    MsgBox "Moving past the last record." & _
                        vbCr & "Try again."
                    rstPublishers.MoveLast
                End If
            Case 2
                rstPublishers.MovePrevious
                If rstPublishers.BOF Then
                    MsgBox "Moving past the first record." & _
                        vbCr & "Try again."
                    rstPublishers.MoveFirst
                End If

            ' Store the bookmark of the current record.
            Case 3
                varBookmark = rstPublishers.Bookmark

            ' Go to the record indicated by the stored
            ' bookmark.
            Case 4
                If IsEmpty(varBookmark) Then
                    MsgBox "No Bookmark set!"
                Else
                    rstPublishers.Bookmark = varBookmark
                End If

            Case Else
                Exit Do
        End Select

    Loop

    rstPublishers.Close

End Sub


CacheSize Property Example (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

CacheSize Property Example

This example uses the CacheSize property to show the difference in performance for an operation performed with and without a 30-record cache.

Public Sub CacheSizeX()

    Dim rstRoySched As ADODB.Recordset
    Dim strCnn As String
    Dim sngStart As Single
    Dim sngEnd As Single
    Dim sngNoCache As Single
    Dim sngCache As Single
    Dim intLoop As Integer
    Dim strTemp As String

    ' Open the RoySched table.
    strCnn = "driver={SQL Server};server=srv;" & _
        "uid=sa;pwd=;database=pubs"
    Set rstRoySched = New ADODB.Recordset
    rstRoySched.Open "roysched", strCnn, , , adCmdTable

    ' Enumerate the Recordset object twice and record
    ' the elapsed time.
    sngStart = Timer

    For intLoop = 1 To 2
        rstRoySched.MoveFirst

        Do While Not rstRoySched.EOF
            ' Execute a simple operation for the
            ' performance test.
            strTemp = rstRoySched!title_id
            rstRoySched.MoveNext
        Loop
    Next intLoop

    sngEnd = Timer
    sngNoCache = sngEnd - sngStart

    ' Cache records in groups of 30 records.
    rstRoySched.MoveFirst
    rstRoySched.CacheSize = 30
    sngStart = Timer

    ' Enumerate the Recordset object twice and record
    ' the elapsed time.
    For intLoop = 1 To 2

        rstRoySched.MoveFirst
        Do While Not rstRoySched.EOF
            ' Execute a simple operation for the
            ' performance test.
            strTemp = rstRoySched!title_id
            rstRoySched.MoveNext
        Loop
    Next intLoop

    sngEnd = Timer
    sngCache = sngEnd - sngStart

    ' Display performance results.
    MsgBox "Caching Performance Results:" & vbCr & _
        "	No cache: " & Format(sngNoCache, _
        "##0.000") & " seconds" & vbCr & _
        "	30-record cache: " & Format(sngCache, _
        "##0.000") & " seconds"
    rstRoySched.Close

End Sub


ConnectionString, ConnectionTimeout, and State Properties Example (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

ConnectionString, ConnectionTimeout, and State Properties Example

This example demonstrates different ways of using the ConnectionString property to open a Connection object. It also uses the ConnectionTimeout property to set a connection timeout period, and the State property to check the state of the connections. The GetState function is required for this procedure to run.

Public Sub ConnectionStringX()

    Dim cnn1 As ADODB.Connection
    Dim cnn2 As ADODB.Connection
    Dim cnn3 As ADODB.Connection
    Dim cnn4 As ADODB.Connection

    ' Open a connection without using a Data Source Name (DSN).
    Set cnn1 = New ADODB.Connection
    cnn1.ConnectionString = "driver={SQL Server};" & _
        "server=bigsmile;uid=sa;pwd=pwd;database=pubs"
    cnn1.ConnectionTimeout = 30
    cnn1.Open

    ' Open a connection using a DSN and ODBC tags.
    Set cnn2 = New ADODB.Connection
    cnn2.ConnectionString = "DSN=Pubs;UID=sa;PWD=pwd;"
    cnn2.Open

    ' Open a connection using a DSN and OLE DB tags.
    Set cnn3 = New ADODB.Connection
    cnn3.ConnectionString = "Data Source=Pubs;User ID=sa;Password=pwd;"
    cnn3.Open

    ' Open a connection using a DSN and individual
    ' arguments instead of a connection string.
    Set cnn4 = New ADODB.Connection
    cnn4.Open "Pubs", "sa", "pwd"

    ' Display the state of the connections.
    MsgBox "cnn1 state: " & GetState(cnn1.State) & vbCr & _
        "cnn2 state: " & GetState(cnn1.State) & vbCr & _
        "cnn3 state: " & GetState(cnn1.State) & vbCr & _
        "cnn4 state: " & GetState(cnn1.State)

    cnn4.Close
    cnn3.Close
    cnn2.Close
    cnn1.Close

End Sub

Public Function GetState(intState As Integer) As String

    Select Case intState
        Case adStateClosed
            GetState = "adStateClosed"
        Case adStateOpen
            GetState = "adStateOpen"
    End Select

End Function


Count Property Example (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Count Property Example

This example demonstrates the Count property with two collections in the Employee database. The property obtains the number of objects in each collection, and sets the upper limit for loops that enumerate these collections. Another way to enumerate these collections without using the Count property would be to use For Each...Next statements.

Public Sub CountX()

    Dim rstEmployees As ADODB.Recordset
    Dim strCnn As String
    Dim intloop As Integer

    ' Open recordset with data from Employee table.
    strCnn = "driver={SQL Server};server=srv;" & _
        "uid=sa;pwd=;database=pubs"
    Set rstEmployees = New ADODB.Recordset
    rstEmployees.Open "employee", strCnn, , , adCmdTable

    ' Print information about Fields collection.
    Debug.Print rstEmployees.Fields.Count & _
        " Fields in Employee"
    For intloop = 0 To rstEmployees.Fields.Count - 1
        Debug.Print "	" & rstEmployees.Fields(intloop).Name
    Next intloop

    ' Print information about Properties collection.
    Debug.Print rstEmployees.Properties.Count & _
        " Properties in Employee"
    For intloop = 0 To rstEmployees.Properties.Count - 1
        Debug.Print "	" & rstEmployees.Properties(intloop).Name
    Next intloop

    rstEmployees.Close

End Sub


CursorType, LockType, and EditMode Properties Example (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

CursorType, LockType, and EditMode Properties Example

This example demonstrates setting the CursorType and LockType properties before opening a Recordset. It also shows the value of the EditMode property under various conditions. The EditModeOutput function is required for this procedure to run.

Public Sub EditModeX()

    Dim cnn1 As ADODB.Connection
    Dim rstEmployees As ADODB.Recordset
    Dim strCnn As String

    ' Open recordset with data from Employee table.
    Set cnn1 = New ADODB.Connection
    strCnn = "driver={SQL Server};server=srv;" & _
        "uid=sa;pwd=;database=pubs"
    cnn1.Open strCnn

    Set rstEmployees = New ADODB.Recordset
    Set rstEmployees.ActiveConnection = cnn1
    rstEmployees.CursorType = adOpenKeyset
    rstEmployees.LockType = adLockBatchOptimistic
    rstEmployees.Open "employee", , , , adCmdTable

    ' Show the EditMode property under different editing
    ' states.
    rstEmployees.AddNew
    rstEmployees!emp_id = "T-T55555M"
    rstEmployees!fname = "temp_fname"
    rstEmployees!lname = "temp_lname"
    EditModeOutput "After AddNew:", rstEmployees.EditMode
    rstEmployees.UpdateBatch
    EditModeOutput "After UpdateBatch:", rstEmployees.EditMode
    rstEmployees!fname = "test"
    EditModeOutput "After Edit:", rstEmployees.EditMode
    rstEmployees.Close

    ' Delete new record because this is a demonstration.
    cnn1.Execute "DELETE FROM employee WHERE emp_id = 'T-T55555M'"

End Sub

Public Function EditModeOutput(strTemp As String, _
    intEditMode As Integer)

    ' Print report based on the value of the EditMode
    ' property.
    Debug.Print strTemp
    Debug.Print "    EditMode = ";

    Select Case intEditMode
        Case adEditNone
            Debug.Print "adEditNone"
        Case adEditInProgress
            Debug.Print "adEditInProgress"
        Case adEditAdd
            Debug.Print "adEditAdd"
    End Select

End Function


Description, HelpContext, HelpFile, NativeError, Number, Source, and SQLState Properties Example (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Description, HelpContext, HelpFile, NativeError, Number, Source, and SQLState Properties Example

This example triggers an error, traps it, and displays the Description, HelpContext, HelpFile, NativeError, Number, Source, and SQLState properties of the resulting Error object.

Public Sub DescriptionX()

    Dim cnn1 As ADODB.Connection
    Dim errLoop As ADODB.Error
    Dim strError As String

    On Error GoTo ErrorHandler

    ' Intentionally trigger an error.
    Set cnn1 = New ADODB.Connection
    cnn1.Open "nothing"

    Exit Sub

ErrorHandler:

    ' Enumerate Errors collection and display
    ' properties of each Error object.
    For Each errLoop In cnn1.Errors
        strError = "Error #" & errLoop.Number & vbCr & _
            "	" & errLoop.Description & vbCr & _
            "	(Source: " & errLoop.Source & ")" & vbCr & _
            "	(SQL State: " & errLoop.SQLState & ")" & vbCr & _
            "	(NativeError: " & errLoop.NativeError & ")" & vbCr
        If errLoop.HelpFile = "" Then
            strError = strError & _
                "	No Help file available" & _
                vbCr & vbCr
        Else
            strError = strError & _
                "	(HelpFile: " & errLoop.HelpFile & ")" & vbCr & _
                "	(HelpContext: " & errLoop.HelpContext & ")" & _
                vbCr & vbCr
        End If

    Debug.Print strError
    Next

    Resume Next

End Sub


Filter and RecordCount Properties Example (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Filter and RecordCount Properties Example

This example uses the Filter property to open a new Recordset based on a specified condition applied to an existing Recordset. It uses the RecordCount property to show the number of records in the two Recordsets. The FilterField function is required for this procedure to run.

Public Sub FilterX()

    Dim rstPublishers As ADODB.Recordset
    Dim rstPublishersCountry As ADODB.Recordset
    Dim strCnn As String
    Dim intPublisherCount As Integer
    Dim strCountry As String
    Dim strMessage As String

    ' Open recordset with data from Publishers table.
    strCnn = "driver={SQL Server};server=srv;" & _
        "uid=sa;pwd=;database=pubs"
    Set rstPublishers = New ADODB.Recordset
    rstPublishers.CursorType = adOpenStatic
    rstPublishers.Open "publishers", strCnn, , , adCmdTable

    ' Populate the Recordset.
    intPublisherCount = rstPublishers.RecordCount

    ' Get user input.
    strCountry = Trim(InputBox( _
        "Enter a country to filter on:"))

    If strCountry <> "" Then
        ' Open a filtered Recordset object.
        Set rstPublishersCountry = _
            FilterField(rstPublishers, "Country", strCountry)

        If rstPublishersCountry.RecordCount = 0 Then
            MsgBox "No publishers from that country."
        Else
            ' Print number of records for the original
            ' Recordset object and the filtered Recordset
            ' object.
            strMessage = "Orders in original recordset: " & _
                vbCr & intPublisherCount & vbCr & _
                "Orders in filtered recordset (Country = '" & _
                strCountry & "'): " & vbCr & _
                rstPublishersCountry.RecordCount
            MsgBox strMessage
        End If
        rstPublishersCountry.Close

    End If

End Sub

Public Function FilterField(rstTemp As ADODB.Recordset, _
    strField As String, strFilter As String) As ADODB.Recordset

    ' Set a filter on the specified Recordset object and then
    ' open a new Recordset object.
    rstTemp.Filter = strField & " = '" & strFilter & "'"
    Set FilterField = rstTemp

End Function

Note When you know the data you want to select, it's usually more efficient to open a Recordset with an SQL statement. This example shows how you can create just one Recordset and obtain records from a particular country.

Public Sub FilterX2()

    Dim rstPublishers As ADODB.Recordset
    Dim strCnn As String

    ' Open recordset with data from Publishers table.
    strCnn = "driver={SQL Server};server=srv;" & _
        "uid=sa;pwd=;database=pubs"
    Set rstPublishers = New ADODB.Recordset
    rstPublishers.CursorType = adOpenStatic
    rstPublishers.Open "SELECT * FROM publishers " & _
        "WHERE Country = 'USA'", strCnn, , , adCmdText

    ' Print current data in recordset.
    rstPublishers.MoveFirst
    Do While Not rstPublishers.EOF
        Debug.Print rstPublishers!pub_name & ", " & _
            rstPublishers!country
        rstPublishers.MoveNext
    Loop

    rstPublishers.Close

End Sub


IsolationLevel and Mode Properties Example (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

IsolationLevel and Mode Properties Example

This example uses the Mode property to open an exclusive connection, and the IsolationLevel property to open a transaction that is conducted in isolation of other transactions.

Public Sub IsolationLevelX()

    Dim cnn1 As ADODB.Connection
    Dim rstTitles As ADODB.Recordset
    Dim strCnn As String

    ' Assign connection string to variable.
    strCnn = "driver={SQL Server};server=srv;" & _
        "uid=sa;pwd=;database=pubs"

    ' Open connection and titles table.
    Set cnn1 = New ADODB.Connection
    cnn1.Mode = adModeShareExclusive
    cnn1.IsolationLevel = adXactIsolated
    cnn1.Open strCnn

    Set rstTitles = New ADODB.Recordset
    rstTitles.CursorType = adOpenDynamic
    rstTitles.LockType = adLockPessimistic
    rstTitles.Open "titles", cnn1, , , adCmdTable

    cnn1.BeginTrans

    ' Display connection mode.
    If cnn1.Mode = adModeShareExclusive Then
        MsgBox "Connection mode is exclusive."
    Else
        MsgBox "Connection mode is not exclusive."
    End If

    ' Display isolation level.
    If cnn1.IsolationLevel = adXactIsolated Then
        MsgBox "Transaction is isolated."
    Else
        MsgBox "Transaction is not isolated."
    End If

    ' Change the type of psychology titles.
    Do Until rstTitles.EOF
        If Trim(rstTitles!Type) = "psychology" Then
            rstTitles!Type = "self_help"
            rstTitles.Update
        End If
        rstTitles.MoveNext
    Loop

    ' Print current data in recordset.
    rstTitles.Requery
    Do While Not rstTitles.EOF
        Debug.Print rstTitles!Title & " - " & rstTitles!Type
        rstTitles.MoveNext
    Loop

    ' Restore original data.
    cnn1.RollbackTrans
    rstTitles.Close

    cnn1.Close

End Sub


MarshalOptions Property Example (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

MarshalOptions Property Example

This example uses the MarshalOptions property to specify what rows are sent back to the server — All Rows or only Modified Rows.

Public Sub MarshalOptionsX()

    Dim rstEmployees As ADODB.Recordset
    Dim strCnn As String
    Dim strOldFirst As String
    Dim strOldLast As String
    Dim strMessage As String
    Dim strMarshalAll As String
    Dim strMarshalModified As String

    ' Open recordset with names from Employee table.
    strCnn = "driver={SQL Server};server=srv;" & _
        "uid=sa;pwd=;database=pubs"
    Set rstEmployees = New ADODB.Recordset
    rstEmployees.CursorType = adOpenKeyset
    rstEmployees.LockType = adLockOptimistic
    rstEmployees.CursorLocation = adUseClient
    rstEmployees.Open "SELECT fname, lname " & _
        "FROM Employee ORDER BY lname", strCnn, , , adCmdText

    ' Store original data.
    strOldFirst = rstEmployees!fname
    strOldLast = rstEmployees!lname

    ' Change data in edit buffer.
    rstEmployees!fname = "Linda"
    rstEmployees!lname = "Kobara"

    ' Show contents of buffer and get user input.
    strMessage = "Edit in progress:" & vbCr & _
        "   Original data = " & strOldFirst & " " & _
        strOldLast & vbCr & "   Data in buffer = " & _
        rstEmployees!fname & " " & rstEmployees!lname & vbCr & vbCr & _
        "Use Update to replace the original data with " & _
        "the buffered data in the Recordset?"
    strMarshalAll = "Would you like to send all the rows " & _
                    "in the recordset back to the server?"
    strMarshalModified = "Would you like to send only " & _
                    "modified rows back to the server?"

    If MsgBox(strMessage, vbYesNo) = vbYes Then
        If MsgBox(strMarshalAll, vbYesNo) = vbYes Then
            rstEmployees.MarshalOptions = adMarshalAll
            rstEmployees.Update
        ElseIf MsgBox(strMarshalModified, vbYesNo) = vbYes Then
            rstEmployees.MarshalOptions = adMarshalModifiedOnly
            rstEmployees.Update
        End If
    End If

    ' Show the resulting data.
    MsgBox "Data in recordset = " & rstEmployees!fname & " " & _
        rstEmployees!lname

    ' Restore original data because this is a demonstration.
    If Not (strOldFirst = rstEmployees!fname And _
            strOldLast = rstEmployees!lname) Then
        rstEmployees!fname = strOldFirst
        rstEmployees!lname = strOldLast
        rstEmployees.Update
    End If

    rstEmployees.Close

End Sub


MaxRecords Property Example (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

MaxRecords Property Example

This example uses the MaxRecords property to open a Recordset containing the ten most expensive titles in the Titles table.

Sub MaxRecordsX()

    Dim rstTemp As ADODB.Recordset
    Dim strCnn As String

    ' Open recordset containing the 10 most expensive
    ' titles in the Titles table.
    strCnn = "driver={SQL Server};server=srv;" & _
        "uid=sa;pwd=;database=pubs"
    Set rstTemp = New ADODB.Recordset
    rstTemp.MaxRecords = 10
    rstTemp.Open "SELECT Title, Price FROM Titles " & _
        "ORDER BY Price DESC", strCnn, , , adCmdText

    ' Display the contents of the recordset.
    Debug.Print "Top Ten Titles by Price:"

    Do While Not rstTemp.EOF
        Debug.Print "    " & rstTemp!Title & " - " & rstTemp!Price
        rstTemp.MoveNext
    Loop
    rstTemp.Close

End Sub


NumericScale and Precision Properties Example (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

NumericScale and Precision Properties Example

This example uses the NumericScale and Precision properties to display the numeric scale and precision of fields in the Discounts table of the Pubs database.

Public Sub NumericScaleX()

    Dim rstDiscounts As ADODB.Recordset
    Dim fldTemp As ADODB.Field
    Dim strCnn As String

    ' Open recordset.
    strCnn = "driver={SQL Server};server=srv;" & _
        "uid=sa;pwd=;database=pubs"
    Set rstDiscounts = New ADODB.Recordset
    rstDiscounts.Open "discounts", strCnn, , , adCmdTable

    ' Display numeric scale and precision of
    ' numeric and small integer fields.
    For Each fldTemp In rstDiscounts.Fields
        If fldTemp.Type = adNumeric _
            Or fldTemp.Type = adSmallInt Then
            MsgBox "Field: " & fldTemp.Name & vbCr & _
                "Numeric scale: " & _
                    fldTemp.NumericScale & vbCr & _
                "Precision: " & fldTemp.Precision
        End If
    Next fldTemp

    rstDiscounts.Close

End Sub


OriginalValue and UnderlyingValue Properties Example (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

OriginalValue and UnderlyingValue Properties Example

This example demonstrates the OriginalValue and UnderlyingValue properties by displaying a message if a record's underlying data has changed during a Recordset batch update.

Public Sub OriginalValueX()

    Dim cnn1 As ADODB.Connection
    Dim rstTitles As ADODB.Recordset
    Dim fldType As ADODB.Field
    Dim strCnn As String

    ' Open connection.
    Set cnn1 = New ADODB.Connection
    strCnn = "driver={SQL Server};server=srv;" & _
        "uid=sa;pwd=;database=pubs"
    cnn1.Open strCnn

    ' Open recordset for batch update.
    Set rstTitles = New ADODB.Recordset
    Set rstTitles.ActiveConnection = cnn1
    rstTitles.CursorType = adOpenKeyset
    rstTitles.LockType = adLockBatchOptimistic
    rstTitles.Open "titles"

    ' Set field object variable for Type field.
    Set fldType = rstTitles!Type

    ' Change the type of psychology titles.
    Do Until rstTitles.EOF
        If Trim(fldType) = "psychology" Then
            fldType = "self_help"
        End If
        rstTitles.MoveNext
    Loop

    ' Similate a change by another user by updating
    ' data using a command string.
    cnn1.Execute "UPDATE titles SET type = 'sociology' " & _
        "WHERE type = 'psychology'"

    'Check for changes.
    rstTitles.MoveFirst
    Do Until rstTitles.EOF
        If fldType.OriginalValue <> _
            fldType.UnderlyingValue Then

            MsgBox "Data has changed!" & vbCr & vbCr & _
                "  Title ID: " & rstTitles!title_id & vbCr & _
                "  Current value: " & fldType & vbCr & _
                "  Original value: " & _
                fldType.OriginalValue & vbCr & _
                "  Underlying value: " & _
                fldType.UnderlyingValue & vbCr
        End If
        rstTitles.MoveNext
    Loop

    ' Cancel the update because this is a demonstration.
    rstTitles.CancelBatch
    rstTitles.Close

    ' Restore original values.
    cnn1.Execute "UPDATE titles SET type = 'psychology' " & _
        "WHERE type = 'sociology'"

    cnn1.Close

End Sub


Prepared Property Example (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Prepared Property Example

This example demonstrates the Prepared property by opening two Command objects — one prepared and one not prepared.

Public Sub PreparedX()

    Dim cnn1 As ADODB.Connection
    Dim cmd1 As ADODB.Command
    Dim cmd2 As ADODB.Command
    Dim strCnn As String
    Dim strCmd As String
    Dim sngStart As Single
    Dim sngEnd As Single
    Dim sngNotPrepared As Single
    Dim sngPrepared As Single
    Dim intLoop As Integer

    ' Open a connection.
    strCnn = "driver={SQL Server};server=srv;" & _
        "uid=sa;pwd=;database=pubs"
    Set cnn1 = New ADODB.Connection
    cnn1.Open strCnn

    ' Create two command objects for the same
    ' command -- one prepared and one not prepared.
    strCmd = "SELECT title, type FROM titles ORDER BY type"

    Set cmd1 = New ADODB.Command
    Set cmd1.ActiveConnection = cnn1
    cmd1.CommandText = strCmd

    Set cmd2 = New ADODB.Command
    Set cmd2.ActiveConnection = cnn1
    cmd2.CommandText = strCmd
    cmd2.Prepared = True

    ' Set a timer, then execute the unprepared
    ' command 20 times.
    sngStart = Timer
    For intLoop = 1 To 20
        cmd1.Execute
    Next intLoop
    sngEnd = Timer
    sngNotPrepared = sngEnd - sngStart

    ' Reset the timer, then execute the prepared
    ' command 20 times.
    sngStart = Timer
    For intLoop = 1 To 20
        cmd2.Execute
    Next intLoop
    sngEnd = Timer
    sngPrepared = sngEnd - sngStart

    ' Display performance results.
    MsgBox "Performance Results:" & vbCr & _
        "	Not Prepared: " & Format(sngNotPrepared, _
        "##0.000") & " seconds" & vbCr & _
        "	Prepared: " & Format(sngPrepared, _
        "##0.000") & " seconds"

    cnn1.Close

End Sub


Provider and DefaultDatabase Properties Example (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Provider and DefaultDatabase Properties Example

This example demonstrates the Provider property by opening two Connection objects using different providers. It also uses the DefaultDatabase property to set the default database for the Microsoft ODBC Provider.

Public Sub ProviderX()

    Dim cnn1 As ADODB.Connection
    Dim cnn2 As ADODB.Connection

    ' Open a connection using the Microsoft ODBC provider.
    Set cnn1 = New ADODB.Connection
    cnn1.ConnectionString = "driver={SQL Server};" & _
        "server=bigsmile;uid=sa;pwd=pwd"
    cnn1.Open strCnn
    cnn1.DefaultDatabase = "pubs"

    ' Display the provider.
    MsgBox "Cnn1 provider: " & cnn1.Provider

    ' Open a connection using the Microsoft Jet provider.
    Set cnn2 = New ADODB.Connection
    cnn2.Provider = "Microsoft.Jet.OLEDB.3.51"
    cnn2.Open "C:\Samples\northwind.mdb", "admin", ""

    ' Display the provider.
    MsgBox "Cnn2 provider: " & cnn2.Provider

    cnn1.Close
    cnn2.Close

End Sub


Source Property Example (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Source Property Example

This example demonstrates the Source property by opening three Recordset objects based on different data sources.

Public Sub SourceX()

    Dim cnn1 As ADODB.Connection
    Dim rstTitles As ADODB.Recordset
    Dim rstPublishers As ADODB.Recordset
    Dim rstTitlesPublishers As ADODB.Recordset
    Dim cmdSQL As ADODB.Command
    Dim strCnn As String
    Dim strSQL As String

    ' Open a connection.
    Set cnn1 = New ADODB.Connection
    strCnn = "driver={SQL Server};server=srv;" & _
        "uid=sa;pwd=;database=pubs"
    cnn1.Open strCnn

    ' Open a recordset based on a command object.
    Set cmdSQL = New ADODB.Command
    Set cmdSQL.ActiveConnection = cnn1
    cmdSQL.CommandText = "Select title, type, pubdate " & _
        "FROM titles ORDER BY title"
    Set rstTitles = cmdSQL.Execute()

    ' Open a recordset based on a table.
    Set rstPublishers = New ADODB.Recordset
    rstPublishers.Open "publishers", strCnn, , , adCmdTable

    ' Open a recordset based on an SQL string.
    Set rstTitlesPublishers = New ADODB.Recordset
    strSQL = "SELECT title_ID AS TitleID, title AS Title, " & _
        "publishers.pub_id AS PubID, pub_name AS PubName " & _
        "FROM publishers INNER JOIN titles " & _
        "ON publishers.pub_id = titles.pub_id " & _
        "ORDER BY Title"
    rstTitlesPublishers.Open strSQL, strCnn, , , adCmdText

    ' Use the Source property to display the source of each recordset.
    MsgBox "rstTitles source: " & vbCr & _
        rstTitles.Source & vbCr & vbCr & _
        "rstPublishers source: " & vbCr & _
        rstPublishers.Source & vbCr & vbCr & _
        "rstTitlesPublishers source: " & vbCr & _
        rstTitlesPublishers.Source

    rstTitles.Close
    rstPublishers.Close
    rstTitlesPublishers.Close
    cnn1.Close

End Sub


Status Property Example (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Status Property Example

This example uses the Status property to display which records have been modified in a batch operation before a batch update has occurred.

Public Sub StatusX()

    Dim rstTitles As ADODB.Recordset
    Dim strCnn As String

    ' Open recordset for batch update.
    strCnn = "driver={SQL Server};server=srv;" & _
        "uid=sa;pwd=;database=pubs"
    Set rstTitles = New ADODB.Recordset
    rstTitles.CursorType = adOpenKeyset
    rstTitles.LockType = adLockBatchOptimistic
    rstTitles.Open "titles", strCnn, , , adCmdTable

    ' Change the type of psychology titles.
    Do Until rstTitles.EOF
        If Trim(rstTitles!Type) = "psychology" Then
            rstTitles!Type = "self_help"
        End If
        rstTitles.MoveNext
    Loop

    ' Display Title ID and status.
    rstTitles.MoveFirst
    Do Until rstTitles.EOF
        If rstTitles.Status = adRecModified Then
            Debug.Print rstTitles!title_id & " - Modified"
        Else
            Debug.Print rstTitles!title_id
        End If
        rstTitles.MoveNext
    Loop

    ' Cancel the update because this is a demonstration.
    rstTitles.CancelBatch
    rstTitles.Close

End Sub


Type Property Example (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Type Property Example

This example demonstrates the Type property by displaying the name of the constant corresponding to the value of the Type property of all the Field objects in the Employee table. The FieldType function is required for this procedure to run.

Public Sub TypeX()

    Dim rstEmployees As ADODB.Recordset
    Dim fldLoop As ADODB.Field
    Dim strCnn As String

    ' Open recordset with data from Employee table.
    strCnn = "driver={SQL Server};server=srv;" & _
        "uid=sa;pwd=;database=pubs"
    Set rstEmployees = New ADODB.Recordset
    rstEmployees.Open "employee", strCnn, , , adCmdTable

    Debug.Print "Fields in Employee Table:" & vbCr

    ' Enumerate Fields collection of Employees table.
    For Each fldLoop In rstEmployees.Fields
        Debug.Print "    Name: " & fldLoop.Name & vbCr & _
            "    Type: " & FieldType(fldLoop.Type) & vbCr
    Next fldLoop

End Sub

Public Function FieldType(intType As Integer) As String

    Select Case intType
        Case adChar
            FieldType = "adChar"
        Case adVarChar
            FieldType = "adVarChar"
        Case adSmallInt
            FieldType = "adSmallInt"
        Case adUnsignedTinyInt
            FieldType = "adUnsignedTinyInt"
        Case adDBTimeStamp
            FieldType = "adDBTimeStamp"
    End Select

End Function


Value Property Example (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Value Property Example

This example demonstrates the Value property with Field and Property objects by displaying field and property values for the Employees table.

Public Sub ValueX()

    Dim rstEmployees As ADODB.Recordset
    Dim fldLoop As ADODB.Field
    Dim prpLoop As ADODB.Property
    Dim strCnn As String

    ' Open recordset with data from Employee table.
    strCnn = "driver={SQL Server};server=srv;" & _
        "uid=sa;pwd=;database=pubs"
    Set rstEmployees = New ADODB.Recordset
    rstEmployees.Open "employee", strCnn, , , adCmdTable

    Debug.Print "Field values in rstEmployees"
    ' Enumerate the Fields collection of the Employees
    ' table.
    For Each fldLoop In rstEmployees.Fields
        ' Because Value is the default property of a
        ' Field object, the use of the actual keyword
        ' here is optional.
        Debug.Print "	" & fldLoop.Name & " = " & fldLoop.Value
    Next fldLoop

    Debug.Print "Property values in rstEmployees"
    ' Enumerate the Properties collection of the
    ' Recordset object.
    For Each prpLoop In rstEmployees.Properties
        ' Because Value is the default property of a
        ' Property object, the use of the actual keyword
        ' here is optional.
        Debug.Print "	" & prpLoop.Name & " = " & prpLoop.Value
    Next prpLoop

    rstEmployees.Close

End Sub


Version Property Example (ADO)

Microsoft ActiveX Data Objects Microsoft ActiveX Data Objects *

Version Property Example

This example uses the Version property of a Connection object to display the current ADO version. It also uses several dynamic properties to show the current DBMS name and version, OLE DB version, provider name and version, driver name and version, and driver ODBC version.

Public Sub VersionX()

    Dim cnn1 As ADODB.Connection

    ' Open connection.
    Set cnn1 = New ADODB.Connection
    strCnn = "driver={SQL Server};server=srv;" & _
        "uid=sa;pwd=;database=pubs"
    cnn1.Open strCnn

    strVersionInfo = "ADO Version: " & cnn1.Version & vbCr & _
    "DBMS Name: " & cnn1.Properties("DBMS Name") & vbCr & _
    "DBMS Version: " & cnn1.Properties("DBMS Version") & vbCr & _
    "OLE DB Version: " & cnn1.Properties("OLE DB Version") & vbCr & _
    "Provider Name: " & cnn1.Properties("Provider Name") & vbCr & _
    "Provider Version: " & cnn1.Properties("Provider Version") & vbCr & _
    "Driver Name: " & cnn1.Properties("Driver Name") & vbCr & _
    "Driver Version: " & cnn1.Properties("Driver Version") & vbCr & _
    "Driver ODBC Version: " & cnn1.Properties("Driver ODBC Version")

    MsgBox strVersionInfo

    cnn1.Close

End Sub


Microsoft CDF Generator

Microsoft CDF Generator is an easy-to-use, highly efficient tool for the creation of Channel Definition Format files (CDFs).

  • It has a simple and intuitive graphical interface that you will get used to in a few minutes.
  • It doesn't require previous knowledge of channels.
  • It supports all CDF tags.
  • It supports UTF-8 encoding.
  • It can also be used for testing purposes, since it parses the CDF files and detects the errors.
  • It supports drag and drop, so there less to type.

Note: Microsoft CDF Generator is able to parse a Channel Definition Format file only if Internet Explorer 4.0 is installed on your machine.

Updates: For the latest versions and information of Microsoft CDF Generator check SiteBuilder Network Downloads.

THE USER INTERFACE
CREATING A NEW CDF
OPENING AND MODIFYING EXISTING AND NEW CDF FILES
ADDING ELEMENTS
MODIFYING ELEMENTS
DELETING ELEMENTS
OTHER OPTIONS

THE USER INTERFACE

The user interface of Microsoft CDF Generator consists of two main parts:

Tree pane: The left side of the main window includes a hierarchical representation of the channel definition format that you are creating. By default all the elements (tags) are visible, but it also allows you to hide some of the elements that are not important.

Code pane: The right side of the main window shows the complete code of the file. Any change in the tree pane is automatically reflected in code pane. In Platform Preview 2, this pane is read-only, and user is not able to change the content in order to modify the CDF file

Microsoft CDF Generator User Interface

CREATING A NEW CDF

Selecting New from the File menu will automatically launch a sequence of the five wizards that you can use to add elements or attributes to your channel, see the wizards section for more details.

PAGES THAT YOU WILL FIND IN THE WIZARDS

Each one of the wizards shows a different subset of pages where you can specify the different attributes of the element you are adding.

  1. The General - Channel - Information page
    • HREF: the URL for the top page of the channel (Select Attribute or Anchor type)
    • BASE: the URL or root of the site where the channel is published (used for resolving relative paths)
    • SELF: The URL where the CDF will be published (full, including the name of the CDF)

  2. The General - Item - Information page
    • HREF: the URL for the item that you are adding (Select Attribute or Anchor type)
    • Last Modified date (ISO date, time, time zone format)
    • The Level
    • Whether the item should be pre-cached or not (checkbox)
    • The Usage attribute for the Item

  3. The - Common - child elements page

    4. Select the checkbox of the elements that you want to associate with the channel and type in their respective properties:

    • Title: the title of the channel, a short text description that will appear as a tool-tip or when the user selects to see it in the channel changer.
    • Abstract: a text description (2 sentences max. recommended) describing the content of the channel, to be used as a tool-tip or in channel guides.
    • Log: type of events that you want to have logged for tracking purposes.

  4. The Logos information

    5. Select the checkbox, and type in the URL of the logos that you want to represent a channel or an item:

    • Icon: URL to the .ICO, .GIF or .JPG file that will be used when viewing large icons in the channel changer
    • Image: URL to the .GIF or .JPG (80x32) file that will be used by default in the desktop channel bar.
    • Wide: URL to the .GIF or .JPG (194x32) file that will be used in the browser channel changer.

  5. The Schedule page

    6. Toggle the top level check box to choose if you want to have a delivery schedule associated with your channel, and if you do want a schedule, edit the schedule dates and the delivery timings sections according to your preferences.

  6. The Log Target page

    7. Again, check or uncheck the element depending on your preferences and edit the characteristics of your tracking notifications.

  7. The Authentication or Login page

    8. Speaks for itself.

OPENING AND MODIFYING EXISTING AND NEW CDF FILES

Microsoft CDF Generator uses COM objects of Internet Explorer 4.0 to parse existing files, which means that it needs to be installed on a machine with Microsoft Internet Explorer 4.0 for this feature to work properly.

To open an existing file, simply select Open from the File menu and point to the CDF file. If an error occurs, or the CDF file contains errors and cannot be parsed, a dialog box appears with details.

Once you have defined a channel (just created or opened) you can Add, Modify or Delete any element in the CDF file.

ADDING ELEMENTS

There are 3 ways of doing this:

  1. Through the main menu, i.e. to add an item to a channel, select that channel in the tree pane (click on it) and then select Tag, New, Item from the main menu.
  2. Right click on the element that you want to modify, i.e. to add an item to a channel, right click on that channel in the Tree pane and select New, Item from the context menu.
  3. Drag and drop; you can drag URL links, links from a web page (<A> - anchor tags) opened in Internet Explorer browser, small icon beside the address (address bar) of the currently opened page in your browser, etc. These objects must be dropped into the channel element of Microsoft CDF Generator that will be its parent. This will launch the Item Wizard and insert the address of the link you had opened into the appropriate box in the Wizard

Microsoft CDF Generator is "intelligent" in the sense that it will not let you add a child element twice if only one child element of that kind is supported for that element. For example if you have already added a title to a channel, it will not display the "Title" element as an option in the menu. Or when you add a sub-channel to a channel it will not even display the schedule page in the wizard.

MODIFYING ELEMENTS

Simply double click (or right click and select Properties) on the element that you want to modify, then type in the new values into the appropriate boxes

DELETING ELEMENTS

Click on the element that you want to delete and press the Delete key, or right click and select Delete.

OTHER OPTIONS

OPENING A REMOTE CDF FILE

To download and open an existing file from the web, select Open (URL) from the File menu and type the URL of the CDF file you want to open.

Note: You will not be able to save this file back to the web server. Save it on your local drive instead.

MANUAL EDITING

You can manually edit a CDF file in the Code Pane. In order to do that, check Edit Mode from the View menu. The content of the Tree Pane will be destroyed, and rebuilt again when you decide to exit the Edit Mode, using the same procedure (View|EditMode).

TESTING YOUR CDF FILE

Select Test from the Tag menu, and all the child elements of the currently selected item in the Tree Pane will be recursively tested.

Note: Only the visible elements are tested.

ENCODING (UTF-8)

Microsoft CDF Generator allows users to save files in UTF-8 format by converting the text using UTF-8 encoding standards. Select View, Options from the main menu, and in General page, type 'UTF-8' in the encoding field.

Note: All HTML character sets are valid in this field (i.e. windows-1250, big5, etc.)

VISIBILITY

If a channel includes a large amount of sub-channels and items, the tree pane (left) can become overpopulated, making the structure hard to follow. To improve performance, the user can hide any tag in the tree pane. Select View, Options from the main menu, and in Advanced page uncheck the boxes beside the tags that should be hidden.

Note: If the channel tag is hidden, the tree pane disappears.

REORDERING

New elements inserted into the CDF file are inserted according to an internal sort order. If you want to modify the order of an element, drag the element, and drop it onto the element to be placed after the dragged element.


Component Development

The documentation in this section contains the information you'll need if you are developing ActiveX™ Controls, ActiveX Control containers, Active Document servers, Active Document hosts, ActiveX Scripting hosts, or ActiveX Scripting engines.

COM Objects for the Internet

ActiveX Controls

ActiveX Control Containers

Active Documents

ActiveX Scripting

Microsoft Scriptlet Technology


Active Documents

Microsoft® Active Documents are also known as Document Objects or Doc Objects. Unlike an OLE embedded object that is displayed within the page of another document, an Active Document is a full-scale document that is embedded in a container. Microsoft Office Binder and Microsoft Internet Explorer are two examples of Active Document containers. Microsoft Word and Microsoft Excel are two examples of Active Document servers. Unlike embedded objects, Active Documents have complete control over their pages and can exploit the complete native functionality of the server (application) that creates them. Users can create documents using the full power of their favorite applications, if they are Active Document-enabled, yet treat the resulting project as a single entity.

If you have Microsoft Word and Internet Explorer installed, you can see an example of Active Document technology at work. Open Internet Explorer and open a Word document in Internet Explorer. You will see that the document is displayed just as it is in Word, except it is contained inside Internet Explorer. Internet Explorer provides the basic menus, toolbars, and status bars, and Word adds all of its menus, toolbars, and status bars to create a user interface that is very familiar to the user.

The following sections describe the major steps involved in creating an Active Document server or an Active Document container in C++ without using the Microsoft Foundation Class Library (MFC). You should, at a minimum, be familiar with C++, OLE, and in-place activation.

All of the Active Document-specific definitions are contained in Docobj.h. No special libraries are required to build an Active Document server or container.

Programming an Active Document Server

Programming an Active Document Container

Reference


Programming an Active Document Container

An Active Document container is an application that provides the view in which an Active Document resides. Instead of providing a document in which an in-place object resides, the container provides the basic user interface features that are specific to the container, and allows the server to merge its menus and add any other user interface components within the view area of the container. This allows the container to host any number of different Active Documents while still maintaining a user interface that is familiar to the user.

The Basics

Loading the Active Document

Miscellaneous Requirements

Palette Management for Active Document Containers

The Basics

To create an Active Document container, you must implement the following interfaces. Some of these interfaces are not required for a minimal implementation of a container. This table specifies which interfaces are required.
Interface | Required | Description
IOleDocumentSite | Yes | The Active Document object uses this interface to request that the container activate it.
IOleClientSite | Yes | The Active Document object uses this interface to obtain information about the location and extent of its display site, its user interface, and other resources provided by the container.
IOleInPlaceSite | Yes | The Active Document object uses this interface to control in-place activation from within the container.
IAdviseSink | Yes | The Active Document object uses this interface to notify objects with which they have an advisory connection of changes in an object's data, view, name, or state.
IOleCommandTarget | No | The Active Document object uses this interface to dispatch commands and obtain command status information from the Active Document.
IContinueCallback | No | This is a generic callback mechanism for interruptible processes that should periodically ask an object whether to continue.

Loading the Active Document

To load the Active Document, your container should perform the following steps. These steps discuss how and when to create, activate, display, and close an Active Document.

Creating the Active Document Object

When opening an Active Document file, you need to create an instance of the Active Document object. This is accomplished with the OleCreateFromFile API. You pass this API a valid IStorage pointer and the name of the file you want to create the object from. If the API succeeds, you will receive a pointer to the Active Document object. This is the interface you will use to control the object. You can use this pointer to use QueryInterface for the IOleObject and/or IOleDocument interface pointers.

When you have the object's interface, you need to do the following:

  1. Set the object's client site by calling its IOleObject::SetClientSite method, passing your IOleClientSite interface.
  2. Set the object's advise sink by calling the object's IOleObject::Advise method, passing your IAdviseSink interface.
  3. Place the Active Document object into the running state by calling OleRun, passing the object's interface pointer.
  4. Obtain the Active Document view pointer by calling the object's IOleObject::DoVerb method with the iVerb parameter equal to OLEIVERB_SHOW. In response to this, the object will call your IOleDocumentSite::ActivateMe method. In IOleDocumentSite::ActivateMe, if the pViewToActivate parameter is not NULL, it contains the object's IOleDocumentView pointer. If pViewToActivate is NULL, you must call the object's IOleDocument::CreateView method to create the view.

    In the IOleDocument::CreateView call, the pIPSite and pstm parameters are optional. If you don't include them, or if you obtained the object's view pointer directly in IOleDocumentSite::ActivateMe, you will need to call the object's IOleDocumentView::SetInPlaceSite method with your IOleInPlaceSite pointer to set the view's in-place site and call the object's IOleDocumentView::ApplyViewState method with your view state stream pointer. This allows the view to obtain its view state information.

Activating the Active Document View

When you have the object's view pointer, you need to activate the view. These are the steps involved in this process:

  1. Call the object's IOleDocumentView::UIActivate method with the fUIActivate parameter set to TRUE.
  2. Set the object's display rectangle by calling its IOleDocumentView::SetRect method.
  3. Show the view by calling the object's IOleDocumentView::Show method with the fShow parameter set to TRUE.

Deactivating the Active Document View

To deactivate the view, hide it by calling the object's IOleDocumentView::Show method with FALSE. You then call the object's IOleDocumentView::UIActivate method with FALSE.

Closing the Active Document

To close the document, perform the following steps:

  1. Deactivate the view.
  2. Call the object's IOleDocumentView::CloseView method to close the view.
  3. When the view has been closed, the IOleDocumentView object is no longer valid, so you must release its pointer.
  4. Release any other pointers you have obtained from the object.
  5. Release the IOleDocument pointer.

Miscellaneous Requirements

You should design your container with these points in mind:

  • The Active Document object will obtain the view window's parent by calling your IOleWindow::GetWindow method. You must provide a handle to your view parent window in response to this method.
  • While it is not required for the most basic implementation of an Active Document container, your container should implement the IOleInPlaceFrame interface. Without this interface the object will not be able to display toolbars or status text, nor will it be able to merge its menus with the container's menu. Some Active Documents might not allow themselves to be displayed without the container having implemented IOleInPlaceFrame.
  • Whenever the size of your view area changes, you need to recalculate the view rectangle and notify the view object by calling its IOleDocumentView::SetRect method.

Palette Management for Active Document Containers

In general, the palette management scheme for Active Document containers is the same as the scheme used for ActiveX™ Controls, except that containers do not give ambient properties to the document. There are two different cases that need to be considered. The first is if the container can activate only one Active Document object at a time. The second is if the container can activate more than one Active Document object at a time.

Single Document Case

In the most common cases, your container will activate only one Active Document at a time. In this situation, it is best to allow the Active Document to have complete control over the palette, which includes managing palette issues for any controls or content within that document. To accomplish this, it is necessary for you to forward all Microsoft® Windows® palette management messages on to the Active Document. The following is a simple demonstration of how to forward these messages to the Active Document.

case WM_PALETTECHANGED:
case WM_QUERYNEWPALETTE:
   {
   HWND hwnd;
   IOleWindow *pOleWindow;
   if(pDocObj && SUCCEEDED(pDocObj->QueryInterface(IID_IOleWindow,
         (LPVOID*)&pOleWindow)))
      {
      LRESULT lres = 0;
      if (SUCCEEDED(pOleWindow->GetWindow(&hwnd)))
         {
         lres = SendMessage(hwnd, uMsg, wParam, lParam);
         }

      pOleWindow->Release();
      return lres;
      }
   break;
   }

Multiple Document Case

In rare cases, your container might be able to activate more than one Active Document at a time. While you can implement such a container, you should avoid doing so if at all possible. One of the reasons this is discouraged is that no protocol currently exists for communicating palettes between an Active Document and its container. Therefore, the container cannot create a palette suitable to all Active Documents that it has activated.

Because of this, the activated Active Document in the foreground has control over the palette and will use foreground palette rendering. Other activated Active Documents in the background will use background palette rendering. The Active Document container itself does not participate in palette management at all.


Programming an Active Document Server

An Active Document server is an OLE local server, similar to an OLE in-place server, that provides all the functionality of the document application. The document is contained inside an Active Document container, but is allowed to merge its menus with the container's menus and has complete use of the container's view area. The server provides the majority of the user interface, including menus, toolbars, status bars, and scroll bars. This allows the server to be hosted by any number of different Active Document containers while still maintaining a user interface that is familiar to the user.

The Basics

Registering an Active Document Server

The IDataObject Interface

The IOleDocument Interface

The IOleDocumentView Interface

Palette Management for Active Document Servers

The Basics

To create an Active Document server, you must create a file-based OLE local server that implements the following interfaces. Some of these interfaces are not required for a minimal implementation of a server. This table specifies which interfaces are required.
Interface | Required | Description
IOleDocument | Yes | The container uses this interface to cause an Active Document to create views of itself, enumerate the views the object supports, and provide miscellaneous information about the object's capabilities.
IOleDocumentView | Yes | The container uses this interface to activate, deactivate, close, and communicate with a document view object.
IPersistStorage | Yes | The container uses this interface to initialize the object and put it in the loaded or running state, and to instruct the object to perform various save operations or to release its storage.
IOleObject | Yes | The container uses this interface to execute verbs, communicate site information, and close the view.
IDataObject | Yes | The container uses this interface to get and set data in the object.
IOleInPlaceObject | Yes | The container uses this interface to activate and deactivate the view object.
IOleInPlaceActiveObject | Yes | The container uses this interface to control the view object while it is active.
IEnumFORMATETC | No | The container uses this interface to determine what data formats the object supports.
IEnumOleDocumentViews | No | The container uses this interface to enumerate the views that an Active Document supports.
IOleCommandTarget | No | The container uses this interface to dispatch commands and obtain command status information from the Active Document.
IPrint | No | The container uses this interface to print an Active Document.

Registering an Active Document Server

The following are the minimum registry entries necessary to register an Active Document server. Any information in "<>" brackets is implementation-specific.

HKEY_CLASSES_ROOT\<file extension> = <prog ID>

HKEY_CLASSES_ROOT\<prog ID> = <document name>

HKEY_CLASSES_ROOT\<prog ID>\CLSID = <clsid>

HKEY_CLASSES_ROOT\CLSID\<clsid>\LocalServer32 = <server path and file>

HKEY_CLASSES_ROOT\CLSID\<clsid>\InprocHandler32 = "ole32.dll"

HKEY_CLASSES_ROOT\CLSID\<clsid>\Insertable = ""

HKEY_CLASSES_ROOT\CLSID\<clsid>\DocObject = ""

The Insertable and DocObject registry keys noted in this example are not required if the CATID_Insertable and CATID_DocObject component categories are registered for the server. Registering the component categories causes these keys to be added automatically. For more information, see the ICatRegister::RegisterClassImplCategories method.

The following registry entry is optional and causes an icon to be displayed for the file in Windows® Explorer.

HKEY_CLASSES_ROOT\CLSID\<clsid>\DefaultIcon = <server path and file>,<icon index>

The IDataObject Interface

The IDataObject interface is not specific to Active Documents, but one point must be clarified. Some Active Document containers will store the document's information in a format specific to the container. Therefore, these containers will make a copy of the data before actually activating the document. This is done by requesting the data using the object's IDataObject::GetDataHere method for the "Embed Source" registered clipboard format, DVASPECT_CONTENT and TYMED_ISTORAGE. In response to this call, your server must store the document's current data in the IStorage interface provided in the STGMEDIUM structure. This can easily be accomplished by using the OleSave API.

The IOleDocument Interface

The IOleDocument interface is the basis for your Active Document server. The container uses this interface to create views, obtain a view enumerator (IEnumOleDocumentViews), and obtain document status.

Creating the Document View

The container will request that your server create a document view to be displayed. It will do so in the following manner:

  1. The container calls your server's IOleObject::DoVerb method with the iVerb parameter equal to OLEIVERB_SHOW, OLEIVERB_PRIMARY, or OLEIVERB_UIACTIVATE.
  2. Your server obtains the container's IOleDocumentSite pointer by calling QueryInterface on the IOleClientSite pointer that is passed to IOleObject::DoVerb.
  3. Your server then calls the container's IOleDocumentSite::ActivateMe method, passing either a valid IOleDocumentView pointer or NULL. If you pass a valid pointer, the document view will be activated. If you pass NULL, the container will call your server's IOleDocument::CreateView method to create the view.

The following is a very simple example of an IOleObject::DoVerb implementation.

STDMETHODIMP COleObject::DoVerb( LONG iVerb,
                                 LPMSG lpmsg,
                                 LPOLECLIENTSITE pActiveSite,
                                 LONG lindex,
                                 HWND hwndParent,
                                 LPCRECT lprcPosRect)
{
HRESULT  hr = E_FAIL;

switch (iVerb)
   {
   case OLEIVERB_SHOW:
   case OLEIVERB_PRIMARY:
   case OLEIVERB_UIACTIVATE:
      {
      //try to get the IOleDocumentSite pointer
      LPOLEDOCUMENTSITE pOleDocSite;
      hr = pActiveSite->QueryInterface(IID_IOleDocumentSite, (LPVOID*)&pOleDocSite);
      if(SUCCEEDED(hr))
         {
         //passing NULL to this will cause the site to call our CreateView method
         hr = pOleDocSite->ActivateMe(NULL);
         }
      }
      break;

   default:
      break;
   }

return hr;
}

The following is a simple example of an IOleDocument::CreateView implementation.

STDMETHODIMP COleDocument::CreateView( IOleInPlaceSite *pInPlaceSite,
                                       IStream *pStream,
                                       DWORD dwReserved,
                                       IOleDocumentView **ppOleDocumentView)
{
HRESULT  hr = E_FAIL;

//NULL the view pointer
*ppOleDocumentView = NULL;

//this implementation only supports one view, so fail if the view already exists
if(!m_pOleDocView)
   {
   m_pOleDocView = new COleDocumentView();

   if(m_pOleDocView)
      {
      //AddRef since the pointer is being given away
      m_pOleDocView->AddRef();

      //if a site has been given, set this as the site for the view just created
      if(pInPlaceSite)
         {
         m_pOleDocView->SetInPlaceSite(pInPlaceSite);
         }

      //if given a stream to initialize from, initialize the view state
      if(pStream)
         {
         m_pOleDocView->ApplyViewState(pStream);
         }

      *ppOleDocumentView = m_pOleDocView;

      hr = S_OK;
      }
   }

return hr;
}

The IOleDocumentView Interface

The IOleDocumentView interface is used by the container to manage the display of your Active Document. The container uses this interface to set the view's site and to activate and deactivate the view, among other things.

Getting the Document View's Site

When your server's IOleDocumentView::SetInPlaceSite method is called, the server should release any saved IOleInPlaceSite pointer that it is maintaining, and then call AddRef and store the new IOleInPlaceSite pointer. This pointer will be used to inform the site of in-place activation and deactivation and to obtain the handle of the view's parent window. The parent window handle is obtained by calling this interface's IOleWindow::GetWindow. The following is a simple example of this method's implementation.

STDMETHODIMP COleDocumentView::SetInPlaceSite(IOleInPlaceSite *pNewSite)
{
//clean up previous site if it exists
if(m_pInPlaceSite)
   {
   if(m_fUIActive)
      {
      //call the view's private method that handles UI deactivation
      DeactivateUI();
      }

   m_pInPlaceSite->Release();
   m_pInPlaceSite = NULL;
   }

m_pInPlaceSite = pNewSite;

if(m_pInPlaceSite)
   {
   m_pInPlaceSite->AddRef();
   }

return S_OK;
}

Activating the Document View

The document view activation occurs in the following manner:

  1. The server's IOleDocumentView::UIActivate method is called with a nonzero fActivate parameter.
  2. The server ensures that the object is in-place active. The object is made in-place active by calling the site's IOleInPlaceSite::OnInPlaceActivate method and showing the view window.
  3. The server performs whatever actions are necessary to become UI-active. This usually involves adding toolbars, merging menu items, and adding any other UI objects.
  4. The server notifies the site that the view is getting UI-activated by calling the site's IOleInPlaceSite::OnUIActivate method.

Some containers can contain more than one Active Document. These containers notify the object that the Active Document window is getting activated by calling the object's IOleInPlaceActiveObject::OnDocWindowActivate method with a nonzero argument. This does not normally occur until the object has already become UI-active. When this occurs, the object must display its UI objects, such as menus and toolbars. It is not necessary, however, to completely UI-deactivate the object.

Deactivating the Document View

The document view deactivation occurs in the following manner:

  1. The server's IOleDocumentView::UIActivate method is called with a zero fActivate parameter.
  2. The server removes any menu items, toolbars, or other UI objects.
  3. The server notifies the site that the view is getting UI-deactivated by calling the site's IOleInPlaceSite::OnUIDeactivate method.

Some containers can contain more than one Active Document. These containers notify the object that the Active Document window is getting deactivated by calling the object's IOleInPlaceActiveObject::OnDocWindowActivate method with a zero argument. When this occurs, the object must hide its UI objects, such as toolbars. It is not necessary to remove the object's menus at this point because the container will do this on its own. It is also not necessary to completely UI-deactivate the object.

Palette Management for Active Document Servers

In general, the palette management scheme for Active Documents is the same as the scheme used for ActiveX™ Controls, except that Active Documents do not receive ambient properties from their client. The Active Document server has these responsibilities for managing palettes:

  • The server notifies the container as to which palette the Active Document needs to use by implementing the IViewObject::GetColorSet method. This is the same method that OLE controls use to manage their palettes.
  • The server must realize its palette in the background except when handling the WM_QUERYNEWPALETTE message (forwarded from the container). Again, this is exactly the way OLE controls handle this.

The only difference between the responsibilities of Active Documents and OLE controls is that Active Documents do not handle the DISPID_AMBIENT_PALETTE property.


DOCMISC

typedef enum
{
    DOCMISC_CANCREATEMULTIPLEVIEWS    =  1,
    DOCMISC_SUPPORTCOMPLEXRECTANGLES  =  2,
    DOCMISC_CANTOPENEDIT,             =  4,
    DOCMISC_NOFILESUPPORT             =  8
} DOCMISC;

Provides miscellaneous property information about an Active Document. A combination of values from DOCMISC is returned at the location specified by the pdwStatus parameter in the IOleDocument::GetDocMiscStatus method.

DOCMISC_CANCREATEMULTIPLEVIEWS
Object supports multiple views.
DOCMISC_SUPPORTCOMPLEXRECTANGLES
Object supports complex rectangles and therefore implements the IOleDocumentView::SetRectComplex method.
DOCMISC_CANTOPENEDIT
Object supports activation in a separate window and therefore implements the IOleDocumentView::Open method.
DOCMISC_NOFILESUPPORT
Object does not support read/write files.

Objects that have a limited user interface for activation purposes should set DOCMISC_CANTOPENEDIT. Those that support the IPersistStorage interface only as a persistence mechanism should specify DOCMISC_NOFILESUPPORT. Otherwise, an object must also implement the IPersistFile interface.

If an object requires none of these flags, it must write a zero to the pdwStatus parameter of the IOleDocument::GetDocMiscStatus method.


Enumerations

This section describes the Active Document enumerations.
DOCMISC
OLECMDEXECOPT
OLECMDF
OLECMDID
OLECMDTEXTF
PRINTFLAG


IContinueCallback

The IContinueCallback interface is a generic callback mechanism for interruptible processes that should periodically ask an object whether to continue.

The IContinueCallback::FContinue method is a generic continuation request. IContinueCallback::FContinuePrinting carries extra information pertaining to a printing process and is used in the context of the IPrint interface.

Methods in Vtable Order
FContinue | Answers whether an operation should continue.
FContinuePrinting | Answers whether a printing operation should continue.


IContinueCallback::FContinue

HRESULT FContinue(void);

Answers whether a given generic operation should continue.

  • Returns S_OK to continue the operation, or S_FALSE to cancel it as soon as possible.


IContinueCallback::FContinuePrinting

HRESULT FContinuePrinting(
    LONG cPagesPrinted,
    LONG nCurrentPage,
    LPOLESTR pszPrintStatus
    );

Answers whether a given lengthy printing operation should continue.

  • Returns one of the following values:
    S_OK | Continue the printing operation.
    E_FAIL | The printing operation failed.
    S_FALSE | Cancel the print job as soon as possible.
cPagesPrinted
Total number of pages that have been printed at the time the object receives a call to this method.
nCurrentPage
Page number of the page being printed at the time the object receives a call to this method.
pszPrintStatus
Address of a message about the current status of the print job. The object being printed may or may not display this message to the user. Can be NULL.

Implementations of IPrint::Print call this method at periodic intervals during the printing process. The IPrint implementation should call back at least after printing each page, so that its client can, if necessary, display useful visual feedback to the user. IPrint::Print can call back multiple times with the same cPagesPrinted and nCurrentPage values, which is useful when a page being printed is complex and it is appropriate to give a user an opportunity to cancel mid-page.


IEnumOleDocumentViews

The IEnumOleDocumentViews interface is used to enumerate the views supported by an Active Document. IEnumOleDocumentViews has the same methods as all enumerator interfaces. For general information on these methods, see IEnumXXXX.

When to Implement

Implement IEnumOleDocumentViews on enumerator objects associated with Active Documents that support more than one view of their data.

When to Use

Use the IEnumOleDocumentViews interface to enumerate all the views supported by an Active Document. The usual procedure is to first call the IOleDocument::EnumViews method. If the Active Document supports only one view, IOleDocument::EnumViews obtains a pointer to that view. If the Active Document supports two or more views, IOleDocument::EnumViews obtains a pointer to IEnumOleDocumentViews. Using this pointer, the container can then ask the Active Document to enumerate the views it supports.

Methods in Vtable Order
Next | Retrieves a specified number of items in the enumeration sequence.
Skip | Skips over a specified number of items in the enumeration sequence.
Reset | Resets the enumeration sequence to the beginning.
Clone | Creates another enumerator that contains the same enumeration state as the current one.


IEnumOleDocumentViews::Clone

HRESULT Clone(
    IEnumOleDocumentViews ** ppenum);

Creates a separate view enumerator with the same state as the current enumerator, and that iterates over the same list. This makes it possible to record a point in the enumeration sequence and return to that point at a later time.

  • Returns S_OK if successful, or an OLE defined error code otherwise.
ppenum
[out] Address of the IEnumOleDocumentViews interface pointer that receives the newly created enumerator. The caller must release this enumerator separately from the original enumerator.


IEnumOleDocumentViews::Next

HRESULT Next(
    ULONG cViews,
    IOleDocumentView * rgpView,
    [out] ULONG * pcFetched);

Enumerates the next cViews elements in the enumerator's list, returning them in rgpView, along with the actual number of enumerated elements in pcFetched. The enumerator object is responsible for calling IUnknown::AddRef and the caller is responsible for calling IUnknown::Release on each pointer returned in rgpView.

  • Returns one of the following values:
    S_OK | The number of items requested in cViews is fetched.
    S_FALSE | Less than the number of items requested is fetched.
    OLE defined error code otherwise.
cViews
[in] Number of IOleDocumentView pointers to be written to the array pointed to by rgpView. If pcFetched is NULL, this argument must be 1.
rgpView
[out, max_is(cViews)] Address of an array of IOleDocumentView pointers that receive the enumerated interfaces. The caller is responsible for allocating this array, and the array must be able to contain at least the number of elements specified in cViews.
pcFetched
[out] Address of a ULONG variable that receives the actual number of views enumerated in the rgpView parameter. This argument can be NULL, in which case the cViews argument must be 1.

E_NOTIMPL is not allowed by this method as a return value. If an error value is returned, no entries in the rgpView array are valid and no calls to IUnknown::Release are required.


IEnumOleDocumentViews::Reset

HRESULT Reset(void);

Resets the enumeration sequence to the beginning of the list of elements. There is no guarantee that the same set of elements will be enumerated on each pass through the list: It depends on the collection being enumerated. It is too expensive for some collections, such as files in a directory, to maintain this condition.

  • Returns S_OK if successful, or an OLE defined error code otherwise.


IEnumOleDocumentViews::Skip

HRESULT Skip(
    ULONG cViews);

Skips over a number of elements, specified in the cViews parameter, in the enumeration so that the next call to the IEnumOleDocumentViews::Next method will not return those elements.

  • Returns one of the following values:
    S_OK | The number of items requested in cViews is skipped.
    S_FALSE | Less than the number of items requested is skipped.
    An OLE defined error code otherwise.
cViews
[in] Number of elements to skip in the enumeration.


Interfaces

This section describes the Active Document interfaces.
IContinueCallback
IEnumOleDocumentViews
IOleCommandTarget
IOleDocument
IOleDocumentSite
IOleDocumentView
IPrint


IOleCommandTarget

The IOleCommandTarget interface enables objects and their containers to determine if an object supports a command, to determine the status of a command, and to execute a command. For example, the container of an object can determine if the object supports the Paste command. If it does support the Paste command, the container can then determine if Paste can currently be executed. If the command can be executed, the container can use that information to enable its Paste command user interface. If the user selects Paste, the container can use this interface to execute the command on the object.

Normal in-place activation guidelines recommend that you remove or disable such buttons because no efficient, standard mechanism has been available to dispatch them to the container. Similarly, a container has heretofore had no efficient means to send commands such as Print, Page Setup, and Properties to an in-place active object. Such simple command routing could have been handled through existing OLE Automation standards and the IDispatch interface, but the overhead with IDispatch is more than is required in the case of Active Documents. The IOleCommandTarget interface provides a simpler means to achieve the same ends.

Available commands are defined by integer identifiers in a group. The group itself is identified with a GUID. The interface allows a caller both to query for support of one or more commands within a group and to issue a supported command to the object.

When to Implement

Implement IOleCommandTarget when your object supports one or more commands.

When to Use

Use IOleCommandTarget to determine the status of or execute a command implemented by an object.

Methods in Vtable Order
QueryStatus | Queries an object for status of commands.
Exec | Executes a command.


IOleCommandTarget::Exec

HRESULT Exec(
    const GUID *pguidCmdGroup,
    DWORD nCmdID,
    DWORD nCmdExecOpt,
    VARIANTARG *pvaIn,
    VARIANTARG *pvaOut
   );

Executes a specified command or displays help for a command.

  • Returns one of the following values:
    S_OK | Success.
    E_FAIL | The command failed.
    E_UNEXPECTED | The command was executed at a time when the object was not expecting the command.
    OLECMDERR_CANCELED | The user canceled the execution of the command.
    OLECMDERR_DISABLED | The command identified by nCmdID is currently disabled and cannot be executed.
    OLECMDERR_E_NOTSUPPORTED | The nCmdID parameter does not identify a valid command in the pguidCmdGroup group.
    OLECMDERR_E_UNKNOWNGROUP | The pguidCmdGroup parameter is not NULL but does not specify a recognized command group.
    OLECMDERR_NOHELP | The caller has asked for help on the command identified by nCmdID, but no help is available.
pguidCmdGroup
[unique][in] Address of a globally unique identifier (GUID) of the command group; can be NULL to specify the standard group.
nCmdID
[in] Identifier of the command to be executed. This command must belong to the group specified in the pguidCmdGroup parameter.
nCmdExecOpt
[in] Values taken from the OLECMDEXECOPT enumeration, which describes how the object should execute the command.
pvaIn
[unique][in] Address of a VARIANTARG structure containing input arguments. Can be NULL.
pvaOut
[unique][in,out] Address of a VARIANTARG structure to receive command output. Can be NULL.

The list of input and output arguments of a command and how they are packaged is unique to each command. Such information should be documented with the specification of the command group. (See the description of OLECMDID_ZOOM in the OLECMDID enumeration.) In the absence of any specific information, the command is assumed to take no arguments and have no return value.

Notes to Callers

The pguidCmdGroup and nCmdID parameters together uniquely identify the command to invoke. The nCmdExecOpt parameter specifies the exact action to be taken. (For more details, see the OLECMDEXECOPT enumeration.)

Most commands neither take arguments nor return values. For such commands, the caller can pass NULL in pvaIn and pvaOut. For commands that expect one or more input values, the caller can declare and initialize a VARIANTARG structure and pass a pointer to that structure in pvaIn. If the input to the command is a single value, the argument can be stored directly in the VARIANTARG structure and passed to the function. If the command expects multiple arguments, those arguments must be packaged appropriately within the VARIANTARG structure, using one of the supported variant types (such as the IDispatch interface or the SAFEARRAY data type).

If a command returns one or more arguments, the caller is expected to declare a VARIANTARG, initialize it to VT_EMPTY, and pass its address in pvaOut. If the command returns a single value, the object can store that value directly in pvaOut. If the command has multiple output values, it will package those in some way appropriate for the VARIANTARG.

Because pvaIn and pvaOut are both caller-allocated, stack variables are permitted for both the caller and the object receiving the call. For commands that take zero or one argument on input and return zero or one value, no additional memory allocation is necessary. Most of the types supported by VARIANTARG do not require memory allocation. Exceptions include SAFEARRAY and BSTR. For a complete list, see the OLE documentation in the Microsoft® Platform SDK.

Notes to Implementers

A command target must implement this function; E_NOTIMPL is not a valid return value.


IOleCommandTarget::QueryStatus

[input_sync] HRESULT QueryStatus(
    const GUID *pguidCmdGroup,
    ULONG cCmds,
    OLECMD *prgCmds,
    OLECMDTEXT *pCmdText
   );

Queries the object for the status of one or more commands generated by user interface events.

  • Returns one of the following values:
    S_OK | The command status and any optional strings were returned successfully.
    E_FAIL | The query failed.
    E_POINTER | The prgCmds argument is NULL.
    E_UNEXPECTED | The query was received at a time that the object was not expecting it.
    OLECMDERR_E_UNKNOWNGROUP | The pguidCmdGroup parameter is not NULL but does not specify a recognized command group.
pguidCmdGroup
[unique][in] Globally unique identifier of the command group; can be NULL to specify the standard group. All the commands that are passed in the prgCmds array must belong to the group specified by this parameter.
cCmds
[in] Number of commands in the prgCmds array.
prgCmds
[in,out] Caller-allocated array of OLECMD structures that indicates the commands for which the caller needs status information. This method fills the cmdf member of each structure with values taken from the OLECMDF enumeration.
pCmdText
[unique][in,out] Address of an OLECMDTEXT structure in which to return name and/or status information of a single command. Can be NULL to indicate that the caller does not need this information.

Callers use this method to determine which commands are supported by a target object. The caller can then disable unavailable commands that would otherwise be routed to the object. The caller can also use this method to get the name or status of a single command.

Notes to Callers

The caller passes an array of OLECMD structures in prgCmds that describes the commands of interest from the group specified in pguidCmdGroup, where each structure's cmdID member is set to a command identifier and the cmdf member is set to zero.

Notes to Implementers

The object receiving the call fills the cmdf member for each command with values taken from the OLECMDF enumeration to describe the status of each command.

The called object should first mark the command as described above. Then, if the command is supported (OLECMDF_SUPPORTED), the object should check the OLECMDTEXTF_ flags in the cmdtextf member of pCmdText. If the OLECMDTEXTF_NAME flag is specified, the object should copy the localized name of the command (for example, "Open", "Copy", and so on) into the rgwz member of pCmdText. Attention should be paid to the size specified by the cwBuf member of pCmdText.

If the caller sets the OLECMDTEXTF_STATUS flag, the object should instead write a localized status string for the command into the rgwz member. The status string is typically contextual and depends on the state of the command—enabled/disabled, for example. If the buffer is not big enough, the object should zero-terminate the buffer. Whether the buffer is big enough or not, the object must return the total actual size of the string that it attempted to copy in the cwActual member of pCmdText.

If the command array contains more than one command, the textual information should be returned for the first command in the array that the object supports. Typically, this functionality is used to show the status text of a command. The caller can use either a stack or a global variable for rgwz, because memory for this parameter is not dynamically allocated.

Because IOleCommandTarget::QueryStatus is defined with the [input_sync] attribute, the implementing object cannot yield or make another non-input_sync RPC call while executing it.

A command target must implement this function; E_NOTIMPL is not an acceptable return value.


IOleDocument

The IOleDocument interface enables an Active Document to communicate its ability to create views of its data to containers. This interface also enables an Active Document to enumerate its views and to provide containers with miscellaneous information about itself, such as whether it supports multiple views or complex rectangles.

When to Implement

An OLE document that is to be activated as an Active Document must, at the very least, implement this interface. If an application exposes more than one type of Active Document, each type must implement IOleDocument.

When to Use

An Active Document container calls the methods of this interface to ask an Active Document to create views of itself, enumerate the views it supports, or provide miscellaneous information about its capabilities.

Methods in Vtable Order
CreateView | Creates a new view object.
GetDocMiscStatus | Returns status information about the Active Document.
EnumViews | Enumerates views supported by the Active Document.


IOleDocument::CreateView

HRESULT CreateView(
    IOleInPlaceSite *pIPSite,
    IStream *pstm,
    DWORD dwReserved,
    IOleDocumentView **ppView
   );

Creates a document view object in the caller's process and obtains a pointer to that object's IOleDocumentView interface.

  • Returns one of the following values:
    S_OK | Success.
    E_FAIL | The view object creation failed.
    E_OUTOFMEMORY | There is not enough memory to create the view object.
    E_POINTER | The address in ppView is NULL.
    E_UNEXPECTED | The method was called at a time when the object was not expecting it.
pIPSite
[in] Address of the view site object to be associated with the new document view object. Can be NULL, as when the view is contained in a new, uninitialized Active Document, in which case the caller must initialize the view with a subsequent call to the IOleDocumentView::SetInPlaceSite method.
pstm
[in] Address of a stream containing data from which the new document view object should initialize itself. If NULL, the Active Document initializes the new document view object with a default state.
dwReserved
[in] Reserved for future use. Must be zero.
ppView
[out] Address of the IOleDocumentView interface pointer on the new document view object. If IOleDocument::CreateView succeeds, the caller is responsible for calling IUnknown::Release on this pointer when the view object is no longer needed.

See also IOleDocumentSite::ActivateMe, IOleDocumentView::ApplyViewState, IOleDocumentView::Show, IOleDocumentView::UIActivate


IOleDocument::EnumViews

HRESULT EnumViews(
    IEnumOleDocumentViews ** ppEnum,
    IOleDocumentView ** ppView
   );

Creates an object that enumerates the views supported by an Active Document, or, if only one view is supported, returns a pointer to that view.

  • Returns one the following values:
    S_OK | If the object supports multiple views, ppEnum contains a pointer to the enumerator object and the content of ppView is NULL. Otherwise, the content of ppEnum is NULL and ppView contains an interface pointer to the single view.
    E_OUTOFMEMORY | There is not enough memory available to create the object.
    E_POINTER | Either ppEnum or ppView is invalid. The caller must pass valid pointers for both parameters.
ppEnum
[out] Address of the IEnumOleDocumentViews interface pointer on the enumerator object.
ppView
[out] Address of the IOleDocumentView interface on a single view object.

If an Active Document supports multiple views of its data, it must also implement IEnumOleDocumentViews and place that interface's pointer in ppEnum. Using this pointer, the container can enumerate the views supported by the Active Document.

If the Active Document supports only a single view, IOleDocument::EnumViews places that view's IOleDocumentView pointer in ppView.

Notes to Callers

Call this method to determine if an Active Document supports more than one view of its data. If it does, the caller can use the pointer written to ppEnum to specify which view to activate. When finished with the pointer, the caller must free it by calling IUnknown::Release.

Notes to Implementers

This method must be completely implemented on all Active Documents; E_NOTIMPL is not an acceptable return value.


IOleDocument::GetDocMiscStatus

HRESULT GetDocMiscStatus(
    DWORD *pdwStatus
   );

Obtains information about whether an Active Document supports behaviors specified in the DOCMISC enumerator.

  • Returns S_OK if successful, or E_POINTER if the address in pdwStatus is NULL.
pdwStatus
[out] Address of the information on supported behaviors. Values written to the address specified by this pointer are taken from the DOCMISC enumeration.

This method provides a way for containers to ascertain whether an Active Document supports multiple views, complex rectangles, opening in a pop-up window, or file read/write.

Notes to Callers

By calling this method prior to activating an Active Document, containers can take whatever steps are necessary to support or otherwise accommodate specified behaviors.

Notes to Implementers

This method must be completely implemented in any Active Document, even if the dereferenced value of pdwStatus is zero. E_NOTIMPL is not an acceptable return value. Normally, the returned DOCMISC value should be hard-coded for performance.


IOleDocumentSite

The IOleDocumentSite interface enables a document that has been implemented as an Active Document to bypass the normal activation sequence for in-place active objects and to directly instruct its client site to activate it as an Active Document object. A client site with this ability is called a document site.

For each Active Document to be hosted, a container must provide a corresponding document site. This document site is an OLE Documents client site that, in addition to implementing the IOleClientSite and IAdviseSink interfaces, also implements IOleDocumentSite. Each document site implements a separate document view site object for each view of a document to be activated. The document view site implements IOleInPlaceSite and, optionally, IContinueCallback.

When to Implement

Implement IOleDocumentSite on each client site that is to host an Active Document. In addition to this interface, a document site must also implement the IOleClientSite, IOleInPlaceSite, and IAdviseSink interfaces. Implementing IContinueCallback is optional.

When to Use

An Active Document calls IOleDocumentSite::ActivateMe to ask its document site to activate it, typically in response to the container's call to IOleObject::DoVerb.

Methods in Vtable Order
ActivateMe Activates an Active Document.


IOleDocumentSite::ActivateMe

HRESULT ActivateMe(
    IOleDocumentView *pViewToActivate
    );

Asks a document site to activate the document making the call as an Active Document rather than an in-place active object. Optionally, specifies which view of the object document to activate.

  • Returns one of the following values:
    S_OK | Success.
    E_FAIL | The method was not successful.
    E_OUTOFMEMORY | There was not enough memory to complete the operation.
pViewToActivate
[in] Address of the document view to be used in activating the Active Document. Can be NULL, in which case the container should call IOleDocument::CreateView to obtain a document view pointer.

See also IOleClientSite, IOleDocumentView::SetInPlaceSite, IOleInPlaceSite, IOleObject::DoVerb


IOleDocumentView

The IOleDocumentView interface enables a container to communicate with each view supported by an Active Document.

An Active Document that supports multiple views of its data represents each view as a separate object. Each document view object implements IOleDocumentView, along with the IOleInPlaceObject and IOleInPlaceActiveObject interfaces, as well as optional interfaces such as IPrint and IOleCommandTarget. An Active Document that supports only a single view does not require that view to be implemented as a separate object. Instead, both document and view can be implemented as a single class.

When to Implement

All Active Documents must implement IOleDocumentView for each view they support. If an Active Document supports multiple views, each view must be implemented as a separate class object. If an Active Document supports only a single view, the Active Document and its view can both be implemented as a single class.

When to Use

A container calls the methods of this interface to activate, deactivate, close, and generally communicate with a document view object.

Methods in Vtable Order
SetInPlaceSite | Associates a container view site with this view.
GetInPlaceSite | Retrieves the view site associated with this view.
GetDocument | Obtains the IUnknown pointer of the Active Document that owns this view.
SetRect | Sets the coordinates of the view port.
GetRect | Retrieves the coordinates last passed in the SetRect method.
SetRectComplex | Sets the coordinates of the view port, scroll bars, and size box.
Show | In-place activates or deactivates a view.
UIActivate | In-place activates or deactivates a view's user-interface elements.
Open | Displays the view in a separate pop-up window.
CloseView | Instructs the view to close.
SaveViewState | Saves the view state into a stream.
ApplyViewState | Initializes the view with the view state previously saved in the call to the SaveViewState method.
Clone | Creates a duplicate view object.


IOleDocumentView::ApplyViewState

HRESULT ApplyViewState(
    IStream *pstm
   );

Initializes a view to a previously saved view state.

  • Returns one of the following values:
    S_OK | Success.
    E_NOTIMPL | This view has no meaningful state to load. This error should be rare because most views will have at least some state information worth loading.
    E_POINTER | The value in the pstm parameter is NULL.
pstm
[in] Address of a stream containing data from which the view should initialize itself.

Typically, this method is called after an existing view has been created in the container but before that view has been displayed. It is the responsibility of the view to validate the data in the view stream; the container does not attempt to interpret the view's state data.

See also IOleDocument::CreateView, IOleDocumentView::SaveViewState


IOleDocumentView::Clone

HRESULT Clone(
    IOleInPlaceSite *pIPSiteNew
    IOleDocumentView **ppViewNew
    );

Creates a duplicate view object with an internal state identical to that of the current view.

  • Returns one of the following values:
    S_OK | Success.
    E_FAIL | The method was not successful.
    E_NOTIMPL | The view object does not implement this interface.
    E_POINTER | The value in the ppViewNew parameter is NULL.
pIPSiteNew
[in] Address of the view site in which the new view object will be activated. On receiving this pointer, the view being cloned should pass it to the new view's IOleDocumentView::SetInPlaceSite method. This can be NULL, in which case the caller is responsible for calling IOleDocumentView::SetInPlaceSite on the new view directly.
ppViewNew
[out] Address of the IOleDocumentView interface pointer to the new view object. The caller is responsible for releasing this pointer when it is no longer needed.

This method is useful for creating a new view with a different view port and view site but with the same view context as the view being cloned. Typically, containers hosting a multiple document interface (MDI) application will call this method to provide "Window/New window" capability.


IOleDocumentView::CloseView

HRESULT CloseView(
    DWORD dwReserved
   );

Instructs a document view to close and release its IOleInPlaceSite pointer.

  • Returns S_OK if the view successfully closed, or an OLE defined error code otherwise.
dwReserved
Reserved; must be zero.

When a separate window is no longer needed, the container calls IOleDocumentView::CloseView, whereupon the view releases its site pointer to the separate window and destroys the window. Unlike the normal in-place deactivation sequence for in-place active objects, a document view continues to hold the IOleInPlaceSite pointer. This pointer is released only when the view's container calls IOleDocumentView::SetInPlaceSite, with the pIPSite parameter set to NULL, or calls IOleDocumentView::CloseView.

When a user closes a view's window, the view should not shut itself down. Instead, it should call IOleInPlaceSite::OnInPlaceActivate. The view site then decides whether to call IOleDocumentView::UIActivate with FALSE to UI-deactivate the view immediately or later. In this way, a document view displayed in a window remains available for activation in the container's own window.

The container must call this method before it deletes the view, that is, releases its last reference to the view. In general, implementation of this method will call IOleDocumentView::Show with FALSE to hide the view if it is not already hidden, then call IOleDocumentView::SetInPlaceSite with NULL and release the view site pointer.

Because IOleDocumentView::CloseView is called when a container is going to completely shut down a view, this method must be implemented and has no reason to fail.


IOleDocumentView::GetDocument

HRESULT GetDocument(
    IUnknown **ppunk
   );

Obtains the IUnknown interface pointer on the Active Document that owns this view.

  • Returns S_OK if successful. This is the only valid return value for this method.
ppunk
[out] Address of the IUnknown pointer of the Active Document that owns this view.

The caller is responsible for incrementing the reference count on the interface pointer obtained by this method. The caller must call IUnknown::Release on this pointer when it is no longer needed.

Because a view object must always be contained or aggregated in an Active Document, this method will always succeed. Before returning, this method should call IUnknown::AddRef on the pointer in the ppunk parameter.


IOleDocumentView::GetInPlaceSite

HRESULT GetInPlaceSite(
    IOleInPlaceSite **ppIPSite
   );

Retrieves the view site associated with this view object.

  • Returns S_OK if successful, or E_FAIL otherwise.
ppIPSite
[out] Address of the view site's IOleInPlaceSite interface pointer.

IOleDocumentView::GetInPlaceSite obtains the most recent IOleInPlaceSite pointer passed by IOleDocumentView::SetInPlaceSite, or NULL if IOleDocumentView::SetInPlaceSite has not yet been called. If this pointer is not NULL, this method will call IUnknown::AddRef on the pointer. The caller is responsible for releasing it. A document view must implement this method completely; E_NOTIMPL is not an acceptable return value.


IOleDocumentView::GetRect

HRESULT GetRect(
    LPRECT prcView
   );

Retrieves the rectangular coordinates of the view port in which the view is or will be activated.

  • Returns S_OK if successful, or E_UNEXPECTED if the view has not yet seen a call to IOleDocumentView::SetRect or IOleDocumentView::SetRectComplex and therefore has no rectangle to return.
prcView
[out] Address of a RECT structure that receives the coordinates of the current view port.

For a single document interface (SDI) application, the view port is the client area of the frame window minus the space allocated for toolbars, status bar, and such. For a multiple document interface (MDI) window, the view port is the client area of the MDI document window minus any other frame-level user-interface elements.

The view port coordinates obtained by this method are those set in the most recent call to either the IOleDocumentView::SetRect or IOleDocumentView::SetRectComplex method.

A document view must implement this method completely; E_NOTIMPL is not an acceptable return value.


IOleDocumentView::Open

HRESULT Open(Void);

Displays the view in a separate pop-up window. The result is similar to calling IOleObject::DoVerb with OLEIVERB_OPEN.

  • Returns one of the following values:
    S_OK | Success.
    E_FAIL | The method was not successful.
    E_NOTIMPL | The Active Document that owns this view does not support separate window activation.
    E_OUTOFMEMORY | There is not enough memory to complete this operation.
    E_UNEXPECTED | The method was called at a time when the view object was not expecting it.

A user viewing an Active Document in a container application such as a browser or binder might want to see two or more views or documents at once. Because the browser displays only one view at a time, the container needs a way to ask the other views or documents to display themselves, as required, in separate windows. The IOleDocumentView::Open method provides that way.

Notes to Callers

A successful call to IOleDocumentView::Open should be followed by a call to IOleDocumentView::Show to hide the window or to show the window and bring it to the foreground. While the view is active in its separate window, a container can show or hide the window as many times as it may require.

Notes to Implementers

An Active Document indicates that it does not support activation in a separate window by setting the DOCMISC_CANTOPENEDIT status flag and returning E_NOTIMPL to containers that call this method.

Implementation consists mainly of the view object calling its own IOleInPlaceObject::InPlaceDeactivate method, which leaves the Active Document in a running state but without in-place activation. The Active Document's user interface is not visible until the container calls IOleDocumentView::Show (see "Notes to Callers" above).

See also IOleDocumentView::CloseView, IOleDocumentView::UIActivate, IOleInPlaceSite, IOleInPlaceSite::OnInPlaceActivate


IOleDocumentView::SaveViewState

HRESULT SaveViewState(
    IStream *pstm
   );

Saves the view state into the specified stream.

  • Returns one of the following values:
    S_OK | Success.
    E_NOTIMPL | This view has no meaningful state to save.
    E_POINTER | The value in the pstm parameter is NULL.
pstm
[in] Address of the stream in which the view is to save its state data.

The E_NOTIMPL error should be rare because most views have at least some state information worth saving.

The view's state includes properties such as the view type, zoom factor, and location of insertion point. The container typically calls this function before deactivating the view. The stream can then later be used to reinitialize a view of the same document to this saved state through the IOleDocumentView::ApplyViewState method.

According to the rules governing the IPersistStream interface, a view must write its class identifier (CLSID) as the first element in the stream. Any cross-platform file format compatibility issues that apply to the document's storage representation also apply to this context.


IOleDocumentView::SetInPlaceSite

HRESULT SetInPlaceSite(
    IOleInPlaceSite * pIPSite
   );

Associates a container's document view site with a document's document view object.

  • Returns S_OK if successful, or E_FAIL otherwise.
pIPSite
[in] Address of the document view site's IOleInPlaceSite interface. Can be NULL, in which case the document view object loses all association with the container.

As part of activating an Active Document, a container must pass the object a pointer to the container's implementation of IOleInPlaceSite. This pointer designates the document view site that is to be associated with the view on which this method is called.

A container normally passes this pointer in response to a document's request to be activated. A document makes such a request by calling IOleDocumentSite::ActivateMe and passing the container a pointer to the view to be activated. The container, in turn, uses this pointer to call IOleDocumentView::SetInPlaceSite.

Notes to Callers

If the container is requesting creation and activation of a new instance of an Active Document, rather than merely the activation of a loaded instance of an Active Document, the view site is passed in the pIPSite argument of IOleDocument::CreateView. Therefore, an explicit call to IOleDocumentView::SetInPlaceSite is unnecessary.

Notes to Implementers

If this method is called on a view that is already associated with a view site, the view must do some housekeeping in preparation for activating itself in the new site. First, the view must deactivate itself in the current site and release its pointer to that site. Next, if the new IOleInPlaceSite pointer is not NULL, the view should both save the pointer and call IUnknown::AddRef on it. The view should then wait for the container to tell it when to activate itself in the new view site.

A document view must implement this method completely; E_NOTIMPL is not an acceptable return value.

See also IOleDocumentView::GetInPlaceSite


IOleDocumentView::SetRect

[input_sync] HRESULT SetRect(
    LPRECT prcView
   );

Sets the rectangular coordinates of the view port in which a view is to be activated, or resets the coordinates of the view port in which a view is currently activated.

  • Returns S_OK if successful, or E_FAIL otherwise.
prcView
[in] Address of a RECT structure containing the coordinates of the view port.

For a single document interface (SDI) application, the view port is the client area of the frame window minus the space allocated for toolbars, status bar, and such. For a multiple document interface (MDI) window, the view port is the client area of the MDI document window minus any other frame-level user-interface elements.

Notes to Callers

Calling IOleDocumentView::SetRect or IOleDocumentView::SetRectComplex is part of the normal activation sequence for Active Documents, usually following a call to IOleDocumentView::UIActivate and preceding a call to IOleDocumentView::Show.

Whenever the window used to display an Active Document is resized, the container should call IOleDocumentView::SetRect (or IOleDocumentView::SetRectComplex) to tell the document view object to resize itself to the new window dimensions.

Notes to Implementers

The coordinates of the view port are within the coordinates of the view window, which is obtained through IOleWindow::GetWindow. The view must resize itself to fit the new coordinates passed in the prcView parameter.

This method is defined with the [input_sync] attribute, which means that the view object cannot yield or make another, non-input_sync RPC call while executing this method.

A document view must implement this method completely; E_NOTIMPL is not an acceptable return value.


IOleDocumentView::SetRectComplex

[input_sync] HRESULT SetRectComplex(
    LPRECT prcView,
    LPRECT prcHScroll,
    LPRECT prcVScroll,
    LPRECT prcSizeBox
   );

Sets the rectangular coordinates of the view port, horizontal and vertical scroll bars, and the size box.

  • Returns one of the following values:
    S_OK | Success.
    E_FAIL | The method was not successful.
    E_NOTIMPL | The Active Document doesn't support complex rectangles.
prcView
[in] Address of a RECT structure containing the coordinates of the view port.
prcHScroll
[in] Address of a RECT structure containing the coordinates of the horizontal scroll bar.
prcVScroll
[in] Address of a RECT structure containing the coordinates of the vertical scroll bar.
prcSizeBox
[in] Address of a RECT structure containing the coordinates of the size box.

View frames that support a workbook metaphor, in which a single document comprises multiple sheets or pages, typically call this method to set the coordinates to be used in common by all the sheets or pages.

Notes to Callers

Calling IOleDocumentView::SetRectComplex is part of the normal activation sequence for Active Documents that support complex rectangles, usually following a call to IOleDocumentView::UIActivate and preceding a call to IOleDocumentView::Show.

Whenever the window used to display an Active Document is resized, the container should call IOleDocumentView::SetRectComplex or IOleDocumentView::SetRect to tell the view object to resize itself to the new window dimensions.

Notes to Implementers

Active Documents that support complex rectangles mark themselves with DOCMISC_SUPPORTCOMPLEXRECTANGLES, as described in DOCMISC and IOleDocument::GetDocMiscStatus. Active Documents that do not support this method can return E_NOTIMPL.

Upon receiving a call to this method, a view should resize itself to fit the coordinates specified in prcView and fit its scroll bars and size box to the areas described in prcHScroll, prcVScroll, and prcSizeBox.

This method is defined with the [input_sync] attribute, which means that the implementing object cannot yield or make another, non-input_sync RPC call while executing this method.


IOleDocumentView::Show

HRESULT Show(
    BOOL fShow
   );

Requests a view to show or hide itself, activating or deactivating itself as necessary.

  • Returns one of the following values:
    S_OK | Success.
    E_FAIL | The method was not successful.
    E_OUTOFMEMORY | There was not enough memory to complete this operation.
    E_UNEXPECTED | The method was called at an unexpected time. This is most likely due to the fact that the view object was not properly initialized before the Show method was called.
fShow
[in] If nonzero, the view is to in-place activate itself if necessary and show itself. If zero, the view is to UI-deactivate itself if necessary and hide itself.

Calling IOleDocumentView::Show is the last step in the activation sequence; before showing itself an Active Document must know exactly what space it occupies and have all its tools available.

Notes to Callers

A call to this method for the purpose of activating a view should follow calls to IOleDocumentView::SetInPlaceSite, IOleDocumentView::UIActivate, and IOleDocumentView::SetRect (or IOleDocumentView::SetRectComplex).

Notes to Implementers

Implementations of this method should embody the following pseudo-code.

if (fShow)
    {
    if(!fInPlaceActive)
        {
        //In-place activate the view but do not UI activate it.
        }

    //Show the view window.
    }
else
    {
    if(fUIActive)
        {
        //UI-deactivate the view.
        }

    //Hide the view window.
    }

All views of an Active Document must at least support in-place activation; E_NOTIMPL is not an acceptable return value.


IOleDocumentView::UIActivate

HRESULT UIActivate(
    BOOL fUIActivate
   );

Activates or deactivates a document view's user interface elements, such as menus, toolbars, and accelerators.

  • Returns one of the following values:
    S_OK | Success.
    E_FAIL | The method was not successful.
    E_OUTOFMEMORY | There was not enough memory to complete this operation.
    E_UNEXPECTED | The method was called at a time when it was not expected by the view object.
fUIActivate
[in] If TRUE, the view is to activate its user interface. If FALSE, the view is to deactivate its user interface.

Notes to Callers

Calling this method before calling IOleDocumentView::SetInPlaceSite returns E_UNEXPECTED, because the view must be associated with a view site before it can activate itself.

When IOleDocumentView::UIActivate is called as part of the activation sequence, the call should precede a call to IOleDocumentView::SetRect or IOleDocumentView::SetRectComplex, because otherwise the view dimensions would not account for toolbar space.

To deactivate a view, the container should call IOleDocumentView::Show with FALSE, followed by IOleDocumentView::UIActivate with FALSE.

Notes to Implementers

Implementations of this method should embody the following pseudo-code.

if (fActivate)
    {
    UI activate the view (do menu merging, show frame level tools, process accelerators)
    Take focus, and bring the view window forward.
    }
else
    call IOleInPlaceObject::UIDeactivate on this view

In addition, the view can and should participate in extended Help menu merging.

All views of an Active Document must support in-place activation. E_NOTIMPL is not an acceptable return value.


IPrint

The IPrint interface enables compound documents in general and Active Documents in particular to support programmatic printing. When a document is loaded, containers and other clients can call IPrint::Print to instruct a document to print itself, specifying printing control flags, the target device, the particular pages to print, and other options. The client can control the continuation of printing by calling the IContinueCallback interface.

An object that implements IPrint registers itself with the Printable key stored under its CLSID as follows:

HKEY_CLASSES_ROOT\CLSID\{...}\Printable

Callers determine whether a particular object class supports programmatic printing of its persistent state by looking in the registry for this key.

When to Implement

Implementing IPrint is optional. You usually implement IPrint on a view object.

When to Use

Call the methods of IPrint when you want an object to print its current state. Using this interface, a caller can tell the object to print itself, set the initial page number of the printed document, and obtain both the number of pages and the number of the first page to be printed.

Methods in Vtable Order
SetInitialPageNum | Sets the page number of the first page.
GetPageInfo | Retrieves the number of pages and the number of the first page.
Print | Prints the object's persistent state.


IPrint::GetPageInfo

HRESULT GetPageInfo(
    LONG *pnFirstPage,
    LONG *pcPages
   );

Retrieves the number of a document's first page and the total number of pages.

  • Returns S_OK if successful, or E_UNEXPECTED otherwise.
pnFirstPage
[out] Address of the page number of the first page. Can be NULL, indicating that the caller doesn't need this number. If the IPrint::SetInitialPageNum method has been called, this parameter should contain the same value passed to that method. Otherwise, the value is the document's internal first page number.
pcPages
[out] Address of the total number of pages in this document. Can be NULL, indicating that the caller doesn't need this number.


IPrint::Print

HRESULT Print(
    DWORD grfFlags,
    DVTARGETDEVICE **pptd,
    PAGESET **ppPageSet,
    STGMEDIUM *pstgmOptions,
    IContinueCallback *pCallback,
    LONG nFirstPage,
    LONG *pcPagesPrinted,
    LONG *pnLastPage
   );

Prints an object on the specified printer, using the specified job requirements.

  • Returns one of the following values:
    S_OK | Success.
    PRINT_E_CANCELED | Printing was canceled before the operation completed.
    PRINT_E_NOSUCHPAGE | A page specified in ppPageSet or nFirstPage does not exist.
    E_UNEXPECTED | The method was called when it was not expected by the object.
grfFlags
[in] Bit field specifying print options from the PRINTFLAG enumeration.
pptd
[in, out] Address of the target printing device.
ppPageSet
[in, out] Address of a PAGESET structure that indicates which pages are to be printed.
pstgmOptions
[unique][in, out] Address of object-specific printing options in a serialized OLE property set. Can be NULL on input or return.
pCallback
[in] Address of the IContinueCallback interface on the view site, which is to be periodically polled at human-response speeds to determine whether printing should be abandoned. Can be NULL.
nFirstPage
[in] Page number of the first page to be printed. This value overrides any value previously passed to the IPrint::SetInitialPageNum method.
pcPagesPrinted
[out] Address of the actual number of pages successfully printed.
pnLastPage
[out] Address of the page number of the last page printed.

The printer on which the object is to be printed is indicated by the DVTARGETDEVICE structure pointed to by pptd. The DEVMODE structure in the target device indicates whole-job printer-specific options, such as number of copies, paper size, and print quality. The DEVMODE structure can also contain orientation information in the dmOrientation member (this is indicated in the dmFields member). If present, this paper orientation should be used; if absent, natural orientation as determined by the object content is to be used.

Due to the possibility of user input, the parameters pptd and ppPageSet are both [in,out] structures. In the absence of user interaction (that is, if the PRINTFLAG_PROMPTUSER flag is not set), both the target device and the page set will necessarily be the same for input and output. However, if the user is prompted for print options, the object returns target device and page-set information appropriate to what the user has actually chosen.

The pstgmOptions parameter is also [in,out]. On exit, the object should write to pstgmOptions any object-specific information that it would need to reproduce this exact print job. Examples might include whether the user selected "sheet, notes, or both" in a spreadsheet application. The data passed is in the format of a serialized property set. The data is normally useful only when passed back in a subsequent call to the same object. Because a subsequent call might specify different user interaction flags, target device, or other settings, the caller can cause the document to be printed multiple times in the same way in slightly different printing contexts.


IPrint::SetInitialPageNum

HRESULT SetInitialPageNum(
    LONG nFirstPage
   );

Sets the number of the first page of a document.

  • Returns one of the following values:
    S_OK | Success.
    E_FAIL | The method was not successful.
    E_UNEXPECTED | The method was called when the object was not expecting it.
nFirstPage
[in] Desired number of the first page.

Setting the first page to a negative number is valid. This can be useful in printing a portion of the document with page numbers that specify an offset from the usual pagination.

Not all implementations permit the initial page number to be set, as some implementations simply lack the information as to how the page number should be presented in the final output.


OLECMD

typedef struct _tagOLECMD
{
    ULONG cmdID;
    DWORD cmdf;
}OLECMDF;

Associates command flags from the OLECMDF enumeration with a command identifier through a call to the IOleCommandTarget::QueryStatus method.

cmdID
Command identifier; taken from the OLECMDID enumeration.
cmdf
Flags associated with cmdID; taken from the OLECMDF enumeration.


OLECMDEXECOPT

typedef enum
{
    OLECMDEXECOPT_DODEFAULT      =  0,
    OLECMDEXECOPT_PROMPTUSER     =  1,
    OLECMDEXECOPT_DONTPROMPTUSER =  2,
    OLECMDEXECOPT_SHOWHELP       =  3
} OLECMDEXECOPT;

Specifies command execution options. One value from this enumeration is passed in the nCmdExecOpt parameter of the IOleCommandTarget::Exec method.

OLECMDEXECOPT_DODEFAULT
Use the default behavior, whether prompting the user for input or not.
OLECMDEXECOPT_PROMPTUSER
Execute the command after obtaining user input.
OLECMDEXECOPT_DONTPROMPTUSER
Execute the command without prompting the user. For example, clicking the Print toolbar button causes a document to be immediately printed without user input.
OLECMDEXECOPT_SHOWHELP
Show help for the corresponding command, but do not actually execute the command.


OLECMDF

typedef enum
{
    OLECMDF_SUPPORTED   =  1,
    OLECMDF_ENABLED     =  2,
    OLECMDF_LATCHED     =  4,
    OLECMDF_NINCHED     =  8
} OLECMDF;

Designates the type of support provided by an object for the command specified in an OLECMD structure.

OLECMDF_SUPPORTED
Command is supported by this object.
OLECMDF_ENABLED
Command is available and enabled.
OLECMDF_LATCHED
Command is an on-off toggle and is currently on.
OLECMDF_NINCHED
Reserved for future use.

Values from the OLECMDF enumeration are used to fill the value of the cmdf member of OLECMD structures passed to the IOleCommandTarget::QueryStatus method.


OLECMDID

typedef enum
{
     OLECMDID_OPEN               =  1,
     OLECMDID_NEW                =  2,
     OLECMDID_SAVE               =  3,
     OLECMDID_SAVEAS             =  4,
     OLECMDID_SAVECOPYAS         =  5,
     OLECMDID_PRINT              =  6,
     OLECMDID_PRINTPREVIEW       =  7,
     OLECMDID_PAGESETUP          =  8,
     OLECMDID_SPELL              =  9,
     OLECMDID_PROPERTIES         = 10,
     OLECMDID_CUT                = 11,
     OLECMDID_COPY               = 12,
     OLECMDID_PASTE              = 13,
     OLECMDID_PASTESPECIAL       = 14,
     OLECMDID_UNDO               = 15,
     OLECMDID_REDO               = 16,
     OLECMDID_SELECTALL          = 17,
     OLECMDID_CLEARSELECTION     = 18,
     OLECMDID_ZOOM               = 19,
     OLECMDID_GETZOOMRANGE       = 20
     OLECMDID_UPDATECOMMANDS     = 21
     OLECMDID_REFRESH            = 22
     OLECMDID_STOP               = 23
     OLECMDID_HIDETOOLBARS       = 24
     OLECMDID_SETPROGRESSMAX     = 25
     OLECMDID_SETPROGRESSPOS     = 26
     OLECMDID_SETPROGRESSTEXT    = 27
     OLECMDID_SETTITLE           = 28
     OLECMDID_SETDOWNLOADSTATE   = 29
     OLECMDID_STOPDOWNLOAD       = 30
     OLECMDID_ONTOOLBARACTIVATED = 31,
     OLECMDID_FIND               = 32,
     OLECMDID_DELETE             = 33,
     OLECMDID_HTTPEQUIV          = 34,
     OLECMDID_HTTPEQUIV_DONE     = 35,
     OLECMDID_ENABLE_INTERACTION = 36,
     OLECMDID_ONUNLOAD           = 37
} OLECMDID;

Specifies which command to execute. (The commands in this enumeration are the standard commands defined by Microsoft® Office 95.) A single value from this enumeration is passed in the nCmdID parameter of the IOleCommandTarget::Exec method.

OLECMDID_OPEN
File menu, Open command.
OLECMDID_NEW
File menu, New command.
OLECMDID_SAVE
File menu, Save command.
OLECMDID_SAVEAS
File menu, Save As command.
OLECMDID_SAVECOPYAS
File menu, Save Copy As command.
OLECMDID_PRINT
File menu, Print command.
OLECMDID_PRINTPREVIEW
File menu, Print Preview command.
OLECMDID_PAGESETUP
File menu, Page Setup command.
OLECMDID_SPELL
Tools menu, Spelling command.
OLECMDID_PROPERTIES
File menu, Properties command.
OLECMDID_CUT
Edit menu, Cut command.
OLECMDID_COPY
Edit menu, Copy command.
OLECMDID_PASTE
Edit menu, Paste command.
OLECMDID_PASTESPECIAL
Edit menu, Paste Special command.
OLECMDID_UNDO
Edit menu, Undo command.
OLECMDID_REDO
Edit menu, Redo command.
OLECMDID_SELECTALL
Edit menu, Select All command.
OLECMDID_CLEARSELECTION
Edit menu, Clear command.
OLECMDID_ZOOM
View menu, Zoom command (see below for details).
OLECMDID_GETZOOMRANGE
Retrieves zoom range applicable to View Zoom (see below for details).
OLECMDID_UPDATECOMMANDS
Informs the receiver, usually a frame, of state changes. The receiver can then query the status of the commands whenever convenient.
OLECMDID_REFRESH
Asks the receiver to refresh its display. Implemented by the document/object.
OLECMDID_STOP
Stops all current processing. Implemented by the document/object.
OLECMDID_HIDETOOLBARS
View menu, Toolbars command. Implemented by the document/object to hide its toolbars.
OLECMDID_SETPROGRESSMAX
Sets the maximum value of a progress indicator if one is owned by the receiving object, usually a frame. The minimum value is always zero.
OLECMDID_SETPROGRESSPOS
Sets the current value of a progress indicator if one is owned by the receiving object, usually a frame.
OLECMDID_SETPROGRESSTEXT
Sets the text contained in a progress indicator if one is owned by the receiving object, usually a frame. If the receiver currently has no progress indicator, this text should be displayed in the status bar (if one exists) as with the IOleInPlaceFrame::SetStatusText method.
OLECMDID_SETTITLE
Sets the title bar text of the receiving object, usually a frame.
OLECMDID_SETDOWNLOADSTATE
Sent by the object when its download state changes. Takes a VT_BOOL parameter, which is TRUE if the object is downloading data or FALSE if it is not.
OLECMDID_STOPDOWNLOAD
Stops the download when executed. Typically, this command is propagated to all contained objects. When queried, sets MSOCMDF_ENABLED. Implemented by the document/object.
OLECMDID_ONTOOLBARACTIVATED
Notifies the object that one of the container's toolbars has received the focus. The object should UI-deactivate any child objects, hide any selection, and set an internal flag. The object should reset this flag when the object gets notified that it or one of its child objects or toolbars has received the focus. While this flag is set, the object should call the container's IOleCommandTarget::QueryStatus method to determine the state of edit items (cut, copy, and paste) and call the container's IOleCommandTarget::Exec method to forward any edit commands to the container. If the object has edit items in its toolbars or menus, they should also be enabled or disabled according to the container's IOleCommandTarget::QueryStatus results. The container's IOleCommandTarget interface can be retrieved by calling the container's QueryInterface method, requesting IID_IOleCommandTarget.
OLECMDID_FIND
Not currently implemented.
OLECMDID_DELETE
TBD.
OLECMDID_HTTPEQUIV
Sent from the Active Document to the container when the parser finds a META HTTP-EQUIV tag in the document. Takes a VT_BSTR parameter that contains the parameter to the META tag, which is equivalent to an HTTP header. The Active Document can send this command more than once, but must send OLECMDID_HTTPEQUIV_DONE after all the META HTTP-EQUIV tags are processed.
OLECMDID_HTTPEQUIV_DONE
Sent from the Active Document to the container when there are no other META HTTP-EQUIV tags in the document. The Active Document must send this command after sending one or more OLECMDID_HTTPEQUIV commands.
OLECMDID_ENABLE_INTERACTION
Sent by the container to tell the object to either pause or resume any multimedia (audio or animation) in the document. Takes a VT_BOOL parameter, which is TRUE if the multimedia should be resumed or FALSE if it should be paused. The Internet Explorer 4.0 browser uses this command to inform the object of when it is minimized or completely covered by another window so that the object can pause playing of multimedia information.
OLECMDID_ONUNLOAD
Sent by the browser before a new navigation is initiated or the browser is being closed. This provides the opportunity for a document to query the user if any unsaved data should be saved. Returning S_OK allows the navigation to close. Returning S_FALSE prevents the operation. This command is sent only once. Because navigation is asynchronous, it is important to remember that the user can make changes in a page or document after this command is received but before the new page is displayed.

In OLE compound documents technology, an object that is being edited in-place disables the Zoom control on its toolbar and the Zoom command on its View menu, because the Zoom command applies logically to the container document, not to the object. The OLECMDID_ZOOM and OLECMDID_GETZOOMRANGE commands notify the container's frame object of the zoom range it should use to display an Active Document in its user interface. The container frame is the client-side object that implements IOleInPlaceFrame and, optionally, IOleCommandTarget.

The OLECMDID_ZOOM command takes one LONG argument as input and writes one LONG argument on output. This command is used for three purposes:

  • To query the current zoom value. The caller of IOleCommandTarget::Exec passes OLECMDEXECOPT_DONTPROMPTUSER as the execute option in the nCmdExecOpt parameter and NULL for pvaIn. The object returns the current zoom value in pvaOut. When the object goes UI active, it retrieves the current zoom value from the container's frame object using this same mechanism and updates its zoom control with the returned value.
  • To display the Zoom dialog box. The caller of IOleCommandTarget::Exec passes OLECMDEXECOPT_PROMPTUSER in nCmdExecOpt. The caller can optionally pass the initial value for the dialog box through pvaIn; otherwise pvaIn must be NULL. If the user clicks Cancel, the object returns OLECMDERR_E_CANCELED. If the user clicks OK, the object passes the user-selected value in pvaOut. When the user chooses the Zoom command from the View menu, the object calls the container's frame object in the same manner. The container then zooms the document to the user-selected value, and the object updates its Zoom control with that value.
  • To set a Zoom value. The caller of IOleCommandTarget::Exec passes OLECMDEXECOPT_DONTPROMPTUSER in nCmdExecOpt and passes the zoom value to apply through pvaIn. The object validates and normalizes the new value and returns the validated value in pvaOut. When the user selects a new zoom value (using the Zoom control on the toolbar, for instance), the object calls the container's frame object in this manner. The container zooms the document to 100 percent, and the object updates the Zoom control with that value.

The OLECMDID_GETZOOMRANGE command is used to determine the range of valid zoom values from an object that implements IOleCommandTarget. The caller passes MSOCMDEXECOPT_DONTPROMPTUSER in nCmdExecOpt and NULL for pvaIn. The object returns its zoom range as a DWORD in pvaOut, where the HIWORD contains the maximum zoom value and the LOWORD contains the minimum zoom value. Typically this command is used when the user drops down the Zoom control on the toolbar of the UI-active object. The applications and objects that support this command are required to support all the integral zoom values that are within the (min,max) pair they return.


OLECMDTEXT

typedef struct _tagOLECMDTEXT
{
    DWORD cmdtextf;
    ULONG cwActual;
    ULONG cwBuf;
    wchar_t rgwz[1];
}OLECMDTEXT;

Specifies a text name or status string for a single command identifier. This structure is used with the IOleCommandTarget::QueryStatus method.

cmdtextf
Value from the OLECMDTEXTF enumeration describing whether the rgwz member contains a command name or status text.
cwActual
Number of characters actually written into the rgwz buffer before IOleCommandTarget::QueryStatus returns.
cwBuf
Number of elements in the rgwz buffer.
rgwz
Caller-allocated wide character buffer to receive the command name or status text.


OLECMDTEXTF

typedef enum
{
    OLECMDTEXTF_NONE   =  0,
    OLECMDTEXTF_NAME   =  1,
    OLECMDTEXTF_STATUS =  2
} OLECMDTEXTF;

Specifies the type of information that an object should store in the OLECMDTEXT structure passed in the IOleCommandTarget::QueryStatus method. One value from this enumeration is stored in the cmdtextf member of the OLECMDTEXT structure to indicate the desired information.

OLECMDTEXTF_NONE
No extra information is requested.
OLECMDTEXTF_NAME
Object should provide the localized name of the command.
OLECMDTEXTF_STATUS
Object should provide a localized status string for the command.


PAGERANGE

typedef struct tagPAGERANGE
{
    LONG nFromPage;
    LONG nToPage;
}PAGERANGE;

Specifies a range of pages. The arrays contained in the rgPages member of the PAGESET structure are PAGERANGE structures.

nFromPage
First page of the range. This member can have any page number as a value. If this value is greater than the value specified in the nToPage member, the document will be printed in reverse page order.
nToPage
Last page of the range. A special value, PAGESET_TOLASTPAGE, indicates that all the remaining pages should be printed. This member can have any page number as a value. If this value is less than the value specified in the nFromPage member, the document will be printed in reverse page order.


PAGESET

typedef struct tagPAGESET
{
    ULONG cbStruct;
    BOOL fOddPages;
    BOOL fEvenPages;
    ULONG cPageRange;
    [size_is(cPageRange)] PAGERANGE rgPages[]
}PAGESET;

Identifies one or more page ranges to be printed and, optionally, identifies only the even or odd pages as part of a page set.

cbStruct
Number of bytes in this instance of the PAGESET structure. Must be a multiple of 4.
fOddPages
If TRUE, only the odd-numbered pages in the page set indicated by the rgPages member are to be printed.
fEvenPages
If TRUE, only the even-numbered pages in the page set indicated by the rgPages member are to be printed.
cPageRange
Number of page-range pairs specified in rgPages.
rgPages
Address of an array of PAGERANGE structures specifying the pages to be printed. One or more page ranges can be specified, as long as the number of page ranges is the value of the cPageRange member. The page ranges must be sorted in ascending order and must be nonoverlapping.


PRINTFLAG

typedef enum
{
    PRINTFLAG_MAYBOTHERUSER         =  1,
    PRINTFLAG_PROMPTUSER            =  2,
    PRINTFLAG_USERMAYCHANGEPRINTER  =  4,
    PRINTFLAG_RECOMPOSETODEVICE     =  8,
    PRINTFLAG_DONTACTUALLYPRINT     = 16,
    PRINTFLAG_FORCEPROPERTIES       = 32,
    PRINTFLAG_PRINTTOFILE           = 64
} PRINTFLAG;

Specifies printing options. A combination of values from PRINTFLAG is passed in the grfFlags parameter of IPrint::Print.

PRINTFLAG_MAYBOTHERUSER
User interaction is permitted. If this flag is not set, no part of the printing process can interact with the user.
PRINTFLAG_PROMPTUSER
Object should prompt the user for job-specific printing options, using the normal print dialog for the object. Support for this option is required. Valid only if PRINTFLAG_MAYBOTHERUSER is set.
PRINTFLAG_USERMAYCHANGEPRINTER
User can change the target printer. If this flag is not set, the user can print only on the default printer. Valid only if PRINTFLAG_PROMPTUSER is set.
PRINTFLAG_RECOMPOSETODEVICE
Object should attempt to recompose itself to the indicated target device. If this flag is not set, the object should, if possible, retain any association that it already has with a compositional device.
PRINTFLAG_DONTACTUALLYPRINT
Object should carry out actions resulting from user actions or object recomposition, but it should not actually carry out the printing operation.
PRINTFLAG_FORCEPROPERTIES
Object should always display the print properties dialog box.
PRINTFLAG_PRINTTOFILE
Object should print to the file that is named in the portname member of the DVTARGETDEVICE structure.


Reference

This reference provides complete and detailed information on all the programming elements used with Active Document servers and containers.

Interfaces

Structures

Enumerations


Structures

This section describes the Active Document structures.
OLECMD
OLECMDTEXT
PAGERANGE
PAGESET


Standard Internet-Aware Objects

As a benefit to control developers, Microsoft will supply Internet-Aware picture, sound, and video objects that will make dealing with these data formats in the Internet environment a non-issue for many controls. The existing picture object, for example, makes a control's manipulation of a bitmap, metafile, or icon nearly effortless. The additional objects described here aim to do the same for their respective data types, where all standard objects will support the ability to retrieve large data BLOBs in an asynchronous manner.

A function called OleLoadPicturePath became available in the final version of Microsoft Internet Explorer 3.0. OLELoadPicturePath takes a moniker and a bind context (which the control retrieves from IBindHost) and will take care of the details of downloading the picture. In return, OLELoadPicturePath provides an IPicture interface pointer that is identical to the standard picture object that already exists. The control can simply call IPicture::Render to draw the image.

The exact specifications for other picture object enhancements and other standard objects are not available at this time. The design may be done along the lines of a "data type" architecture so that new objects supporting other data types can be added in the same manner. In addition, the architecture may support plug-in "player" objects that extend the usable formats for each data type object. For example, a standard picture object would probably support formats like BMP, DIB, Metafile, Icon, GIF, and JPEG natively. Individual "players" could be then plugged into this picture object for supporting other formats like TIFF, PCX, or other proprietary formats. As each player would be a COM object in itself, controls could take advantage of any "code download" technology for these players.


Internet Awareness for Objects, Controls, and Containers

The following documents, which are referenced in text using shortened names, contain information relevant to COM Objects:
Full name | Referenced as
Asynchronous Moniker Design Specification | Asynchronous Monikers
Component Categories | Component Categories
Compound Files on the Internet | Internet Files
OLE Control and Control Container Guidelines v2.0 | Control Guidelines
URL Monikers | URL Monikers


COM Objects for the Internet

This document offers solutions for making a control work well in the Internet environment, with the ultimate goal of delivering optimal quality of service to users. Because browser speed is one of the primary factors in users' perception of quality, this document aims to provide solutions that allow an HTML document or page to become visible as soon as possible and interactive very shortly thereafter, while allowing controls to retrieve large data blocks in the background.

Internet Awareness for Objects, Controls, and Containers

Introduction and Requirements

Control Instantiation

Storage of Control Persistent Data

Data Path Properties

Cooperative and Asynchronous Data Retrieval

Communicating Control "Readiness"

Other Considerations

Summary

Standard Internet-Aware Objects

Interface Reference


Control Instantiation

How does a container bring control class code (binary executable code) into memory and instantiate a control of that class? There are two relevant scenarios:

  1. The control's class code is on the client machine already (or somewhere in the name space addressable through the registry on that machine). Therefore, the document only needs the CLSID of that class code because COM/OLE provides mapping from CLSID to code bits using the registry. A container generally creates a control directly using the CLSID with CoCreateInstance.
  2. The control's class code is located somewhere other than on the client machine, possibly on another Internet site, and must be brought to the client machine before a control of that class can be instantiated. The exact details of this "Code Download" scenario will be described in a future specification.

This document only concerns itself with scenario 1 above, because the purpose of "code download" described in scenario 2 is to install a control on the client machine so that scenario 1 works.

The next three sections describe the issues for instantiation at author, publish, and run time.

Author Time Instantiation

A designer of a document or page will use the user interface functionality of the authoring tool to decide which object or control to insert into a document, ultimately ending up with a CLSID for the object or control. The authoring tool is responsible for providing the browsing capabilities to locate objects and controls wherever they may be, in the local name space or on some other Web location. For more information on standards related to browsing available object and control classes, see the user interface guidelines.

Once a control's CLSID is known, the authoring tool simply uses standard COM/OLE instantiation (using CoCreateInstance, OleCreate, and so on) to instantiate the control. In this case, the authoring tool will need to include the control's CLSID when saving the document persistently. Handling other possibilities is still under consideration.

In other respects, the authoring tool treats each control instance in exactly the same manner: calling methods, setting properties, attaching event handlers, specifying layout, and so on.

Saving a Control at Publish Time

At publish time, the authoring tool must create a document, in HTML or another format, that describes the exact source of each control's class code, because it will be referenced at run time, in addition to each control's instance data.

If the code is assumed to be on the client machine along with the browser, the authoring tool need only store the CLSID for the control class (the CLASSID attribute in HTML) in addition to the control's properties and persistent data, as described below. Such would be the assumption for standard system-provided control classes as well as implementations that the document will manage in its own code repository (part of a future specification).

If the control's class code will be found at another Internet site at run time, the authoring tool must save the URL for that site. This can be done by saving the URL text directly (as the CODE attribute in HTML).

If the document incorporates custom control classes that are on the author's machine at publish time, but may not be on each client machine at run time, the authoring tool must facilitate the placement of the class code (according to license restrictions) on an appropriate Internet site, converting the CLSIDs of the control instances in the document into the appropriate monikers and then saving the monikers in the document.

In addition to each control instance (CLSID/moniker and the control's instance data), the authoring tool, at publish time, also saves its own "extended properties," which a control instance itself never deals with, such as Name, Width, Height, Align, and so on. Documents stored in their own formats use whatever data formats they want; documents saved in HTML must follow the guidelines described in HTML Standards.

Run-Time Instantiation

An Internet browsing tool, when it wants to view a document, will generally activate the necessary viewer for that document type, which may be itself (in HTML cases, for instance) or some other view through DocObjects. The viewer then loads the document, recreating the control instances therein according to the prioritization scheme determined at author time.

"Recreating a control" means creating a previously saved instance of a control so that some persistent data for that control exists in the document or somewhere else. In the OLE model, instance data always has an associated CLSID—thus, the container knows which class code it must have to instantiate an uninitialized control using the CLSID directly ( CoCreateInstance, OleLoadFromStream, and so on). Once the container creates that instance, it initializes the instance with whatever persistent data was previously saved through the Load member of some IPersist* interface. A section below covers exactly where this persistent data comes from and which interfaces are involved.

In some cases, the class code for a control and its instance data resides in other locations named with monikers (or URLs, which can be turned into URL monikers as is the case with the CODE attribute in HTML). In this case, the container must first retrieve the control's class code and then proceed with creation and initialization as described above.

As with initial creation, the container now has an interface pointer to an initialized control that is generally ready for use (depending on the internal state of the control as discussed in a later section). At this time, a container may have other properties in its storage that lay outside the control's own persistent image (such as PARAM fields in HTML). In that case, it sends these property values to the control after the control has returned from IPersist*::Load.


Communicating Control "Readiness"

For all persistence interfaces other than IPersistMoniker, the authoring tool or container assumes that once IPersist*::Load returns, the control has loaded all of its properties. However, controls that use data paths may not actually have all of their data at this time. That is, within IPersistStreamInit::Load, for instance, a control might load a data path property for an AVI file and begin an asynchronous retrieval of that AVI data before returning from Load as shown in an earlier section.

When data is coming in asynchronously like this, the control may not necessarily be ready to handle all requests the container might make of it. Accordingly, the control may return E_PENDING from some interface member functions. The next section describes the use of E_PENDING.

In addition, certain user-supplied code, in a container like Visual Basic for example, may want to take action on the current "readiness" state of a control, such as enabling or disabling one control based on the ability of another control to accept certain calls. The second section below describes a standard property, ReadyState, that reflects this aspect of a control, and a standard event, OnReadyStateChange, that informs the container that the state has changed. Because the ReadyState property is primarily of interest to user-supplied code, this standard event is used instead of IPropertyNotifySink::OnChanged to make the event visible in programming tools, and to pass the new ReadyState value along with the event.

Use of E_PENDING

In the lifetime of any particular control that uses data paths, there are generally four (possibly five) distinct states of readiness that a control may have:
State | Description
Uninitialized | The control is waiting to be initialized through. IPersist*::Load.
Loading | The control is initializing itself through one or more asynchronous properties. Some property values may not be available.
Loaded/Can-Render | The control has returned from IPersist*::Load so that all its properties are available and it has started any asynchronous data transfers. The control's properties are available and it is ready to draw at least something through IViewObject2::Draw. Making properties available doesn't necessarily require the control's type information.
Interactive | The control is capable of interacting with the user in at least some limited sense and can supply its type information. Full interaction may not be available until all asynchronous data arrives.
Complete | The control is completely ready for all requests.

These states are listed in order of priority, which is to say that a control should strive to makes its properties and some basic rendering capabilities available as soon as it can (even if the rendering is to just draw a rectangle with text in it) before going on to become interactive and before being able to fulfill requests that depend on asynchronous data.

From the point in time when a control is first instantiated, certain interface members may return E_PENDING to indicate that the control has not retrieved enough data yet to carry out the request (note that all interfaces must be available through QueryInterface although none of their members may do anything yet). To understand the implications, it is useful to step through the moments in time during the loading of a document and the creation and initialization of the controls in that document.

  1. (NonExistent!): The container has loaded the document but has not yet instantiated any control. At this point, the container can display the document with nothing but rectangle placeholders for each visible control. That is, because no controls are yet loaded, the container cannot call IViewObject2::Draw for any of them, and must rely on cached information (extent, label, and so on) to render anything for a control.
  2. Unintiailized: The container has loaded a control, but the control is completely uninitialized—that is, the container has not yet called IPersist*::Load. The control must be loaded first before the container can expect to call any other interface member. If the container wishes to draw an image for the control, it must do so itself using any cached information (like a caption string).
  3. Loading: A control has returned from IPersist*::Load and is making properties available as they arrive. The control must be capable of rendering something minimal (like a rectangle and text) through IViewObject2::Draw and should give priority to retrieving its Caption and Text properties first, followed by rendering-related properties ( BackColor, ForeColor, DrawStyle, and so on)
  4. Loaded/Can-Render: The control has returned from a call to IPersist*::Load so that it has loaded its properties (or a control that was Loading has now retrieved all its immediate properties). At this point, the control must be prepared to at least render something minimal (like a rectangle and text) through IViewObject2::Draw. In simple cases, like a button, the control will already have all its data necessary for rendering such as colors, text, font, and styles.
  5. Interactive: The control has enough information to be mostly interactive: it can be in-place activated (and perform layout negotiation), handle all property operations, accept user input, and so on. The control also has its type information available. In addition, progressively higher detailed renderings (or other streamed data) may be coming into the control at this point so that the control sends IAdviseSink::OnViewChange notifications to tell the container that the control should be redrawn (that is, if the control doesn't have a window; if it has a window, it just redraws when it wants to).
  6. Complete: The control has loaded all of its data including that obtained through paths so that it can do more sophisticated renderings using possibly medium- and high-detail graphics.

During each state other than Complete, various interface member functions may not be operative; that is, they will return E_PENDING, and certain properties may not be available. The following table describes which interfaces and methods must be ready in each of these states, if the control supports those interfaces at all.
State | Required Interfaces/Members/Properties
Uninitialized | IPersist*::Load and IPersist*::InitNew
Loading | IViewObject2::Draw, Idispatch::Invoke for some properties.
Loaded/Can-Render | All of IviewObject2, Idispatch::Invoke for all properties that don't depend on extra data.
Interactive | All of Idispatch (methods and type information), all of IRunnableObject, IOleObject, IOleInPlaceObject (and IOleInPlaceActiveObject), IProvideClassInfo2, IspecifyPropertyPages, IDataObject, IOleControl, IconnectionPointContainer, and IConnectionPoint, with the exception of any operation that depends on asynchronous data that is not yet available, such as IDataObject::GetData for certain formats.
Complete | Everything is ready including other members of rest of IPersist*.

Obviously, this puts a some burden on a control, which needs to maintain one or more "readiness" flags that are checked on entry to various interface members so that the function returns E_PENDING if the flag says "not ready." The more distinct states the control chooses to support, the more complex this will become internally; however, the container doesn't need to differentiate these states: it simply handles E_PENDING by providing some default action of its own where appropriate, then trying the operation again later.

In other words, these states are not something that the container has to internally maintain—they are simply a guide to how a control implementation should be structured to work best in the Internet environment.

Many controls will never have occasion to differentiate between Loaded and Interactive because nearly all simple controls have data dependencies for becoming interactive. The differentiation between the states is made here because some controls with data paths may not be ready for Interactive until at least some data is received asynchronously. Nevertheless, a control should attempt to become interactive as soon as possible.

The OnReadyStateChange Event and ReadyState Property

How does a container know when any given control is ready to render itself, can be interactive with the user, or has completely retrieved all its necessary data for full operation? That is, how does a container know the "readiness" state of a control?

A simple scenario demonstrates the need for the container to have such knowledge. Imagine that you have a form on which there is a video control and a "Play" button that calls the Play method in the video control. The video control has a VideoPath property set to some URL. When this form is first opened, the video control will not have any data that it will play, so the container will want to disable the "Play" button immediately. When the video control is asked to load itself, it will load its embedded and begin an asynchronous transfer of its AVI file. When the transfer is complete, the container will want to enable the Play button.

More precisely, user code will pick up some event from the video control and use that event to enable the button (the container would not generally be hardcoded to do this). In addition, user code outside of a change event may need to know the current readiness state of a control.

For the purposes described here, readiness is defined as one of the following values, each of which corresponds to one of the states described in the previous section:

enum
    {
    READYSTATE_UNINITIALIZED=0, //Never used except as default initialization. state
    READYSTATE_LOADING=1,       //Control is currently loading its properties
    READYSTATE_LOADED=2,        //Control has been initialized via IPersist*::Load.
    READYSTATE_INTERACTIVE=3,   //Control is interactive but not all data is available.
    READYSTATE_COMPLETE=4       //Control has all its data.
    }

Again, the "loading" state is only used for controls that are initializing themselves asynchronously through IPeristMoniker::Load. Otherwise, controls begin with READYSTATE_LOADED.

A control makes its current state available through the standard ReadyState property (DISPID_READYSTATE, of type long). Until a control is initialized with IPersist*::Load, the value of this property is undefined (and unavailable, because the control is not ready at all). When a control has loaded its properties, the property must be at least READYSTATE_LOADED. In many cases, the control will not differentiate between loaded and interactive; in that case, the control is interactive immediately and this property reflects at least READYSTATE_INTERACTIVE. In addition, some controls do not differentiate between "loaded" and any other state (such as buttons that load all their properties and have no external data to retrieve); in that case, the property should always be READYSTATE_COMPLETE. A control need not support the ReadyState property at all; in that case, the container always assumes READYSTATE_COMPLETE.

When a control differentiates at least two of these states, it must notify the container of the state transition with the standard control event called OnReadyStateChange (DISPID_ONREADYSTATECHANGE), which has the following prototype:

[id(DISPID_ONREADYCHANGE)]
        void OnReadyStateChange(long lReadyState);

The state flag passed with this event is one of the READYSTATE_* flags shown above. The general meaning of these states was described in the last section, but to make use of the event, the programmer must understand—from the control's documentation—what methods and properties or other features of the control are available in any given state. In our example, the video control might not say it's "interactive" until it has at least some of its data, and its definition of "complete" might mean that it's ready to play. On the other hand, a graphical hyperlink control might describe itself as "interactive" as soon as it's loaded, because it can receive user input and then only send the "complete" state when it has actually retrieved all of its graphics.

Because this event is designed for use in user code, the programmer is responsible for understanding what each particular state means for whatever control might be sending it. In the video example, the programmer has read that the video's Play method is not available until the ready state is "complete"; in that case, the Visual Basic code enables the "Play" button on READYSTATE_COMPLETE only:

Private Sub video1.OnReadyStateChange(ReadyState as Long)

    if ReadyState=READYSTATE_COMPLETE
        buttonPlay.Enabled=TRUE

End Sub

Controls that do not differentiate between all the states can simply choose to send only the appropriate ones, such as READYSTATE_COMPLETE, if the control is completely ready as soon as it's loaded. Sending "complete" implies that the control has already passed through "loaded" and "interactive." Sending "interactive" implies that "loaded" has already passed but "complete" has not been reached. Again, because user code is what's generally interested in this event, the programmer is assumed to understand any particular control's behavior with this event. User code should not depend on all three states being sent explicitly.

Of course, any control that may not be ready to receive certain requests still has to protect itself in case a container makes some request that the control cannot yet fulfill. In that case the control returns E_PENDING from the interface member function.


Cooperative and Asynchronous Data Retrieval

Once a control has a moniker for a data path property, it will eventually want to call that moniker's IMoniker::BindToStorage to retrieve an interface pointer through which the control can retrieve data (or write it as described in the next section).

To deliver optimal quality of service to browser users, a control must read data from an external source in a cooperative manner as much as possible. That is to say, the control should support reading linked data in an asynchronous manner, paying attention to container prioritization and allowing the container to participate in the transfer as it wants. To provide the container with authority over the binding operation, the control should use the IBindHost::MonikerBindToStorage and IBindHost::MonikerBindToObject member functions to bind to any moniker.

A control will first, of course, check whether the moniker it obtained from the container is, in fact, an asynchronous moniker at all by querying it for IMonikerAsync (see Asynchronous Monikers, which specified this interface as an alias for IUnknown). If this interface is not present, the moniker is synchronous and the control does not need to create an IBindStatusCallback callback interface to receive asynchronous notifications from the moniker bind operaion.

If the moniker is asynchronous, the control operates as any other client of such a moniker does, by creating an IBindStatusCallback callback interface for asynchronous download, as described in the document Asynchronous Moniker. The specific requirement for a control is that instead of binding to its moniker directly, it should bind to the moniker through its container, through IBindHost::MonikerBindToStorage or IBindHost::MonikerBindToObject. This call gives the container a chance to register any callbacks or other bits in the bind operation as desired. For example, a container that wishes to watch the progress of the transfer through IBindStatusCallback::OnProgress will register its own callback for the bind operation, paying attention to OnProgress callbacks and delegating all other callbacks to the control that initiated the bind operation.

If the container does not implement IBindHost, the control can always bind to its moniker(s) directly through IMoniker::BindToStorage and IMoniker::BindToObject. These should only be used in degenerate cases when there is no IBindHost present.

A control passes its IBindStatusCallback to its container directly through IBindHost::BindToXXX. However, if the control wishes to participate in format negotiation (for example, HTTP), it must create a bind context and register its FORMATETC enumerator on this bind context before calling IBindHost::BindToXXX. When a control initiates an asynchronous transfer for a data path, usually within IPersist*::Load, it should always obtain the data through IBindStatusCallback::OnDataAvailable exclusively. This is so the control can immediately release the moniker and the bind context and return immediately from IPersist*::Load so that the container can continue processing. Such code inside IPersistStreamInit::Load where another asynchronous stream is obtained, for example, would appear as follows:

HRESULT CImpIPersistStream::Load(IStream *pstm)
   {
    IMoniker *pmkPath;
    IStream  *pstmAsync;
    IBindCtx *pbc;

    /*
     * Load properties with pstm->Read, which is either blocking or synchronous.
     * Assume that one property is a path moniker, which we re-create with
     * OleLoadFromStream into pmkPath.
     *
     * Also, assume that m_pbsc is our IBindStatusCallback implementation, and
     * m_pEnumFE is our FORMATETC enumerator.
     */

    //pIBindHost is a pointer to the container's IbindHost.
    CreateAsyncBindCtx(0, NULL, m_pEnumFE, &pbc);
    pIBindHost->MonikerBindToStorage(pmkPath, pbc, m_pbsc, IID_IStream, &pstmAsync);

    //Do this only for async monikers.
    if (NULL!=pstm)
        pstmAsync->Release();

    pbc->Release();
    pmkPath->Release();

    //Data shows up in IBindStatusCallback::OnDataAvailable.

    return S_OK;
    }

When retrieving data, the path moniker that names the external storage location is either synchronous or asynchronous. If the moniker used in binding is a synchronous moniker, read calls from the control will effectively block the execution thread as is expected—this is how the OLE programming model already works with regards to moniker binding.

Of course, an object that does not want to block and can return E_PENDING as necessary from some of its interface members (see below) may elect to perform the otherwise blocking read operations in another thread, thereby allowing the original thread to continue. This still allows IPersist*::Load to return right away without waiting for the data to arrive.

The tricky part in handling asynchronous data is communicating the control's "readiness" state (including E_PENDING return codes). These topics are covered in later in this document.

Aborting a Data Transfer

Any control that is currently reading or writing data in an asynchronous manner must pay attention to IBindStatusCallback::OnStopBinding. If the control has all its data already, this notification merely says that the transfer is complete. If the control has not received all its data, the transfer was aborted for some other reason—perhaps the container scrolled the object out of view and stopped the transfers itself.

The control itself can call IBinding::Abort if it needs to stop the transfer for some reason. The control receives the IBinding pointer through IBindStatusCallback::OnStartBinding and must save it for later use. One such use is for handling the case where a container destroys a control while a transfer is underway—the control has to stop the transfer as part of its destruction procedure.

Also, if a container or authoring tool assigns a new value to a path property while the control is currently retrieving data asynchronously for that path, the control must stop the transfer through IBinding::Abort as soon as is reasonable and save the new path value.

Because a control cannot predict exactly how and when one or more data transfers will be aborted, it must be careful where reentrancy is concerned, especially inside the implementation of IBindStatusCallback::OnStopBinding (but in all other members as well). That is, the control should maintain an internal state machine to protect itself from operations that occur during or after an aborted transfer.

Transfer Priority

As the container owns the "document" as a whole, the container establishes which control will be given the right to transfer data first, second, and so on. When multiple transfers are going on at the same time, a container can control the relative priority of each transfer through its own implementations of IBindStatusCallback, which are used to control each bind operation (as managed through IBindHost::MonikerBindToXXX). A container can establish its desired relative priority in IBindStatusCallback::GetPriority. Once the transfer begins and the callbacks receive IBindStatusCallback::OnStartBinding, the container will have the IBinding interface through which it can set the priority there as well. Controls should not interfere with this process.

Controls that use WinINet or Sockets Directly

There are a certain class of controls that may want to bypass the mechanisms of the URL moniker to retrieve bits for some data path directly from the network through a transport layer like WinInet or Sockets. In such cases, the control is not willing to call IBindHost::MonikerBindToStorage, but instead wants to use the absolute URL directly.

To accomplish this, the control still asks the container for the full moniker in the first place because this step is necessary to resolve any relative path names. Once the control has the moniker, it can retrieve the full URL simply by calling IMoniker::GetDisplayName.

Object Persistence and Path Properties

When a control is asked to save its persistent data through some IPersist*::Save call, it is being asked to save its properties, including its current path properties and the BLOBs in the locations specified with those path properties. That is, once the control has saved its properties into the storage appropriate for the IPersist* interface in use, it also synchronously saves its BLOBs by obtaining the moniker for the path property from the container as described in a later section, calling IMoniker::BindToStorage with the container's bind context, and writing data to the storage obtained earlier. When IPersist*::Save returns, the object has completely written any data it needed to save.

A control should save its path property values as strings, not as monikers. In short, a control should simply save whatever values are assigned to its data path properties (as opposed to serializing any monikers that might have been created using these strings).

Container Flexibility in Moniker Choice

The discussion in the previous section made no stipulations as to what class of moniker must be assigned to any path property. This is intentional: a container can instruct a control to store its persistent data in any location of the container's choosing, as long as the container can create a path name that, when turned into a moniker, references the exact piece of storage that the control needs to load. In the case of creating a complex Web site, most of these monikers will be URL monikers. But there are many other moniker classes that can be used effectively, such as File monikers, generic composite monikers, or even custom monikers.

This design, therefore, allows the container full flexibility in choosing storage locations, depending on the authoring state of the document. At author time, the container (generally at the author's request) may choose to keep the persistent data of all controls embedded in the document. In this case, the container merely passes each control a name identifying some location in the document or on the local file system, such as a single Item moniker or a File moniker. The container then provides the necessary binding support for whatever moniker it supplies through IBindHost::CreateMoniker. In the case where the authoring tool has the data stored in the document itself, supplying a File Item moniker to the control means that the control's call to IBindHost::MonikerBindToStorage returns very quickly.

At publish time, the container may then choose to break whatever portions of control data it desires out of the document, saving that data in other locations and reassigning paths. Because the container will have some idea of the size of each control's persistent data, it may choose to leave some of that data embedded in the document anyway, leaving the controls concerned with simple File Item monikers (and such). If the container moves some data to other Web sites, it would create URL monikers for those sites and assign them the path properties of the appropriate controls. As far as the control is concerned, the data has moved, but the data is still named with some moniker. The control continues to use the same IBindHost::MonikerBindToStorage code that it did before.

What is important to understand here is that the control never has to distinguish between author-time and publish/run-time differences as far as its data path storage is concerned. The control always has some moniker naming its persistent data store(s), and always calls IBindHost::MonikerBindToStorage in all circumstances. This maintains a single programming model across all document modes, while still giving the container complete flexibility in choose storage locations and how the data in the document is distributed.

Exposing Path Properties from Nested Controls

Some controls, regardless of whether they themselves use any path properties, may contain other nested controls that do use such paths. Nevertheless, an authoring tool will want to construct a list of all paths used by all controls, regardless of the level of nesting involved. This facilitates site management—the authoring tool can examine all external data references from the top-level document and correct the paths involved if the site is being relocated.

Any control that itself uses one or more path properties need only expose those properties as described in earlier sections. Those controls that themselves contain other controls must expose those nested controls so that an authoring tool can check the path properties in those controls as well.

For this reason, a containing control must implement IOleContainer [note that the containing control might also choose to implement IOleItemContainer as well (which is derived from IOleContainer) to allow easier navigation to a particular control given the control's name] with the following behavior:
Member Function | Behavior
Iunknown members | Implemented as usual.
ParseDisplayName | Returns E_NOTIMPL.
LockContainer | Returns E_NOTIMPL.
EnumObjects | Returns an IEnumUnknown enumerator through which the caller can retrieve the IUnknown pointers for each nested control.

Given this behavior, the top-level container or authoring tool that wishes to examine all path properties in all controls, regardless of the nesting level, uses IProvideClassInfo::GetClassInfo to retrieve the control's type information and then uses the same procedures described earlier to build a list of the control's dispIDs that each correspond to some data path property. The caller can retrieve this property value, examine it, and modify it as necessary. This procedure is summarized in the following pseudo-code:

//In top-level container
construct IEnumUnknown for all top-level controls in pEnum
FindAllPaths(pEnum)
//Done

function FindAllPaths(IEnumUnknown *pEnum)
    }
    IUnknown *pObj;

    while (SUCCEEDED(pEnum->Next(&pObj)))
        {
        call IProvideClassInfo::GetClassInfo or obtain coclass type information via type lib

        if (SUCCEEDED(ITypeInfo2::GetCustData) and value is greater than zero)
            {
            iterate over properties
                {
                for each path property
                    {
                    examine the path
                    update/modify the path as necessary
                    }
                }

            ITypeInfo2::Release();
            }

        if (SUCCEEDED(pObj->QueryInterface(IID_IOleContainer, &pCont)))
            {
            pCont->EnumObjects(&pEnumNested)

            if (NULL!=pEnumNested)
                FindAllPaths(pEnumNested)

            pCont->Release();
            }

        pObj->Release();
        }
    }

Through this process, the top-level container can examine all path properties in use in the document. It is unlikely that this will be a seriously expensive operation in all except the most complex documents. Typically, there will only be a handful of controls on a page with any path properties at all, and even fewer containing controls with a significant number of nested controls. Second, third, fourth, and deeper levels of nesting will be exceptionally rare, so implementing this scheme with a recursive code structure will not be expensive in probably ninety percent of all situations.

What is described here for a containing control does not apply to controls that internally use some kind of helper object as a supporting component. In such cases, the helper object is not a "nested control"—it is merely a provider of a useful service. The control that is using the helper should not consider itself a "containing control" because it does not implement the necessary container-side services that would be necessary to nest an actual control.


Other Considerations

Component Categories for Describing Internet-Aware Objects

In all the various features defined in this document, there are various useful categories for describing what a object requires from its container as well as what features an object supports, which is useful in a container's browsing UI. The following tables describe the meaning for various categories as both "implemented" and "required" categories:
"Required" Categories | Description
CATID_PersistsToMoniker, CATID_PersistsToStreamInit, CATID_PersistsToStream, CATID_PersistsToStorage, CATID_PersistsToMemory, CATID_PersistsToFile, CATID_PersistsToPropertyBag | Each of these categories are mutually exclusive and are only used when an object supports only one persistence mechanism at all (hence, the mutual exclusion). Containers that do not support the persistence mechanism described by one of these categories should prevent themselves from creating an object of classes so marked.
CATID_RequiresDataPathHost | The object requires the ability to save data to one or more paths and requires container involvement, therefore requiring container support for IbindHost.
"Implemented" Categories | Description
CATID_PersistsToMoniker, CATID_PersistsToStreamInit, CATID_PersistsToStream, CATID_PersistsToStorage, CATID_PersistsToMemory, CATID_PersistsToFile, CATID_PersistsToPropertyBag | Object supports the corresponding IPersist*mmechanism for the category.
CATID_InternetAware | The object is "Internet-aware" meaning that the object needs no special behavior to work well in the Internet environment, or the object uses large data sets but is written to retrieve that data asynchronously. In addition, all "Internet-aware" objects are marked with OLEMISC_SETCLIENTSITEFIRST. This category is defined to aid authoring tools differentiate between objects that may or may not understand the special implications of the Internet.

The following table provides the exact CATIDs assigned to each category:
Category | CATID
CATID_RequiresDataPathHost | 0de86a50-2baa-11cf-a229-00aa003d7352
CATID_PersistsToMoniker | 0de86a51-2baa-11cf-a229-00aa003d7352
CATID_PersistsToStorage | 0de86a52-2baa-11cf-a229-00aa003d7352
CATID_PersistsToStreamInit | 0de86a53-2baa-11cf-a229-00aa003d7352
CATID_PersistsToStream | 0de86a54-2baa-11cf-a229-00aa003d7352
CATID_PersistsToMemory | 0de86a55-2baa-11cf-a229-00aa003d7352
CATID_PersistsToFile | 0de86a56-2baa-11cf-a229-00aa003d7352
CATID_PersistsToPropertyBag | 0de86a57-2baa-11cf-a229-00aa003d7352
CATID_InternetAware | 0de86a58-2baa-11cf-a229-00aa003d7352

For more information on categories, see the Component Categories document.


Data Path Properties

The impetus for much of the work in this document finds its origins in the concept of "progressive rendering" ("progressive disclosure") for something like a picture or a picture control. In such cases, the picture should be able to display an initial low-detail picture, followed by mid-detail and high-detail renderings.

This document is, however, concerned with the more general problem of retrieving any significant amounts of data in a cooperative fashion from possibly many distributed locations after the control has already been instantiated and is possibly interacting with the container and the user in other ways. This capability has been called "Progressive Rendering," "Progressive Property Disclosure," and "Progressive Downloading." The term "Progressive Data Retrieval" will be used to refer to all of these more special cases at once, because it makes no assumptions about the exact type of data that is being retrieved—for example, it might be properties, might be images, might be anything.

In all the following sections, it is very important to keep in mind that the control is ultimately responsible for specifying the exact format and structure of any linked data and decides exactly how it will be pulled from the named source. The container has nothing to do with this other than being able to control the relative priority of the retrieval and being notified when the loading state of a control changes. So, for example, a container doesn't have to care about how a picture control chooses to progressively render low-, mid-, and high-detail images (from a GIF, for instance). The picture control would internally know where and how each image is stored in its data, and retrieve those in turn. The container would then be notified through IAdviseSink::OnViewChange when the control has enough data to do something meaningful in IViewObject2::Draw (which is a moot point for an in-place active control whose window is visible because the control would just update itself, but this will be important later on for windowless controls).

The point of all this is that the container chooses where to tell controls to store and retrieve their data; the controls choose how to store and retrieve that data in a cooperative, asynchronous, and progressive manner. The asynchronous aspect may apply to none, some, or all of a control's data.

This section is, thus, about "Data Path Properties," and describes the architecture for having a control save and load pieces of its data (BLOBs especially) in locations other than where the control's properties are kept. That is, for any number of reasons, it may be inappropriate or impossible for a control to store absolutely all of its data in the same location as its properties. Here are some examples:

  • The control is being embedded and its BLOB data is too large to store in an embedded manner, such as in an HTML document.
  • The control wants to retrieve BLOBs in an asynchronous manner regardless of where the control's properties are stored. A video control is a good example where this would be important.
  • The control may be sharing BLOBs with other controls so it is inappropriate and/or wasteful to duplicate the BLOB in each control's persistent state (this is similar to the original linking concept in OLE Documents). Sharing a company logo across many Web pages is a good example, and excellent performance can be achieved in this case when a URL cache is in operation—the BLOB itself may have already been downloaded from another page and can simply be pulled from the cache immediately.
  • The control may want to allow BLOBs to be modified so that whenever the control retrieves the data, it can retrieve the most recent information. A weather-map control that always shows the latest satellite image is a good example.
  • The control may simply want to separate properties from BLOBs for its own reasons.

To address these particular concerns, a control may use one or more "Data Path Properties" to reference external sources of data. As shown in the following illustration, each "path" (as they're called for short) is a value of some kind that is stored like any other properties in the control's persistent data. When the control needs to retrieve data from a source, it has the container create a moniker from the string representation of the property value and calls IMoniker::BindToStorage to retrieve some sort of storage pointer (usually IStream, but not limited to that). In binding a URL moniker, the control can choose whether the binding itself will be synchronous or asynchronous, and whether or not the data transfer itself will be synchronous or asynchronous.

Figure 4: Data Path Properties are values which can be parsed into monikers that reference sources of data external to the control's embedded properties

In short, each path property is a control-managed "link" to an outside data source. As described in an earlier section, this capability has always been available in OLE Documents, except that such links were always internal to the control. Such hidden use of external resources is not acceptable in the Internet environment where authoring tools need to manage the interconnections between many Internet sites.

Data Path Properties address the following issues:

  • How to expose the existence of path properties from a control.
  • How to specify exactly what type of data a particular path should refer to so that an authoring tool can provide appropriate browsing UI or automatically assign a path property referring to the correct format of data.
  • How to assign values to path properties, which may occur through either the authoring tool (automatically or manually) or the control itself (manually through its own property pages).
  • How to save each path property in the control's persistent data.
  • How to cooperatively retrieve data referred to with a path property ,which might include container participation.
  • How to communicate a control's "readiness" to a container at run time so that the container can manage dependencies on the control's internal state.

Linking capabilities using path properties are equally usable in both the Persistent Embedding and Persistent Linking cases as described in an earlier section. For clarity, the combinations of Persistent Embedding and Persistent Linking with Data Path Properties are shown in the following illustrations.

Figure 5: A control that uses data paths is embedded in a document, but each path references an external source of data

Figure 6: A control that uses data paths is linked to a document and itself contains addition paths that reference external sources of data

With data paths, a control can allow its persistent data to be distributed around a file system or the Internet. For example, a sophisticated motion-picture control may separately reference its AVI data, its audio data, and a lengthy text transcript of the dialogue. The control could then have MoviePath, AudioPath, and TranscriptPath properties. In a similar manner, a picture control might store three separate detail images and use the properties LowDetailImagePath, MediumDetailImagePath, and HighDetailImagePath (and maybe the motion picture control uses these three as well to provide progressive rendering of a static image—anything is possible). This document places no restrictions on the exact data formats stored in locations given to path properties—the control ultimately determines the formats it can employ.

The following sections provide information about data path properties, starting with how a control exposes its path properties and the data formats associated with those paths. This is followed with a discussion of how path values are assigned, how a control saves a path property, and how a control uses a property to retrieve data asynchronously. A later section describes how the control communicates its "readiness" to a container and how the container handles different readiness states.

Exposing Data Path Properties and Corresponding Data Format

The following characteristics apply to publicly exposed path properties and controls that provide them:

  1. A path property can be a property of any type, most commonly a BSTR (allowing easy manipulation through Microsoft®Visual Basic® code such as MyObj.TranscriptPath), but other types are allowed, such as IUnknown or IDispatch. Choice of the exact property type is the decision of the control developer.
  2. All path properties regardless of type are tagged with a special custom attribute GUID that identifies the property as being a "path." This simplifies the process for an authoring tool to find path properties with a quick check through the control's type information. This standard GUID is defined as GUID_PathProperty with the value of {0002DE80-0000-0000-C000-000000000046}.
  3. The custom attribute described in 2 can express one or more MIME type values to describe the actual data type that this path should reference. The syntax is the same as that for the Accept: fields of HTTP headers (see below, and see the HTTP specification for complete information).
  4. A path property can be assigned any dispID that the control developer sees fit.
  5. A control marks each path property with the [bindable] attribute. This is because a container may allow path assignment through its own user interface and may be displaying path properties in its own property browser. [bindable] is, thus, necessary to keep the property browser synchronized with the control's state. With this attribute, the control must call IPropertyNotifySink methods if the container has connected an implementation of that sink interface through the control's connection points. Controls can choose to mark path properties as [requestedit] and [displaybind], if desired, but these are not requirements.
  6. The control's coclass entry in its type information is tagged with another special custom attribute GUID that specifies "this control has one or more path properties." This standard GUID is defined as GUID_HasPathProperties with the value {0002DE81-0000-0000-C000-000000000046}. The value of this attribute is the number of path properties that exist in the control. This attribute thus allows authoring tools to quickly and efficiently determine if a control has path properties at all and quickly describes how many path properties exist.

The HTTP Accept: syntax is summarized as follows:

    <field>  =    Accept: <entry> *[ , <entry>
    <entry>  =    <content type> *[ ; <param> ]
    <param>  =    <attr> = <float>
    <attr>   =    q / mxs / mxb
    <float>  =    <ANSI-C floating point text representation>

as in:

Accept: text/plain, text/html, image/*
Accept: text/x-dvi; q=.8; mxb=100000; mxt=5.0, text/x-c

A "custom attribute" as now supported in type information is defined using the keyword custom with a (GUID, value) pair as arguments for the attribute. This is shown in the following example:

#define GUID_PathProperty 0002DE80-0000-0000-C000-000000000046

[id(1), bindable, displaybind, propget, custom(GUID_PathProperty
    , "text/plain; q=0.5, text/html, text/*")]
    BSTR TranscriptPath(void);

This defines the BSTR property TranscriptPath as a path property with the types of plain text, HTML text, and other text (using HTTP Accept: syntax). This information is retrieved from the type information through the new type library interface ITypeInfo2 as described in the next section.

As an example of defining path properties in this way, consider a control that has an AVI MoviePath property, a RIFF AudioPath property, and an ANSI text TranscriptPath property that would include them in its type library this way (in ODL syntax; exact MIME types have been omitted because the code below is demonstrating the definition of multiple properties):

#define GUID_PathProperty      0002DE80-0000-0000-C000-000000000046
#define GUID_HasPathProperties 0002DE81-0000-0000-C000-000000000046

[<attributes>]
library
    {
    importlib <path to header that includes GUID_PropertyPath and GUID_HasPathProperties>

    [<attributes>]
    interface IMyObjectProperties
        {
        //Other stuff here...

        [id(1), bindable, displaybind, propget, custom(GUID_PathProperty, "...")]
            BSTR MoviePath(void);

        [id(1), bindable, displaybind, propput, custom(GUID_PathProperty, "...")]
            void MoviePath([in] BSTR pathVideo);

        [id(2), bindable, propget, custom(GUID_PathProperty, "...")]
            BSTR AudioPath(void);

        [id(2), bindable, propput, custom(GUID_PathProperty, "...")]
            void AudioPath([in] BSTR pathAudio);

        [id(3), bindable, propget, custom(GUID_PathProperty, "...")]
            BSTR TranscriptPath(void);

        [id(3), bindable, propput, custom(GUID_PathProperty, "...")]
            void TranscriptPath([in] BSTR pathText);

        //Other stuff here...
        }

    [<other attributes>, custom(GUID_HasPathProperties, "3")]
    coclass MyObject
        {
        interface IMyObjectProperties;
        ...
        }

    }

Author-Time Discovery of Path Properties

Authoring tools and other containers will want to know exactly which control properties are, in fact, data path properties as well as the type of data that should be referenced through each property. This allows the authoring tool to effectively enumerate data paths and retrieve their current values, which is useful when the authoring tool needs to update any such properties to perform link management.

First, to determine if any particular control has any path properties, the authoring tool should perform the following actions:

  1. Retrieve the control's type information for its coclass either through IProvideClassInfo::GetClassInfo or from the type library directly. These methods result in an ITypeInfo interface for that part of the type library.
  2. Call ITypeInfo::QueryInterface(IID_ITypeInfo2, &pITypeInfo2) to retrieve the interface necessary to read custom attributes. If this interface does not exist, the container has to assume that no path properties exist.
  3. Call pITypeInfo2->GetCustData(GUID_HasPathProperties, &va) to retrieve the value of the custom attribute into the VARIANT in va. If this function fails, or if the value in va is empty or zero, the control has no path properties.

Having this knowledge in hand, the authoring tool can then enumerate the properties in any of the control's incoming interfaces and check if those properties are data paths using the following procedure. These steps assume that pTI2 is the ITypeinfo2 pointer to one of the control's interface or dispinterface entries (available through the ITypeInfo of the control's coclass):

  1. Get the count of the functions in the interface using pTI2->GetTypeAttr which returns a TYPEATTR whose cFuncs field has the number of function. Call pTI2->ReleaseTypeAttr when finished.
  2. Iterate in a for loop where the index counter ( index) begins at zero and counts to cFuncs-1 (cFuncs is from step 1) through the functions.
  3. For each function, call pTI2->GetFuncCustData(index, GUID_PathProperty, &va) to attempt to read the custom path property attribute's value into the VARIANT va.
  4. If the GetFuncCustData call fails, or if the contents of va are empty, this property is not a data path. On success, the property is a data path and the value in va will be the description of the MIME type.
  5. To determine the dispID of the property, call pTI2->GetFuncDesc and look in the FUNCDESC structure for the memid field, which is the dispID. Be sure to call pTI2->ReleaseFuncDesc when done with the FUNCDESC structure.
  6. For optimization purposes, one can count the number of path properties found so far and exit the loop early if that number matches the value that was read from the GUID_HasPathProperties in the steps used to determine if the control had any paths.
  7. Once the loop is complete, the authoring tool will have a list of dispIDs (which may have some duplicates) for all the control's data path properties. The authoring tool can use pTI2->GetNames with these dispIDs to retrieve text names for those properties.

What then does a tool do with such knowledge of paths and their data types? There are three general scenarios:

  1. If the authoring tool is interactive, it might be able to display the data browsing UI based on the data format associated with any given path property. That is, if the tool knows that a path property uses the MIME type given in the value of the GUID_PathProperty attribute and that tool has a UI that can browse for that type, the tool can enable a "..." button in its property browser UI that invokes a File/Open type of dialog box when pressed. The user then selects a file and the name of that data file is assigned to the path property.
  2. If the authoring tool is automatic, it uses other available information (for example, a data repository) to determine the source of any particular piece of data. Knowing the format that the control needs for a data path allows such a tool to find some appropriate data, create a path name for it, and assign that name to the control.
  3. When the authoring tool publishes a document to an Internet site, it will want to check for any dependencies on outside data—that is, it will want to check for any control properties that reference data outside the document. The authoring tool can then check whether that path will be valid at run time and if not, it can choose to relocate the data to an accessible location and assign a new path to the control before saving that control. This is necessary, for example, when a control references a file on the local file system when the document is being placed on an Internet site.

Of course, the sophistication of the authoring tool is almost limitless. With the tagging and MIME-typing of data path properties, this document guarantees that any such tool can always determine the data format associated with a path. It's then a matter of whether the tool recognizes that GUID.

Assigning Path Properties

The values of path properties—the strings that identify storage locations—are assumed to be assigned only at author-time. In this case there are two possibilities:

  1. The authoring tool obtains the name from the user or creates it automatically, assigning it to the control through a "set property" operation (through a dispinterface or dual interface depending on the nature of the control). Note that if a transfer is already underway for this property, the control must abort the transfer as described below.
  2. The control obtains the name itself from its own property page UI; in that case it makes the change unilaterally. Any path properties marked with [requestedit] means the control is required to call any connected IPropertyNotifySink interface's OnRequestEdit function to decide whether the change is actually allowed. If OnRequestEdit returns S_FALSE, the control must not change its path in this way (the authoring tool is essentially saying that the document or Internet site state is read-only as far as document/page contents are concerned).

In both cases, a change in the value of any path property will generate a call to any connected IPropertyNotifySink interface's OnChanged member, because path properties are marked with [bindable]. In both cases, an authoring tool that displays its own property browsing UI would update itself to reflect the current state of the control. This also gives the authoring tool the chance to modify the path when the user changes it through the control's property pages directly. When the user makes the change, the control will notify the authoring tool through OnChanged. The authoring tool then reads the new value of the path property, modifies it as necessary, and sends the modified value back to the control. Therefore, in both the first and second cases above, the authoring tool has the final say in the exact value assigned to any path property.

The most preferable case is where the value is simply a container-relative name. Relative file names and URLs are identical in form: "../pictures/tree.bmp" serves equally well in both the local file system and Internet environments. Relative item names, like "!Picture 6", identifies the path as pointing to some other part of the same container document. In URL cases, the name may be absolute, which indicates that there's no relative path between the container document and the location described in the data path.

In any case, a control must always obtain some moniker from a data path name to bind to the storage so referenced. Because the name may only be relative, the container is always given the chance to create the actual moniker itself. The details of this are covered in the next section.

Use of relative names allows an authoring tool to move the root document—and possibly an entire site—around, without invalidating any external links stored in data paths. For example, consider the author-time case where the document being created is stored in "c:\pages\mypage.doc" and in that document is a bitmap control with an ImagePath property. The authoring tool assigns the name "frog.bmp" to this property. When the control wishes to access the bitmap named in the ImagePath property, it passes "frog.bmp" to the authoring tool and asks for a moniker in return. The authoring tool sees two file names and can combine them into one "c:\pages\frog.bmp" name. The authoring tool then returns this name in a moniker so that the control can bind that moniker and retrieve the data.

Now when the author saves the document to an Internet site at Publish time, the location of the document changes to something like "http://www.bogons.com/bogazoid/mypage.htm". In addition, the authoring tool copies "frog.bmp" to that same site where it becomes "http://www.bogons.com/bogazoid/frog.bmp". At run time, the control reloads the path property name "frog.bmp" and asks the container to make it a moniker. The container simply combines the document URL with the relative name "frog.bmp" to generate the exact URL for the bitmap.

In some cases, the control may have obtained an absolute filename (or URL) from its own property pages at author-time. So, for instance, the user types in "c:\pages\frog.bmp" instead of just "frog.bmp." Initially, the control will internally save the absolute string, but because it sends an OnChanged notification (data path is [bindable]), the authoring tool retrieves this new value and computes the relative path to that same file from the document's current location (using the file moniker's RelativePathTo member, for example). The relative path in this case will end up as just "frog.bmp", which the authoring tool simply assigns back to the control.

In the case where the user gives a control an absolute URL, there's nothing the authoring tool can do at author-time when the document is stored on a local file system. At publish time, however, the authoring tool first determines the new URL of the document. It can then cycle through all known path properties of each control before it saves that control. If the authoring tool finds an absolute URL in a property, that tool can attempt to compute the relative path between the document's URL and the path's URL. Once it has computed this relative path, it can assign the relative name to the path property and proceed with saving the control.

When the authoring tool supports relative path names that are not either file names or URLs, but are instead item names that identify a piece of storage in the document itself, such as "#Picture 6", the authoring tool must specify, in its own documentation, what prefix character marks the name as an item of some kind. This is a note to the container's moniker creation mechanism in IBindHost::CreateMoniker as described in the next section.

Storing and Comparing Path Properties

Controls should always ensure that they can produce a string for any path property. This is because all interfaces that deal with path properties (either IDispatch for the property itself or IBindHost, in a section below, for converting the string into a moniker) deal with paths as strings.

However, controls should not compare two path properties as strings. Instead, the comparison should be carried out using two monikers created from those strings through IBindHost::CreateMoniker (see below). With monikers, the comparison between pmk1 and pmk2 is the call pmk1->IsEqual(pmk2) or pmk2->IsEqual(pmk1).

Integrated Author Tool Browsing and Control Property Pages

A sophisticated container or authoring tool will likely provide its own browsing UI for various types of data, typically the most common types of data that would be assigned to path properties (images, sound, and video). To maintain as much of a consistent user interface as possible, a container should make such browsing UI available to a control's property pages so that the property page can invoke that UI instead of showing its own, which would likely be inconsistent.

This integration is achieved through a container-side interface called IOleBuilderManager. An exact specification for this interface is not, however, available at this time and will be provided at a later date. The basic idea, however, is that through this interface a control's property page can test for the availability of container-side browsing UI and invoke that UI if it is available. This allows the page to enable a "Browse..." button for a particular path property, invoking the container's UI when that button is pressed.

Container Supply of Monikers Through IBindHost

Working with data paths requires, of course, the ability of the control to access data referenced by its path properties. The key part of such data access is providing some means by which the control turns a data path name into a moniker that it can bind. Because the container/authoring tool is the one that generally knows the context that modifies any relative path name, the container, in this relationship, is responsible for generating an appropriate moniker when the control asks for one.

This step happens through a container's (or authoring tool's) implementation of the interface IBindHost, which is implemented as a service available through a container site's implementation of IServiceProvider, and is the topic of the next section. The control accesses the bind host implementation by calling QueryInterface(IID_IServiceProvider...) on whatever site pointer it already has and calling IServiceProvider::QueryService(SID_SBindHost). Use of the service provider means that the bind host is generally a separate object from the site; although as an implementation convenience, it could be implemented on the site directly.

Of course, in order for a control to have a site through which it can access these services, the control must provide some means through which the container can pass its site pointer to the control in the first place. Many controls implement IOleObject whose SetClientSite member accomplishes exactly this. However, not all controls need to implement IOleObject, so a section below describes a simple siting mechanism using IObjectWithSite to achieve the same ends.

This document requires that a control using data paths supports a siting mechanism. If the control doesn't support IOleObject, it must support IObjectWithSite. A container that supports data paths must provide a site through one of these mechanisms and must generally implement IBindHost and provide access to it through the site's IServiceProvider. If a control that uses paths finds itself without a container site, it can still degenerate gracefully by calling MkParseDisplayNameEx itself, as necessary.

Overview of IBindHost

The creation of a moniker from a potentially relative path name is what is considered a container-side "service" that a control accesses through IBindHost::CreateMoniker. In addition, a control asks its container to download data through IBindHost::MonikerBindToStorage as described in a later section.

The IBindHost interface is defined as follows:

interface IBindHost : IUnknown
    {
    HRESULT CreateMoniker([in] LPCOLESTR pszName, [in] IBindCtx *pBC
        , [out] IMoniker** ppmk, [in] DWORD dwReserved);

    HRESULT MonikerBindToStorage([in] IMoniker *pMk, [in] IBindCtx *pBC
        , [in] IBindStatusCallback *pBSC, [in] REFIID riid
        , [out, iid_is(riid)] void **ppvObj);

    HRESULT MonikerBindToObject([in] IMoniker *pMk, [in] IBindCtx *pBC
        , [in] IBindStatusCallback *pBSC, [in] REFIID riid
        , [out, iid_is(riid)] void **ppvObj);
    }

The CreateMoniker member takes a text string of some path—which may be absolute or relative—and returns a moniker that references the actual absolute location. That is, the container combines its known document location with the path supplied in pszName to create the resulting moniker. How the container does this depends on the document path and the type of name found in pszName, which is either something that the URL moniker can handle (including file names) or an item name referring to some portion of the container document itself.

In the item name case, a container can specify a prefix character, like "#" or ">", that it will use to differentiate an item name from some other kind of name. This fact should be known to users of the container at author-time so that those users can enter the correct names in whatever UI is used to assign path values. When the container detects its prefix character, it knows that it has to parse the name according to its own rules.

In any other case, the container creates a moniker from the text string directly using MkParseDisplayNameEx This handles the cases where URLs are given as well as display names of File Item monikers and other similar composites. If for some reason IBindHost::CreateMoniker fails, the calling control can degenerate to calling MkParseDisplayNameEx itself, but this should only be used as a last resort.

Either way, the container now has a moniker for the data path as well as a moniker naming its own document. To return a full moniker from ParseDisplayName it calls pmkDocument->ComposeWith(pmkPath, kReturn) where pmkReturn receives the moniker to return to the caller.

This rule assumes that the document moniker class implements ComposeWith in an intelligent manner. If the document moniker is a File moniker, for example, and the path moniker is a File moniker, ComposeWith will return one File moniker with the combination. The same applies for any case where the path moniker is a URL and the document is either a File or a URL. It is even possible to mix a URL document moniker with a File moniker for the path, provided that the File moniker is not absolute (where the combination would make no sense).

When the path moniker is some item or composite, the File or URL moniker ComposeWith implementations simply create another composite.

The bottom line is that IBindHost::CreateMoniker will create a precise moniker that is the combination of the document's own moniker (obtainable through IOleClientSite::GetMoniker(OLEWHICHMK_CONTAINER) and a moniker created from the path name. The control can use this moniker to bind, but this is not the moniker that the control should save. See below for more information on persistence.

Generic Siting with IObjectWithSite

A control that does not need IOleObject, but still requires access to its container site, specifically for the purposes of accessing container-side services, must instead implement IObjectWithSite:

interface IObjectWithSite : IUnknown
    {
    HRESULT SetSite([in] IUnknown *pUnkSite);
    HRESULT GetSite([in] REFIID riid, [out, iid_is(riid)] void **ppvSite);
    }

In the absence of IOleObject a container can attempt to provide the IUnknown pointer to its site through IObjectWithSite::SetSite. IObjectWithSite::GetSite is included as a hooking mechanism, which allows a third party to intercept calls from the control to the site.

When a control needs to create a moniker from a data path, it obtains the bind host through the site's IServiceProvider interface and proceeds from there.


Introduction and Requirements

There is no question that OLE Controls, or COM objects in general, are useful as part of a document or page on an Internet site. However, some problems exist with regards to how a control is specified within a document, and how a control can behave well in a "slow-link" environment such as the Internet (including how the control retrieves its data in an incremental or progressive fashion, working well with other controls that may also be retrieving their data in the same manner).

Many controls, such as small buttons and label controls, which do not have significant amounts of persistent data, are already suitable for use in the Internet environment. Such controls, even those that already exist, need virtually no changes to work well inside browsers. This document focuses primarily on those controls that have significant amounts of persistent data.

The topics under consideration are listed here:

  • What is the exact instantiation mechanism for a control? That is, how does a container get the class code bits into memory?
  • What options are available for the storage of a control's persistent data, both properties and large data BLOBs (such as a bitmap image or video data)?
  • When a control's data includes potentially huge binary streams (bitmap, video, sound, and so on), how does the control access this data asynchronously and incrementally in cooperation with the container (including the ability for the container to display a progress UI)?
  • How does a control notify the container that the control has finished retrieving asynchronous data and is ready for interaction with the user?

Other topics include miscellaneous subjects, including component categories; "Internet-awareness" requirements and options, including new dispIDs and GUIDs; standard Internet-aware picture, sound, and video objects; and reference material for interfaces described in this document.

In addressing the problem above, one must recognize that there are three different points in the lifetime of a Web document when these concerns arise:

  1. Author Time: the author of the document typically saves the contents of all the controls directly in the document so that the working document may be entirely self-contained. This is the same idea as "design time" in the original OLE Controls specification, and a container's UserMode ambient property is set to FALSE at this time.
  2. Publish Time: the author has completed creation of the document and wishes to finalize it for publication. This is not so much an operational mode because it is a transition between design and "ready-to-run" states. Anyway, at this point the author can break the data for any and all controls out into separate document/storage locations, assigning to each control the name of its storage location.
  3. Run Time: a user is viewing the document with controls that must become interactive at some point. The controls whose data exists at some other location must progressively retrieve their data (using the names assigned at publish time, if needed) without blocking the entire process—that is, cooperating with the container. In this state, a container's UserMode property is set to TRUE.

It is also a requirement of this document to preserve as much of the existing Windows, COM, and OLE programming model as possible—that is, to avoid creating new technology whenever possible, especially to avoid adding additional properties or interfaces that all controls would have to support regardless of their feature set. This ensures that this document does not significantly raise the amount of baseline technology for controls, meaning that only controls that need Internet features implement support for those features. It also leverages a great deal of work that has already been done on OLE Controls, both in design and implementation.

Note: Everything in this document applies to generic COM objects as well as controls, although the term "control" is used most often. In fact, the distinction between controls and generic COM objects is gradually becoming non-existent. Controls are, at the time of writing, now considered to be nothing more than a COM object with support of the IUnknown interface at the minimum. Numerous optional interfaces provide the specific features that the control requires (such controls no longer use the "Control" registry key for identity, but use instead a new component category). This allows a control vendor to implement only as much code as is absolutely necessary for the control's functionality, placing the small added burden on the container to degenerate gracefully when a certain interface or feature is not available.

"Controls," as the term is used in this document, refers to any generic usage of OLE technologies in creating component software. The solutions presented here are extensions to the totality of OLE (not just extensions for a complete OLE Control that implements all possible control features). It should also be noted that this document describes only minimal extensions to the OLE model that has succeeded in the marketplace for several years now. As such, this document does not contain a substantial amount of "new" technology, merely extensions to make the existing technology work well in a new environment.

The extensions in this document also apply identically, without modification to the new additions to the OLE Controls model to support windowless controls.

Note: For more information on this view of controls, see the Control Guidelines document listed in the references.

Non-Requirements

In any situation where the source and consumer of any data are physically separate, there is the possibility for "broken links" where the consumer loses track of the source. This is a problem when it comes to standard OLE compound documents where a user may move a source or consumer document independent of the other, possibly breaking any links between the two. This problem exists because file systems are read-write as far as the user is concerned.

There is ongoing work to solve the link-tracking problem for OLE compound documents where monikers are involved. As solutions become available in that context, they will also become available to any other architecture that employs monikers. As moniker usage is part of this document, some degree of link tracking automatically comes into play without any extra work on the part of controls.

Furthermore, for Internet browsing purposes, link tracking is generally not required because it is assumed that only authors/designers of Web pages and Web sites will have the capability to rearrange the relative positions between source and consumer documents. In other words, the user sees the Web as a read-only file system. Because of that, it is the author's/designer's responsibility—with the help of an authoring tool built on the system-level link tracking services—to ensure that a document with external links contains accurate specifications of those external links. The same issues apply to hyperlinks, but no solutions are readily available given the widely distributed and heterogeneous nature of the Web. This document simply doesn't attempt to address link tracking.

This document does offer some assistance to authoring tools for managing external references made within controls. At the present time, however, it doesn't offer any solutions for nested controls where external references may exist at any level. This document handles a large majority of cases, but does not provide a complete solution.

It is also an author's/designer's responsibility to manage data stored in external locations so that the data can be removed when no document container links to those sources. For example, someone could author a document with a picture control whose data comes from a source specified with a URL moniker. However, at a later time, someone (the author or another person) could delete that picture control from the document. The author would then be responsible to determine whether the data source itself should be deleted if there are no controls referencing that data any longer.

This document does not offer any solutions to this resource management/reference counting issue. Solutions are the domain of content-management and authoring tools.


Storage of Control Persistent Data

Note This section is primarily background material to set the stage for a later section. Those interested only in the details of writing good Internet-aware controls and containers can skip directly to that section.

For the purposes of this discussion, any given control may potentially have the following types of persistent data:

  • CLSID (16 bytes): The CLSID identifies the class code that can read other data that follows.
  • Properties (usually less than 10K-20K bytes): The control has a set of named values, accessible generally through OLE Automation (that is, vtable interfaces with type information, IDispatch, or dual interfaces). These may be standard or custom properties, of course.
  • BLOBs (arbitrary sizes): The control has any number of large binary data blocks, each of which exists in any format (standard or custom) and can be arbitrarily large. Bitmaps, videos, sounds, and other sizable data fall into this category where controls are concerned. "Native data," as used to describe the persistent data of a "compound document object" in OLE Documents, is another example.

Note The description of these three elements is for conceptual purposes only. These elements do not describe any kind of actual stream, file, or data format.

The following illustration shows the CLSID, properties, and BLOBs.

Figure 1: Possible elements of a control's persistent data

There may be controls that have no persistent data; none of these elements exist in a document. In that case, the container has the CLSID of the control (directly from the CLSID attribute in HTML or indirectly from CODE) and the control needs no other initialization after creation.

When a control has any persistent data at all, the CLSID element always exists along with one or both of the other two elements. How these elements are stored in relation to the container document involves the concepts of "embedding" and "linking," which originated in OLE Documents (the OLE compound document architecture), described in a following section. Because of certain limitations inherent in the compound document model, that section extends the "embedding" and "linking" concepts as persistence mechanisms only to allow more flexibility in control implementations. Additional sections provide notes regarding the use of IPersistMoniker, HTML, and progressive property retrieval.

Many readers will already be asking themselves how a control might be able to split its properties element from its BLOB elements so that the CLSID and properties are stored in one location and the BLOBs in other locations. This topic is described further in a later section.

A Review of Embedding and Linking: OLE Documents

"Object Linking and Embedding" as OLE was originally called in its version 1.0 days, introduced the idea of "embedded compound document objects" and "linked compound document objects." These concepts carried forward into OLE 2:

  1. Embedding: All of the object's native data (and CLSID) is completely stored in-line—that is, embedded, within the document itself. The container also stores any container-owned information, such as a presentation cache, with the object's native data.
  2. Linking: The container still stores any container-owned information and the presentation cache in the document but the object's native data (and CLSID) is stored in an outside location. The location is named with some moniker which is itself serialized in the document (usually the object's CLSID is cached here as well for various optimization purposes). Linked objects also have the user interface restriction that they cannot be in-place activated.

The following illustration illustrates embedding and linking.

Figure 2: Embedding and Linking as persistence mechanisms in OLE Documents

Because of the demands of the presentation cache, a container in OLE Documents must always provide an instance of IStorage to each embedded or linked objects. In the embedding case, the class code for that object must itself implement IPersistStorage. In the linking case, OLE provides the "default handler" that handles the moniker and the cache in the container document (through IPersistStorage), but the class code itself has to provide whatever interfaces are appropriate for the binding behavior of the moniker. For example, if a File moniker is used, the class code must implement IPersistFile to learn from the moniker where the native data resides on the file system.

Note also that an embedded (or even linked) object may internally, in its own native data, store references to external data sources, essentially doing a simpler form of "linking" unbeknownst to the container. The system-provided "Package" object is a perfect example of this. A Package can contain an "embedded" file or a "command line" along with an icon and label (which make up its presentation in the document). When a file is embedded in the package, the file image itself makes up the package's "native" data. When the package contains a command line, the command line is embedded along with the icon and label, but the "native" data is ultimately in some other file in the name space as described by the command line. This can be described as a "link" to that other file, although the link is entirely internal to the package object and is entirely hidden from the container.

While this architecture works fine within the confines of a single high-speed file system, where storage space is cheap and network latency and transfer speed are usually not an issue, it does not apply all that well to an environment like the Internet. In particular there are the following problems:

  • There is almost always some sizable data stored inside the document, usually the presentation cache. Unless the container chooses to eliminate the cache entirely, the document size becomes significant, which is undesirable in a slow-speed network.
  • An embedded object can only use IPersistStorage as a persistence mechanism, which is simply too "heavyweight" for many types of controls that store all their properties in only use a few hundred bytes or less (such as simple labels, buttons, checkboxes, group boxes, scrolling marquees, and so on). This leads to wasted storage space.
  • A link source must generally implement IPersistFile to support moniker binding, which works only in the domain of UNC path names whereas the Internet requires the ability to use URLs.
  • Any external references in the object's native data are known only to the object, which precludes any container participation in managing or assigning those locations and in managing the data stored there.

OLE Controls as first introduced in 1994 gave controls the ability to implement the IPersistStreamInit persistence mechanisms for the "embedding" case, eliminating the caching issue in the process and providing a lightweight alternative to IPersistStorage. However, OLE Controls was not originally concerned with complete flexibility in persistence mechanisms nor alternate forms of "linking" that addressed all of these issues.

Persistent Embedding and Linking (IPersist* Interfaces)

This document extends the concepts of embedding and linking to work outside the particulars of OLE Documents ( IPersistStorage, caching, IPersistFile), specifically to work with all available persistence mechanisms as well as with URL monikers and the possibility of asynchronous retrieval of linked data. The concepts of embedding and linking are described as follows:

  1. Persistent Embedding: The object's/control's CLSID, properties, and BLOBs are completely stored in-line—that is, embedded, within the document itself.
  2. Persistent Linking: The object's/control's CLSID, properties, and BLOBs are stored in another location identified with some single moniker.

Note The "linking" architecture of OLE Documents is itself more than just a persistence mechanism because it also involves various user interface standards, such as the stipulation that a linked object cannot be in-place activated. Any user interface guidelines concerned with OLE Documents are not of interest to what this section calls "Persistent Embedding" and "Persistent Linking" because the mechanisms here are solely concerned with the location of data and have nothing to do with user interface models. A control can, thus, work with persistently linked data while still being in-place activated.

In addition, in OLE documents the idea of "linking" generally means that the source itself (of the linked object) supplies the exact moniker to name the object. In "persistent linking" the container provides the moniker to the object and the object binds that moniker to some piece of storage in which the object reads or writes its data.

The following illustration shows persistent embedding and persistent linking.

Figure 3: Persistent Embedding and Persistent Linking

Again, a later section covers the case where one or more of the control's properties name other external storage locations so that the BLOBs do not have to be stored with the control's properties in either the embedding or linking case. For the purposes of this discussion, we assume that any in-line BLOBs in the embedding case are still small so that the byte count of the properties and the BLOBs still fall within a reasonable size. One can simply see these small portions of binary data as additional control properties.

The extensions that enable these generic persistent mechanisms are as follows:

  1. A control may use any of IPersistStreamInit, IPersistStorage, IPersistMemory, and IPersistPropertyBag as a Persistent Embedding mechanism. A control can choose to support as many of these as it wants.
  2. A container that wants to use Persistent Embedding must be able to provide controls with storage space appropriate for the preferred interfaces on the control: IStream for IPersistStreamInit, IStorage for IPersistStorage, memory (void *) for IPersistMemory, IPropertyBag for IPersistPropertyBag, and IPropertyBag2 for IPersistPropertyBag2. Containers will determine what method is used to save a control initially (according to its own preference for these methods) and expect that the control can be reinitialized through the same means.
  3. A control may use any of IPersistStreamInit, IPersistStorage, IPersistMemory, and IPersistFile as a Persistent Linking mechanism, again choosing to support as many interfaces as wanted ( IPersistMoniker is also an option although the feasibility of this interface is questionable at this time). It is strongly recommended that Internet-aware controls implement at least one other interface than IPersistMemory and IPersistFile because both of these require that all the data exists locally, which is unsuitable for use with asynchronous data transfers.
  4. A container that wants to use Persistent Linking must use a moniker that supports the possible persistence mechanisms that a control might support. In the immediate term, this is limited to the URL moniker.
  5. A container is allowed to make a copy of a control's persistent data at any time through any IPersist*::Save member functions regardless of which IPersist* interface was used to initialize the control. When doing so, the container must not pass TRUE as the fRemember argument of IPersistStorage::Save, IPersistMoniker::Save, and IPersistFile::Save and must pass FALSE as the fClearDirty argument to IPersistStreamInit::Save, IPersistPropertyBag::Save, and IPersistMemory::Save. The container must also call the SaveCompleted members of IPersistStorage and IPersistFile (and perhaps IPersistMoniker) with NULL arguments after calling their Save members.

The following table summarizes all these IPersist* interfaces:
Storage Location | Persistence Interface | Comments
Storage Element | IPersistStorage | Standard in OLE Documents; the container provides an IStorage pointer to the storage element in which the control can create any structure it wants. This will be potentially common for author-time scenarios, typically rare for publish/run-time scenarios.
Expandable Stream | IPersistStreamInit, IPersistStream | Most suitable for small and fully embedded controls; all the data including paths goes into one stream which can be easily placed inline in the document. IPersistStreamInit is a superset and replacement for IPersistStream. IPersistStreamInit should be used preferentially.
Fixed-Size Memory Block | IPersistMemory | Alternative for IPersistStreamInit, but allows the container to specify a fixed-size memory allocation as the storage medium with the restriction that the control does not attempt to access data outside that boundary.
"Property Bag" (container-supplied) | IPersistPropertyBag | Alternative for IPersistStreamInit in which the control tells the container to save and load individual properties (described in a VARIANT) through IPropertyBag. The implementor of the property bag can deal with each property in any way it wants.
"Property Bag 2" (container-supplied) | IPersistPropertyBag2 | Alternative for IPersistStreamInit in which the control tells the container to save and load individual properties (described in a VARIANT) through IPropertyBag2. The implementor of the property bag can deal with each property in any way it wants.
File | IPersistFile | The object is given a UNC path name and is told to read or write its data to that file.
External: named with a moniker | IPersistMoniker | The object is given a moniker and told to read and write its data to whatever storage mechanism ( IStorage, IStream, ILockBytes, or IDataObject) it wants when dealing with that external data. The storage mechanism may also be asynchronous; in that case, the IPersistMoniker implementation understands the necessary considerations.

Details about IPersistMemory, IPersistPropertyBag, and related interfaces are provided in a later section. For information on IPersistMoniker, see Asynchronous Monikers.

These extensions are basically concerned with the protocol through which a container communicates persistence intentions ( IPersist*::Load and so on) to controls in its document, which also addresses the needs of author, publish, and run-time scenarios. At author time, the designer may want to keep all the data for all controls in-line so there is only one document to manage, or some controls may be told to save and load their data in another site already. At publish time, the author might want to store the bulky portions of data (controls with large BLOBs) in other locations, thus breaking the document up into its final distribution on the Internet. At run time, then, the controls in the document will access their data as instructed to do so by the container.

An Internet-aware object or control is one that understands the options available here and implements support for whatever mechanisms it needs and can support best. Such a control need not support all storage cases and can choose to support only those it sees fit to support or can support reasonably well. At a minimum, controls that have any persistent data should implement at least IPersistStreamInit or IPersistStorage (whichever is most suitable), adding other interfaces as features demand them. For example, controls whose persistent data is made up entirely of name/value property pairs will likely implement IPersistPropertyBag as well). Information about why a control might choose to implement IPersistMoniker is provided in a later section.

If a control for some reason only implements one persistence interface out of IPersistStreamInit, IPersistStorage, IPersistMemory, and IPersistPropertyBag, it must mark itself with the appropriate component category to say that support for that interface in a container is mandatory. These categories are described in a later section. Controls that implement IPersistStorage and can work in down-level containers as simple compound document embeddings can mark themselves with the "Insertable" registry key so that they appear in the Insert Object UI of such containers (a category is not used because down-level containers don't see categories).

Note that it takes less than 200 bytes to persistently save values for all of the standard properties defined for a full-featured OLE Control, such as text, caption, colors, drawing styles, and font; if the control wants to include a small metafile for immediate rendering, adding a few hundred bytes more bytes should not be a big problem.

On the other hand, containers should support—for Persistent Embedding—as many different persistence interfaces as reasonable with IPersistStreamInit and IPersistStorage as a baseline, adding support for IPersistMemory for optimization purposes and IPersistPropertyBag for Save-As-Text capabilities. Authoring tools and containers must also pay attention to component categories when it does not implement support for any one interface so that it can avoid inserting a control into a document when its persistence needs cannot be met.

In this Persistent Embedding case as well, the container chooses which interface it will attempt to use first with any given control. Some containers may look for IPersistStorage before IPersistStreamInit; others will try IPersistPropertyBag before all others, or will place IPersistMemory before IPersistStreamInit as the former might be more efficient for the container. Because the size of embedded data is of high concern for Internet-aware containers, IPersistStreamInit and IPersistMemory should generally be given priority over IPersistStorage and IPersistPropertyBag as they generally produce the smallest amount of data.

Note that it is perfectly reasonable for a container to have a control save its data into any location specified in any of these interfaces after which the container copies the resulting binary data to another location altogether. The container then saves a reference to that other location so that when loading the control, it can recreate the necessary storage structure and hand it back to the control. This option, by the way, has been available in OLE since version 1.0.

For Persistent Linking, containers need not be concerned with the interfaces directly but must understand its own usage and storage of monikers, specifically URL and other asynchronous monikers. Because the monikers themselves internally query for and call the various IPersist* interfaces, the container does not have to understand those persistence interfaces directly. Such intelligence is encapsulated in the monikers.

In this case, the moniker itself chooses the priority as the container merely needs only to choose how it will save the moniker. As described in Asynchronous Monikers, such monikers will look for interfaces in the order of IPersistMoniker, IPersistStreamInit, IPersistStorage, IPersistMemory, and IPersistFile, the latter two requiring that all the data is available before any members of either interface can be called.

The use of IPersistMoniker is questionable and has limitations. This issue is described in a later section.

In both embedding and linking cases, the container is responsible for handling the details of asynchronous storage as described in "Compound Files on the Internet" and "Asynchronous Monikers Design Specification." In short, all persistence interfaces other than IPersistMoniker are considered synchronous in that the control expects all the data to be available when it gets a call to IPersist*::Load. In the case of IPersistFile and IPersistMemory, this is explicit because you can't create the file or the memory block unless you have the data.

In the case of IPersistStream[Init] and IPersistStorage, a container can pass either a "synchronous" storage object or a "blocking" storage object. In the "synchronous" case, the container will retrieve all the data before calling IPersist*::Load so nothing has changed from all historical uses of these interfaces. In the "blocking" case, the data might not actually be available, but any call that the control makes to IStorage::OpenStorage, IStorage::OpenStream, or IStream::Read (and so on) will simply not return until the data is actually available. From the control's point of view, the storage or stream objects are simply slow—the control won't usually care because it just waits for the call to return. But from the container's point of view, simultaneously loading multiple controls using asynchronous "blocking" storage may be a perfect way to manage multiple data transfers.

Use of IPersistMoniker

As described in a previous section, the IPersistMoniker interface is the primary interface through which an asynchronous moniker will attempt to have a control initialize in the Persistent Linking case. In general, IPersistMoniker is the successor of IPersistFile that allows persistence to and from any abstract location that can be named with a moniker as opposed to only a file name. The interface is defined as follows (see Asynchronous Monikers for complete information):

interface IPersistMoniker : public IPersist
   {
    HRESULT IsDirty(void);
    HRESULT InitNew([in] IMoniker* pmkStore, [in] DWORD grfMode
        ,[in] IBindCtx* pbindctx);
    HRESULT Load([in] IMoniker *pmkStore, [in] DWORD grfMode
        , [in] IBindCtx *pBindCtx);
    HRESULT Save([in] IMoniker *pmkStore, [in] BOOL fRemember
        , [in] IBindCtx *pBindCtx);
    HRESULT SaveCompleted([in] IMoniker *pmkStore);
    HRESULT GetCurMoniker([out] IMoniker **ppmkStore);
    }

In short, this interface is just like IPersistFile (plus the InitNew member) except that where IPersistFile takes a filename string, IPersistMoniker takes a moniker and a bind context. The semantics of the Load and Save members are as follows:

pmkStore->BindToStorage(pBindCtx, ..., IID_<xxx>, &pInterface);

if (load)
    pInterface->[Read](...)   //May be asynchronous
else if (save)
    pInterface->[Write](...)

That is, the control is asked to save or load itself from a moniker using the supplied bind context, and the control is responsible to call IMoniker::BindToStorage to get the appropriate storage-related interface to which it reads (or writes) its data. This may involve asynchronous considerations as described in the Internet Files and Asynchronous Monikers documents. When the control obtains an asynchronous IStorage or IStream, it has to ensure that it can handle IMoniker::BindToObject, returning a NULL interface pointer that will be passed to IBindStatusCallback::OnDataAvailable when it becomes available; IStream::Read and other reading calls that might return E_PENDING; and data that becomes available in segments through IBindStatusCallback::OnDataAvailable. The considerations here are the same as for any client of an asynchronous monikers, so again, see Asynchronous Monikers for more information. A later section also discusses this to some extent in terms of a control's use of "data paths."

Thus, implementing IPersistMoniker is not a requirement, even for asynchronous transfer of persistently linked data that goes on outside the control before any of its other IPersist*::Load members are called. This is because asynchronous monikers themselves (that is, the URL moniker presently) will take whatever data it sees at the named location and package that data in some storage object appropriate for other IPersist* interfaces. That is, if the moniker does not find IPersistMoniker on the object, it will query for IPersistStreamInit. If that interface exists, the moniker will wrap up the data in an asynchronous-blocking IStream and pass it to the control. If the interface is not there, the moniker will try other interfaces like IPersistStorage, IPersistMemory, and IPersistFile, in turn, wrapping the data in an asynchronous-blocking IStorage if needed, or retrieving all the data and placing it in memory or a file before handing it to the control.

Relationship to the HTML OBJECT Tag

It is useful at this point to describe the relationships between the persistent embedding and persistent linking scenarios described above and the attributes described in HTML Standards, namely the CLASSID, DATA, and PARAM attributes within an OBJECT tag.

In the persistent embedding case, the authoring tool that is writing the HTML document first asks the control to save all of its data through some persistence interface. After the IPersist*::Save call, the authoring tool has some bucket of control-created bits and the CLSID for the control itself. When writing the HTML OBJECT tag, the authoring tool always writes a CLASSID attribute and then includes a DATA attribute describing the control's data in some way. In all cases, the data must have a CLSID in the first 16 bytes to identify the exact format of the data.

In some cases, the stream data might be too large. In that case, the authoring tool might use IPersistPropertyBag to be handed each property in turn, which it would then write into the HTML document as individual PARAM attributes. Other PARAM attributes might also be later added manually to this set by someone editing the HTML directly.


Summary

Added Standard Properties, Methods, Events, and Interfaces

The following table summarizes the added standard dispIDs described in this document:
Control Property | Value
DISPID_READYSTATE | (-525)
Control Methods | Value
none
Control Events | Value
DISPID_READYSTATECHANGE | (-609)

The following table summarizes the new interfaces and other GUID values described in this document, as well as those that are described here with the exception of category IDs described in a later section:
Symbol | Value
IID_IBindHost | FC4801A1-2BA9-11CF-A229-00AA003D7352
IID_IServiceProvider | 6D5140C1-7436-11CE-8034-00AA006009FA
IID_IObjectWithSite | FC4801A3-2BA9-11CF-A229-00AA003D7352
IID_IPersistMemory | BD1AE5E0-A6AE-11CE-BD37-504200C10000
IID_IPersistPropertyBag | 37D84F60-42CB-11CE-8135-00AA004BB851
IID_IPropertyBag | 55272A00-42CB-11CE-8135-00AA004BB851
IID_IPersistPropertyBag2 | 22F55881-280B-11d0-A8A9-00A0C90C2004
IID_IPropertyBag2 | 22F55882-280B-11d0-A8A9-00A0C90C2004
IID_IErrorLog | 3127CA40-446E-11CE-8135-00AA004BB851
GUID_PathProperty | 0002DE80-0000-0000-C000-000000000046
GUID_HasPathProperties | 0002DE81-0000-0000-C000-000000000046
SID_SBindHost | FC4801A1-2BA9-11CF-A229-00AA003D7352 (same as IID_IBindHost)

IPersistMoniker and its IID is documented in Asynchronous Monikers.

Requirements for Internet-Aware Controls and Objects

If a control does not use any data paths for BLOB data, working well within Internet-aware containers mostly means that a control supports as many IPersist* interfaces as is reasonable for it, giving the container and asynchronous monikers a great deal of flexibility in how they initialize the control in both persistent embedding and persistent linking cases.

Controls that only support one persistence interface must mark themselves as mandatory users of the appropriate category.

Controls with one or more data paths have these requirements:

  1. Must support either IOleObject or IObjectWithSite as a siting mechanism.
  2. Must mark data path properties in type information with the [bindable] attribute as well as the appropriate custom attribute using GUID_PathProperty.
  3. Must mark the coclass entry in the control's type information with the custom attribute using GUID_HasPathProperties.
  4. Must follow the rules of moniker creation and persistence, using the container's IBindHost as necessary and as IBindHost is available.
  5. Must understand how to bind with an asynchronous moniker using a container-provided bind context from IBindHost if available and how to receive data through IBindStatusCallback.
  6. Must prioritize initialization sequences and data retrieval to render and interact as soon as possible, returning E_PENDING from member functions as appropriate for the control's initialization state.
  7. Should supply a ReadyState property, if applicable, and fire OnReadyStateChange events as needed.
  8. Should support IPersistPropertyBag for supporting HTML PARAM attributes.

This document also recommends that controls be OLE Accessibility-aware for the benefit of users requiring accessibility services.

Requirements for Internet-Aware Containers/Clients/Controllers

Whereas much of a control's functionality is optional (with the exceptions of necessary support for data paths), a container, on the other hand, generally wants to support as many features as possible. As guidelines, a container that wishes to host Internet-aware controls at run time should meet these requirements:

  1. Must expect and handle E_PENDING, especially from IViewObject2::Draw.
  2. Must provide a site to a control through either IOleObject or IObjectWithSite mechanisms.
  3. Must supply initialized bind contexts and name parsing through IBindHost.
  4. Must support at least IPersistStreamInit as a control persistence mechanism.
  5. Must support the HTML Extensions for COM Objects if the client is HTML-oriented.
  6. Should manage relative creation/initialization priorities for each control in the document.
  7. Should supply browsers for common data types required by data paths (authoring tools).
  8. Should support as many IPersist* interfaces as possible to allow maximum control flexibility.

This document also recommends that controls be OLE Accessibility-aware for the benefit of users requiring accessibility services.


IBindHost

This interface is implemented as a service available from a site object through which a container supplies services and information that objects require when performing an asynchronous data transfer, specifically name-to-moniker parsing and a container-initialized bind context.

IDL:

[
uuid(fc4801a1-2ba9-11cf-a229-00aa003d7352)
    , object,pointer_default(unique)
]

interface IBindHost : IUnknown
    {
    HRESULT CreateMoniker([in] LPCOLESTR pszName, [in] IBindCtx *pBC
        , [out] IMoniker** ppmk, [in] DWORD dwReserved);

    HRESULT MonikerBindToStorage([in] IMoniker *pMk, [in] IBindCtx *pBC
        , [in] IBindStatusCallback *pBSC, [in] REFIID riid
        , [out, iid_is(riid)] void **ppvObj);

    HRESULT MonikerBindToObject([in] IMoniker *pMk, [in] IBindCtx *pBC
        , [in] IBindStatusCallback *pBSC, [in] REFIID riid
        , [out, iid_is(riid)] void **ppvObj);
    }

IBindHost::CreateMoniker

IBindHost::MonikerBindToStorage

IBindHost::MonikerBindToObject


IBindHost::CreateMoniker

HRESULT CreateMoniker(
    LPCOLESTR pszName,
    IBindCtx *pBC,
    IMoniker **ppmk,
    DWORD dwReserved);

Provides the caller with a means to turn some sort of text name into a moniker so that the caller does not have to interpret the name in any way itself. In many cases, the implementation of CreateMoniker will simply call MkParseDisplayNameEx, but this method gives the implementor of IBindHost a chance to catch host-specific strings that MkParseDisplayNameEx would not otherwise recognize.

  • Returns one of the following values:
    S_OK | The moniker was successfully obtained and the caller is responsible for the interface pointer.
    E_OUTOFMEMORY | There is insufficient memory to create the moniker.
    E_UNEXPECTED | An unknown error occurred.
    MK_E_SYNTAX | The bind host was unable to parse the string into a moniker because the information in the name was unrecognizable.
pszName
[in] Address of the string containing the name to parse.
pBC
[in] Optional bind context to be used when creating the moniker. This parameter is currently ignored, but may be used in the future for passing additional information.
ppmk
[out] Address of the caller's IMoniker * variable in which to store the moniker created from pszName. The caller is responsible for calling IMoniker::Release when the moniker is no longer needed.
dwReserved
[in] Reserved for future use, must be zero.

E_NOTIMPL is disallowed—a bind host is responsible for providing moniker parsing services.


IBindHost::MonikerBindToObject

HRESULT MonikerBindToObject(
    IMoniker *pMk,
    IBindCtx *pBC,
    IBindStatusCallback *pBSC,
    REFIID riid,
    void **ppvObj);

Should be the single mechanism controls use when trying to bind to the object addressed by a moniker.

  • Returns one of the following values:
    S_OK | The bind operation completed synchronously and successfully. The result of the bind operation is available in ppvObj.
    MK_S_ASYNCHRONOUS | The bind operation will complete asynchronously. Behavior matches that of IMoniker::BindToObject.
    E_OUTOFMEMORY | There is insufficient memory to create the moniker.
    E_UNEXPECTED | An unknown error occurred.
pMk
[in] Moniker to bind to.
pBC
[in] Optional bind context to be used when binding the moniker. This parameter can be used by the control for passing in additional bind options, such as a format enumerator (IEnumFormatETC).
pBSC
[in] Callback interface whereby the control receives asynchronous callbacks pertaining to the bind operation. The control must provide its callback interface separately, not registered on the pBC parameter.
riid
[in] Identifier of the desired storage interface. Serves the same purpose as the analogous parameter in IMoniker::BindToObject.
ppvObj
[out] Result of the bind operation (if it is synchronous). This parameter serves the same purpose as the analogous parameter in IMoniker::BindToObject.

This method behaves exactly the same as IMoniker::BindToObject, except that it provides the control container (implementor of IBindHost) enough authority over the bind operation so that the control container can take charge of setting bind options and priority, while delegating all results and callbacks for the bind operation back to the control.


IBindHost::MonikerBindToStorage

HRESULT MonikerBindToStorage(
    IMoniker *pMk,
    IBindCtx *pBC,
    IBindStatusCallback *pBSC,
    REFIID riid,
    void **ppvObj);

Should be the single mechanism controls use when trying to bind to the data addressed by a moniker.

  • Returns one of the following values:
    S_OK | The bind operation completed synchronously and successfully. The result of the bind operation is available in ppvObj.
    MK_S_ASYNCHRONOUS | The bind operation will complete asynchronously. Behavior matches that of IMoniker::BindToStorage.
    E_OUTOFMEMORY | There is insufficient memory to create the moniker.
    E_UNEXPECTED | An unknown error occurred.
pMk
[in] Moniker to bind to.
pBC
[in] Optional bind context to be used when binding the moniker. This parameter can be used by the control for passing in additional bind options, such as a format enumerator (IEnumFormatETC).
pBSC
[in] Callback interface whereby the control receives asynchronous callbacks pertaining to the bind operation. The control must provide its callback interface separately, not registered on the pBC parameter.
riid
[in] Identifier of the desired storage interface. Serves the same purpose as the analogous parameter in IMoniker::BindToStorage.
ppvObj
[out] Result of the bind operation (if it is synchronous). This parameter serves the same purpose as the analogous parameter in IMoniker::BindToStorage.

This method behaves exactly the same as IMoniker::BindToStorage, except that it provides the control container (implementor of IBindHost) enough authority over the bind operation so that the control container can take charge of setting bind options and priority, while delegating all results and callbacks for the bind operation back to the control.


IErrorLog

The IErrorLog interface is an abstraction for an "error log" that is used to communicate detailed error information between a client and an object. The caller of the single interface member, AddError, simply "logs" an error where the error is an EXCEPINFO structure attached to a specific property. The implementor of the interface is responsible for handling the error in whatever way it desires.

IErrorLog is used in the protocol between a client that implements IPropertyBag and an object that implements IPersistPropertyBag.

IDL:

[
uuid(3127CA40-446E-11CE-8135-00AA004BB851)
    , object, pointer_default(unique)
]
interface IErrorLog : IUnknown
    {
    HRESULT AddError([in] LPCOLESTR pszPropName, [in] LPEXCEPINFO pExcepInfo);
    };

IErrorLog::AddError


IErrorLog::AddError

HRESULT AddError(
    [in] LPCOLESTR pszPropName,
    [in] LPEXCEPINFO pExcepInfo);

Logs an error (an EXCEPINFO structure) in the error log for a named property.

  • Returns one of the following values:
    S_OK | The error was logged successfully.
    E_FAIL | There was a problem logging the error.
    E_OUTOFMEMORY | There was not enough memory to log the error.
    E_POINTER | The address in pszPropName or pExcepInfo is not valid (such as NULL). The caller must supply both.
pszPropName
[in] Name of the property involved with the error. Cannot be NULL.
pExcepInfo
[in] Address of the caller-initialized EXCEPINFO structure that describes the error to log. Cannot be NULL.

E_NOTIMPL is not a valid return code because the member function is the only one in the entire interface.


Interface Reference

The following interfaces are relevant to components hosted by Internet Explorer. This section describes these interfaces.

IBindHost

IServiceProvider

IObjectWithSite

IPersistMemory

IPersistPropertyBag

IPropertyBag

IPersistPropertyBag2

IPropertyBag2

IErrorLog

IPersistHistory

For information on the following interfaces, see the Asynchronous and URL Monikers Reference:

IBinding

IBindStatusCallback

IPersistMoniker


IObjectWithSite

Often, an object needs to communicate directly with a "container site" that is managing the object itself. Outside of IOleObject::SetClientSite, there is no generic means through which an object becomes aware of its site. IObjectWithSite provides simple objects with a lightweight means (lighter than IOleObject) with a siting mechanism. This interface should only be used when IOleObject is not already in use.

Through IObjectWithSite, a container can pass the IUnknown pointer of its site to the object through SetSite. Callers can also retrieve the latest site passed to SetSite through GetSite. This latter function is included as a hooking mechanism, allowing a third party to intercept calls from the object to the site.

IDL:

[
uuid(fc4801a3-2ba9-11cf-a229-00aa003d7352)
    , object,pointer_default(unique)
]
interface IObjectWithSite : IUnknown
    {
    HRESULT SetSite([in] IUnknown *pUnkSite);
    HRESULT GetSite([in] REFIID riid, [out, iid_is(riid)] void **ppvSite);
    }

IObjectWithSite::GetSite

IObjectWithSite::SetSite


IObjectWithSite::GetSite

HRESULT GetSite([in] REFIID riid, [out, iid_is(riid)] void **ppvSite);

Retrieves the last site set with IObjectWithSite::SetSite. If there's no known site, the object returns a failure code.

  • Returns:
    S_OK | The site was returned successfully and the caller is responsible for calling ((IUnknown *)(*ppvSite))->Release() when the site is no longer needed.
    E_FAIL | There is no site; in that case, *ppvSite contains NULL on return.
    E_NOINTERFACE | There is a site, but it does not support the interface requested by riid.
riid
[in] The IID of the interface pointer that should be returned in ppvSite.
ppvSite
[out] The address of the caller's void* variable in which the object stores the interface pointer of the site last seen in IObjectWithSite::SetSite. The specific interface returned depends in the riid argument—in essence, the two arguments act identically to those in QueryInterface. If the appropriate interface pointer is available, the object must call AddRef on that pointer before returning successfully. If no site is available, or the requested interface is not supported, the object sets this argument to NULL and returns a failure code.

E_NOTIMPL is disallowed—any object implementing this interface must be able to return the last site seen in SetSite.


IObjectWithSite::SetSite

HRESULT SetSite(
    IUnknown *pUnkSite);

Provides the site's IUnknown pointer to the object. The object should hold onto this pointer, calling AddRef in doing so. If the object already has a site, it should first call pUnkSite->AddRef to secure the new site, call IUnknown::Release on the existing site, then save pUnkSite.

  • Returns:
    S_OK Returned in all circumstances
pUnkSite
[in] Interface pointer of the site managing this object. If NULL, the object should call IUnknown::Release on any existing site at which point the object no longer knows its site.

E_NOTIMPL is disallowed—without implementation of SetSite, the IObjectWithSite interface is unnecessary.


The IPersistHistory Interface

The IPersistHistory interface provides a mechanism for a component to persist its state within its containing application during the current session.

IDL:

[
    uuid(91A565C1-E38F-11d0-94BF-00A0C9055CBF),
    object, pointer_default(unique)
]
interface IPersistHistory : IPersist
{
    typedef [unique] IPersistHistory *LPPERSISTHISTORY;

    HRESULT LoadHistory(
            [in]IStream *pStream,
            [in]IBindCtx *pbc);

    HRESULT SaveHistory(
            [in]IStream *pStream);

    HRESULT SetPositionCookie(
            [in]DWORD dwPositioncookie);

    HRESULT GetPositionCookie(
            [out]DWORD *pdwPositioncookie);
}

When to Implement

This interface is implemented by a component that wishes to maintain its state across navigations in a Web browser. Take the following example: a user enters data into a Web-based form containing intrinsic controls as well as a custom edit control. The user navigates away from the page and later returns during the current browser session to find that the data entered into the custom component is lost while the intrinsic controls have maintained their state.

In Internet Explorer 4.0, when a user navigates away from a page, all controls on the page are queried for IPersistHistory. Those that implement the interface are handed a stream through the SaveHistory method into which they can store their current state. If the page is loaded again during the current browser session, each control is handed a stream through the LoadHistory method from which they can reload their previous state.

Warning

Internet Explorer 4.0 caches up to 2 MB of persistent data for all controls. When this limit is exceeded data is discarded on a least recently used basis. Component developers should respect the needs of other controls and limit their use of the history cache.

Historical Note

This interface replaces the four-page cache implemented by Internet Explorer 3.0x; Internet Explorer 4.0 does not implement the four-page cache.

IPersistHistory::SaveHistory

IPersistHistory::LoadHistory

IPersistHistory::SetPositionCookie

IPersistHistory::GetPositionCookie


IPersistHistory::GetPositionCookie

HRESULT GetPositionCookie(
    [out]DWORD *pdwPositioncookie);

Reserved for future use. Components are not required to implement this method.

  • Returns:
    E_NOTIMPL The component does not implement this method.


IPersistHistory::LoadHistory

HRESULT LoadHistory(
    [in]IStream *pStream,
    [in]IBindCtx *pbc);

The container calls this method to request that the component restore its state.

  • Returns:
    S_OK | The component was able to reload its persistent state.
    E_FAIL | The component was unable to reload its persistent state.
    E_OUTOFMEMORY | There was not enough memory to reload the persistent state of the component.
    E_POINTER | The stream or the bind context supplied by the container were invalid.
pStream
[in] Pointer to an interface on the stream from which the object should loaded its persistent state
pbc
[in] Pointer to an interface on a bind context. The bind context can be used in binding operations to restore the component's state and should be passed along to any objects contained by the component if a binding is to be performed by the contained component.

The component should under no circumstances add a reference to the supplied stream. The stream should not be cached by the component.


IPersistHistory::SaveHistory

HRESULT SaveHistory(
    [in]IStream *pStream);

The container calls this method to request that the component save its state.

  • Returns:
    S_OK | The component successfully saved its state to the supplied stream.
    E_FAIL | The component was unable to save its state.
    E_POINTER | The stream pointer was invalid.
pStream
[in] Pointer to the stream into which the object should save its persistent state.

The component should under no circumstances add a reference to the supplied stream. The stream should not be cached by the component.


IPersistHistory::SetPositionCookie

HRESULT SetPositionCookie(
    [in]DWORD dwPositioncookie);

Reserved for future use. Components are not required to implement this method.

  • Returns:
    E_NOTIMPL The component does not implement this method.


The IPersistMemory Interface

IPersistMemory operates exactly as IPersistStreamInit, except that it allows the caller to provide a fixed-size memory block (identified with a void *) as opposed to IPersistStreamInit, which involves an arbitrarily expandable IStream.

IDL:

[
uuid(BD1AE5E0-A6AE-11CE-BD37-504200C10000)
    , object, pointer_default(unique)
]
interface IPersistMemory : IPersist
    {
    HRESULT IsDirty(void);
    HRESULT Load([in, size_is(cbSize)] void *pvMem, [in] ULONG cbSize);
    HRESULT Save([in,out, size_is(cbSize)] void *pvMem, [in] BOOL fClearDirty, [in] ULONG cbSize);
    HRESULT GetSizeMax([out] ULONG* pcbSize);
    HRESULT InitNew(void);
    };

The cbSize argument to Load and Save indicate the amount of memory accessible through pvMem.

The IsDirty, GetSizeMax, and InitNew members are semantically and syntactically identical to those in IPersistStreamInit. Only Load and Save differ as described below.

IPersistMemory::Load

IPersistMemory::Save


IPersistMemory::Load

HRESULT IPersistMemory::Load([in] void *pvMem,
        [in] ULONG cbSize);

Instructs the object to load its persistent data from the memory pointed to by pvMem where cbSize indicates the amount of memory at pvMem. The object must not read past the address (BYTE*)((BYTE *)pvMem+cbSize).

  • Returns:
    S_OK | The object successfully loaded its data.
    E_UNEXPECTED | This member was called after the object was already initialized with IPersistMemory::Load. Only one initialization is allowed per instance.
    E_POINTER | The pointer in pvMem is NULL.
pvMem
[in] The address of the memory from which the object can read up to cbSize bytes of its data.
cbSize
[in] The amount of memory available at pvMem form which the object can read its data.

Any object that implements IPersistMemory has some information to load persistently; therefore, E_NOTIMPL is not a valid return code.


IPersistMemory::Save

HRESULT IPersistMemory::Save([in] void *pvMem,
        [in] BOOL fClearDirty,
        [in] ULONG cbSize);

Instructs the object to save its persistent data to the memory pointed to by pvMem where cbSize indicates the amount of memory available at pvMem. The object must not write past the address (BYTE*)((BYTE *)pvMem+cbSize). The fClearDirty flag determines whether the object is to clear its dirty state after the save is complete.

  • Returns:
    S_OK | The object successfully initialized itself.
    E_UNEXPECTED | This member was called before the object was initialized with IPersistMemory::InitNew or IPersistMemory::Load.
    E_INVALIDARG | The number of bytes indicated by cbSize is too small to allow the object to save itself completely.
    E_POINTER | The pointer in pvMem is NULL.
pvMem
[in] The address of the memory in which the object should save up to cbSize bytes of its data.
fClearDirty
[in] A flag indicating whether the object should clear its dirty state on return from Save or leave that state as is.
cbSize
[in] The amount of memory available at pvMem to which the object can write its data.

Any object that implements IPersistMemory has some information to save persistently; therefore, E_NOTIMPL is not a valid return code.

The caller should ideally allocate as many bytes as the object returns from IPersistMemory::GetSizeMax.


The IPersistPropertyBag Interface

The IPersistPropertyBag interface works in conjunction with IPropertyBag (see below) and IErrorLog (see below) to define an individual property-based persistence mechanism. Whereas a mechanism like IPersistStream gives an object an IStream in which to store its binary data, IPersistPropertyBag provides an object with an IPropertyBag interface through which it can save and load individual properties. The implementor of IPropertyBag can then save those properties in whatever way it chooses, such as name/value pairs in a text file. Errors encountered in the process (on either side) are recorded in an "error log" through IErrorLog. This error reporting mechanism works on a per-property basis instead of an "all properties as a whole" basis through just the return value of IPersist*::Load or IPersist*::Save.

IDL:

[
uuid(37D84F60-42CB-11CE-8135-00AA004BB851)
    , object, pointer_default(unique)
]
interface IPersistPropertyBag : IPersist
    {
    HRESULT InitNew(void);
    HRESULT Load([in] IPropertyBag *pPropBag, [in] IErrorLog *pErrorLog);
    HRESULT Save([in] IPropertyBag *pPropBag, [in] BOOL fClearDirty
        , [in] BOOL fSaveAllProperties);
    };

The basic mechanism is that a container tells the object to save or load its properties through IPersistPropertyBag. For each property, the object calls the container's IPropertyBag interface passed to the IPersistPropertyBag members. IPropertyBag::Write obviously saves a property in whatever place the container wants to put it, and IPropertyBag::Read retrieves a property.

This protocol is essentially a means of sequentially communicating individual property values from the object to the container, which is useful for doing save-as-text operations and the like. The object gives the container the choice of the format in which each property is saved, while retaining itself the decision as to which properties are saved or loaded.

IPersistPropertyBag::InitNew

IPersistPropertyBag::Load

IPersistPropertyBag::Save


The IPersistPropertyBag2 Interface

The IPersistPropertyBag2 interface works in conjunction with the IPropertyBag2 and IErrorLog interfaces to define an individual property-based persistence mechanism. This interface is similar to IPersistPropertyBag, but allows the object to support property bags that implement IPropertyBag2.

Whereas a mechanism like IPersistStream gives an object an IStream in which to store its binary data, IPersistPropertyBag2 provides an object with an IPropertyBag2 interface through which it can save and load individual properties. The implementor of IPropertyBag2 can then save those properties in whatever way it chooses, such as name/value pairs in a text file. Errors encountered in the process (on either side) are recorded in an "error log" through IErrorLog. This error reporting mechanism work on a per-property basis instead of an "all properties as a whole" basis through just the return value of IPersist*::Load or IPersist*::Save.

When requesting a persistent property bag interface, a property bag that supports IPropertyBag2 will attempt to obtain the object's IPersistPropertyBag2 interface before attempting to obtain the object's IPersistPropertyBag interface. This allows objects that support either interface to communicate with the property bag.

IDL:

[object, uuid(22F55881-280B-11d0-A8A9-00A0C90C2004), pointer_default(unique)]
interface IPersistPropertyBag2 : IPersist
    {
    typedef [unique] IPersistPropertyBag2 *LPPERSISTPROPERTYBAG2;

    HRESULT InitNew();

    HRESULT Load(
        [in]IPropertyBag2 * pPropBag,
        [in]IErrorLog * pErrLog);

    HRESULT Save(
        [in]IPropertyBag2 * pPropBag,
        [in]BOOL fClearDirty,
        [in]BOOL fSaveAllProperties);

    HRESULT IsDirty();
    }

The basic mechanism is that a container tells the object to save or load its properties through IPersistPropertyBag2. For each property, the object calls the container's IPropertyBag2 interface passed to the IPersistPropertyBag members. IPropertyBag2::Write saves a property in whatever place the container wants to put it, and IPropertyBag2::Read retrieves a property.

This protocol is essentially a means of sequentially communicating individual property values from the object to the container, which is useful for doing save-as-text operations and the like. The object gives the container the choice of the format in which each property is saved, while retaining itself the decision as to which properties are saved or loaded.

IPersistPropertyBag2::InitNew

IPersistPropertyBag2::IsDirty

IPersistPropertyBag2::Load

IPersistPropertyBag2::Save


IPersistPropertyBag2::InitNew

HRESULT InitNew(void);

Informs the object that it is being initialized as a newly created object.

  • Returns one of the following values:
    S_OK | The object successfully initialized itself. This should be returned even if the object doesn't do anything in the function.
    E_UNEXPECTED | This member was called after IPersistPropertyBag2::Load or IPersistPropertyBag2::Save.

E_NOTIMPL should not be returned. Return S_OK even if the object does not perform any function in this method.


IPersistPropertyBag2::IsDirty

HRESULT IsDirty(void);

Indicates if one or more properties have changed since the last initialization or save operation.

  • Returns:
    S_OK | One or more properties has changed.
    S_FALSE | None of the properties has changed.

E_NOTIMPL is not a valid return code because any object implementing this interface must support the entire functionality of the interface.


IPersistPropertyBag2::Load

HRESULT Load(
    [in] IPropertyBag2 *pPropBag,
    [in] IErrorLog *pErrorLog
);

Instructs the object to initialize itself using the properties available in the property bag, notifying the provided error log object when errors occur. All property storage must take place within this function call as the object cannot keep the IPropertyBag2 interface pointer passed in pPropBag.

  • Returns one of the following values:
    S_OK | The object successfully initialized itself.
    E_UNEXPECTED | This member was called after IPersistPropertyBag2::InitNew has already been called. The two initialization methods are mutually exclusive.
    E_POINTER | The address in pPropBag is not valid (such as NULL) and therefore the object cannot initialize itself.
    E_FAIL | The object was unable to retrieve a critical property that is necessary for the object's successful operation. The object was, therefore, unable to initialize itself completely.
pPropBag
[in] Address of the caller's IPropertyBag2 interface through which the object can read properties. This argument cannot be NULL.
pErrorLog
[in] Address of the caller's IErrorLog interface in which the object stores any errors that occur during initialization. This argument can be NULL; in that case, the caller is not interested in errors.

E_NOTIMPL is not a valid return code because any object implementing this interface must support the entire functionality of the interface.


IPersistPropertyBag2::Save

HRESULT Save(
    IPropertyBag *pPropBag,
    BOOL fClearDirty,
    BOOL fSaveAllProperties
);

Instructs the object to save its properties to the given property bag, optionally clearing the object's "dirty" flag. The caller can request that the object save all properties or that the object save only those known to have changed.

  • Returns one of the following values:
    S_OK | The object successfully saved the requested properties itself.
    E_FAIL | One or more essential properties could not be saved. The object can choose to succeed (return S_OK) if all essential properties could be saved but one or more non-essential properties could not be saved.
    E_POINTER | The address in pPropBag is not valid (such as NULL) and, therefore, the object cannot initialize itself.
pPropBag
[in] Address of the caller's IPropertyBag2 interface through which the object can write properties. This argument cannot be NULL.
fClearDirty
[in] Flag indicating whether the object should clear its dirty flag when saving is complete. If this argument is nonzero, the dirty flag should be cleared. If this argument is zero, the dirty flag should not be changed. Zero is used when the caller wants to do a "Save Copy As" operation.
fSaveAllProperties
[in] Flag indicating whether the object should save all its properties or only those that have changed from their default values. If this argument is nonzero, all properties should be saved. If this argument is zero, only those properties that have changed from their default values should be saved.

E_NOTIMPL is not a valid return code because any object implementing this interface must support the entire functionality of the interface.


IPersistPropertyBag::InitNew

HRESULT InitNew(void);

Informs the object that it is being initialized as a newly created object.

  • Returns:
    S_OK | The object successfully initialized itself. This should be returned even if the object doesn't do anything in the function.
    E_UNEXPECTED | This member was called after IPersistPropertyBag::Load or IPersistPropertyBag::Save.
none

E_NOTIMPL should not be returned—use S_OK when the object has nothing to do in the function.


IPersistPropertyBag::Load

HRESULT Load([in] IPropertyBag *pPropBag,
        [in] IErrorLog *pErrorLog);

Instructs the object to initialize itself using the properties available in the property bag, notifying the provided error log object when errors occur. All property loading must take place within this function call because the object cannot hold the IPropertyBag pointer.

  • Returns:
    S_OK | The object successfully initialized itself.
    E_UNEXPECTED | This member was called after IPersistPropertyBag::InitNew has already been called. They two initialization methods are mutually exclusive.
    E_POINTER | The address in pPropBag is not valid (such as NULL,) and, therefore, the object cannot initialize itself.
    E_FAIL | The object was unable to retrieve a critical property that is necessary for the object's successful operation. The object was, therefore, unable to initialize itself completely.
pPropBag
[in] Address of the caller's property bag through which the object can read properties. Cannot be NULL.
pErrorLog
[in] Address of the caller's error log in which the object stores any errors that occur during initialization. Can be NULL; in that case, the caller is not interested in errors.

E_NOTIMPL is not a valid return code because any object implementing this interface must support the entire functionality of the interface.


IPersistPropertyBag::Save

HRESULT Save(
    IPropertyBag *pPropBag,
    BOOL fClearDirty,
    BOOL fSaveAllProperties);

Instructs the object to save its properties to the given property bag, optionally clearing the object's "dirty" flag. The caller can request that the object save all properties or that the object save only those that are known to have changed.

  • Returns one of the following values:
    S_OK | The object successfully saved the requested properties itself.
    E_FAIL | There was a problem saving one of the properties. The object can choose to fail only if a necessary property could not be saved, meaning that the object can assume default property values if a given property is not seen through Load at some later time.
    E_POINTER | The address in pPropBag is not valid (such as NULL) and therefore the object cannot initialize itself.
pPropBag
[in] Address of the caller's property bag through which the object can write properties. Cannot be NULL.
fClearDirty
[in] Flag indicating whether the object should clear its dirty flag when saving is complete. TRUE means clear the flag, FALSE means leave the flag unaffected. FALSE is used when the caller wants to do a "Save Copy As" operation.
fSaveAllProperties
[in] Flag indicating whether the object should save all its properties (TRUE) or only those that have changed from the default value (FALSE).

E_NOTIMPL is not a valid return code because any object implementing this interface must support the entire functionality of the interface.


The IPropertyBag Interface

When a client wants to have exact control over how individually named properties of an object are saved, it would attempt to use an object's IPersistPropertyBag interface as a persistence mechanism. In that case, the client supplies a "property bag" to the object in the form of an IPropertyBag interface.

IDL:

[
uuid(55272A00-42CB-11CE-8135-00AA004BB851)
    , object, pointer_default(unique)
]
interface IPropertyBag : IUnknown
    {
    HRESULT Read([in] LPCOLESTR pszPropName, [in,out] VARIANT *pVar
        , [in,out] IErrorLog *pErrorLog);
    HRESULT Write([in] LPCOLESTR pszPropName, [in] VARIANT *pVar);
    };

When the object wishes to read a property in IPersistPropertyBag::Load, it will call IPropertyBag::Read. When the object is saving properties in IPersistPropertyBag::Save, it will call IPropertyBag::Write. Each property is described with a name in pszPropName whose value is exchanged in a VARIANT. This information allows a client to save the property values as text, for instance, which is the primary reason why a client might choose to support IPersistPropertyBag.

The client records errors that occur during Read into the supplied "error log."

IPropertyBag::Read

IPropertyBag::Write


The IPropertyBag2 Interface

When a client wants to have exact control over how individually named properties of an object are saved, it will attempt to use an object's IPersistPropertyBag2 interface as a persistence mechanism. In that case, the client supplies a "property bag" to the object in the form of an IPropertyBag2 interface.

IPropertyBag2 is an enhancement of the IPropertyBag interface. IPropertyBag2 allows the object to obtain type information for each property through the use of the CountProperties and GetPropertyInfo methods. A property bag that implements IPropertyBag2 must also support IPropertyBag so that objects that only support IPropertyBag can access their properties. Likewise, an object that supports IPropertyBag2 must also support IPropertyBag so that it can communicate with property bags that only support IPropertyBag.

IDL:

[object, uuid(22F55882-280B-11d0-A8A9-00A0C90C2004), pointer_default(unique)]
interface IPropertyBag2 : IUnknown
{
    typedef [unique]IPropertyBag2 *LPPROPERTYBAG2;

    HRESULT Read(
        [in]	ULONG cProperties,
        [in]	PROPBAG2 * pPropBag,
        [in]  	IErrorLog * pErrLog,
        [out] 	VARIANT * pvarValue,
        [out]   HRESULT * phrError);

    HRESULT Write(
        [in]	ULONG cProperties,
        [in] 	PROPBAG2 * pPropBag,
        [in] 	VARIANT * pvarValue);

    HRESULT CountProperties(
        [out] 	ULONG * pcProperties);

    HRESULT GetPropertyInfo(
        [in]  	ULONG iProperty,
        [in]  	ULONG cProperties,
        [out] 	PROPBAG2 * pPropBag,
        [out] 	ULONG * pcProperties);

    HRESULT LoadObject(
        [in]	LPCOLESTR pstrName,
        [in]	DWORD dwHint,
        [in]	IUnknown * pUnkObject,
        [in]	IErrorLog * pErrLog);
}

When the object wants to read a property in IPersistPropertyBag2::Load, it will call IPropertyBag2::Read. When the object is saving properties in IPersistPropertyBag2::Save, it will call IPropertyBag2::Write.

The client records errors that occur during Read with the supplied IErrorLog interface.

IPropertyBag2::CountProperties

IPropertyBag2::GetPropertyInfo

IPropertyBag2::LoadObject

IPropertyBag2::Read

IPropertyBag2::Write

PROPBAG2

PROPBAG2_TYPE


IPropertyBag2::CountProperties

 HRESULT CountProperties(
    [out] ULONG *pcProperties
);

Retrieves the number of properties in the property bag.

  • Returns one of the following values:
    S_OK | The method was successful.
    E_POINTER | pcProperties is not valid.
pcProperties
[out] Address of a ULONG that receives the number of properties in the property bag.


IPropertyBag2::GetPropertyInfo

HRESULT GetPropertyInfo(
    [in] ULONG iProperty,
    [in] ULONG cProperties,
    [out] PROPBAG2 * pPropBag,
    [out] ULONG * pcProperties
);

Retrieves information for properties in a property bag without actually retrieving the properties themselves.

  • Returns one of the following values:
    S_OK | Information was successfully retrieved for all of the requested properties.
    E_INVALIDARG | iProperty is greater than the number of properties in the property bag.
    E_OUTOFMEMORY | A memory allocation error occurred.
iProperty
[in] Zero-based index of the first property that information is being requested for. This argument must be less than the number of properties retrieved by IPropertyBag2::CountProperties.
cProperties
[in] Number of properties to retrieve information for. This argument specifies the number of array elements in pPropBag.
pPropBag
[out] Address of an array of PROPBAG2 structures that receive the information for the properties. There must be at least cProperties elements in this array. This argument cannot be NULL.
pcProperties
[out] Address of a ULONG that receives the number of properties that information was retrieved for. This argument cannot be NULL.


IPropertyBag2::LoadObject

HRESULT LoadObject(
    [in] LPCOLESTR pstrName,
    [in] DWORD dwHint,
    [in] IUnknown * pUnkObject,
    [in] IErrorLog * pErrLog);

Causes the property bag to instruct a previously created and initialized property object to read its persistent properties.

  • Returns one of the following values or any of the IPersist*::Read method return values:
    S_OK | The object successfully retrieved its properties.
    E_INVALIDARG | One or more of the arguments is not valid.
pstrName
[in] Name of the property object.
dwHint
[in] Hint value that was retrieved using GetPropertyInfo. This argument is optional and must be zero if the hint is not known or used.
pUnkObject
[in] Address of the object's IUnknown interface. This argument cannot be NULL.
pErrLog
[in] Address of an IErrorLog interface in which the property bag stores any errors that occur during the load. This argument can be NULL; in that case, the caller is not interested in logging errors.

LoadObject allows the calling application to participate in the creation and initialization of a property object. When using the IPropertyBag interface, it is possible to load a property object using the IPropertyBag::Read method with VT_UNKNOWN. The IPropertyBag method does not, however, allow the property object to be initialized by the calling application before the property object reads its own persistent data. LoadObject allows the property object to be created and initialized by the calling application instead of having the property bag create and initialize it.

To use LoadObject, the property object's name and CLSID are retrieved using GetPropertyInfo. The property object is then created and initialized. LoadObject is then used in lieu of IPropertyBag2::Read to cause the property object to read its persistent data.


IPropertyBag2::Read

HRESULT Read(
    [in] ULONG cProperties,
    [in] PROPBAG2 * pPropBag,
    [in] IErrorLog * pErrLog,
    [out] VARIANT * pvarValue,
    [out] HRESULT * phrError
);

Causes one or more properties to be read from the property bag.

  • Returns one of the following values:
    S_OK | All of the properties were successfully read.
    E_FAIL | One or more of the properties was not successfully read. It is possible that one or more properties were successfully read. The array at phrError will contain a success or error code for each property. If the caller supplied an IErrorLog for pErrLog, a more descriptive error will be added.
cProperties
[in] Number of properties to read. This argument specifies the number of elements in the arrays at pPropBag, pvarValue and phrError.
pPropBag
[in] Address of an array of PROPBAG2 structures that specify the properties being requested. The vt and pstrName members of these structures must be filled in before calling this method. The dwHint member of these structures is optional. There must be at least cProperties elements in this array. This argument cannot be NULL.
pErrLog
[in] Address of an IErrorLog interface in which the property bag stores any errors that occur during the reads. This argument can be NULL; in that case, the caller is not interested in logging errors.
pvarValue
[out] Address of an array of VARIANT structures that receive the property values. The caller does not need to initialize these structures before calling Read. The Read method will fill both type and value fields in these structures before returning. There must be at least cProperties elements in this array. The calling application is responsible for freeing any allocations that are contained in these structures. This argument cannot be NULL.
phrError
[out] Address of an array of HRESULT values that will receive the result of each property read. There must be at least cProperties elements in this array. This argument cannot be NULL.


IPropertyBag2::Write

 HRESULT Write(
    [in] ULONG cProperties,
    [in] PROPBAG2 * pPropBag,
    [in] VARIANT * pvarValue
);

Causes one or more properties to be saved into the property bag.

  • Returns one of the following values:
    S_OK | The property bag successfully saved all of the properties.
    E_FAIL | One or more of the properties could not be saved.
cProperties
[in] Number of properties to save. This argument specifies the number of elements in the arrays at pPropBag and pvarValue.
pPropBag
[in] Address of an array of PROPBAG2 structures that specify the properties being saved. The pstrName member of these structures must be filled in before calling this method. The dwHint member of these structures is optional. There must be at least cProperties elements in this array. This argument cannot be NULL.
pvarValue
[out] Address of an array of VARIANT structures that contain the property values to be saved. There must be at least cProperties elements in this array. This argument cannot be NULL.


IPropertyBag::Read

HRESULT Read([in] LPCOLESTR pszPropName,
        [in,out] VARIANT *pVar,
        [in,out] IErrorLog *pErrorLog);

Asks the property bag to read the property named with pszPropName into the caller-initialized VARIANT in pVar. Errors that occur are logged in the error log pointed to by pErrorLog. When pVar->vt specifies another object pointer (VT_UNKNOWN), the property bag is responsible for creating and initializing the object described by pszPropName. See IPropertyBag::Write for more information.

  • Returns:
    S_OK | The property was read successfully. The caller becomes responsible for any allocations that are contained in the VARIANT in pVar.
    E_POINTER | The address in pszPropName is not valid (such as NULL).
    E_INVALIDARG | The property named with pszPropName does not exist in the property bag.
    E_FAIL | The property bag was unable to read the specified property, such as if the caller specified a data type to which the property bag could not coerce the known value. If the caller supplied an error log, a more descriptive error was sent there.
pszPropName
[in] The name of the property to read. Cannot be NULL.
pVar
[in, out] The address of the caller-initialized VARIANT that is to receive the property value on output. The function must set both type and value fields in the VARIANT before returning. If the caller initialized the pVar->vt field on entry, the property bag should attempt to coerce the value it knows into this type. If the caller sets pVar->vt to VT_EMPTY, the property bag can use whatever type is convenient.
pErrorLog
[in] Address of the caller's error log in which the property bag stores any errors that occur during reads. Can be NULL; in that case, the caller is not interested in errors.

E_NOTIMPL is not a valid return code because any object implementing this interface must support the entire functionality of the interface.


IPropertyBag::Write

HRESULT Write([in] LPCOLESTR pszPropName,
        [in] VARIANT *pVar);

Asks the property bag to save the property named with pszPropName using the type and value in the caller-initialized VARIANT in pVar. In some cases, the caller may be asking the property bag to save another object—that is, when pVar->vt is VT_UNKNOWN. In such cases, the property bag queries this object pointer for some persistence interface, like IPersistStream or even IPersistPropertyBag again, and has that object save its data as well. Usually this results in the property bag having some byte array for this object which can be saved as encoded text (hex string, MIME, and so on). When the property bag is later used to reinitialize a control, the client that owns the property bag must recreate the object when the caller asks for it, initializing that object with the previously saved bits.

This allows very efficient persistence operations for large BLOB properties like a picture, where the owner of the property bag itself directly asks the picture object (managed as a property in the control being saved) to save into a specific location. This avoids potential extra copy operations that would be involved with other property-based persistence mechanisms.

  • Returns:
    S_OK | The property bag successfully saved the requested property.
    E_FAIL | There was a problem writing the property. It is possible that the property bag does not understand how to save a particular VARIANT type.
    E_POINTER | The address in pszPropName or pVar is not valid (such as NULL). The caller must supply both.
pszPropName
[in] The name of the property to write. Cannot be NULL.
pVar
[in] The address of the caller-initialized VARIANT that holds the property value to save. The caller owns this VARIANT and is responsible for all allocations therein. That is, the property bag itself does not attempt to free data in the VARIANT.

E_NOTIMPL is not a valid return code because any object implementing this interface must support the entire functionality of the interface.


The IServiceProvider Interface

IServiceProvider is a generic access mechanism to locate a GUID-identified "service" that is provided through a control or any other objects that it can communicate with. For example, an embedded object (such as an OLE control) normally only communicates with its associated "client site" object in the container through the IOleClientSite interface supplied through IOleObject::SetClientSite. Such an embedded object is required to ask the client site for some other service that the container supports when that service may not necessarily be implemented in the site itself.

In this regard, the site must provide a means through which the control managed by that site can access the service when necessary. A specific example of this necessity can be found in the function IOleInPlaceSite::GetWindowContext, through which an in-place object or control can access interface pointers for the document object that contains the site and the frame object that contains the document. Because these interface pointers exists on separate objects, the control cannot call the site's QueryInterface to obtain those pointers.

The generic architecture for achieving the same ends, without requiring ad hoc solutions where the need arises, is the interface IServiceProvider whose existence says "somewhere in the code of which I'm part exists some set of services that can be accessed through this interface."

The interface itself has only one member, QueryService, through which a caller specifies the service ID (SID, a GUID), the IID of the interface desired in return, and the address of the caller's interface pointer variable.

IDL:

[
uuid(6d5140c1-7436-11ce-8034-00aa006009fa)
    , object,pointer_default(unique)
]
interface IServiceProvider : IUnknown
    {
    HRESULT QueryService([in] REFGUID guidService
, [in] REFIID riid, [out, iid_is(riid)] void **ppv);
    }

IServiceProvider::QueryService


IServiceProvider::QueryService

HRESULT QueryService([in] REFGUID guidService, [in] REFIID riid, [out, iid_is(riid)] void **ppv);

QueryService is the factory method for any services exposed through an implementation of IServiceProvider. It creates or accesses the implementation the service identified with guidService, returning in *ppv the address of the interface specified by riid.

  • Returns:
    S_OK | The service was successfully created or retrieved. The caller is responsible for calling ((IUnknown *)*ppv)->Release();.
    E_OUTOFMEMORY | There is insufficient memory to create the service.
    E_UNEXPECTED | An unknown error occurred.
    E_NOINTERFACE | The service exists, but the interface requested does not exist on that service.
    SVC_E_UNKNOWNSERVICE | The service identified with guidService is not recognized.
guidService
[in] The unique identifier of the service (a SID)
riid
[in] The unique identifier of the interface the caller wishes to receive for the service.
Ppv
[out] The address of the caller-allocated variable to receive the interface pointer of the service on successful return from this function. The caller becomes responsible for calling Release through this interface pointer when the service is no longer needed.

Because there is only one member function in this interface, E_NOTIMPL is not a valid return code—if the function is not implemented, the interface has no reason to exist.


PROPBAG2

typedef struct _tagPROPBAG2{
    DWORD dwType;
    VARTYPE vt;
    CLIPFORMAT cfType;
    DWORD dwHint;
    LPOLESTR pstrName;
    CLSID clsid;
} PROPBAG2;

Contains or receives property information. This structure is used with the IPropertyBag2::GetPropertyInfo, IPropertyBag2::Read, and IPropertyBag2::Write methods.

dwType
Type of property. This will be one of the PROPBAG2_TYPE values.
vt
VARIANT type of the property.
cfType
Clipboard format or MIME type of the property.
dwHint
Property name hint. If possible, this member will be filled by IPropertyBag2::GetPropertyInfo and can be used with IPropertyBag2::Read and IPropertyBag2::Write to accelerate the read or write operation. These values are not valid outside of the property bag that created them.
pstrName
Address of an OLESTR that specifies the property name.
clsid
CLSID of the object. This member is only valid if dwType is PROPBAG2_TYPE_OBJECT.


PROPBAG2_TYPE

typedef enum _tagPROPBAG2_TYPE{
    PROPBAG2_TYPE_UNDEFINED = 0,
    PROPBAG2_TYPE_DATA = 1,
    PROPBAG2_TYPE_URL = 2,
    PROPBAG2_TYPE_OBJECT = 3,
    PROPBAG2_TYPE_STREAM = 4,
    PROPBAG2_TYPE_STORAGE = 5,
    PROPBAG2_TYPE_MONIKER = 6
} PROPBAG2_TYPE;

Identifies the type of data contained in a PROPBAG2 structure.

PROPBAG2_TYPE_UNDEFINED
The value type is unknown or undefined.
PROPBAG2_TYPE_DATA
The value type is simple data.
PROPBAG2_TYPE_URL
The value type is a URL reference.
PROPBAG2_TYPE_OBJECT
The value type is an object.
PROPBAG2_TYPE_STREAM
The value type is a stream.
PROPBAG2_TYPE_STORAGE
The value type is a storage.
PROPBAG2_TYPE_MONIKER
The value type is a moniker.


ActiveX Control Containers

The purpose of this topic is to provide guidelines for implementing containers that will interoperate well with other controls and containers. This document defines the minimum set of interfaces, methods, and features that are required of ActiveX™ containers to accomplish seamless and useful interoperability.

Overview

ActiveX Control Containers

General Guidelines

Related Topics

Overview

An ActiveX control container must be able to host a minimal ActiveX control as specified in this document. It will also support a number of additional interfaces. A container can optionally support a number of interfaces and methods, which are grouped into functional areas known as component categories. A container can support any combination of component categories. For example, a component category exists for Databinding; a container may or may not support the data-binding functionality, depending on the market needs of the container. If a control needs data-binding support from a container to function, the control will enter this requirement in the registry. This allows a container to offer for insertion only those controls it knows it can successfully host. It is important to note that component categories are specified as part of OLE and are not specific to ActiveX Controls. The controls architecture uses component categories to identify areas of functionality that an OLE component might support. Component categories are not cumulative or exclusive, so a container can support one category without necessarily supporting another.

These guidelines define those interfaces and methods that a control can expect a container to support, although as always a control should check the return values when using QueryInterface or other methods to obtain pointers to these interfaces. A container should not expect a control to support anything more than the IUnknown interface. These guidelines identify what interfaces a control can support and what the presence of a particular interface means.

Why Are the ActiveX Control Container Guidelines Important?

ActiveX Controls have become the primary architecture for developing programmable software components for use in a variety of different containers, ranging from software development tools to end-user productivity tools. For a control to operate well in a variety of containers, the control must be able to assume some minimum level of functionality that it can rely on in all containers.

By following these guidelines, control and container developers make their controls and containers more reliable and interoperable, and, ultimately, better and more usable components for building component-based solutions.

This document provides guidelines toward good interoperability. It is expected that new interfaces and component categories will develop over time; future versions of this document reflecting these changes will be made readily available through Microsoft. It is important to note that this document does not cover detailed semantics of the OLE interfaces; this is covered by the SDK documentation.

What If an Interface You Need Is Not Available?

This section states some fundamental rules that apply to all OLE programming. OLE programs should use QueryInterface to acquire interface pointers, and must check the return value. OLE applications cannot safely assume that QueryInterface will succeed; this requirement applies to all OLE applications. If the requested interface is not available (that is, QueryInterface returns E_NOINTERFACE), the control or container must degrade gracefully, even if that means it cannot perform its designated job function.

What's New?

This release of the guidelines embraces the concept of component categories, which are a part of the OLE specification. In previous versions of this document, component categories were loosely referred to as "function groups" and were used to identify areas of functionality that a container can optionally support. For this version there has been a definition of how component categories work for ActiveX Controls, and some fundamental categories are identified. The use of component categories allows the relaxing of some of the previous rules that identified interfaces as being mandatory, and allows greater flexibility for controls to efficiently target certain areas of functionality without having to provide superfluous additional support in order to qualify as a control. This edition of the guidelines also discusses what the presence or absence of an interface means and what to do in that situation.

ActiveX Control Containers

ActiveX control containers must provide support for the following features:

  • Embedded objects from in-process servers
  • In-place activation
  • OLEMISC_ACTIVATEWHENVISIBLE
  • Event handling

The following sections describe the specific interfaces, methods, and other features that are required of ActiveX control containers. The last section describes how to gracefully degrade when a particular control interface is not supported.

Required Interfaces

The following table lists the ActiveX control container interfaces, denoting which interfaces are optional, and which are mandatory and must be implemented by containers.
Interface | Support mandatory? | Comments
IOleClientSite | Yes
IAdviseSink | No | Only when the container wants data change notifications (controls with IDataObject), view change notification (controls that are not active and have IViewObject[2]), and other notifications from controls acting as standard embedded objects.
IOleInPlaceSite | Yes
IOleControlSite | Yes
IOleInPlaceFrame | Yes
IOleContainer | Yes | See Note 1.
IDispatch for ambient properties | Yes | See Note 2 and "Ambient Properties" section
Control Event Sets | Yes | See Note 2.
ISimpleFrameSite | No | This interface and support for nested simple frames is optional.
IPropertyNotifySink | No | Only needed for containers that have their own property-editing UI, which would require updating whenever a control changed a property itself, or containers that want to control [requestedit] property changes and other such data-binding features.
IErrorInfo | Yes | Mandatory if container supports dual interfaces. See Note 2.
IClassFactory2 | No | Support is strongly recommended.

Notes:

  1. IOleContainer is implemented on the document or form object (or appropriate analog) that holds the container sites. Controls use IOleContainer to navigate to other controls in the same document or form.
  2. Support for dual interfaces is not mandatory, but is strongly recommended. Writing ActiveX control containers to take advantage of dual interfaces will afford better performance with controls that offer dual interface support.

ActiveX control containers must support OLE Automation exceptions. If a container supports dual interfaces, it must capture automation exceptions through IErrorInfo.

Optional Methods

An OLE component can implement an interface without implementing all the semantics of every method in the interface, instead returning E_NOTIMPL or S_OK as appropriate. The following table describes those methods that an ActiveX control container is not required to implement (that is, the container can return E_NOTIMPL).

The table also describes optional methods; note that the method must still exist, but can simply return E_NOTIMPL instead of implementing "real" semantics. Note that any method from a mandatory interface that is not listed in the table must be considered mandatory and cannot return E_NOTIMPL.
Method | Comments
IOleClientSite
SaveObject | Necessary for persistence to be successfully supported.
GetMoniker | Necessary only if the container supports linking to controls within its own form or document.
IOleInPlaceSite
ContextSensitiveHelp | Optional.
Scroll | Can return S_FALSE with no action.
DiscardUndoState | Can return S_OK with no action.
DeactivateAndUndo | Deactivation is mandatory; Undo is optional.
IOleControlSite
GetExtendedControl | Necessary for containers that support extended controls.
ShowPropertyFrame | Necessary for containers that want to include their own property pages to handle extended control properties in addition to those provided by a control.
TranslateAccelerator | Can return S_FALSE with no action.
LockInPlaceActive | Optional.
IDispatch (ambient properties)
GetTypeInfoCount | Necessary for containers that support nonstandard ambient properties.
GetTypeInfo | Necessary for containers that support nonstandard ambient properties.
GetIDsOfNames | Necessary for containers that support nonstandard ambient properties.
IDispatch (event sink)
GetTypeInfoCount | The control knows its own type information, so it has no need to call this.
GetTypeInfo | The control knows its own type information, so it has no need to call this.
GetIDsOfNames | The control knows its own type information, so it has no need to call this.
IOleInPlaceFrame
ContextSensitiveHelp
GetBorder | Necessary for containers with toolbar UI (which is optional).
RequestBorderSpace | Necessary for containers with toolbar UI (which is optional).
SetBorderSpace | Necessary for containers with toolbar UI (which is optional).
InsertMenus | Necessary for containers with menu UI (which is optional).
SetMenu | Necessary for containers with menu UI (which is optional).
RemoveMenus | Necessary for containers with menu UI (which is optional).
SetStatusText | Necessary only for containers that have a status line.
EnableModeless | Optional.
TranslateAccelerator | Optional.
IOleContainer
ParseDisplayName | Only if linking to controls or other embeddings in the container is supported, as this is necessary for moniker binding.
LockContainer | As for ParseDisplayName.
EnumObjects | Returns all ActiveX Controls through an enumerator with IEnumUnknown, but not necessarily all objects (since there's no guarantee that all objects are ActiveX Controls; some might be regular Windows® controls).

Miscellaneous Status Bits Support

ActiveX control containers must recognize and support the following OLEMISC_ status bits.
Status bit | Support mandatory? | Comments
ACTIVATEWHENVISIBLE | Yes
IGNOREACTIVATEWHENVISIBLE | No | Needed for inactive and windowless control support. See Note 1.
INSIDEOUT | No | Not generally used with ActiveX Controls but rather with compound document embeddings. Note this is contrary to some SDK documentation that says this bit must be set for the ACTIVATEWHENVISIBLE bit to be set.
INVISIBLEATRUNTIME | Yes | Designates a control that should be visible at design time, but invisible at run time.
ALWAYSRUN | Yes
ACTSLIKEBUTTON | No | Support is normally mandatory, although it is not necessary for document-style containers.
ACTSLIKELABEL | No | Support is normally mandatory, although it is not necessary for document-style containers.
NOUIACTIVATE | Yes
ALIGNABLE | No
SIMPLEFRAME | No
SETCLIENTSITEFIRST | No | Support for this bit is recommended but not mandatory.
IMEMODE | No

Notes:

  1. The IGNOREACTIVATEWHENVISIBLE bit is for containers hosting inactive and windowless controls. The bit is introduced as part of the ActiveX Controls 96 specification; see this documentation for more details.

Keyboard Handling

Keyboard handling support for the following functionality is strongly recommended, although it is recognized that it is not applicable to all containers:

  • Support for OLEMISC_ACTSLIKELABEL and OLEMISC_ACTSLIKEBUTTON status bits.
  • Implementing the DisplayAsDefault ambient property (if it exists, it can return FALSE).
  • Implementing tab handling, including tab order.

Some containers use ActiveX Controls in traditional compound document scenarios. For example, a spreadsheet might allow a user to embed an ActiveX control into a worksheet. In such scenarios, the container would do keyboard handling differently, because the keyboard interface should remain consistent with the user's expectations of a spreadsheet. Documentation for such products should inform users of differences in control handling in these different scenarios. Other containers should endeavor to honor the above functionality correctly, including mnemonic handling.

Storage Interfaces

Containers must be able to support controls that implement IPersistStorage, IPersistStream, or IPersistStreamInit. Optionally, a container can support any other persistence interfaces, such as IPersistMemory, IPersistPropertyBag, and IPersistMoniker, for those controls that provide support.

After an ActiveX control container has chosen and initialized a storage interface to use ( IPersistStorage, IPersistStream, IPersistStreamInit, and so on), that storage interface will remain the primary storage interface for the lifetime of the control; that is, the control will remain in possession of the storage. This does not preclude the container from saving to other storage interfaces.

ActiveX control containers do not need to support a "save as text" mechanism, thus using IPersistPropertyBag and the associated container-side interface IPropertyBag are optional.

Ambient Properties

At a minimum, ActiveX control containers must support the following ambient properties using the standard DISPIDs.
Ambient property | DISPID | Comments/Conditions
LocaleID | -705
UserMode | -709 | For containers that have different user and run environments.
DisplayAsDefault | -713 | For those containers where a default button is relevant.

Extended Properties, Events, and Methods

ActiveX control containers are not required to support extended controls. However, if the container does support extended properties, it must support the following minimal set:
Visible
Parent
Default
Cancel

Currently, extended properties, events, and methods do not have standard DISPIDs.

Message Reflection

It is strongly recommended that an ActiveX control container support message reflection. This will result in more efficient operation for subclassed controls. If message reflection is supported, the MessageReflect ambient property must be supported and have a value of TRUE. If a container does not implement message reflection, the OLE CDK creates two windows for every subclassed control, to provide message reflection on behalf on the container.

Automatic Clipping

It is strongly recommended that an ActiveX control container support automatic clipping of its controls. This will result in more efficient operation for most controls. If automatic clipping is supported, the AutoClip ambient property must be supported and have a value of TRUE.

Automatic clipping is the ability of a container to ensure that a control's drawn output goes only to the container's current clipping region. In a container that supports automatic clipping, a control can paint without regard to its clipping region, because the container will automatically clip any painting that occurs outside the control's area. If a container does not support automatic clipping, CDK-generated controls will create an extra parent window if a nonnull clipping region is passed.

Degrading Gracefully in the Absence of an Interface

Because a control might not support any interface other than IUnknown, a container has to degrade gracefully when it encounters the absence of any particular interface.

One might question the usefulness of a "control" with nothing more than IUnknown. But consider the advantages that a control receives from a container's visual programming environment (such as Microsoft Visual Basic®) when the container recognizes the object as a "control":

  1. A button for the object appears in a toolbox.
  2. One can create an object by dragging it from the toolbox onto a form.
  3. One can give the object a name that is recognized in the visual programming environment.
  4. The same name in (3) above can be used immediately in writing any other code for controls on the same form (or even a different form).
  5. The container can automatically provide code entry points for any events available from that object.
  6. The container provides its own property browsing UI for any available properties.

When an object isn't recognized as a "control," it potentially loses all of these very powerful and beneficial integration features. For example, in Visual Basic 4.0 it is very difficult to really integrate some random object that is not a "control" in the complete sense, but may still have properties and events. Because Visual Basic 4.0's idea of a control is very restrictive, the object does not gain any of the integration features mentioned previously. But even a control with IUnknown, where the mere lifetime of the control determines the existence of some resource, should be able to gain the integration capabilities described above.

Because current tools require a large set of control interfaces to gain any advantage, controls are generally led to over-implementation, such that they contain more code than they really need. Controls that could be 7K might end up being 25K, which is a big performance problem in areas such as the Internet. This has also led to the perception that one can only implement a control with one tool, such as the CDK, because of the complexity of implementing all the interfaces. This has implications when a large DLL such as Oc30.dll is required for such a control, increasing the working set. If not all interfaces are required, this opens up many developers to writing very small and light controls with straight OLE or with other tools as well, minimizing the overhead for each control.

This is why this document recognizes a "control" as any object with a CLSID and an IUnknown interface. Even with nothing more than IUnknown, a container with a programming environment should be able to provide at least features (3) and (4) from the list above. If the object provides a ToolBoxBitmap32 registry entry, it gains (1) and (2). If the object supplies IConnectionPointContainer (and IProvideClassInfo generally) for some event set, it gains (5), and if it supports IDispatch for properties and methods, it gains (6), as well as better code integration in the container.

In short, an object should be able to implement as little as IDispatch and one event set exposed through IConnectionPointContainer to gain all the visual features above.

With this in mind, the following table describes what a container might do in the absence of any possible interface. Note that only those interfaces are listed that the container will directly obtain through QueryInterface. Other interfaces, such as IOleInPlaceActiveObject, are obtained through other means.
Interface | Meaning of interface absence
IViewObject2 | The control has no visuals that it will draw itself, so has no definite extents to provide. In run time, the container simply doesn't attempt to draw anything when this interface is absent. In design time, the container must at least draw some kind of default rectangle with a name in it for such a control, so a user in a visual programming environment can select the object and check out its properties, methods, and events that exist. Handling the absence of IViewObject2 is critical for good visual programming support.
IOleObject | The control doesn't need the site whatsoever, nor does it take part in any embedded object layout negotiation. Any information (such as control extents) that a container might expect from this interface should be filled in with container-provided defaults.
IOleInPlaceObject | The control doesn't go in-place active (like a label) and thus never attempts to activate in this manner. Its only activation might be its property pages.
IOleControl | Control has no mnemonics and no use of ambient properties, and doesn't care if the container ignores events. In the absence of this interface, the container just doesn't call its members.
IDataObject | The control provides no property sets nor any visual renderings that could be cached, so the container would choose to cache some default presentation in the absence of this interface (support for CF_METAFILEPICT, specifically) and disable any property-set related functionality.
IDispatch | The control has no custom properties or methods. The container does not need to try to show any control properties in this case, and should disallow any custom method calls that the container doesn't recognize as belonging to its own extended controls (that might support methods and properties). As extended controls generally delegate certain IDispatch calls to the control, an extended control should not expect the control to have IDispatch at all.
IConnectionPointContainer | The control has no events, so the container doesn't have to think about handling any.
IProvideClassInfo[2] | The control either doesn't have type information or events, or the container needs to go into the control's type information through the control's registry entries. The existence of this interface is an optimization.
ISpecifyPropertyPages | The control has no property pages, so if the container has any UI that would invoke them, the container should disable that UI.
IPerPropertyBrowsing | The control has no display name itself, no predetermined strings and values, and no property to page mapping. This interface is nearly always used for generating container user interface, so such UI elements would be disabled in the absence of this interface.
IPersist* | The control has no persistent state to speak of, so the container doesn't have to worry about saving any control-specific data. The container will, of course, save its own information about the control in its own form or document, but the control itself has nothing to contribute to that information.
IOleCache[2] | The object doesn't support caching. A container can still support caching by just creating a data cache itself using CreateDataCache.

General Guidelines

This section describes various features, hints, and tips for ActiveX control and ActiveX control container developers to help ensure good interoperability between controls and containers.

Overloading IpropertyNotifySink

Many ActiveX control containers implement a modeless property browsing window. If a control's properties are altered through the control's property pages, the control's properties can get out of sync with the container's view of those properties (the control is always right, of course). To ensure that it always has the current values for a control's properties, an ActiveX control container can overload the IPropertyNotifySink interface (data binding) and also use it to be notified that a control property has changed. This technique is optional, and is not required of ActiveX control containers or ActiveX Controls.

Note A control should use IPropertyNotifySink::OnRequestEdit only for data binding; it is free to use OnChanged for either or both purposes.

Container-Specific Private Interfaces

Some containers provide container-specific private interfaces for additional functionality or improved performance. Controls that rely on those container-specific interfaces should, if possible, work without those container-specific interfaces present so that the control functions in different containers. For example, Visual Basic implements private interfaces that provide string formatting functionality to controls. If a control makes use of the Visual Basic private formatting interfaces, it should be able to run with default formatting support if these interfaces are not available. If the control can function without the private interfaces, it should take appropriate action (such as warn the user of reduced functionality) but continue to work. If this is not an option, a component category should be registered as required to ensure that only containers supporting this functionality can host these controls.

Multithreaded Issues

Starting with Microsoft Windows 95 and Microsoft Windows NT® 3.51, OLE provides support for multithreaded applications, allowing applications to make OLE calls from multiple threads. This multithreaded support is called the "apartment model"; it is important that all OLE components using multiple threads follow this model. The apartment model requires that interface pointers are marshaled (using CoMarshalInterface and CoUnmarshalInterface) when passed between threads. For more information about apartment model threading, refer to the Platform SDK documentation and the OLEAPT sample (in the Platform SDK).

Event Freezing

A container can notify a control that it is not ready to respond to events by calling IOleControl::FreezeEvents(TRUE). It can unfreeze the events by calling IOleControl::FreezeEvents(FALSE). When a container freezes events, it is freezing event processing, not event receiving; that is, a container can still receive events while events are frozen. If a container receives an event notification while its events are frozen, the container should ignore the event. No other action is appropriate.

A control should take note of a container's call to IOleControl::FreezeEvents(TRUE) if it is important to the control that an event is not missed. While a container's event processing is frozen, a control should implement one of the following techniques:

  • Fire the events in the full knowledge that the container will take no action.
  • Discard all events that the control would have fired.
  • Queue up all pending events and fire them after the container has called IOleControl::FreezeEvents(FALSE).
  • Queue up only relevant or important events and fire them after the container has called IOleControl::FreezeEvents(FALSE).

Each technique is acceptable and appropriate in different circumstances. The control developer is responsible for determining and implementing the appropriate technique for the control's functionality.

Container Controls

As described previously, container controls are ActiveX Controls that visually contain other controls. The ActiveX Controls architecture specifies the ISimpleFrameSite interface to enable container controls. Containers can also support container controls without supporting ISimpleFrameSite, although the behavior cannot be guaranteed. For this reason, a component category exists for SimpleFrameSite controls where the full functionality of this interface is required.

To support container controls without implementing ISimpleFrameSite, an ActiveX control container must:

  • Activate all controls at all times.
  • Reparent the contained controls to the hWnd of the containing control.
  • Remain the parent of the container control.

WS_GROUP and WS_TABSTOP Flags in Controls

A control should not use the WS_GROUP and WS_TABSTOP flags internally; some containers rely on these flags to manage keyboard handling.

Multiple Controls in One DLL

A single .ocx DLL can container any number of ActiveX Controls, thus simplifying the distribution and use of a set of related controls.

If you ship multiple controls in a single DLL, be sure to include the vendor name in each control name in the package. Including the vendors' names in each control name will enable users to easily identify controls within a package. For example, if you ship a DLL that implements three controls, Con1, Con2 and Con3, the control names should be:

<Your company name> Con1 Control
<Your company name> Con2 Control
<Your company name> Con3 Control

IOleContainer::EnumObjects

This method is used to enumerate over all the OLE objects contained in a document or form, returning an interface pointer for each OLE object. The container must return pointers to each OLE object that shares the same container. Nested forms or nested controls must also be enumerated.

Some containers implement "extender controls," which wrap non-ActiveX controls, and then return pointers to these extender controls as a form is enumerated. This behavior enables ActiveX Controls and ActiveX control containers to integrate well with non-ActiveX controls, and is thus recommended but not required.

Enhanced Metafiles

Not surprisingly, enhanced metafiles provide more functionality than standard metafiles; using enhanced metafiles generally simplifies rendering code. An enhanced metafile device context (DC) is used in exactly the same way as a standard metafile DC. Enhanced metafiles are not available in 16-bit OLE. OLE supports enhanced metafiles, and includes backward compatibility with standard metafiles and 16-bit applications.

A 32-bit ActiveX control container should use enhanced metafiles instead of standard metafiles.

Licensing

In order to embed licensed controls successfully, ActiveX control containers must use IClassFactory2 instead of IClassFactory. Several OLE creation and loading helper functions (for example, OleLoad and CoCreateInstance) explicitly call IClassFactory and not IClassFactory2, and therefore cannot be used to create or load licensed ActiveX Controls. ActiveX control containers should explicitly create and load ActiveX Controls using IClassFactory2. In the future, Microsoft will update these standard APIs to use both IClassFactory and IClassFactory2, as appropriate.

Dual Interfaces

OLE Automation enables an object to expose a set of methods in two ways: through the IDispatch interface, and through direct OLE Vtable binding. IDispatch is used by most tools available today, and offers support for late binding to properties and methods. Vtable binding offers much higher performance because this method is called directly instead of through IDispatch::Invoke. IDispatch offers late bound support, where direct Vtable binding offers a significant performance gain; both techniques are valuable and important in different scenarios. By labeling an interface as "dual" in the type library, an OLE Automation interface can be used through IDispatch, or it can be bound to directly. Containers can thus choose the most appropriate technique. Support for dual interfaces is strongly recommended for both controls and containers.

IPropertyBag and IpersistPropertyBag

IPropertyBag and IPersistPropertyBag optimize "save as text" mechanisms, and therefore are recommended for ActiveX control containers that implement a "save as text" mechanism. IPropertyBag is implemented by a container, and is roughly analogous to IStream. IPersistPropertyBag is implemented by controls, and is roughly analogous to IPersistStream.

Related Topics

COM Objects for the Internet
Asynchronous and URL Monikers
Hyperlinks


Signing Code with Microsoft Authenticode Technology

This document explains how to digitally sign files with Microsoft(r) Authenticode(tm) technology included in the Microsoft Internet Client SDK. These digital signatures associate a software vendor's name and unique public key with a file, thus assuring some level of accountability.

Currently, Authenticode allows software vendors to sign:

  • .exe files
  • .cab files
  • .ocx and .dll files
  • .ctl files

Important Release Information

Introduction to Code Signing

Signing and Checking Code with Authenticode

Glossary

Appendix A: Required Files

Appendix B: The X.509 Certificate

Appendix C: Suggested Reading


Building ActiveX Controls for Internet Explorer 4.0

This article covers features of Microsoft® Internet Explorer 4.0 that a developer writing ActiveX™ Controls should take into account when targeting Internet Explorer 4.0 as a container. Some of the material in this article discusses existing technologies that have increased relevance with Internet Explorer 4.0; other sections discuss new technologies and services that are only available to a control in Internet Explorer 4.0. For an in-depth description of these technologies and reference documentation, the Internet Client SDK is the best source of information. To get the most out of this article the reader should already be familiar ActiveX Controls and associated COM technologies.

Justification for Targeting Internet Explorer as an ActiveX Control Container

Apartment-Model Awareness

OC96 and Windowless Controls

Accessing Dynamic HTML

Multimedia Services

Security

Authoring Controls for the Active Desktop

Debugging

Deployment

Appendix: Additional Guidelines and Version Differences

Justification for Targeting Internet Explorer as an ActiveX Control Container

Internet Explorer is built upon a foundation of reusable and extensible components; two of the main components—the WebBrowser Control (SHDOCVW) and the HTML parsing and rendering engine (MSHTML)—are available for reuse as part of other applications. An increasing number of Microsoft and third-party applications will be using the same underlying control container; thus, if a control works well in Internet Explorer 4.0 it will also work well in future applications. Current examples of this component reuse in the Internet Explorer suite include the Active Desktop and Outlook Express. Both use the same HTML rendering engine as Internet Explorer.

Apartment-Model Awareness

Apartment-model awareness is not a new issue with Internet Explorer 4.0, but it is an important one because of architectural changes in the multithreaded nature of containers such as Internet Explorer, the Active Desktop, and Outlook Express. Multiple instances of these containers are now quite common, so ActiveX Controls should be developed to conform to apartment-model rules to ensure that they behave correctly.

If a control is not apartment-model aware, the control might not function correctly. At the very least, it will suffer from degraded performance because calls to the control will be marshaled. This is due to the creation of the control being handled differently by the system if the control marks itself as being apartment-model-aware. Internet Explorer 4.0 will also reject improper calls across thread boundaries.

There are two relatively simple steps involved in making a control apartment-model-aware:

  • Protect global resources. When data that is shared among instances of the control is being accessed, it should be protected so that other instances of the control do not attempt to access it at the same time. For example:
    ::EnterCriticalSection(&g_cs);
// Access global data
// ....
::LeaveCriticalSection( &g_cs );
  • Mark the control in the registry as "Apartment". This indicates to the system that the control understands and conforms to apartment-model rules and causes COM to create the control in its own apartment.

For further details about OLE threading models, see article Q150777, "Descriptions and Workings of OLE Threading Models," in the Microsoft Knowledge Base.

OC96 and Windowless Controls

While the OC96 (or OLE Controls '96) specification is not new, full support is only now appearing in common containers such as Office 97 and Internet Explorer 4.0; thus, the specification deserves further attention. One of the primary driving forces behind this specification was to improve the performance of controls for use on the Internet. An additional key feature is support for windowless controls. Windowless controls not only provide better performance, but they also can participate in overlapping 2D layout, can maintain a specific z-order, and can exhibit transparency as well as irregular shapes. Visual Filter effects will only function on components that support the windowless control specification since traditional windowed controls don't provide the hooks required for filters to affect painting. All the enhancements are designed to be compatible with existing OLE Controls technology, so a control can leverage these new features while maintaining backward-compatibility with down-level containers.

Key features of OC96 include:

Delayed activation.
Delaying the activation of a control means that a page can instantiate and be ready for interaction with the user faster, particularly if there are multiple controls on the page. A new interface, IPointerInactive, allows a control to remain inactive but still interact minimally with the mouse and drag and drop. Although the control still activates, it does so only as the result of some interaction with the user.
Windowless.
By supporting the windowless control specification, a control can make efficient use of its container's window rather than having a window of its own. This results in using fewer system resources and improves performance through faster activation/deactivation. The new interfaces introduced to support windowless controls include IOleInPlaceObjectWindowless and IOleInPlaceSiteWindowless. When drawing itself, a control asks the container-provided IOleInPlaceSiteWindowless interface for a device context and returns the device context to the container after drawing into it. Providing windowless support not only provides transparency for interesting visual effects, but also further improves the performance of the control.
Hit detection.
Hit detection is provided so that a windowless control can have an irregular shape and to complete the visual benefits of transparency. If the container detects that the rectangular extent occupied by a windowless control has been hit, it calls IViewObjectEx::QueryHitPoint (another new interface for windowless controls). The control then determines if it has been hit and returns an indication to the container.
Quick activation.
A new, optional interface, IQuickActivate, has been introduced to further speed activation of a control. If a container such as Internet Explorer 4.0 determines that this interface is supported by a control it is instantiating, the container calls IQuickActivate, passing two structures, one that the container uses to provide ambient properties and interface pointers to the control and the other for data that the control returns to the container. Replacing multiple calls with a single call increases the efficiency of instantiating a control.

Accessing Dynamic HTML

Internet Explorer 4.0 allows components to access the Dynamic HTML object model of the document in which the control is hosted. All the capabilities of the object model are available to the control, allowing it to both read and modify the document content. If a control supports either the IObjectWithSite or IOleObject interface, accessing the object model is very simple and consists of the following two steps:

  1. Call IOleClientSite::GetContainer. This returns the IOleContainer interface of the host of the control.
  2. Call QueryInterface on the IOleContainer interface for the IHTMLDocument2 interface.

The IHTMLDocument2 interface provides access to the document in which the control is hosted. Given this interface, it is possible to traverse the entire HTML object model. The following bit of code, written using Active Template Library (ATL) 2.0 smart pointers, accesses the object model and sets the background color of the document to pink. In script this is equivalent to document.bgColor = "pink".

// Get the document
CComPtr<IOleContainer> spContainer;
m_spClientSite->GetContainer(&spContainer);
CComQIPtr<IHTMLDocument2, &IID_IHTMLDocument2> spDoc(spContainer);
if (spDoc)
    spDoc->put_bgColor(CComBSTR(_T("pink")));

Controls can perform any of the manipulations available to script in Internet Explorer 4.0. They can also perform functions that aren't possible from script due to security restrictions that do not apply to ActiveX Controls. To aid in the development process, use script to prove a concept; then translate that script to interface-level manipulation.

Note Any of the new interfaces introduced with Internet Explorer 4.0 are subject to change until the product is officially released. It is recommended that you maintain a copy of the header files you used to develop your code. When you upgrade to a later build of Internet Explorer 4.0, upgrade to the corresponding build of the Internet Client SDK, and use a file comparison tool such as Windiff to compare headers. Windiff is a utility that ships with the Microsoft Platform SDK as well as Microsoft Visual C++®.

Multimedia Services

Internet Explorer 4.0 ships with a number of multimedia controls; however, the services these controls use are also available to third-party controls. These include pixel-level manipulation, soon-to-be-introduced DirectDraw® support, timer and synchronization services, and visual filters and transitions. The full specifications and samples are included in the Internet Client SDK.

Security

Any ActiveX control to be deployed and used with Internet Explorer should be conceived and designed with object safety in mind from the start. Object safety is a promise by the control author about the potential for the control to be used in a manner that might compromise security. There are two variations of object safety that usually, but not always, go together:

  • Safe for untrusted data asserts that the control is safe for any possible arguments (< PARAM> tags of an < OBJECT>).
  • Safe for scripting asserts that the control is safe for any possible use of its properties, methods, and events.

ActiveX Control Safety Checklist

Safety of the control is ultimately a subjective judgment, but as a general rule "safe" means that none of the following undesirable effects will result for any conceivable use of the control:

  • Exposure of private information on the local computer or network
  • Modification or destruction of information on the local computer or network
  • Faulting of the control and the potential crashing of the browser
  • Consumption of excessive time or resources such as memory
  • Execution of potentially damaging system calls, including execution of files
  • Use of the control in a deceptive manner and causing unexpected results

To help check these abstract requirements, here are some questions to consider carefully before marking a control as safe. The same questions apply to both untrusted data and scripting.

  • What files can the control potentially access?
    • The ability to create files can be used to put content into the trusted local computer file system, possibly overwriting valuable data.
    • Any arguments that allow arbitrary file paths to be specified are particularly suspect as potentially allowing access to private information.
    • Writing excessive amounts of data even to restricted sets of files can use up disk space.
  • Is registry access possible?
    • Access to even limited parts of the registry could reveal information that should be kept private.
    • Writing large amounts of data to the registry could waste resources or possibly corrupt the system.
  • What system calls can the control be made to do?
    • Executing code or arbitrary shell commands (such as FORMAT) is particularly dangerous.
    • Think about how any system calls might be used by a malicious page, especially those calls with arguments that can be influenced by an untrusted data (<PARAM>) or script invocation.
  • Other issues:
    • Since any control can be used by any page that happens to know its CLSID, think about how the control might be reused maliciously in a completely unrelated page. Would the user possibly be tricked by seeing the familiar control out of context?
    • Be sure the control won't loop infinitely or crash when given bad data or arguments.
    • Can the control be made to call other objects on the page, including Java™ applets? The Java virtual machine (VM) called from native code in the control could attribute greater permissions to the control than script on the page has. If the script can manipulate the control to call the Java VM for it, an indirect security attack is possible.
    • Can the control tunnel out of the frame in which it is hosted and access content in another frame? The data accessed could potentially violate the privacy of the user.

Using ActiveX Controls Safely in an Enterprise Intranet Environment

Using Internet Explorer 4.0 Security Zones, it is possible to configure the browser to only download or run ActiveX Controls located with the enterprise, a.k.a. the intranet. When a control is downloaded and installed on the local system, however, the location of the original download is no longer available, and the control is available for use on any page that might reference its CLSID. Thus, take heed to the possibility that an Internet page might reference a control intended only for the intranet. There are several approaches to handling this issue. If the ActiveX Controls are safe for untrusted data and for scripting, supporting IObjectSafety and requiring only safe controls is the simplest solution. Controls that are truly safe should not be usable to break security, even by an untrusted Internet page. To prevent an ActiveX control from being used on pages other than the one on which it is intended, the control can check the context in which it is instantiated. That is, a control can get access to the DHTML object model as described previously to get the URL of the page instantiating it. The location properties of the document object return the URL of the page in which the control is embedded. For instance, an ActiveX control could be designed to run only in the "http://admin" intranet area. When the URL of the containing document begins with a different protocol and host name, it could run with reduced functionality or otherwise completely disable itself. Be aware that some important controls might be inherently unsafe for scripting. They include tools to aid system configuration or installation. To safely use these ActiveX Controls in the intranet environment, it is important to guarantee:

  • That these controls be used only by intranet pages and cannot be reused by other untrusted security zones;
  • That any intranet pages that use these controls do so in the intended manner and with appropriate safeguards.

The first restriction can be enforced because, by default, ActiveX Controls are not safe for scripting. A system administrator can configure a custom security policy to override object safety for a specific intranet zone. Controls that are not marked as safe will run only in pages from this zone. In fact, it is possible to restrict a control to run only in a designated secure zone by explicitly not marking the control as safe. Of course the Internet zone should never be set to override object safety.

Authoring Controls for the Active Desktop

Internet Explorer 4.0 introduces several key innovations to the user's browsing experience. Among these are offline browsing and the Active Desktop. The former uses a caching mechanism to allow the user to read content from the Web without requiring them to be connected to it. The latter turns the desktop into a Web page by enabling the user to add any content viewable in the browser as an item to the Active Desktop including ActiveX controls. Network-aware components should understand the issues involved in authoring components for the Active Desktop that behave well in the offline state. For more information see the article on Supporting Offline Browsing in Applications and Components.

Debugging

In Internet Explorer 4.0 Integrated Browser Mode, the Windows® shell and the Web browser run in the same process space. This poses a challenge to developers who are attempting to debug their controls. Testing controls in Integrated Browser Mode is recommended because it helps to reveal apartment-model issues. For specific information on debugging ActiveX Controls in Internet Explorer 4.0, see Q167715, "Debugging ActiveX Controls in IE 4.0 Integrated Browser," in the Microsoft Knowledge Base.

Deployment

When deploying controls, use cabinet (.cab) files, and sign your controls. Issues regarding security have received great attention recently. End users are not advised to download executable content unless it is signed. If you do not sign your control, you cannot expect users to download your product. Cabinet files also create a better end-user experience because only one certificate is presented to the user, and a single, compressed download brings multiple files to the client computer. Details of this technology are in the Internet Client SDK.

Don't assume that non-system DLLs are already installed on a client computer. Although some releases of Internet Explorer ship with certain DLLs, such as MFC and Ctl3d32, this is not a reasonable assumption for minimal installations as well as future versions of Internet Explorer. In circumstances where a control is dependent on such DLLs, the main cabinet file should reference additional cabinets that contain the dependencies so they will be downloaded if necessary.

Appendix: Additional Guidelines and Version Differences

This section presents additional guidelines for creating controls as well as known differences in Internet Explorer's control hosting behavior between version 3.0 and 4.0. Internet Explorer 3.0 hosted controls in a slightly more relaxed fashion than Internet Explorer 4.0; Internet Explorer 4.0 follows the control container specification more stringently. This allows control authors to better anticipate the behavior of Internet Explorer 4.0 as a control container; however, it also means that controls which made assumptions based on Internet Explorer 3.0 behavior might no longer function as desired in Internet Explorer 4.0. Here we present the caveats we have discovered to control authors.

  • If a control fires an event from a thread that it creates, rather than from the thread in which it was created, the connection point interface through which the event is fired must be marshaled to the secondary thread. For more information, see Q157437, "FIREV.EXE Fires Events from a Second Thread," in the Microsoft Knowledge Base.
  • Internet Explorer 4.0 calls FindConnectionPoint on a control to hook up events even if the control exposes no events. A control should be written to expect this call.
  • As previously mentioned, controls should be authored to respect apartment-model rules.
  • The VBScript engine no longer passes parameters to controls by value (ByVal); they are now passed by reference (ByRef). Controls should check the VARTYPE field of parameters of type VARIANT explicitly.
  • Internet Explorer 3.0 sent DoVerb with the verbs OLEIVERB_SHOW and OLEIVERB_HIDE to controls in addition to the verb OLEIVERB_INPLACEACTIVATE and IOleInPlaceObject::InPlaceDeactivate. Internet Explorer 4.0 no longer sends the show and hide verbs. A control should rely only on receiving the OLEIVERB_INPLACEACTIVATE verb and the IOleInPlaceObject::InPlaceDeactivate call.
  • Internet Explorer 3.0 activated all controls immediately upon initialization of the control. Internet Explorer 4.0 does not. Instead it implements an optimization, only activating a control when it is visible (OLEMISC_ACTIVATEWHENVISIBLE). If a control needs to process window messages at initialization, it should create a hidden window for that purpose.
  • In Internet Explorer 4.0, if a control implements a ReadyState property (DISPID_READYSTATE), events will remain frozen until the control notifies the container that the ready state has changed to READYSTATE_COMPLETE. Internet Explorer expects this notification through its IPropertyNotifySink::OnChanged implementation. Internet Explorer 3.0 would unfreeze events even if the control never reached the completed state. All controls should implement a ReadyState property to communicate their initialization status to scripts.
  • A control should listen to IOleControl::FreezeEvents calls from the container. If a control fires an event that is important when events are frozen, the event will not be received by scripts. While it is not typically harmful to fire an event when events are frozen, if events are critical, the control should maintain a freeze count and implement a queuing mechanism, firing those queued events when FreezeEvents is called with FALSE and the freeze count reaches 0.
  • In Internet Explorer 3.0, controls were unloaded when the browser was closed. Internet Explorer 4.0 relies upon proper COM reference counting. When the last reference to a control is released, the control will unload. Likewise, when the last reference to Internet Explorer is released, the browser will unload. A control should take care when caching interface pointers such as those returned by IOleClientSite::GetContainer and IOleControlSite::GetExtendedObject.
  • A control should use the WM_CONTEXTMENU message to trigger a context menu and not utilize the WM_RBUTTONUP message.
  • A control should not forcefully UI activate itself, or assume itself to be UI active. This is an area in which the page author should be in control, and a control that needs the focus should have it set through script. In the case of multiple controls on a page, a UI activation battle could cause strange results. Take as another example a control at the bottom of a large page that forcefully scrolls into view were it to UI activate itself upon instantiation.
  • A control should only bring up modal dialog boxes when requiring immediate response to some user interaction. On the contrary, a control asynchronously downloading data in the background should not display a modal dialog box if the link fails. Instead it should fire an error event that a script could handle in its own fashion. Always keep the user in mind, as well as the effect a control's behavior will have upon applications hosting your control directly or indirectly through Internet Explorer 4.0 components.
  • Controls should take advantage of the Internet Explorer 4.0 implementation of the IBindHost interface when performing data download. IBindHost can be obtained from Internet Explorer through the IServiceProvider interface, which is available by querying the IOleClientSite interface. For details, see the ATL 2.0 implementation of IBindStatusCallback, specifically IBindStatusCallbackImpl::StartAsyncDownload.
  • Internet Explorer 4.0 eliminates the four-page in-memory cache. In Internet Explorer 3.0, controls would remain alive even though the page in which they were embedded was no longer in view. Assuming proper reference counting, Internet Explorer 4.0 destroys all controls embedded on the page when the user navigates away from the page. To keep a control alive, consider implementing a FRAMESET and placing the OBJECT tag in the HEAD element of the page containing the FRAMESET. While this instance of the control is not visible, it could provide global data for use by other objects contained within other frames within the frameset.
  • Internet Explorer 4.0 prints documents by instantiating a second instance of the document on a background thread, by restoring the state of the document, and by requesting that the document print itself. To provide proper support for printing in Internet Explorer 4.0, controls should support one of the persistence interfaces (IPersist*). In addition, controls should make no assumptions about the type of device context (DC) they receive: controls should provide device independent rendering support. Finally, since controls are not put into the UI Active state when printed in the background, they should not rely upon window handles (HWND).


ActiveX Controls

This section introduces ActiveX™ Controls and provides general guidelines for control developers. It includes information about run-time licensing for an ActiveX control, identifying an ActiveX control as safe for scripting or safe for code download, packaging an ActiveX control in a .cab file, and applying a test certificate to an ActiveX control.

In addition, this section includes information describing the differences between ActiveX Controls written for Internet Explorer 3.0 and ActiveX Controls written for Internet Explorer 4.0.

Introduction to ActiveX Controls

Building ActiveX Controls for Internet Explorer 4.0

ActiveX Control Tutorial

Safe Initialization and Scripting for ActiveX Controls

Licensing ActiveX Controls

Signing Code with Microsoft Authenticode Technology

Packaging ActiveX Controls

Palette Management for ActiveX Objects

Registering an ActiveX Object as the Player for a Media Type

Related Topics

Asynchronous and URL Monikers

Hyperlinks


Introduction to ActiveX Controls

The purpose of this topic is to provide guidelines for implementing ActiveX™ Controls that interoperate well with containers and other controls. This document defines the minimum set of interfaces, methods, and features that are required of ActiveX Controls to accomplish seamless and useful interoperability.

Overview

ActiveX Controls

General Guidelines

Overview

An ActiveX control is essentially a simple OLE object that supports the IUnknown interface. It usually supports many more interfaces in order to offer functionality, but all additional interfaces can be viewed as optional and, as such, a container should not rely on any additional interfaces being supported. By not specifying additional interfaces that a control must support, a control can efficiently target a particular area of functionality without having to support particular interfaces to qualify as a control. As always with OLE, whether in a control or a container, it should never be assumed that an interface is available, and standard return-checking conventions should always be followed. It is important for a control or container to degrade gracefully and offer alternative functionality if a required interface is not available.

It is important for controls that require optional features, or features specific to a certain container, to be clearly packaged and marketed with those requirements. Similarly, containers that offer certain features or component categories must be marketed and packaged as offering those levels of support when hosting ActiveX Controls. It is recommended that controls target and test with as many containers as possible, and degrade gracefully to offer less or alternative functionality if interfaces or methods are not available. In a situation where a control cannot perform its designated job function without the support of a component category, that category should be entered as a requirement in the registry to prevent the control being inserted in an inappropriate container.

These guidelines define those interfaces and methods that a control can expect a container to support, although as always a control should check the return values when using QueryInterface or other methods to obtain pointers to these interfaces. A container should not expect a control to support anything more than the IUnknown interface. These guidelines identify what interfaces a control can support and what the presence of a particular interface means.

Why Are ActiveX Controls Important?

ActiveX Controls have become the primary architecture for developing programmable software components for use in a variety of different containers, ranging from software development tools to end-user productivity tools. For a control to operate well in a variety of containers, the control must be able to assume some minimum level of functionality that it can rely on in all containers.

By following these guidelines, control developers make their controls more reliable and interoperable, and, ultimately, better and more usable components for building component-based solutions.

This document provides guidelines toward good interoperability. It is expected that new interfaces and component categories will develop over time; future versions of this document reflecting these changes will be made readily available through Microsoft. It is important to note that this document does not cover detailed semantics of the OLE interfaces; this is covered by the SDK documentation.

What If an Interface You Need Is Not Available?

This section states some fundamental rules that apply to all OLE programming. OLE programs should use QueryInterface to acquire interface pointers, and must check the return value. OLE applications cannot safely assume that QueryInterface will succeed. This requirement applies to all OLE applications. If the requested interface is not available (that is, QueryInterface returns E_NOINTERFACE), the control or container must degrade gracefully, even if that means it cannot perform its designated job function.

What's New?

This release of the guidelines embraces the concept of component categories, which are a part of the OLE specification. In previous versions of this document, component categories were loosely referred to as "function groups" and were used to identify areas of functionality that a container can optionally support. For this version there has been a definition of how component categories work for ActiveX Controls, and some fundamental categories are identified. The use of component categories allows the relaxing of some of the previous rules that identified interfaces as being mandatory, and allows greater flexibility for controls to efficiently target certain areas of functionality without having to provide superfluous additional support in order to qualify as a control. This edition of the guidelines also discusses what the presence or absence of an interface means and what to do in that situation.

The remainder of this document is divided into four sections. The first discusses guidelines for implementing controls, the second discusses guidelines for implementing containers, the third discusses component categories, and the fourth discusses general guidelines, relevant to both control and container developers.

ActiveX Controls

An ActiveX control is really just another term for "OLE Object" or, more specifically, "COM Object." In other words, a control, at the very least, is some COM object that supports the IUnknown interface and is also self-registering. Through IUnknown::QueryInterface a container can manage the lifetime of the control, as well as dynamically discover the full extent of a control's functionality based on the available interfaces. This allows a control to implement as little functionality as it needs to, instead of supporting a large number of interfaces that actually don't do anything. In short, this minimal requirement for nothing more than IUnknown allows any control to be as lightweight as it can.

Other than IUnknown and self-registration, there are no other requirements for a control. There are, however, conventions that should be followed about what the support of an interface means in terms of functionality provided to the container by the control. This section describes what it means for a control to actually support an interface, as well as methods, properties, and events that a control should provide as a baseline if it has occasion to support methods, properties, and events.

Self-Registration

ActiveX Controls must support self-registration by implementing the DllRegisterServer and DllUnregisterServer functions. ActiveX Controls must register all the standard registry entries for embeddable objects and automation servers.

ActiveX Controls must use the Component Categories API to register themselves as a control and register the component categories that they require a host to support, and any categories that the control implements. In addition, an ActiveX control might want to register the "control" keyword in order to allow older containers, such as Visual Basic® 4, to host them.

ActiveX Controls should also register the ToolBoxBitmap32 registry key, although this is not mandatory.

The Insertable component category should only be registered if the control is suitable for use as a compound document object. It is important to note that a compound document object must support certain interfaces beyond the minimum IUnknown required for an ActiveX control. Although an ActiveX control might qualify as a compound document object, the control's documentation should clearly state what behavior to expect under these circumstances.

What Support for an Interface Means

In addition to the IUnknown interface, an ActiveX control—or COM Object for that matter—expresses whatever optional functionality it supports through additional interfaces. This is to say that no other interfaces are required above IUnknown. To that end, the following table lists the interfaces that an ActiveX control might support, and what it means to support that interface. Further details about the methods of these interfaces are given in a later section.
Interface | Comments/What it means to support the interface
IOleObject | If the control requires communication with its client site for anything other than events (see IConnectionPointContainer), IOleObject is a necessity. When implementing this interface, the control must also support the semantics of the following methods: SetHostNames, Close, EnumVerbs, Update, IsUpToDate, GetUserClassID, GetUserType, GetMiscStatus, and the Advise, Unadvise, and EnumAdvise methods that work in conjunction with a container's IAdviseSink implementation. [Note: A control implementing IOleObject must be able to handle IAdviseSink if the container provides one; a container might not, in which case a control ensures, of course, that it does not attempt to call a nonexistent sink.]
IOleInPlaceObject | Expresses the control's ability to be in-place activated and possibly user-interface (UI) activated. This interface means that the control has a user interface of some kind that can be activated, and IOleInPlaceActiveObject is supported as well. Required methods are GetWindow, InPlaceActivate, UIDeactivate, SetObjectRects, and ReactivateAndUndo. Support for this interface requires support for IOleObject.
IOleInPlaceActiveObject | An in-place capable object that supports IOleInPlaceObject must also provide this interface as well, though the control itself doesn't necessarily implement the interface directly.
IOleControl Expresses the control's ability and desire to deal with mnemonics (GetControlInfo, OnMnemonic methods); ambient properties (OnAmbientPropertyChange); and/or events that the control requires the container to handle (FreezeEvents). Note that mnemonics are different from accelerators that are handled through IOleInPlaceActiveObject: mnemonics have an associated UI and are active even when the control is not UI active. A control's support for mnemonics means that the control also knows how to use the container's IOleControlSite::OnControlInfoChanged method. Because this requires the control to know the container's site, support for mnemonics also means support for IOleObject. In addition, knowledge of mnemonics requires in-place support and thus IOleInPlaceObject.

If a control uses any container-ambient properties, it must also implement this interface to receive change notifications, because following the semantics of changes is required. Because ambient properties are available only through the container site's IDispatch, ambient property support means that the control supports IOleObject (to get the site) as well as being able to generate IDispatch::Invoke calls.

The FreezeEvents method is necessary for controls that must know when a container is not going to handle an event—this is the only way for a control to know this condition. If FreezeEvents is only necessary in isolation, such that other IOleControl methods are not implemented, then IOleControl can stand alone without IOleObject or IOleInPlaceObject.

IDataObject | Indicates that the control can supply at least graphical renderings of the control (CF_METAFILEPICT is the minimum if the control has any visuals at all) and/or property sets, if the control has any properties to provide. The GetData, QueryGetData, EnumFormatEtc, DAdvise, DUnadvise, and EnumDAdvise methods are required. Support for graphical formats other than CF_METAFILEPICT is optional.
IViewObject2 | Indicates that the control has some interesting visuals when it is not in-place active. If implemented, a control must support the Draw, GetAdvise, SetAdvise, and GetExtent methods.
IDispatch Indicates that the control has either custom methods or custom properties that are both available by late-binding through IDispatch::Invoke. This also requires that the control provides type information through other IDispatch methods. A control can support multiple IDispatch implementations where only one is associated with IID_IDispatch—the others must have their own unique dispinterface identifiers.

A control is encouraged to supply dual interfaces for custom method and property access, but this is optional if methods and properties exist.

IConnectionPointContainer Indicates that a control supports at least one "outgoing" interface, such as events or property change notifications. All methods of this interface must be implemented if this interface is available at all, including EnumConnectionPoints, which requires a separate object with IEnumConnectionPoints.

Support for IConnectionPointContainer means that the object also supports one or more related objects with IConnectionPoint that are available through IConnectionPointContainer methods. Each "connection point" object itself must implement the full IConnectionPoint interface, including EnumConnections, which requires another enumerator object with the IEnumConnections interface.

IProvideClassInfo[2] | Indicates that the object can provide its own coclass type information directly through IProvideClassInfo::GetClassInfo. If the control supports the later variation, IProvideClassInfo2, it also indicates its ability to provide its primary source IID through IProvideClassInfo2::GetGUID. All methods of this interface must be implemented.
ISpecifyPropertyPages | Indicates that the control has property pages that it can display so that a container can coordinate this control's property pages with other controls' pages when property pages are to be shown for a multicontrol selection. All methods of this interface must be implemented when support exists.
IPerPropertyBrowsing | Indicates the control's ability to provide a display string for a property, provide predefined strings and values for its properties, and/or map a property DISPID to a specific property page. Support for this interface means that support for properties through IDispatch as above is provided. If mapping a property DISPID to a specific property page is supported, it also means that the object's property pages mapped through IPerPropertyBrowsing::MapPropertyToPage themselves implement IPropertyPage2, as opposed to the basic IPropertyPage interface.
IPersistStream | See "Persistence Interfaces" section.
IPersistStreamInit | See "Persistence Interfaces" section.
IPersistMemory | See "Persistence Interfaces" section.
IPersistStorage | See "Persistence Interfaces" section.
IPersistMoniker | See "Persistence Interfaces" section.
IPersistPropertyBag | See "Persistence Interfaces" section.
IOleCache[2] | Indicates support for container caching of control visuals. A control generally obtains caching support itself through the OLE CreateDataCache function. Only controls with meaningful static content should choose to do this (although it is not required). If a control supports caching at all, it should simply aggregate the data cache and expose both IOleCache and IOleCache2 interfaces from the data cache. [Note: IOleCacheControl is only important if the control has an external out-of-process data source that itself implements IDataObject such that the control could directly connect the data source to the cache without any intervening layers. This is exceptionally rare.]
IExternalConnection | Indicates that the control supports external links to itself; that is, the control is not marked with OLEMISC_CANTLINKINSIDE and supports IOleObject::SetMoniker and IOleObject::GetMoniker. A container never queries for this interface itself nor calls it directly, because calls are generated from inside OLE's remoting layer.
IRunnableObject | Indicates that the control differentiates being "loaded" from being "running," as some in-process objects do.

Persistence Interfaces

Objects that have a "persistent state" of any kind must implement at least one IPersist* interface, and preferably multiple interfaces, in order to provide the container with the most flexible choice of how it wants to save a control's state.

If a control has any persistent state whatsoever, it must, as a minimum, implement either IPersistStream or IPersistStreamInit (the two are mutually exclusive and shouldn't be implemented together for the most part). The latter is used when a control wants to know when it is created new as opposed to reloaded from an existing persistent state (IPersistStream does not have the "created new" capability). The existence of either interface indicates that the control can save and load its persistent state into a stream, that is, an instance of IStream.

Beyond these two stream-based interfaces, the IPersist* interfaces listed in the following table can be optionally provided in order to support persistence to locations other than an expandable IStream.
Interface | Usage
IPersistMemory | The object can save and load its state into a fixed-length sequential byte array (in memory).
IPersistStorage | The object can save and load its state into an IStorage instance. Controls that want to be marked "Insertable" as other compound document objects (for insertion into non-control-aware containers) must support this interface.
IPersistPropertyBag | The object can save and load its state as individual properties written to IPropertyBag, which the container implements. This is used for "save as text" functionality in some containers.
IPersistMoniker | The object can save and load its state to a location named by a moniker. The control calls IMoniker::BindToStorage to retrieve the storage interface it requires, such as IStorage, IStream, ILockBytes, IDataObject, and so on.

While support for IPersistPropertyBag is optional, it is strongly recommended as an optimization for containers with "save as text" features, such as Visual Basic.

With the exception of IPersistStream[Init]::GetSizeMax and IPersistMemory::GetSizeMax, all methods of each interface must be fully implemented.

Optional Methods

Implementing an interface doesn't necessarily mean implementing all methods of that interface to do anything more than return E_NOTIMPL or S_OK as appropriate. The following table identifies the methods of the interfaces that a control can implement in this manner. Check with the Platform SDK OLE Reference documentation for full syntax and valid return values from these methods. Any method not listed here must be fully implemented if the interface is supported.
Method | Comments
IOleControl
GetControlInfo, OnMnemonic | Mandatory for controls with mnemonics.
OnAmbientPropertyChange | Mandatory for controls that use ambient properties.
FreezeEvents | See "Event Freezing" in the General Guidelines section.
IOleObject
SetMoniker | Mandatory if the control is not marked with OLEMISC_CANTLINKINSIDE.
GetMoniker | Mandatory if the control is not marked with OLEMISC_CANTLINKINSIDE.
InitFromData | Optional.
GetClipboardData | Optional.
SetExtent | Mandatory only for DVASPECT_CONTENT.
GetExtent | Mandatory only for DVASPECT_CONTENT.
SetColorScheme | Optional.
DoVerbs | See Note 1.
IoleInPlaceObject
ContextSensitiveHelp | Optional.
ReactivateAndUndo | Optional.
IOleInPlaceActiveObject
ContextSensitiveHelp | Optional.
IViewObject2
Freeze | Optional.
Unfreeze | Optional.
GetColorSet | Optional.
IPersistStream[Init], IPersistMemory
GetSizeMax | See Note 2.

Notes:

  1. A control with property pages must support IOleObject::DoVerbs for the OLEIVERB_PROPERTIES and OLEIVERB_PRIMARY verbs. A control that can be active must support IOleObject::DoVerbs for the OLEIVERB_INPLACEACTIVATE verb. A control that can be UI active must also support IOleObject::DoVerbs for the OLEIVERB_UIACTIVATE verb.
  2. If a control supports IPersistStream[Init] and can return an accurate value, it should do so.

Class Factory Options

An ActiveX control, by virtue of being a COM object, must have associated server code that supports control creation through IClassFactory as a minimum.

It is optional, not required, that this class object also supports IClassFactory2 for licensing management. Only those vendors that are concerned about licensing need to support COM's licensing mechanism. In other words, because IClassFactory2 is the only way to achieve COM-level licensing, this interface is required on the class object for those controls that want to be licensed.

Properties

Although most controls do have properties, controls are not required to expose any properties and thus the control does not require IDispatch. If the control does have properties, there are no requirements for which properties a control must expose.

Methods (through IDispatch and Other Dispinterfaces)

Although most controls do expose and support several methods, controls are not required to expose or support any methods; thus the control does not require IDispatch. If the control does have any methods, there are no requirements for which methods a control must expose.

Events

Although most controls do expose and fire several events, controls are not required to expose or fire any events; thus the control does not require IConnectionPointContainer. If the control does have any events, there are no requirements for which events a control must expose.

Property Pages

Support for property pages and per-property browsing is strongly recommended, but not required. If a control does implement property pages, those pages should conform to one of the standard sizes: 250 x 62 or 250 x 110 dialog units (DLUs).

Ambient Properties

If a control supports any ambient properties at all, it must at least respect the values of the following ambient properties under the conditions stated in the following table using the standard DISPIDs.
Ambient property | DISPID | Comment/Conditions for use
LocaleID | -705 | If locale is significant to the control, for example, for text output.
UserMode | -709 | If the control behaves differently in user (design) mode and run mode.
UIDead | -710 | If the control reacts to UI events, it should honor this ambient property.
ShowGrabHandles | -711 | If the control support in-place resizing of itself.
ShowHatching | -712 | If the control supports in-place activation and UI activation.
DisplayAsDefault | -713 | Only if the control is marked OLEMISC_ACTSLIKEBUTTON (which means that support for keyboard mnemonics is provided, thus IOleControl::GetControlInfo and IOleControl::OnMnemonic must be implemented).

As described previously, use of ambients requires both IOleControl (for OnAmbientPropertyChange as a minimum) as well as IOleObject (for SetClientSite and GetClientSite).

The OLEMISC_SETCLIENTSITEFIRST bit might not necessarily be supported by a container. In these circumstances, a control must resort to default values for the ambient properties that it requires.

Using the Container's Functionality

The previous sections have described some of the necessary caller-side support that an ActiveX control must have in order to access certain features of its container. The following table describes a control's usage of container-side interfaces and when such usage would occur.
Interface | Container object | Usage
IOleClientSite | Site | Controls that implement IOleObject call IOleClientSite methods as part of the standard OLE embedding protocol, specifically the methods SaveObject, ShowObject, OnShowWindow (only if a separate window activation state is supported), RequestNewObjectLayout, and GetContainer (if communication with other controls is desired). The GetMoniker method is only used when the control can be linked to externally, that is, the control is not marked with OLEMISC_CANTLINKINSIDE.
IOleInPlaceSite | Site | Controls that have an in-place activate and possibly a UI active state call IOleInPlaceSite methods (generally all of them, with the exception of ContextSensitiveHelp) as part of the standard OLE in-place activation protocol.
IAdviseSink | Site | Control calls OnDataChange if the control supports IDataObject, OnViewChange if the control supports IViewObject2, and OnClose, OnSave, and OnRename if the control supports IOleObject.
IOleControlSite | Site | If supported, control calls OnControlInfoChanged when mnemonics change, LockInPlaceActive and TransformCoords if events are fired (the latter method is only used if coordinates are passed as event arguments), OnFocus and TranslateAccelerator if the control has a UI active state, and GetExtendedControl if the control wants to look at extended-control (container-owned) properties.
IDispatch (ambient properties) | Site | Used to access ambient properties.
IPropertyNotifySink | Varies | A control must generate OnChanged and OnRequestEdit for any control properties that are marked as [bindable] and [request], respectively.
Other event sink interfaces | Varies | A control that has outgoing interfaces other than IPropertyNotifySink will be handed other interface pointers of the correct IID to the control's IConnectionPoint::Advise implementations (which are usually found in subobjects of the control). A control always knows how to call its own event interfaces, since the control defines those interfaces.
IOleInPlaceFrame | Frame | Used when a control has an in-place UI active state that requires frame-level tools or menu items.
IOleInPlaceUIWindow | Document | Used only when a control has an in-place UI active state that requires document-level or pane-level UI tools. This is rare.

General Guidelines

This section describes various features, hints, and tips for ActiveX control developers to help ensure good interoperability between controls and containers.

Overloading IPropertyNotifySink

Many ActiveX control containers implement a modeless property browsing window. If a control's properties are altered through the control's property pages, the control's properties can get out of sync with the container's view of those properties (the control is always right, of course). To ensure that it always has the current values for a control's properties, an ActiveX control container can overload the IPropertyNotifySink interface (data binding) and also use it to be notified that a control property has changed. This technique is optional, and is not required of ActiveX control containers or ActiveX Controls.

Note A control should use IPropertyNotifySink::OnRequestEdit only for data binding; it is free to use OnChanged for either or both purposes.

Container-Specific Private Interfaces

Some containers provide container-specific private interfaces for additional functionality or improved performance. Controls that rely on those container-specific interfaces should, if possible, work without those container-specific interfaces present so that the control functions in different containers. For example, Visual Basic implements private interfaces that provide string formatting functionality to controls. If a control makes use of the Visual Basic private formatting interfaces, it should be able to run with default formatting support if these interfaces are not available. If the control can function without the private interfaces, it should take appropriate action (such as warn the user of reduced functionality) but continue to work. If this is not an option, a component category should be registered as required to ensure that only containers supporting this functionality can host these controls.

Multithreaded Issues

Starting with Microsoft Windows® 95 and Microsoft Windows NT® 3.51, OLE provides support for multithreaded applications, allowing applications to make OLE calls from multiple threads. This multithreaded support is called the "apartment model"; it is important that all OLE components using multiple threads follow this model. The apartment model requires that interface pointers are marshaled (using CoMarshallInterface and CoUnmarshalInterface) when passed between threads. For more information about apartment model threading, refer to the Platform SDK documentation and the OLEAPT sample (in the Platform SDK).

Event Freezing

A container can notify a control that it is not ready to respond to events by calling IOleControl::FreezeEvents(TRUE). It can unfreeze the events by calling IOleControl::FreezeEvents(FALSE). When a container freezes events, it is freezing event processing, not event receiving; that is, a container can still receive events while events are frozen. If a container receives an event notification while its events are frozen, the container should ignore the event. No other action is appropriate.

A control should take note of a container's call to IOleControl::FreezeEvents(TRUE) if it is important to the control that an event is not missed. While a container's event processing is frozen, a control should implement one of the following techniques:

  • Fire the events in the full knowledge that the container will take no action.
  • Discard all events that the control would have fired.
  • Queue up all pending events and fire them after the container has called IOleControl::FreezeEvents(FALSE).
  • Queue up only relevant or important events and fire them after the container has called IOleControl::FreezeEvents(FALSE).

Each technique is acceptable and appropriate in different circumstances. The control developer is responsible for determining and implementing the appropriate technique for the control's functionality.

Container Controls

As described previously, container controls are ActiveX Controls that visually contain other controls. The ActiveX Controls architecture specifies the ISimpleFrameSite interface to enable container controls. Containers can also support container controls without supporting ISimpleFrameSite, although the behavior cannot be guaranteed. For this reason, a component category exists for SimpleFrameSite controls where the full functionality of this interface is required.

To support container controls without implementing ISimpleFrameSite, an ActiveX control container must:

  • Activate all controls at all times.
  • Reparent the contained controls to the hWnd of the containing control.
  • Remain the parent of the container control.

WS_GROUP and WS_TABSTOP Flags in Controls

A control should not use the WS_GROUP and WS_TABSTOP flags internally; some containers rely on these flags to manage keyboard handling.

Multiple Controls in One DLL

A single .ocx DLL can container any number of ActiveX Controls, thus simplifying the distribution and use of a set of related controls.

If you ship multiple controls in a single DLL, be sure to include the vendor name in each control name in the package. Including the vendors' names in each control name enables users to easily identify controls within a package. For example, if you ship a DLL that implements three controls, Con1, Con2, and Con3, the control names should be:

<Your company name> Con1 Control
<Your company name> Con2 Control
<Your company name> Con3 Control

IOleContainer::EnumObjects

This method is used to enumerate over all the OLE objects contained in a document or form, returning an interface pointer for each OLE object. The container must return pointers to each OLE object that shares the same container. Nested forms or nested controls must also be enumerated.

Some containers implement "extender controls," which wrap non-ActiveX controls, and then return pointers to these extender controls as a form is enumerated. This behavior enables ActiveX Controls and ActiveX control containers to integrate well with non-ActiveX controls, and is thus recommended but not required.

Enhanced Metafiles

Not surprisingly, enhanced metafiles provide more functionality than standard metafiles; using enhanced metafiles generally simplifies rendering code. An enhanced metafile device context (DC) is used in exactly the same way as a standard metafile DC. Enhanced metafiles are not available in 16-bit OLE. OLE supports enhanced metafiles, and includes backward compatibility with standard metafiles and 16-bit applications.

A 32-bit ActiveX control container should use enhanced metafiles instead of standard metafiles.

Licensing

In order to embed licensed controls successfully, ActiveX control containers must use IClassFactory2 instead of IClassFactory. Several OLE creation and loading helper functions (for example, OleLoad and CoCreateInstance) explicitly call IClassFactory and not IClassFactory2, and therefore cannot be used to create or load licensed ActiveX Controls. ActiveX control containers should explicitly create and load ActiveX Controls using IClassFactory2. In the future, Microsoft will update these standard APIs to use both IClassFactory and IClassFactory2, as appropriate.

Dual Interfaces

OLE Automation enables an object to expose a set of methods in two ways: through the IDispatch interface, and through direct OLE Vtable binding. IDispatch is used by most tools available today, and offers support for late binding to properties and methods. Vtable binding offers much higher performance because this method is called directly instead of through IDispatch::Invoke. IDispatch offers late bound support, where direct Vtable binding offers a significant performance gain; both techniques are valuable and important in different scenarios. By labeling an interface as "dual" in the type library, an OLE Automation interface can be used through IDispatch, or it can be bound to directly. Containers can thus choose the most appropriate technique. Support for dual interfaces is strongly recommended for both controls and containers.

IPropertyBag and IPersistPropertyBag

IPropertyBag and IPersistPropertyBag optimize "save as text" mechanisms, and therefore are recommended for ActiveX control containers that implement a "save as text" mechanism. IPropertyBag is implemented by a container, and is roughly analogous to IStream. IPersistPropertyBag is implemented by controls, and is roughly analogous to IPersistStream.


Licensing ActiveX Controls

This article explains the licensing strategy for Microsoft® ActiveX™ Controls. In addition, it describes the functionality that must be implemented on an ActiveX control in order to support this strategy.

Introduction

Design-Time Licensing

Run-Time Licensing

Appendix A - Generating a License Package with LPK_TOOL

Appendix B - Authoring Tools

Introduction

Most Microsoft® ActiveX™ Controls should support design-time licensing and run-time licensing. (The exception is the control that is distributed free of charge.) Design-time licensing ensures that a developer is building his or her application or Web page with a legally purchased control; run-time licensing ensures that a user is running an application or displaying a Web page that contains a legally purchased control.

Design-time licensing is verified by control containers such as Microsoft Visual Basic®, Microsoft Access, or Microsoft Visual InterDev. Before these containers allow a developer to place a control on a form or Web page, they first verify that the control is licensed by the developer or content creator. These containers verify that a control is licensed by calling certain functions in the control: If the license is verified, the developer can add it.

Run-time licensing is also an issue for these containers (which are sometimes bundled as part of the final application); the containers again call functions in the control to validate the license that was embedded at design time.

Microsoft Internet Explorer 4.0 is another type of container. Like the other containers, Internet Explorer 4.0 also calls functions in the control to verify that it is licensed. However, unlike Visual Basic or Microsoft Access, which embed ActiveX Controls within the binary code of their application's executable files, Internet Explorer 4.0 uses a different model. This unique model is a necessary response due to:

  • The openness of the browser (the ability to view the HTML source file).
  • Client/server issues imposed by the Internet (or corporate intranet).

Because any Internet Explorer 4.0 user can view the HTML source code for a given Web page, and because an ActiveX control is copied to a user's computer before it is displayed, a level of indirection is required to "hide" the license for an ActiveX control from the user. This prevents an Internet Explorer 4.0 user from pirating and reusing a control that they have not purchased. Microsoft addresses these run-time licensing issues with a new file called the license package file (or LPK file). This file can be included in any HTML page by using the OBJECT tag. For more information about .lpk files, their use, and their format, refer to The License Package File.

The functions that support design-time and run-time licensing are members of the IClassFactory2 interface. Any ActiveX control that supports licensing must support and implement this interface (an extension of the IClassFactory interface). The IClassFactory interface supports the CreateInstance and LockServer methods. ( IClassFactory::CreateInstance is called by a container to instantiate a control; IClassFactory::LockServer is called by a container to lock the control into memory once it is instantiated). The IClassFactory2 interface built upon IClassFactory by adding three new methods: GetLicInfo, RequestLicKey, and CreateInstanceLic. IClassFactory2::GetLicInfo retrieves a structure that specifies the licensing capabilities for an ActiveX control. IClassFactory2::RequestLicKey retrieves a license key. IClassFactory2::CreateInstanceLic instantiates the ActiveX control using the license key (which was retrieved by calling IClassFactory2::RequestLicKey).

If you've created your control with the Microsoft Foundation Class Library (MFC), the IClassFactory2 interface is wrapped by the COleObjectFactory class. In addition to handling licensing issues, COleObjectFactory handles object registration as well.

This article provides general information about design-time and run-time licensing for ActiveX Controls. In addition, it provides specific details about run-time licensing for Internet Explorer 4.0. The samples in this article are based on a sample MFC control. For more information about non-MFC controls, refer to the OLE documentation that is part of the Microsoft Platform SDK.

Design-Time Licensing

Design-time licensing is verified by ActiveX control containers such as Microsoft Visual Basic, Microsoft Access, and Microsoft Visual InterDev. These containers verify that a control is licensed to the developer by calling IClassFactory2::CreateInstanceLic and passing a NULL value for the bstrKey parameter. The corresponding code found in the control's implementation of CreateInstanceLic verifies that the control is licensed. In most cases, this is done by checking for a license (.lic) file and examining the contents of the first line that appears in this file (the contents of this line are sometimes called the license key).

Implementing Design-Time Licensing with MFC

In the sample control, which was created with MFC, the IClassFactory2 interface's functions are wrapped by the COleObjectFactory class. The implementation of the COleObjectFactory::IClassFactory2 interface is found in the MFC Olefact.cpp source file. The following excerpt from this file shows the MFC implementation of the IClassFactory2::CreateInstanceLic method.

STDMETHODIMP COleObjectFactory::XClassFactory::CreateInstanceLic(
    LPUNKNOWN pUnkOuter, LPUNKNOWN /* pUnkReserved */, REFIID riid,
    BSTR bstrKey, LPVOID* ppvObject)
{
    METHOD_PROLOGUE_EX(COleObjectFactory, ClassFactory)
    ASSERT_VALID(pThis);

    *ppvObject = NULL;

    if (((bstrKey != NULL) && !pThis->VerifyLicenseKey(bstrKey)) ||
        ((bstrKey == NULL) && !pThis->IsLicenseValid()))
        return CLASS_E_NOTLICENSED;

    // outer objects must ask for IUnknown only
    ASSERT(pUnkOuter == NULL || riid == IID_IUnknown);

    // attempt to create the object
    CCmdTarget* pTarget = NULL;
    SCODE sc = E_OUTOFMEMORY;
    TRY
    {
        // attempt to create the object
        pTarget = pThis->OnCreateObject();
        if (pTarget != NULL)
        {
            // check for aggregation on object not supporting it
            sc = CLASS_E_NOAGGREGATION;
            if (pUnkOuter == NULL || pTarget->m_xInnerUnknown != 0)
            {
                // create aggregates used by the object
                pTarget->m_pOuterUnknown = pUnkOuter;
                sc = E_OUTOFMEMORY;
                if (pTarget->OnCreateAggregates())
                    sc = S_OK;
            }
        }
    }
    END_TRY

    // finish creation
    if (sc == S_OK)
    {
        DWORD dwRef = 1;
        if (pUnkOuter != NULL)
        {
            // return inner unknown instead of IUnknown
            *ppvObject = &pTarget->m_xInnerUnknown;
        }
        else
        {
            // query for requested interface
            sc = pTarget->InternalQueryInterface(&riid, ppvObject);
            if (sc == S_OK)
            {
                dwRef = pTarget->InternalRelease();
                ASSERT(dwRef != 0);
            }
        }
        if (dwRef != 1)
            TRACE1("Warning: object created with reference of %ld\n", dwRef);
    }

    // cleanup in case of errors
    if (sc != S_OK)
        delete pTarget;

    return sc;
}

When the license key (bstrKey) is NULL, this function calls the COleObjectFactory::IsLicenseValid member function to determine whether a valid design-time license exists for the control. The implementation of COleObjectFactory::IsLicenseValid is also found in the MFC Olefact.cpp source file. The following excerpt from this file shows the MFC implementation of this function.

BOOL COleObjectFactory::IsLicenseValid()
{
    if (!m_bLicenseChecked)
    {
        m_bLicenseValid = (BYTE)VerifyUserLicense();
        m_bLicenseChecked = TRUE;
    }
    return m_bLicenseValid;
}

Initially, the member variable, m_bLicenseChecked, is false. As a result, the COleObjectFactory::VerifyUserLicense member function is called. This function is one of three COleObjectFactory functions that are usually overridden by the ActiveX control developer. In the case of the sample control, this function was overridden and implemented in the Timectrl.cpp module. It was implemented as follows:

BOOL CTimeCtrl::CTimeCtrlFactory::VerifyUserLicense()
{
    return AfxVerifyLicFile(AfxGetInstanceHandle(), _szLicFileName,
        _szLicString);
}

The AfxVerifyLicFile function returns a Boolean value if the license file identified by the _szLicFileName parameter exists and if the first line of this file contains the license string (or key) specified by the _szLicString parameter. These parameters are static variables that appear at the beginning of the Timectrl.cpp file.

// Licensing strings

static const TCHAR BASED_CODE _szLicFileName[] = _T("time.lic");

static const WCHAR BASED_CODE _szLicString[] =
    L"Copyright (c) 1996 ";

Note that the sample control uses the default implementation of COleObjectFactory::VerifyUserLicense, which was generated by the ControlWizard. It is possible that a control developer may want to implement a more secure licensing scheme. For example, a developer might want to embed the license key at a location other than the first line in the licensing file. In this case, the implementation of VerifyUserLicense would not call AfxVerifyLicFile; instead, it would contain code that parsed the file as required to extract the embedded key.

Run-Time Licensing

Run-time licensing is similar for containers such as Microsoft Visual Basic or Microsoft Access; however, as stated in the introduction, run-time licensing is handled differently by Internet Explorer 4.0. This section will first describe run-time licensing for general containers (such as Visual Basic or Microsoft Access) and will conclude with a description of run-time licensing for Internet Explorer 4.0.

General Run-Time Licensing Considerations

There are two points in time when run-time licensing is an issue for a container such as Microsoft Visual Basic: the first is during the creation of the application's executable file; the second is immediately prior to running the application. In both instances, the container calls one or more of the IClassFactory2 methods found in the control in order to determine whether a valid license exists.

Embedding the License Key

When you build an executable file with Visual Basic for an application that uses ActiveX Controls, Visual Basic attempts to embed copies of each control's license keys within the executable file. The container retrieves a license key by calling the IClassFactory2::GetLicInfo method found in each control. This function returns the address of a structure, LICINFO, whose members specify whether a run-time key is available and whether a full machine license exists.

typedef struct tagLICINFO
    {
    ULONG cbLicInfo;
    BOOL  fRuntimeKeyAvail;
    BOOL  fLicVerified;
    } LICINFO;

If Visual Basic determines that the container does support run-time licensing (that is, if the LICINFO.fRuntimeKeyAvail member was set to TRUE), it then calls the IClassFactory2::RequestLicKey method to retrieve a copy of the key, which it then embeds in the executable file.

Using the embedded key

At run time, a container calls IClassFactory2::CreateInstanceLic for each control that is part of the application or Web page that it is displaying. Unlike the earlier call to CreateInstanceLic (at design time, when the container passed a NULL value as the fourth parameter, bstrKey), the container passes a valid string that contains the embedded license key. This allows the control to run on any user's computer (whether or not they are licensed) as long as the embedded key matches the key found in the control.

Embedding the License Key with MFC

In the sample ActiveX control, the IClassFactory2 interface's functions are wrapped by the COleObjectFactory class. The implementation of the COleObjectFactory::IClassFactory2 interface is found in the MFC Olefact.cpp source file. The following excerpt from this file shows the MFC implementation of the IClassFactory2::GetLicInfo method.

STDMETHODIMP COleObjectFactory::XClassFactory::GetLicInfo(
    LPLICINFO pLicInfo)
{
    METHOD_PROLOGUE_EX(COleObjectFactory, ClassFactory)
    ASSERT_VALID(pThis);

    BSTR bstr = NULL;
    pLicInfo->fLicVerified = pThis->IsLicenseValid();
    pLicInfo->fRuntimeKeyAvail = pThis->GetLicenseKey(0, &bstr);
    if (bstr != NULL)
        SysFreeString(bstr);

    return S_OK;
}

COleObjectFactory::GetLicInfo calls two other member functions: COleObjectFactory::IsLicenseValid and COleObjectFactory::GetLicenseKey. The first function is part of the class definition found in Olefact.cpp; the second function was overridden by the sample control and appears in the Timectl.cpp file. The code for COleObjectFactory::IsLicenseValid appears as follows:

BOOL COleObjectFactory::IsLicenseValid()
{
    if (!m_bLicenseChecked)
    {
        m_bLicenseValid = (BYTE)VerifyUserLicense();
        m_bLicenseChecked = TRUE;
    }
    return m_bLicenseValid;
}

The COleObjectFactory::IsLicenseValid member function, in turn, calls COleObjectFactory::VerifyUserLicense, another function that was overridden by the control. (The Implementing Design-Time Licensing with MFC section contains a listing for VerifyUserLicense.) In the sample control, this function simply checks the first line of the .lic file and verifies that it contains the specified license key.

After the sample control calls COleObjectFactory::VerifyUserLicense, it then calls the COleObjectFactory::GetLicenseKey member function. This function is overridden by the sample control and is found in the Timectl.cpp file. The code for COleObjectFactory::GetLicenseKey appears as follows:

BOOL CTimeCtrl::CTimeCtrlFactory::GetLicenseKey(DWORD dwReserved,
    BSTR FAR* pbstrKey)
{
    if (pbstrKey == NULL)
        return FALSE;

    *pbstrKey = SysAllocString(_szLicString);
    return (*pbstrKey != NULL);
}

The CTimeCtrl::CTimeCtrlFactory function retrieves a copy of the license key, which the container can store in the appropriate location. (In the case of Visual Basic or Microsoft Access, the key is embedded in the application's executable file.)

Run-Time Licensing for Internet Explorer 4.0

Like the other containers, Internet Explorer 4.0 also calls the IClassFactory2 methods to verify that an ActiveX control is licensed. However, unlike Visual Basic or Microsoft Access, which embed ActiveX Controls within the binary code of their application's executable files, Internet Explorer 4.0 uses a different model. This unique model is a necessary response to the following factors:

  • The openness of the browser (the ability to view the HTML source file).
  • Client/server issues imposed by the Internet (or corporate intranet).

Because any Internet Explorer 4.0 user can view the HTML source code for a given Web page, and because an ActiveX control is copied to a user's computer before it is displayed, a level of indirection is required to "hide" the license for an ActiveX control from the user. This prevents an Internet Explorer 4.0 user from pirating and reusing a control that they have not purchased. Microsoft addresses these run-time licensing issues with a new file called the license package file (or LPK file).

The License Package File

A license package is stored as a license package (.lpk) file. From a very simplistic perspective, this file can be thought of as an array of ActiveX control CLSIDs and license keys. The file has the following format.
Element | Description
.lpk header | This header identifies the file type: "LPK License Package"
Copyright text or other legal statement | "Legalese" to dissuade casual copying of .lpk files
LPK version GUID | In plain-text on a line by itself. This GUID is used to mark the beginning of the real license package data; it is also used to identify the LPK file format version.
Uuencoded(Base64) license package
struct {
    UUID uuidLPKFile;   // unique per LPK
    DWORD dwLicenses;   // number of licenses in the file
    LICENSEPAIR aLicenses[]; // array of license pairs
} LICENSEPACKAGE;

struct {
    CLSID clsid;        // clsid of object
    DWORD cchLic;       // number of characters in the license
    WCHAR ach[];        // license (saved as UNICODE characters)
} LICENSEPAIR;

The ActiveX License Manager is a component of Internet Explorer 4.0 found in the Licmgr10.dll file. This component parses an .lpk file and extracts the license key for each corresponding CLSID in the file.

At run time, when Internet Explorer 4.0 is rendering an HTML page that contains ActiveX Controls, the License Manager calls the IClassFactory2::CreateInstanceLic method, passing the license key that it extracted from the .lpk file in order to verify that a control is licensed. If the license key matches the control's license, the control will be rendered on the page.

Embedding a License Package in an HTML file

An HTML author can embed a license package in any HTML page by using the OBJECT tag, a CLSID that identifies the object as a license package, and a PARAM tag that specifies the relative location of the license package file with respect to the HTML page.

<OBJECT CLASSID="clsid:5220CB21-C88D-11cf-B347-00AA00A28331">
    <PARAM NAME="LPKPath" VALUE="time.lpk">
</OBJECT>

The contents of the .lpk file are parsed by the license manager object. Only one .lpk file can be included in a given HTML page. (If more than one .lpk file is included in a page, Internet Explorer 4.0 ignores all but the first.)

Appendix A - Generating a License Package with LPK_TOOL

The Internet Client SDK ships with an executable file named Lpk_Tool.exe that you can use to generate license package files. This file is copied to the \bin subdirectory found in the SDK.

The application is actually simple to use. When you start the application, it displays a combo box that lists all of the ActiveX Controls currently running on your computer.

Combo box showing all ActiveX Controls running on your computer

The next step requires that you choose the controls that you want to display on a given HTML page. You choose a control by highlighting it in the combo box and then clicking the Add button.

Combo box with selected control

Once you've selected all the controls that you want to display on a given page, you can create and save the actual .lpk file by clicking the Save & Exit button. (This causes the application to display the File Save dialog box, which allows you to specify the path and file name.)

Appendix B - Authoring Tools

HTML authoring tools will make it easy to create HTML pages with embedded ActiveX Controls. Such tools should be responsible for creating the .lpk license package for licensed controls used on a page or on a Web site. Since there may be a one-to-many mapping between LPKs and HTMs, this may be more difficult for page-based authoring tools as opposed to Web-based authoring tools (for example, Microsoft FrontPage™).

Clearly, tool support is necessary for Notepad HTML authors as well. The solution is a simple GUI tool that lists all controls that are installed on a computer with design-time licenses. The tool allows a user to create an .lpk license package by selecting which controls should be included in the package. A second tool could parse HTML pages and create an .lpk file for all the controls that require licensing.


Packaging ActiveX Controls

This article introduces a data-compression technology and associated toolset that you can use to package your Microsoft® ActiveX™ control for faster, more efficient downloading over the Internet or an intranet. (This same technology and toolset can be applied to Microsoft Win32® applications, Java™ classes, and Java libraries.)

Cabinet Files

Packaging the Sample ActiveX Control

Cabarc.exe

.INF Files

Cabinet Files

For a number of years, Microsoft used cabinet (.cab) files to compress software that was distributed on disks. Originally, these files were used to minimize the number of disks shipped with packaged product; today, .cab files are used to reduce the file size and the associated download time for Web content that is found on the Internet or corporate intranet servers.

The .cab file format is a nonproprietary compression format, also known as MSZIP, that is based on the Lempel-Ziv data-compression algorithm. (At a future date, other compression formats might also be supported.)

Accessing Controls Stored in Cabinet Files

An ActiveX control is identified by the OBJECT tag in an HTML file. If the control has been stored in a .cab file, the OBJECT tag must include a CODEBASE= attribute that specifies the URL for this .cab file. The following excerpt from a sample HTML file demonstrates how the OBJECT tag and CODEBASE= attribute are used.

<OBJECT CLASSID="clsid:dcf0768D-ba7a-101a-b57a-0000c0c3ed5f" codebase="http://webserver/time.cab"
    ALIGN="CENTER" WIDTH=270 HEIGHT=26 ID="T1"><PARAM NAME="Interval" VALUE=1000>
    <PARAM NAME="Enabled" VALUE=1></OBJECT>

Microsoft Internet Explorer version 4.0 handles the OBJECT tag and the CODEBASE= attribute in the following manner:

  1. Internet Explorer 4.0 parses the OBJECT tag and searches for the CODEBASE= attribute. If the CODEBASE= attribute is absent or is preceded by a URL-to-object index server in the CodeBaseSearchPath, this index is used to retrieve the file.
  2. Internet Explorer 4.0 locates the .cab file identified by the CODEBASE= attribute.
  3. Internet Explorer 4.0 expands the files found in the .cab file.
  4. Internet Explorer 4.0 copies the expanded files to the user's computer (the default directory is \windows\occache).
  5. Internet Explorer 4.0 registers the objects and/or files that require registration.
  6. Internet Explorer 4.0 calls the Component Object Model (COM) function CoCreateInstance to create an instance of the specified object.

Signing Cabinet Files

A .cab file can be digitally signed like an ActiveX control. A digital signature provides accountability for software developers: The signature associates a software vendor's name with a given file. A signature is applied to a .cab file (or control) using the new Authenticode™ technology.

The .cab toolset assists software developers in applying digital signatures to .cab files by allowing a developer to allocate space in the .cab file for the signature.

CABinet Resource Kit

Microsoft supplies a CABinet resource kit that contains tools that a developer can use to build .cab files. You access this technology by executing a self-extracting executable, Cab-sdk.exe, that installs from the ..\inetsdk\bin subdirectory.

One of the tools installed by Cab-sdk.exe is Cabarc.exe. This command-line application lets you compress an ActiveX control and store it in a .cab file. In addition to creating .cab files, you can use Cabarc.exe to list the contents of or extract files from an existing .cab file.

For an example that demonstrates how you can use Cabarc.exe to package an ActiveX control, see Packaging the Sample ActiveX Control.

For more information about Cabarc.exe and its options, see Cabarc.exe.

Packaging Strategies for Multiple Platforms

Internet Explorer 4.0 and ActiveX Controls can run on the Apple Macintosh® and on Intel® x86 computers, as well as on any of several RISC machines. As a result, it's important that control developers create, test, and bundle their control's binaries for all platforms.

This section outlines three packaging strategies for supporting multiple platforms:

  • Multiple .cab files with the .inf saved in a separate .cab file
  • Multiple .cab files with the .inf and x86 binary bundled in a single .cab file
  • A single .cab file

Multiple .cab files with .inf in separate .cab

The first strategy requires that one .cab file contain a Windows® 95 .inf file, the second contain the x86 binary, the third contain the Apple MacIntosh binary, and so on. Using this strategy, the CODEBASE= attribute of the OBJECT tag specifies the relative path for the .cab file that contains the Windows 95 .inf file.

The primary benefit of this strategy is reduced file size at download time—only the first .cab file containing the .inf file and a second .cab file with the appropriate binary for a given platform are downloaded.

The one drawback of this strategy is that two digital certificates will appear (one certificate per .cab file).

Multiple .cab files with .inf and x86 binary bundled in single .cab

The second strategy requires that one .cab file contain both the Windows 95 .inf file and the x86 binary. The remaining .cab files contain the Apple MacIntosh and RISC binaries (one binary per .cab file). Using this strategy, the CODEBASE= attribute of the OBJECT tag will specify the relative path for the .cab file that contains the Windows 95 .inf file and the x86 binary.

This strategy is most beneficial for controls that are primarily targeted at the x86 platform. Another benefit of this strategy is reduced file size at download time.

The one drawback of this strategy is that Apple MacIntosh or RISC users will have to wait for the x86 binaries to download.

Single .cab file

The third strategy requires that a single .cab file contain all binaries.

This strategy is most beneficial for small controls that have no dependent DLLs and that are primarily targeted at an intranet.

The drawbacks of this solution are that it does not optimize for dependent DLLs that might already be on the user's computer, and this solution might not be acceptable on some intranets.

Packaging the Sample ActiveX Control

This section describes how a single .cab file was created for the sample digital clock control. This .cab file contains a Windows 95 .inf file as well as the x86 binary for the control.

This example is based on the second packaging format described in the previous section of this article. However, the sample package is incomplete: a couple of final steps, which were omitted, require that a separate .cab file be created for the Apple Macintosh binary as well as for each of the supported RISC platforms. In addition to creating the separate .cab files, the .inf file would need to be modified to point to these additional .cab files. These steps were omitted to simplify the example.

Installing the CABinet Development Kit

To package an ActiveX control, it's necessary to install Cabarc.exe in the ..inetsdk\bin subdirectory. When the kit is installed, you can begin using the tools it contains to build the necessary .cab files for your control.

Creating the .inf File

As previously stated, the sample .cab file bundles a Windows 95 .inf file with an x86 binary. The bundled .inf file contains information about the control, such as its name, its class identifier (CLSID), the name and location of required DLLs, whether the control requires registration, and so on. This .inf file has the following format:

 [version]
    signature="$CHICAGO$"
    AdvancedINF=2.0
 [Add.Code]
    time.ocx=time.ocx
    msvcrt.dll=msvcrt.dll
    mfc42.dll=mfc42.dll
    olepro32.dll=olepro32.dll
 [time.ocx]
    file-win32-x86=thiscab
    clsid={DCF0768D-BA7A-101A-B57A-0000C0C3ED5F}
    FileVersion=1,0,0,0
    RegisterServer=yes
 [msvcrt.dll]
    FileVersion=4,20,0,6164
    hook=mfc42installer
 [mfc42.dll]
    FileVersion=4,2,0,6256
    hook=mfc42installer
 [olepro32.dll]
    FileVersion=4,2,0,6068
    hook=mfc42installer
 [mfc42installer]
    file-win32-x86=http://activex.microsoft.com/controls/vc/mfc42.cab
    run=%EXTRACT_DIR%\mfc42.exe

If you're bundling the .inf file and your control's x86 binary in a single .cab file, and if your control was written with Microsoft Foundation Class Library (MFC) 4.2, you can use the previous example after you replace all occurrences of the sample control name (time.ocx) with the name of your control and replace the sample control's CLSID with the CLSID for your control.

If you're organizing your files differently, or if your control requires DLLs other than the Microsoft Visual C++® 4.2 DLLs, you'll need to modify the .inf file to accommodate your unique requirements. Note that if your control requires that a DLL be registered before the control, its corresponding entry in the .inf file must precede the control's entry in the file. Also note that the order of the source files in the command line that is passed to Cabarc.exe must match the order of the file references in the .inf file.

For more information about .inf files and the section tags found within them, see .INF Files.

Building the .cab File

Once you've installed Cabarc.exe and built the .inf file for your package, you can build the .cab file. In the case of the sample .cab file, this entailed running Cabarc.exe with the following arguments:

cabarc.exe -s 6144 N time.cab time.ocx time.inf

This command created a .cab file named Time.cab, which contains a compressed x86 binary for the sample control as well as a compressed version of the corresponding .inf file. The -s 6144 switch specifies that Cabarc.exe should allocate 6144 bytes for a digital certificate. (Code signing with digital certificates is described briefly in the next section).

For more information about Cabarc.exe and its use, see Cabarc.exe.

Signing the .cab File

The default security level for Internet Explorer 4.0 is High. When a user runs at this level, any object identified by the OBJECT tag on an HTML page must be digitally signed. Digital signatures are created using the Authenticode technology that is included in the Internet Client SDK. A digital signature associates a software vendor's name and a unique public key with a file that contains an ActiveX object (ensuring some sort of accountability on the part of the object's developer).

Before you purchase a certificate for your control's .cab file from a vendor, you can use the test certificate provided by Microsoft for verification purposes. The following steps were required to add the SDK test certificate to the sample control's .cab file:

  1. Use Setreg.exe, which is found in the \inetsdk\bin directory, to validate the test root in the trust hierarchy.
    setreg 1 true

    Setreg.exe replaces the Wvtston.reg and Wvtstoff.reg files that were shipped as part of the ActiveX SDK. Validation of the test root means that Internet Explorer 4.0 will treat a .cab file signed under the test root as though it included credentials.

  2. Use the Makecert.exe utility, which is found in the \inetsdk\bin directory, to create a key pair (the pair consists of a public and a private key).
    makecert -u:mykey -n:CN=mysoftwarecompany cert.cer

    In addition to creating the key pair, Makecert.exe associates the key pair with an X.500 distinguished name and creates an X.509 certificate that is signed by the root key (and that binds your name to the public part of the new key pair).

  3. Use the Cert2SPC.exe utility, which is found in the \inetsdk\bin directory, to generate a software publishing certificate (.spc file).
    cert2spc root.cer cert.cer cert.spc

  4. Use the Signcode.exe utility (and accompanying wizard), which is found in the \inetsdk\bin directory, to sign the .cab file.
    signcode -prog mycab.cab -spc cert.spc -pvk mykey

    If Signcode.exe is successful, it will have embedded a PKCS7 certificate in the .cab file.

If you package your control in one or more .cab files, each file must be digitally signed.

For information about X.500 distinguished names, X.509 certificates, software publishing certificates, or PKCS7 certificates, see the article titled Signing Code with Microsoft Authenticode Technology.

Cabarc.exe

Cabarc.exe is a utility that creates, lists, and extracts the contents of cabinet (.cab) files. Cabarc uses a command-line interface similar to that of popular archiving tools. Cabarc supports wildcards and recursive directory searches.

Cabarc is used as follows:

cabarc [<options>] <command> [<file list>]

Three commands are currently supported:

  • n (create a new .cab file)
  • l (list contents of an existing .cab file)
  • x (extract files from a .cab file)

Creating New .cab Files (n Command)

Cabinets are created by using the n command, followed by the name of the cabinet to create, followed by a file name list, as shown in this example:

cabarc n mycab.cab prog.c prog.h prog.exe readme.txt

This command creates the cabinet Mycab.cab, containing the files Prog.c, Prog.h, Prog.exe, and Readme.txt, in a single folder, using the default compression mode, MSZIP.

Cabarc supports wildcards in the file name list, as shown in the following example:

cabarc n mycab.cab prog.* readme.txt

Options (-p, -P, -r, -s, -i, -m, -l, +, @)

Directory names are not preserved in the cabinet (by default); only the file name component is stored. For example, the following command stores Prog.c in the cabinet:

cabarc n mycab.cab c:\source\myproj\prog.c

Path preservation (-p)

To preserve paths, use the -p option as shown in the following example:

cabarc -p n mycab.cab c:\mysource\myproj\prog.c

This command puts mysource\myproj\prog.c in the cabinet. Be aware that the c:\ prefix is still removed from the file name: Cabarc cannot store absolute paths in the cabinet nor extract such absolute paths.

Path stripping (-P)

The path stripping option, -P, is used for preserving part (but not all) of a path. The following example shows how this option can archive everything in the c:\mysource\myproj\ directory, but store only the myproj\ component of the path.

cabarc -p -P mysource\ n mycab.cab c:\mysource\myproj\prog.c

The -P option strips any strings that begin with the provided string. Wildcards are not supported by the -P option; it is a simple text match. Absolute path prefixes, such as c:\ or \, are stripped before the comparison takes place. Do not include absolute path prefixes when using the -P option.

The -P option can be reused to strip out multiple paths. Cabarc builds a list of all paths to be stripped and applies only the first one that matches. Consider the following example:

cabarc -p -P mysrc\ -P yoursrc\ n mycab.cab c:\mysrc\myproj\*.* d:\yoursrc\yourproj\*.c

The trailing slash at the end of the path is important: Entering -P mysrc instead of -P mysrc\ adds files as \myproj\file name.

Recursive directory search (-r)

Cabarc has an option, -r, for a recursive directory search. Using this option archives files in a directory and all of its subdirectories. For example, the following command example archives all files ending in .h that are in c:\msdev\include\, c:\msdev\include\sys, and c:\msdev\include\gl (assuming these directories exist on your system).

cabarc -r -p n mycab.cab c:\msdev\include\*.h

The -p option is used here to preserve the path information when the files are added to the cabinet. Without this option, only the file names would be stored.

Reserving space for digital signatures (-s)

Cabarc can reserve space in the cabinet for a code signature. This is done with the -s option, which reserves a specified amount of empty space in the cabinet. For code signatures, reserve 6144 bytes. Consider the following example for doing so:

cabarc -s 6144 n mycab.cab test.exe

The -s option does not actually write the code signature; it reserves space for it in the cabinet. Use the code signature utility to fill out the code signature.

Setting the cabinet ID (-i)

Cabinet files have a 16-bit cabinet identification field that is designed for application use. The default value of this field is zero; however, use the -i option of Cabarc to set this field to any 16-bit value, as shown in the following example:

cabarc -i 12345 n mycab.cab test.exe

Setting the compression type (-m)

Set the compression type with the -m option. The default compression type for a cabinet is MSZIP. Only MSZIP compression (-m MSZIP) and no compression (-m NONE) are supported. The following command stores files in the cabinet without compression.

cabarc -m NONE n mycab.c *.*

Creating a file list from a file (-l)

Cabarc can create a file list from a file. Cabarc compiles a list of file inputs from a text file (instead of from the command line), using the -l option, followed by the name of the file from which to take the inputs. Consider the following example:

cabarc -l filelist.txt n mycab.cab

The -l option can be reused to retrieve file lists from multiple files. Cabarc does not check for duplicate files. If the same physical file appears in multiple file lists, it gets added to the cabinet multiple times.

The -l option can be combined with file names on the command line. The files from the -l option are added first. Consider the following example:

cabarc -l filelist1.txt -l filelist2.txt n mycab.cab *.c *.h

Beginning new folders (+)

All files are put in one folder in the cabinet (by default). It is possible to instruct Cabarc to begin a new folder by using the plus sign (+) for the file to be added, as shown in the following example:

cabarc n mycab.cab test.c main.c + test.exe *.obj

This command creates the cabinet Mycab.cab with one folder containing Test.c and Main.c, and a second folder containing Test.exe and all files matching *.obj.

Generating a file listing from an existing file list (@)

Cabarc can input its list of files from a text file, instead of from the command line, by using @files ("at files"). This is done by using the @ symbol to prefix the name of the file that contains the file list. For example:

cabarc n mycab.cab @filelist.txt

The text file must list the physical file names of the files to be added, one per line. As is the case when specifying file names on the command line, the plus (+) symbol can be used as a file name to specify the beginning of a new folder. If a file name contains any embedded spaces, it must be enclosed in quotes, as shown here:

test.c
myapp.exe
"output file.exe"

The reason for requiring quotes is that each physical file name might be followed on the same line by an optional logical file name, which specifies the name under which the file will be stored in the cabinet.

test.c myapp.c
myapp.exe
"output file.exe" foobar.exe

If the logical file name contains spaces, it must also be enclosed in quotes. Note that the logical file name overrides the -p (preserve path names) and -P (strip path name) options—the file will be added to the cabinet exactly as indicated. Wildcards are allowed in the physical file name, but in this situation a logical file name is not allowed.

The @ feature can be used multiple times to retrieve file lists from multiple files. Cabarc does not check for the presence of duplicate files, so if the same physical file appears in multiple file lists, it will be added to the cabinet multiple times.

The @ feature can be combined with file names on the command line. Files are added in the order in which they are parsed on the command line. For example:

cabarc n mycab.cab @filelist1.txt *.c @filelist2.txt *.h

The @ feature is available only when creating cabinets, not when extracting or listing cabinets.

Listing Contents of Existing Files (l Command)

The list cabinet contents command, l, makes it possible to view the contents of a cabinet. Consider the following example:

cabarc l mycab.cab

Cabarc displays the Set ID in the cabinet (see the -s option for cabinet creation). Cabarc also displays the following file information: size, date, time, and attributes.

Extracting Files from Cabinet Files (x Command)

The extracting cabinets command, x, extracts files from a cabinet. The simplest use of the x command is shown in the following example, which extracts all files from the cabinet.

cabarc x mycab.cab

Alternatively, it is possible to selectively extract files by providing a list of file names or a list of file names and wildcards. Consider the following example:

cabarc x mycab.cab readme.txt *.exe *.c

Full paths (if they are present in the cabinet), by default, are not preserved upon extraction. For example, if mysrc\myproj\test.c is in the cabinet, the command cabarc x mycab.cab causes Test.c to be extracted into the current directory. To preserve file names upon extraction, the -p option must be used. This option causes any required directories to be created, if necessary.

By default, the extracted files are stored in the current directory (and its subdirectories, if -p is used). However, it is possible to specify a destination directory for the extracted files. This is accomplished by appending a directory name to the command line. The directory name must end in a backslash ( \ ). For example:

cabarc x mycab.cab c:\somedir\

cabarc x mycab.cab *.exe c:\somedir\

The extracting cabinets option considers only the file name component in the matching process; the path name is ignored. For example, cabarc x mycab.cab test.c causes mysrc\myproj\test.c to be extracted to the current directory as Test.c, as will cabarc x mycab.cab *.c (which also extracts any other files matching *.c).

.INF Files

An .inf file contains data that Microsoft Windows NT® and Windows® 95 use to load and register a bundled control (as well as any files required by that control). Each section of the .inf file is described below.

The [version] Section of the .inf File

The first section in the .inf file is the [version] section. In the sample .inf, this section has the following format:

[version]
    signature="$CHICAGO$"
    AdvancedINF=2.0

The signature= tag specifies that the .inf version is compatible with both Windows NT and Windows 95.

The AdvancedINF= tag identifies the version of Advpack.dll that Internet Explorer 4.0 must load in order to parse this .inf file. In this case, version 2.0 is required.

The [Add.Code] Section of the .inf File

The second section of the .inf file is the largest section. In addition to the section immediately following the [Add.Code] tag, this section includes the subsections that are identified by the [time.ocx], [msvcrt.dll], [mfc42.dll], and [olepro32.dll] tags.

The [Add.Code] section maps files required by a given .ocx file to subsections in the .inf file. In the sample .inf file, this section has the following format:

[Add.Code]
    time.ocx=time.ocx
    msvcrt.dll=msvcrt.dll
    mfc42.dll=mfc42.dll
    olepro32.dll=olepro32.dll

The first line in this section maps time.ocx (the file that contains the sample control) to a subsection of the same name. The second, third, and fourth lines map DLLs that are required by the control to corresponding subsections in the .inf file. (The names of the .inf subsections are not restricted to the mapped file name; these names were chosen strictly for convenience in the sample.)

Since the sample control was created with MFC 4.2, the three named DLLs are required on a user's computer before the control will successfully run.

The [time.ocx] subsection of the [Add.Code] section

The [time.ocx] subsection has the following format:

[time.ocx]
    file-win32-x86=thiscab
    clsid={DCF0768D-BA7A-101A-B57A-0000C0C3ED5F}
    FileVersion=1,0,0,0
    RegisterServer=yes
  • The first line in this subsection specifies that the x86 binary is found in the same .cab file as the .inf file.
  • The second line specifies the control's CLSID.
  • The third line specifies the control's version.
  • The fourth line specifies that Internet Explorer 4.0 should register the control (using the specified CLSID and version number).

The [msvcrt.dll] subsection of the [Add.Code] section

The [msvcrt.dll] subsection has the following format:

[msvcrt.dll]
    FileVersion=4,20,0,6164
    hook=mfc42installer

The first line specifies the file version from the fixedfileinfo section of the DLL's version resource.

Note that Windows 95 Explorer shows only a partial version number in the Properties dialog box. For example, in the case of Msvcrt.dll, the Properties dialog box will return 4.20.6164 as the version number (ignoring the third section [0] in the 4,20,0,6164 series).

The second line in this subsection, hook=mfc42installer, identifies a section in the .inf file that points to a .cab file that contains the required DLL (Msvcrt.dll).

The [mfc42.dll] subsection of the [Add.Code] section

The [mfc42.dll] subsection has the following format:

[mfc42.dll]
    FileVersion=4,2,0,6256
    hook=mfc42installer

For more information about these entries, see the description of the [msvcrt.dll] subsection.

The [olepro32] subsection of the [Add.Code] section

The [olepro32.dll] subsection has the following format:

[olepro32.dll]
    FileVersion=4,2,0,6068
    hook=mfc42installer

For more information about these entries, see the description of the [msvcrt.dll] subsection.

The [mfc42installer] Section of the .inf File

The final section in the .inf file is the [mfc42installer] section. In the sample .inf file, this section has the following format:

[mfc42installer]
    file-win32-x86=http://activex.microsoft.com/controls/vc/mfc42.cab
    run=%EXTRACT_DIR%\mfc42.exe

The file-win32-x86= tag specifies that the .cab file containing the MFC 4.2 DLLs is located at the specified site.

The run= tag specifies that the .cab file contains a self-extracting executable named Mfc42.exe.


Palette Management for ActiveX Objects

This document describes palette management for ActiveX objects, specifically ActiveX Controls and Active Document Objects. The palette management rules described herein allow multiple controls inside a form or an HTML page to display correctly, while still leaving enough flexibility to allow a control to demand palette control. In general, containers are responsible for palette management, and contained objects (for example, controls) should only realize their palettes in the background.

Palette Management for ActiveX Controls and Containers

Palette Management for Active Document Objects

Palette Management for ActiveX Controls and Containers

This section describes how ActiveX controls and containers should manage the palette.

Palette selection

Because there may be more than one control on a page or form, it is up to the container to choose a common palette, and every control should realize its palette in the background. Anything else would result in chaos as each control realized its palette while painting. The display would flicker madly and most controls would look awful.

Ultimately it is the container's responsibility to choose the common palette. Some containers may use the UI active object's palette; others may compute the palette at run-time.

Ambient palette property

The container makes its palette available to contained controls through an ambient property: DISPID_AMBIENT_PALETTE. This property is defined as part of the OLE Controls 96 specification and is implemented by Microsoft Internet Explorer. Controls can receive the value of this ambient initially by implementing IOleObject::SetClientSite or IObjectWithSite::SetSite, then querying the container client site for IDispatch, and finally calling IDispatch::Invoke on the property to obtain its value. Afterwards, controls can receive notification of changes to this property by implementing: IOleControl::OnAmbientPropertyChange().

Containers should realize the ambient palette before calling this function or IViewObject2::Draw(). Older containers that do not implement this property will typically iterate through their controls, forwarding the WM_QUERYNEWPALETTE message until a control returns TRUE (indicating it has realized a palette). Containers that implement DISPID_AMBIENT_PALETTE should never send WM_QUERYNEWPALETTE to their controls.

Palette change notification

Palette-aware controls that need to be notified of changes to the ambient palette should implement IOleControl::OnAmbientPropertyChange and handle DISPID_AMBIENT_PALETTE and DISPID_UNKNOWN. DISPID_UNKNOWN is sent when the values of more than one ambient property changes. When this happens, controls should explicitly check for a changed palette.

Older containers that do not define an ambient palette will send WM_PALETTECHANGED messages. Controls are encouraged to handle this message as well.

Note that controls can still realize a different palette (in the background). The ambient palette property is useful only if a control needs to optimize its display to the palette of the container. If this is not necessary, the control should ignore the ambient palette property.

IViewObject2::GetColorSet

All palette-aware controls should implement IViewObject2::GetColorSet if they want to specify a palette preference. Containers can use the return value to determine if a control is palette-aware. Containers can also use the color information returned to choose what palette to realize.
E_NOTIMPL | The control is not palette-aware.
S_FALSE | The control is palette-aware but does not have a palette at this time.
S_OK | The control is palette-aware and has returned its palette to the container.

It should be noted that the container does not have to call IViewObject2::GetColorSet. The container can determine its palette independently of its controls.

Realizing the palette

Older OLE guidelines allowed the UI active object to realize its own palette in the foreground. Revised guidelines disallow this practice.

Controls should realize their palette in the foreground only when receiving a WM_QUERYNEWPALETTE message. In every other situation, the control must realize its palette in the background. Containers that implement DISPID_AMBIENT_PALETTE will never send this message.

Summary:

  • Containers determine the palette.
  • Containers can choose to implement DISPID_AMBIENT_PALETTE.
  • Containers must realize the ambient palette before calling IViewObject2::Draw or IOleControl::OnAmbientPropertyChange.
  • Controls must always realize their palette in the background. The only exception is when receiving a WM_QUERYNEWPALETTE message.
  • Controls should implement IViewObject2::GetColorSet if they want to tell the container about their palette preferences.
  • Controls should implement IOleControl::OnAmbientPropertyChange if they want to be notified about changes in the ambient palette property in order to optimize their display to the container's palette.

Palette Management for Active Document Objects

The following sections describe issues related to palette management by OLE Document Objects. In general, the palette management scheme for document objects is the same as the scheme used for controls, except that document objects do not receive ambient properties from their container.

Responsibilities of the document object

Palette management for document objects is similar to palette management for controls. The following are the responsibilities of the document object:

  • Document objects should implement IViewObject2::GetColorSet if interested in notifying the container about the palette they want to display. This is exactly the same as the corresponding responsibility for controls (as previously discussed).
  • Document objects should realize their palette in the background except when handling WM_QUERYNEWPALETTE messages (forwarded from the container). Again, this is exactly the same as the corresponding responsibility for controls.

The only difference between the responsibilities of controls and document objects is that document objects do not handle the DISPID_AMBIENT_PALETTE property.

Single document case

In the most common cases, a DocObject container will activate only one DocObject at a time. In such a situation, it is acceptable that the activated DocObject should have complete control over the palette, which includes managing palette issues for any controls or content within that document.

The DocObject container in this case has nothing to do with palettes and need not be concerned with palette issues. It should leave palette handling up to the DocObject— in other words, it should forward all Windows® palette management messages on to the DocObject.

The following is example code for the window procedure of the document object host:

case WM_PALETTECHANGED:
case WM_QUERYNEWPALETTE:
{
    HWND hwnd;
    IOleWindow *pOleWindow;
    if (pDocObj && SUCCEEDED(pDocObj->QueryInterface(IID_IOleWindow,
            (LPVOID*)&pOleWindow))) {
        LRESULT lres = 0;
        if (SUCCEEDED(pOleWindow->GetWindow(&hwnd))) {
            lres = SendMessage(hwnd, uMsg, wParam, lParam);
        }
        pOleWindow->Release();
        return lres;
    }
    break;
}

Multiple DocObject case

In rare cases, a DocObject container may be able to activate more than one DocObject at a time within multiple container frames. While this user interface is discouraged at this time, it can be achieved.

However, no palette-management solution exists for this scenario because there is currently no protocol for communicating palettes between a DocObject and its container. Therefore, the container cannot create a palette suitable to all DocObjects that it has activated.

Because of this, the activated DocObject in the foreground has control over the palette and should use foreground palette rendering. Other activated DocObjects in the background use background palette rendering. The DocObject container itself does not participate in palette management at all.


Registering an ActiveX Object as the Player for a Media Type

This topic describes how to register an ActiveX™ object as the viewer or player for a particular media type (MIME). This registration is essential for Microsoft® Internet Explorer to launch the correct player when interpreting the standard HTML A HREF tag or the Netscape-introduced EMBED tag. Without this registration, it is impossible to guess what application to use to display or play an unknown media file. The registration process associates an ActiveX object with a given MIME type or file-name extension so that Internet Explorer or any other ActiveX control container can launch the correct player for files of that type. Internet Explorer first tries to find a match for the correct media type; if that is not possible, it uses the file-name extension.

What Information Needs To Be Registered

An ActiveX object has four pieces of identifying information:

  • The class identifier (CLSID) of the object. This is a globally unique identifier (GUID). The examples below use this CLSID:
    {01234567-89AB-CDEF-0123-456789ABCDEF}
  • The ProgId of the object. This is a textual program identifier. The examples use FooCorp.BarControl.
  • The MIME type for media types the object understands. Note that not all ActiveX objects are viewers or players for media types, so not every object needs to be associated with a MIME type. The examples use the MIME type application/foobar.
  • The file extension for media types the object understands. Note that not all ActiveX objects are viewers or players for media types, so not every object needs to be associated with a file extension. The examples use the extension .foo.

Step 1: Registering the CLSID for the ActiveX Object

All ActiveX/COM objects must be entered in the registry so COM (Component Object Model) knows how to instantiate the object servers from the appropriate executable file. For full details on this registration process, see the COM Specification or OLE Reference (in the Platform SDK). A simple in-proc server would enter information such as the following in the registry.

HKEY_CLASSES_ROOT\CLSID\
    {01234567-89AB-CDEF-0123-456789ABCDEF}\
        InProcServer32        DLL File location
        ProgId                FooCorp.BarControl
        ......

To see an example, run Regedit.exe and look under HKEY_CLASSES_ROOT\CLSID.

Note For an ActiveX control to act as a full-frame viewer (for HTML A HREF tags) or as an embedded viewer (for EMBED tags), it is also necessary to include the CONTROL keyword in the registry settings for the control.

HKEY_CLASSES_ROOT\CLSID\
    {01234567-89AB-CDEF-0123-456789ABCDEF}\
        Control               (value not set)

It is also possible to register an ActiveX control as a full-frame viewer so it is used as the viewer/player when following A HREF links to a particular media type. To mark an ActiveX control as capable of full-frame display, use the following registry setting:

HKEY_CLASSES_ROOT\CLSID\
    {01234567-89AB-CDEF-0123-456789ABCDEF}\
        EnableFullPane\
           .foo

Note A requirement of this EnableFullPane registration process is to register the control as the viewer for the .foo file extension as described below.

Step 2: Associating the Object's CLSID with a ProgId

To associate a given ActiveX object with data types, it is first necessary to associate the object CLSID with a ProgId (program identifier). This is explained fully in the COM Specification or OLE Reference pages (Platform SDK), and is illustrated in the following simple example for defining the new ProgId, FooCorp.BarControl.

HKEY_CLASSES_ROOT\
    FooCorp.BarControl\
        CLSID                 {01234567-89AB-CDEF-0123-456789ABCDEF}

Also under the ProgId key it is possible to register shell commands to be used to edit or open files for this ProgId, as in the following example:

HKEY_CLASSES_ROOT\FooCorp.BarControl\
    Shell\Open\
        Command               c:\Program Files\foobar.exe %1

Step 3: Associating the Object with a MIME Type

It is possible to associate an ActiveX object as a viewer for various media types. The following keys must be entered in the registry to associate a given ActiveX object with a given media type, application/foobar.

HKEY_CLASSES_ROOT\
    MIME\Database\Content Type\
        application/foobar\
            Extension         .foo
            CLSID             {01234567-89AB-CDEF-0123-456789ABCDEF}

Note Neither the Extension nor the CLSID key is necessary. One key associates the MIME type with a file extension; the other associates it with the CLSID of an ActiveX object.

Step 4: Associating the File Extension with a ProgId and Optionally with a MIME Type

If an ActiveX control container such as Microsoft Internet Explorer does not have a (server-provided) MIME type to choose a viewer for a new data type, the data file-name extension is used to find the appropriate ActiveX object to understand the new media format. If the file-name extension is associated with a MIME type, the MIME-CLSID mapping is used to pick the object. Otherwise, the extension-ProgId mapping is used. The example below shows how to associate a three-letter file extension with a MIME type and a ProgId, although the MIME association is optional.

HKEY_CLASSES_ROOT\
    .foo\
        (Default)             FooCorp.BarControl
        Content Type          application/foobar


Safe Initialization and Scripting for ActiveX Controls

This document describes the code that a control developer should implement to ensure safe initialization and safe scripting for a Microsoft® ActiveX™ control.

Introduction

Internet Explorer 3.0 Security Levels

Initialization Security

Scripting Security

Using the Component Categories Manager

Supporting the IObjectSafety Interface

Reference

Introduction

Many Microsoft® ActiveX™ Controls are initialized with persistent data, which is either local or remote, and most ActiveX Controls are scriptable (they support a set of methods, events, and properties). Both initialization (with persistent data) and scripting require certain safeguards to ensure that security is not violated.

An example of a control that poses a security risk at initialization time would be a data compression/decompression control. If the user pointed this control to a remote, compressed file that contained a Trojan-horse copy of a system file (such as Kernel.dll) and requested that the control decompress this file, system security could be breached.

An example of a control that poses a security risk at scripting time would be a control that relies on certain system settings before a script can be safely executed. It would be up to the control developer to provide the necessary code that retrieves the system settings before allowing the script to execute.

Internet Explorer 3.0 Security Levels

Microsoft Internet Explorer 3.0 has three security levels: low, medium, and high. When the user attempts to display a page containing a control that does not guarantee safe initialization or scripting, Internet Explorer 3.0 does one of the following based on the current security level.
Security level | Internet Explorer 3.0 notification
Low | No warnings. Controls can be initialized or scripted regardless of data source or scripts.
Medium | User is warned of potential safety violation prior to loading the page. User can accept or reject initialization or scripting. If user disables scripting, scripting errors occur when user views the page and attempts to execute the script.
High | User is warned of potential safety violation prior to loading the page. User cannot accept or reject initialization or scripting. Scripting errors occur if user attempts to view page and execute script.

Note Most control developers set their Internet Explorer 3.0 security level to low during the early stages of control development. However, prior to implementing the safe initialization and scripting code, security should be reset to high (the default setting) to ensure adequate testing of the control.

Initialization Security

When a control is initialized, it can receive data from an arbitrary IPersist* interface (from either a local or a remote URL) for initializing its state. This is a potential security hazard because the data could come from an untrusted source. Controls that guarantee no security breach regardless of the data source are considered safe for initialization.

There are two methods for indicating that your control is safe for initialization. The first method uses the Component Categories Manager to create the appropriate entries in the system registry. Internet Explorer 3.0 examines the registry prior to loading your control to determine whether these entries appear. The second method implements an interface named IObjectSafety on your control. If Internet Explorer 3.0 determines that your control supports IObjectSafety, it calls the IObjectSafety::SetInterfaceSafetyOptions method prior to loading your control in order to determine whether your control is safe for initialization.

Scripting Security

Code signing can guarantee a user that code is trusted. However, allowing ActiveX Controls to be accessed from scripts raises several new security issues. Even if a control is known to be safe in the hands of a user, it is not necessarily safe when automated by an untrusted script. For example, Microsoft Word is a trusted tool from a reputable source, but a malicious script can use its automation model to delete files on the user's computer, install macro viruses, and worse.

There are two methods for indicating that your control is safe for scripting. The first method uses the Component Categories Manager to create the appropriate entries in the system registry (when your control is loaded). Internet Explorer 3.0 examines the registry prior to loading your control to determine whether these entries appear. The second method implements the IObjectSafety interface on your control. If Internet Explorer 3.0 determines that your control supports IObjectSafety, it calls the IObjectSafety::SetInterfaceSafetyOptions method prior to loading your control in order to determine whether your control is safe for scripting.

Using the Component Categories Manager

As mentioned previously, Internet Explorer 3.0 examines the system registry to determine whether a control is safe for initialization and/or scripting. Internet Explorer 3.0 examines the registry by calling the ICatInformation::IsClassOfCategories method to determine if the control supports the given category (safe for initializing or safe for scripting).

If a control uses the Component Categories Manager to register itself as being safe, the registry entry for that control contains an Implemented Categories key, which contains one or two subkeys. One subkey is set if the control supports safe initialization, and the other subkey is set if the control supports safe scripting. The safe initialization subkey corresponds to CATID_SafeForInitializing; the safe scripting subkey corresponds to CATID_SafeForScripting. (Unlike the other subkeys for the component categories that are defined in the Comcat.h file, the subkeys for safe initialization and scripting are defined in Objsafe.h.)

The following illustration shows a snapshot of the registry entry for the Tabular Data Control, an ActiveX™ control that ships with Internet Explorer and allows authors to create data-driven Web pages. Because the control is safe for scripting and initialization, it marks itself in the registry as safe for scripting (7DD95801-9882-11CF-9FA9-00AA006C42C4)and safe for initializing from persistent data (7DD95802-9882-11CF-9FA9-00AA006C42C4).

Registry entry for a control

Registering a Control as Safe

The system registry contains a Component Categories key that lists subkeys for each of the categories of functionality that are implemented or required by components and applications installed on the system. The following illustration shows a snapshot of the Component Categories key. Observe that the CATID_SafeForScripting (7DD95801-9882-11CF-9FA9-00AA006C42C4) and the CATID_SafeForInitializing (7DD95802-9882-11CF-9FA9-00AA006C42C4) are included in the list:

Component Categories key and subkeys

To create the subkey for the appropriate component category, your control must complete the following steps:

  1. Create an instance of the Component Categories Manager and retrieve the address of the ICatRegister interface.
  2. Set the appropriate members of a CATEGORYINFO structure.
  3. Call the ICatRegister::RegisterCategories method, passing the address of the initialized CATEGORYINFO structure.

The following example shows how these steps were accomplished and combined into a single function named CreateComponentCategory in the sample control.

#include "comcat.h"
HRESULT CreateComponentCategory(CATID catid, WCHAR* catDescription)
    {

    ICatRegister* pcr = NULL ;
    HRESULT hr = S_OK ;

    hr = CoCreateInstance(CLSID_StdComponentCategoriesMgr,
            NULL, CLSCTX_INPROC_SERVER, IID_ICatRegister, (void**)&pcr);
    if (FAILED(hr))
        return hr;

    // Make sure the HKCR\Component Categories\{..catid...}
    // key is registered.
    CATEGORYINFO catinfo;
    catinfo.catid = catid;
    catinfo.lcid = 0x0409 ; // english

    // Make sure the provided description is not too long.
    // Only copy the first 127 characters if it is.
    int len = wcslen(catDescription);
    if (len>127)
        len = 127;
    wcsncpy(catinfo.szDescription, catDescription, len);
        // Make sure the description is null terminated.
        catinfo.szDescription[len] = '\0';

    hr = pcr->RegisterCategories(1, &catinfo);
        pcr->Release();

        return hr;
    }

When a subkey has been created for the requisite category, the control should register the category as being implemented by the control. To register the category as being implemented, your control should complete these tasks:

  1. Create an instance of the Component Categories Manager and retrieve the address of the ICatRegister interface.
  2. Call the ICatRegister::RegisterClassImplCategories method, passing the control's CLSID and the requisite category ID as arguments.

The following example shows how these steps were accomplished and combined into a single function named RegisterCLSIDInCategory in the sample control.

#include "comcat.h"
HRESULT RegisterCLSIDInCategory(REFCLSID clsid, CATID catid)
    {
// Register your component categories information.
    ICatRegister* pcr = NULL ;
    HRESULT hr = S_OK ;
    hr = CoCreateInstance(CLSID_StdComponentCategoriesMgr,
                NULL, CLSCTX_INPROC_SERVER, IID_ICatRegister, (void**)&pcr);
    if (SUCCEEDED(hr))
    {
       // Register this category as being "implemented" by the class.
       CATID rgcatid[1] ;
       rgcatid[0] = catid;
       hr = pcr->RegisterClassImplCategories(clsid, 1, rgcatid);
    }

    if (pcr != NULL)
        pcr->Release();

        return hr;
        }

A control should register the safe initialization and scripting categories when its DLLRegisterServer function is called. (DLLRegisterServer is called by the Component Object Model [COM] to create the registry entries for all classes supported by the control.) In the sample control, the DLLRegisterServer function contains calls to the CreateComponentCategory and RegisterCLSIDInCategory functions (which register the control as safe for initialization and scripting). The following implementation of DLLRegisterServer was taken from the sample control.

STDAPI DllRegisterServer(void)
{
    HRESULT  hr;    // return for safety functions

    AFX_MANAGE_STATE(_afxModuleAddrThis);

    if (!AfxOleRegisterTypeLib(AfxGetInstanceHandle(), _tlid))
        return ResultFromScode(SELFREG_E_TYPELIB);

    if (!COleObjectFactoryEx::UpdateRegistryAll(TRUE))
        return ResultFromScode(SELFREG_E_CLASS);

    // Mark the control as safe for initializing.

    hr = CreateComponentCategory(CATID_SafeForInitializing, L"Controls
        safely initializable from persistent data!");
    if (FAILED(hr))
        return hr;

    hr = RegisterCLSIDInCategory(CLSID_SafeItem, CATID_SafeForInitializing);
    if (FAILED(hr))
        return hr;

    // Mark the control as safe for scripting.

    hr = CreateComponentCategory(CATID_SafeForScripting, L"Controls
        safely scriptable!");
    if (FAILED(hr))
        return hr;

    hr = RegisterCLSIDInCategory(CLSID_SafeItem, CATID_SafeForScripting);
    if (FAILED(hr))
        return hr;

    return NOERROR;
}

Just as a control is responsible for creating the registry entries for all safety categories it supports, a control is also responsible for unregistering its categories. The COM calls a control's DLLUnRegisterServer function to remove appropriate registry entries before unloading the control.

To unregister the safe initialization and/or safe scripting categories, the control should do the following:

  1. Create an instance of the Component Categories Manager and retrieve the address of the ICatRegister interface.
  2. Call the ICatRegister::UnRegisterClassImplCategories method, passing the control's CLSID and the requisite category ID as arguments.

The following example shows how these steps were accomplished and combined into a single function named UnRegisterCLSIDInCategory in a sample control.

HRESULT UnRegisterCLSIDInCategory(REFCLSID clsid, CATID catid)
    {
    ICatRegister* pcr = NULL ;
    HRESULT hr = S_OK ;

    hr = CoCreateInstance(CLSID_StdComponentCategoriesMgr,
            NULL, CLSCTX_INPROC_SERVER, IID_ICatRegister, (void**)&pcr);
    if (SUCCEEDED(hr))
    {
       // Unregister this category as being "implemented" by the class.
       CATID rgcatid[1] ;
       rgcatid[0] = catid;
       hr = pcr->UnRegisterClassImplCategories(clsid, 1, rgcatid);
    }

    if (pcr != NULL)
        pcr->Release();

        return hr;
        }

As mentioned previously, a control is responsible for removing the safe initialization and scripting category entries when the DLLUnRegisterServer function is called. The following excerpt is taken from a sample control that supports both safe initialization and safe scripting.

STDAPI DllUnregisterServer(void)
{
    HRESULT hr;    // HResult used by Safety Functions

    AFX_MANAGE_STATE(_afxModuleAddrThis);

    if (!AfxOleUnregisterTypeLib(_tlid))
        return ResultFromScode(SELFREG_E_TYPELIB);

    if (!COleObjectFactoryEx::UpdateRegistryAll(FALSE))
        return ResultFromScode(SELFREG_E_CLASS);

    // Remove entries from the registry.

    hr=UnRegisterCLSIDInCategory(CLSID_SafeItem, CATID_SafeForInitializing);
    if (FAILED(hr))
        return hr;

    hr=UnRegisterCLSIDInCategory(CLSID_SafeItem, CATID_SafeForScripting);
    if (FAILED(hr))
        return hr;

    return NOERROR;
}

Supporting the IObjectSafety Interface

The IObjectSafety interface allows a container to ask a control to make itself safe, or to retrieve the current initialization or scripting capabilities for the control. This interface is defined in the Objsafe.h file. Currently two capabilities are supported: safe for scripting and safe for initialization. These capabilities correspond to the following bit flags, which are defined in Objsafe.h:
INTERFACESAFE_FOR_UNTRUSTED_DATA | Specifies that the interface is safe for initialization.
INTERFACESAFE_FOR_UNTRUSTED_CALLER | Specifies that the interface is safe for scripting.

(Additional capabilities may be defined at a future date.)

The IObjectSafety interface supports two methods: IObjectSafety::GetInterfaceSafetyOptions and IObjectSafety::SetInterfaceSafetyOptions. The first method returns the control's security capabilities (as specified by either of the two bit flags listed above). The second method allows a container to request that a control configure itself for safe initialization or scripting. The following listing from Objsafe.h contains the interface and method definitions.

// Option bit definitions for IObjectSafety:
#define    INTERFACESAFE_FOR_UNTRUSTED_CALLER    0x00000001
        // Caller of interface may be untrusted.
#define    INTERFACESAFE_FOR_UNTRUSTED_DATA    0x00000002
        // Data passed into interface may be untrusted.

// {CB5BDC81-93C1-11cf-8F20-00805F2CD064}
DEFINE_GUID(IID_IObjectSafety, 0xcb5bdc81, 0x93c1, 0x11cf, 0x8f, 0x20,
    0x0, 0x80, 0x5f, 0x2c, 0xd0, 0x64);

interface IObjectSafety : public IUnknown
    {
    public:
        virtual HRESULT __stdcall GetInterfaceSafetyOptions(
            /* [in]  */ REFIID riid,
            /* [out] */ DWORD __RPC_FAR *pdwSupportedOptions,
            /* [out] */ DWORD __RPC_FAR *pdwEnabledOptions) = 0;

        virtual HRESULT __stdcall SetInterfaceSafetyOptions(
            /* [in] */ REFIID riid,
            /* [in] */ DWORD dwOptionSetMask,
            /* [in] */ DWORD dwEnabledOptions) = 0;

    };

Although some containers call IObjectSafety::GetInterfaceSafetyOptions to retrieve the default capabilities for a control, Internet Explorer 3.0 does not. Instead, it calls IObjectSafety::SetInterfaceSafetyOptions prior to initializing a control. And, if the control supports scripting, it calls IObjectSafety::SetInterfaceSafetyOptions a second time. This function has three arguments: the first specifies the interface ID for an interface on the control that the container wants to access; the second specifies the capabilities that the container would like to set; the third specifies how the container would like to set these options.


ActiveX Control Tutorial

This article describes how a developer can add ActiveX™ support to an existing OLE Automation control.

Introduction

Prerequisites

Document Roadmap

What Is an ActiveX Control?

Porting the Timer Control

Introduction

An ActiveX control is an object that supports a customizable, programmatic interface. Using the methods, events, and properties exposed by a control, Web authors can automate their HTML pages. Examples of ActiveX Controls include text boxes, command buttons, audio players, video players, stock tickers, and so on.

You can develop ActiveX Controls using Microsoft® Visual Basic® 5.0, Java™, and Microsoft Visual C++®. This article focuses on controls developed with Microsoft Visual C++. (For more information about developing controls with Microsoft Visual Basic, refer to http://www.microsoft.com/vbasic/prodinfo/cce/; for more information about developing controls with Java, refer to http://splash.javasoft.com/beans/javadoc/packages.html.)

Because ActiveX Controls are complex, Microsoft offers several tools that help a C++ developer create an ActiveX control. The following table describes these tools.
Tool | Description | Ships with
Microsoft Foundation Class Library (MFC) | A set of C++ classes that support COM, OLE, and ActiveX (among other things). MFC provides the simplest means of creating ActiveX Controls. | Microsoft Visual C++ version 4.2 or later. (MFC ships with earlier versions of Visual C++; however, these versions do not support ActiveX.)
ActiveX Controls Framework | A set of C++ classes designed specifically to support control development. The framework requires more knowledge of OLE Automation and dual interfaces than does MFC. | Internet Client SDK.
Microsoft ActiveX Template Library | A set of C++ templates designed to create small and fast COM objects. | ATL 2.1 ships with Microsoft Visual C++ version 5.0. (ATL 2.0 is a web release that relies on the Microsoft Visual C++ 4.2 IDE).

This tutorial focuses on controls developed with MFC. It demonstrates how you can convert an existing OLE control into an ActiveX control. The tutorial is based on the sample MFC timer control that ships with Microsoft Visual C++ version 4.2. The timer control supported a single event and a single property: It fired a Timer event at a user-specified interval (which corresponded to the control's Interval property). For the purpose of this tutorial, the timer control was converted into a digital alarm clock (which can be inserted into an HTML page using the OBJECT tag).

Digital-Clock ActiveX Control

The modifications to the sample timer control include:

  • Overriding the COleControl::OnDraw member function so that the control renders current time.
  • Adding support for stock font, foreground color, and background color properties.
  • Adding support for the alarm's hour and minute properties.
  • Identifying the control as safe for scripting.
  • Adding support for run-time licensing.
  • Packaging the control for efficient download on the Internet.

Prerequisites

To benefit from this tutorial, you should be familiar with COM (the OLE Component Object Model) and OLE Automation; in addition, you should know C++ and be familiar with the Microsoft Foundation Class Library (MFC).

If you need an introduction to COM, you should read the second edition of Inside OLE by Kraig Brockschmidt (published by Microsoft Press). If you need an introduction to OLE Automation, you should read ActiveX Controls Inside Out by Adam Denning (also published by Microsoft Press).

If you need an introduction to C++ or the Microsoft Foundation Class Library, you should read Inside Visual C++ by David Kruglinski (and published by Microsoft Press).

Document Roadmap

This document contains the following sections.
Section | Description
What Is an ActiveX Control? | Reviews the parts of an OLE control; in addition, it describes the new features that differentiate an ActiveX control from an OLE control. This section includes descriptions of topics such as security, run-time licensing, and packaging.
Porting the Timer Control | Describes the work required to convert the sample MFC timer control into a digital clock (with alarm functionality). It includes information about modifying the MFC OnDraw function, adding support for stock properties, adding support for custom properties, adding support for security, and so on.

What Is an ActiveX Control?

An ActiveX control is an OLE control that supports additional ActiveX features. This section reviews the architecture of an OLE control and then describes those additional ActiveX features (such as safety, run-time licensing, digital certificates, packaging the control, and so on).

Description of an OLE Control

At a minimum, an OLE control is a COM object that supports the IUnknown and IClassFactory (or IClassFactory2) interfaces. As stated, support for these interfaces is the minimal requirement for an OLE control; however, in order to do any meaningful work, an OLE control also supports a number of other interfaces that provide features such as writing persistent data to disk, supporting automation (methods, events, and properties), and supporting a user interface for the control.

The following table describes the interfaces that can be supported by an OLE control.
Interface | Description
IOleObject | Supports communication between container and the control.
IOleInPlaceObject | Supports in-place activation.
IOleControl | Supports mnemonics and ambient properties.
IDataObject | Supports data transfer (emulates DDE and the Windows® clipboard).
IViewObject2 | Supports functions that a container uses to render the control.
IDispatch | Supports a control's methods and properties.
IConnectionPointContainer | Supports a control's events or property-change notifications.
IProvideClassInfo2 | Supports functions that a container calls in order to obtain a pointer to the control's type information.
ISpecifyPropertyPages | Supports functions that a container calls to determine the extent of a control's property-page support.
IPerPropertyBrowsing | Supports functions that allow containers to retrieve individual control properties.
IPersist* | Includes six interfaces that support functions that enable a control to read or write its persistent data to storage, stream, or file.
IOleCache2 | Supports the functions that a container calls in order to cache a control's data.
IExternalConnection | Supports functions that a control uses to track external connections.
IRunnableObject | Supports functions that a container uses to determine whether a control differentiates between a "loaded" and a "running" state.

As the previous list notes, the IPersist* interfaces support functions that allow a control to read or write its persistent data to storage, stream, or file. The following list identifies these interfaces and their purpose.
Interface | Purpose
IPersistMemory | Saves and loads the control's data into a fixed-length sequential byte array (in memory).
IPersistStorage | Saves and loads the control's data into an IStorage instance. Controls that want to be marked "Insertable" as other compound document objects (for insertion into non-control-aware containers) must support this interface.
IPersistPropertyBag | Saves and loads the control's data as individual properties written to IPropertyBag, which the container implements. This is used for "Save As Text" functionality in some containers.
IPersistMoniker | Saves and loads the control's data to a location named by a moniker. The control calls IMoniker::BindToStorage to retrieve the storage interface it requires, such as IStorage, IStream, ILockBytes, IDataObject, and so on.

For more information about any of these interfaces, refer to the OLE core documentation that ships with the Platform SDK.

Description of an ActiveX Control

An ActiveX control is an OLE control that supports several additional features. These features include:

  • Initialization security
  • Scripting security
  • Run-time licensing
  • Reduced footprint (for quick downloading)
  • Digital certification

Initialization security

When a control is initialized, it can receive data from an arbitrary IPersist* interface (from either a local or a remote URL) for initializing its state. This is a potential security hazard because the data could come from an untrusted source. Controls that guarantee no security breach regardless of the data source are considered safe for initialization.

There are two methods for indicating that your control is safe for initialization. The first method uses the Component Categories Manager to create the appropriate entries in the system registry. Internet Explorer examines the registry prior to loading your control to determine whether these entries appear. The second method implements an interface named IObjectSafety on your control. If Internet Explorer determines that your control supports IObjectSafety, it calls the IObjectSafety::SetInterfaceSafetyOptions method prior to loading your control in order to determine whether your control is safe for initialization.

For more information about identifying a control as safe for initialization using the Component Categories Manager, see Using the Component Categories Manager. For more information about identifying a control as safe for initialization using IObjectSafety, see Supporting the IObjectSafety Interface.

Scripting security

Code signing can guarantee a user that code is trusted. However, allowing ActiveX Controls to be accessed from scripts raises several new security issues. Even if a control is known to be safe in the hands of a user, it is not necessarily safe when automated by an untrusted script. For example, Microsoft Word is a trusted tool from a reputable source, but a malicious script can use its automation model to delete files on the user's computer, install macro viruses, and worse.

Just as there are two methods for indicating that your control is safe for initialization, so there are two methods for identifying a control as safe for scripting. The first method uses the Component Categories Manager to create the appropriate entries in the system registry (when your control is loaded). Internet Explorer 3.0 examines the registry prior to loading your control to determine whether these entries appear. The second method implements the IObjectSafety interface on your control. If Internet Explorer 3.0 determines that your control supports IObjectSafety, it calls the IObjectSafety::SetInterfaceSafetyOptions method prior to loading your control in order to determine whether your control is safe for scripting.

For more information about identifying a control as safe for scripting using the Component Categories Manager, see Using the Component Categories Manager. For more information about identifying a control as safe for scripting using IObjectSafety, see Supporting the IObjectSafety Interface.

Run-time licensing

Most Microsoft ActiveX Controls should support design-time licensing and run-time licensing. (The exception is the control that is distributed free of charge.) Design-time licensing ensures that a developer is building his or her application or Web page with a legally purchased control; run-time licensing ensures that a user is running an application or displaying a Web page that contains a legally purchased control.

Design-time licensing is verified by control containers such as Microsoft Visual Basic, Microsoft Access, or Microsoft Visual InterDev. Before these containers allow a developer to place a control on a form or Web page, they first verify that the control is licensed by the developer or content creator. These containers verify that a control is licensed by calling certain functions in the control: If the license is verified, the developer can add it.

Run-time licensing is also an issue for these containers (which are sometimes bundled as part of the final application); the containers again call functions in the control to validate the license that was embedded at design time.

Microsoft Internet Explorer 4.0 is another type of container. Like the other containers, Internet Explorer 4.0 also calls functions in the control to verify that it is licensed. However, unlike Visual Basic or Microsoft Access, which embed ActiveX Controls within the binary code of their application's executable files, Internet Explorer 4.0 uses a different model. This unique model is a necessary response due to:

  • The openness of the browser (the ability to view the HTML source file).
  • Client/server issues imposed by the Internet (or corporate intranet).

Because any Internet Explorer 4.0 user can view the HTML source code for a given Web page, and because an ActiveX control is copied to a user's computer before it is displayed, a level of indirection is required to "hide" the license for an ActiveX control from the user. This prevents an Internet Explorer 4.0 user from pirating and reusing a control that he or she has not purchased. Microsoft addresses these run-time licensing issues with a new file called the license package file (or LPK file). This file can be included in any HTML page by using the OBJECT tag. For more information about .lpk files, their use, and their format, refer to The License Package File.

The functions that support run-time licensing are members of the IClassFactory2 interface. Any ActiveX control that supports run-time licensing must support and implement this interface (an extension of the IClassFactory interface).

For more detailed information about implementing run-time licensing for an ActiveX control, see Run-Time Licensing.

Reduced footprint

Microsoft supports a data-compression technology and associated toolset that you can use to package your ActiveX control for faster, more efficient downloading over the Internet or an intranet. (This same technology and toolset can be applied to Microsoft Win32® applications, Java classes, and Java libraries.)

Cabinet files

For a number of years, Microsoft used cabinet (.cab) files to compress software that was distributed on disks. Originally, these files were used to minimize the number of disks shipped with packaged product; today, .cab files are used to reduce the file size and the associated download time for Web content that is found on the Internet or corporate intranet servers.

The cabinet file format

The .cab file format is a nonproprietary compression format, also known as MSZIP, that is based on the Lempel-Ziv data-compression algorithm. (At a future date, other compression formats might also be supported.)

For information about Cabarc.exe, the tool you can use to compress your ActiveX control, see Cabarc.exe.

For a description of the HTML tags required to access a control contained in a cabinet file, see Accessing Controls Stored in Cabinet Files.

Digital certification

The default security level for Internet Explorer 4.0 is High. When a user runs at this level, any object identified by the OBJECT tag on an HTML page must be digitally signed. Digital signatures are created using the Authenticode™ technology that is included in the Internet Client SDK. A digital signature associates a software vendor's name and a unique public key with a file that contains an ActiveX object (ensuring some sort of accountability on the part of the object's developer).

Before you purchase a certificate for your control's .cab file from a vendor, you can use the test certificate provided by Microsoft for verification purposes.

For a description of how you can add a digital certificate to your control's .cab file, see Signing Code with Microsoft Authenticode Technology.

Porting the Timer Control

The original OLE timer control was an ideal starting point for a digital clock example: existing code was already in place to handle the firing of an event at a user-specified interval. The remaining work required the addition of:

  • Drawing code (which retrieves the current system time and then renders it within the control's real estate).
  • Stock properties (which let the user customize the appearance of the clock's output).
  • Custom properties (which let the user set the clock's alarm).
  • Support for safety (required by Internet Explorer).
  • Support for run-time licensing (required by Internet Explorer).
  • Packaging into a .cab file (required for efficient downloads).

The following sections describe how clock-like features were added to the timer control.

Modifying the OnDraw Function

As noted earlier in the Description of an OLE Control section, IViewObject is one of the interfaces commonly supported by an OLE control. This interface supports functions that a container calls to draw a control, to retrieve the logical palette used by a control, and to temporarily freeze the current view of the control.

MFC wraps the IViewObject functions in the COleControl class. These functions are defined in the Ctlview.cpp file. The COleControl::XViewObject::Draw function contains most of the functionality typically found in an implementation of IViewObject::Draw; this functionality includes:

  • Checking for optimized drawing.
  • Saving the DC state.
  • Switching to MM_TEXT mode.
  • Drawing the control.

To draw the control, COleControl::XViewObject::Draw calls the COleControl::DrawContent member function, which is found in Ctlcore.cpp. This function maps logical coordinates into device coordinates. Once the coordinates are converted, COleControl::DrawContent calls COleControl::OnDraw to actually render the control. COleControl::OnDraw must be overridden by the control developer in the source code, which is generated by the OLE Control wizard. The default version of COleControl::OnDraw simply draws an ellipse. The following excerpt shows the code provided by the OLE Control wizard.

/////////////////////////////////////////////////////////////////////////////
// CTimeCtrl::OnDraw - Drawing function

void CTimeCtrl::OnDraw(
            CDC* pdc, const CRect& rcBounds, const CRect& rcInvalid)
{
    // TODO: Replace the following code with your own drawing code.
    pdc->FillRect(rcBounds, CBrush::FromHandle((HBRUSH)GetStockObject(WHITE_BRUSH)));
    pdc->Ellipse(rcBounds);
}

Most of the code required to convert the sample timer control into a digital clock is actually found in the OnDraw function. This includes code that:

  • Sets the user's requested foreground color, background color, and font.
  • Sets the background mode to transparent for drawing.
  • Paints the control's background using the background color.
  • Retrieves the current system time.
  • Compares the current time to the user's requested alarm time.
  • Sounds the alarm if necessary.
  • Packages the time for rendering.
  • Renders the string containing the time.
  • Reselects the original font and brush into the device context.

The entire OnDraw function from the Timectl.cpp file appears below.

/////////////////////////////////////////////////////////////////////////////
// CTimeCtrl::OnDraw - Drawing function

void CTimeCtrl::OnDraw(
            CDC* pdc, const CRect& rcBounds, const CRect&)
{

    //Variables required for text output
    CFont* pOldFont;
    TEXTMETRIC tm;
    char tText[30];
    CString strTime;
    CRect rc = rcBounds;
    CBrush bkBrush(TranslateColor(GetBackColor()));

    //Variables required for alarm handler
    time_t aclock;     // Elapsed time in seconds since 00:00:00 on 1/1/1970
    struct tm *now;    // Time structure (contains useful time data)
    BOOL bTest;

    //Set the foreground color property and the transparent bk mode
    pdc->SetTextColor(TranslateColor(GetForeColor()));
    pdc->SetBkMode(TRANSPARENT);

    //Paint the background using the BackColor property
    pdc->FillRect(rcBounds, &bkBrush);

    //Retrieve the time, check the alarm, package a string specifying the time
    time(&aclock);    //Retrieve elapsed time in seconds
    now = localtime(&aclock);    //Convert elapsed seconds to meaningful data

    //Examine the alarm properties
    if ((now->tm_hour == m_alarmHour) && (now->tm_min == m_alarmMinute))
        if (bAlarm == TRUE)
    {
        bTest = PlaySound((const char*)IDR_WAVE3, AfxGetResourceHandle(), SND_RESOURCE);
        bAlarm = FALSE;
    }

    //Package time for rendering
    sprintf(tText, "Current Time: %.8s\n", asctime(now)+11);
    strTime = tText;

    //Draw the time string
    pOldFont = SelectStockFont(pdc);
    pdc->GetTextMetrics(&tm);
    pdc->SetTextAlign(TA_CENTER | TA_TOP);
    pdc->ExtTextOut((rc.left + rc.right) / 2, (rc.top + rc.bottom - tm.tmHeight) / 2, ETO_CLIPPED, rc, strTime, (strTime.GetLength())-1, NULL);

    //Reselect the old font and brush
    pdc->SelectObject(pOldFont);

}

Adding Support for Color and Font Properties

As noted in the previous section that describes the OnDraw function, the current time is rendered by using the background color, foreground color, and font properties that the user selected. These properties are three of the nine stock properties supported by the COleControl class. The following list identifies the nine supported stock properties:

  • Appearance
  • BackColor
  • BorderStyle
  • Caption
  • Enabled
  • Font
  • ForeColor
  • hWnd
  • Text

Support for the three stock properties was added using the ClassWizard. For example, support for the background color property was added through the following steps when the control's project was open in Microsoft Visual C++:

  1. Select ClassWizard from the View menu.
  2. Select the OLE Automation tab.
  3. Select the control's class from the Class Name combo box.
  4. Select the Add Property button.
  5. Select the BackColor property in the External Name box.
  6. Select the OK button to close the Add Property dialog box.
  7. Select the OK button to confirm choices and close the ClassWizard.

When support for a stock property is added using the ClassWizard, the control's implementation file (Timectl.cpp in the case of the sample) and the control's object description (.odl) file (Timectl.odl) are updated. In the case of the sample control's implementation file, the following line was added to the control's dispatch map:

DISP_STOCKPROP_BACKCOLOR()

In the case of the sample control's object description file, the following line was added:

[id(DISPID_BACKCOLOR), bindable, requestedit] OLE_COLOR BackColor;

After support for the stock properties was added to the sample control, these properties were available for drawing operations. The background color was retrieved by calling the GetBackColor function and applying the result to a background brush variable (bkBrush) as follows:

CBrush bkBrush(TranslateColor(GetBackColor()));

Adding Support for the Alarm (Properties and Resource)

As noted in the Adding Support for Color and Font Properties section, COleControl supports nine stock properties that are common to most ActiveX Controls. However, invariably a control requires custom properties such as the Alarm properties that are supported by the digital clock control.

There are four types of custom properties: member variables, member variables with notification, get/set methods, and parameterized. The sample digital-clock control supports three custom properties (each of which falls into the category of member variables with notification). These properties are the AlarmHour, AlarmMinute, and Interval. The AlarmHour property specifies the hour at which the alarm should trigger; the AlarmMinute property specifies the minute at which the alarm should trigger; and the Interval property specifies the interval (in milliseconds) for updating the clock that's displayed by the control. When the user resets any of these custom properties, a notification function is called to handle any work necessitated by those changes.

The MFC framework supports COleControl::DoPropExchange to load or store persistent data for a control. This function normally makes calls to the PX_ family of functions to load or store specific user-defined properties. The sample control takes advantage of the MFC property-exchange functionality to save and load the custom interval and alarm properties.

/////////////////////////////////////////////////////////////////////////////
// CTimeCtrl::DoPropExchange - Persistence support

void CTimeCtrl::DoPropExchange(CPropExchange* pPX)
{
    ExchangeVersion(pPX, MAKELONG(_wVerMinor, _wVerMajor));
    COleControl::DoPropExchange(pPX);

    long nInterval = m_interval;
    short sAlarmHr = m_alarmHour;
    short sAlarmMin = m_alarmMinute;

    PX_Long(pPX, _T("Interval"), m_interval, DEFAULT_INTERVAL);
    if (pPX->IsLoading())
    {
        if (nInterval != m_interval)
            OnIntervalChanged();
    }

    PX_Short(pPX, _T("AlarmHour"), m_alarmHour, DEFAULT_HOUR);
    if (pPX->IsLoading())
    {
        if (sAlarmHr != m_alarmHour)
            OnAlarmHourChanged();
    }

    PX_Short(pPX, _T("AlarmMinute"), m_alarmMinute, DEFAULT_MINUTE);
    if (pPX->IsLoading())
    {
        if (sAlarmMin != m_alarmMinute)
            OnAlarmMinuteChanged();
    }
}

In the case of the AlarmHour property, when the OnAlarmHourChanged function is called, a global Boolean variable (bAlarm) is set to TRUE and the COleControl::SetModifiedFlag function is called to notify the container that the control's persistent state has changed.

void CTimeCtrl::OnAlarmHourChanged()
{
    bAlarm = TRUE;
    SetModifiedFlag(TRUE);
}

The global variable (bAlarm) is examined within the COleControl::OnDraw function to ensure that the alarm should be triggered at the specified time.

//Examine the alarm properties
    if ((now->tm_hour == m_alarmHour) && (now->tm_min == m_alarmMinute))
        if (bAlarm == TRUE)
    {
        bTest = PlaySound((const char*)IDR_WAVE3, AfxGetResourceHandle(), SND_RESOURCE);
        bAlarm = FALSE;
    }

As this code excerpt shows, the alarm sounds when the PlaySound function is called. This function takes three arguments: the first (IDR_WAVE3) is a resource identifier; the second is an instance handle for the control's resources; and the third is a flag specifying that the sound is a resource.

The current alarm sound (a ringing phone) was inserted into the sample control's DLL to ensure that the alarm would activate on any system that supported audio output. This .wav file was inserted using the Insert Resource dialog box.

Adding Support for Safety

The sample control uses the Component Categories Manager to identify its safety features. For sample code demonstrating how this support was implemented, see Registering a Control as Safe.

Adding Support for Run-Time Licensing

The sample control supports run-time licensing for most containers through the IClassFactory2 interface. However, when Internet Explorer is the container, it's also necessary to generate an .lpk file as part of the run-time licensing scheme.

For more information about run-time licensing and .lpk files, see Run-Time Licensing for Internet Explorer 4.0.

For more information about using LPKTool.exe to create an .lpk file for a control, see Appendix A - Generating a License Package with LPK_TOOL.

Reducing a Control's Footprint

The sample control was compressed using Cabarc.exe, a tool provided as part of the Internet Client SDK. For a description of this process, see Packaging the Sample ActiveX Control.

Creating a Test Certificate for an ActiveX Control

For testing purposes, a digital certificate was added to the sample control's .cab file using several tools shipped with the Internet Client SDK. For a description of this process, see Signing the .cab File.


Appendix A: Required Files

To use Authenticode, a set of client files, publishing tools, and a signing DLL are required.

Client files are installed in the \WinNT\System32 directory on Microsoft(r) Windows NT(r), or in the \Windows\System directory on Microsoft Windows(r) 95, and include the following:

  • Wintrust.dll
  • Softpub.dll
  • Mssip32.dll
  • Vsrevoke.dll
  • Crypt32.dll

Publishing tools and the signing DLL are installed in the \INetSDK\Bin directory and include the following:

  • MakeCert.exe (creates an X.509 certificate for testing purposes only)
  • Cert2SPC.exe (creates an SPC for testing purposes only)
  • SignCode.exe (signs and timestamps a file)
  • ChkTrust.exe (checks the validity of the file)
  • MakeCTL.exe (creates a certificate trust list)
  • CertMgr.exe (manages certificates, CTLs, and CRLs)
  • SetReg.exe (sets registry keys controlling certificate verification)
  • Signer.dll (performs signing)

Appendix B: The X.509 Certificate

The X.509 protocols include a structure for public-key certificates. A CA assigns a unique name to each user and issues a signed certificate containing this name and the user's public key. The following diagram shows an X.509 certificate.

These are the meanings for each field.
Field | Meaning
Version | Identifies the certificate format.
Serial Number | A value unique to the CA.
Algorithm Identifier | Identifies the algorithm used to sign the certificate, together with any necessary parameters.
Issuer | The name of the CA.
Period of Validity | A pair of dates. The certificate is valid during the time period between the two.
Subject | The name of the user.
Subject's Public Key | Contains the public key algorithm name, any necessary parameters, and the public key.
Signature | The CA's signature.

Appendix C: Suggested Reading

The topic of digital signing is discussed more fully in the following documents.

CCITT, Recommendation X.509, The Directory-Authentication Framework, Consultation Committee, International Telephone and Telegraph, International Telecommunications Union, Geneva, 1989.

Microsoft Cryptographic Service Provider Programmer's Guide, Microsoft, 1995.

Microsoft Application Programmer's Guide, Microsoft, 1995

RSA Laboratories, PKCS #7: Cryptographic Message Syntax Standard. Version 1.5, November, 1993.

Schneier, Bruce, Applied Cryptography, 2d ed. New York: John Wiley & Sons, 1996.

http://www.microsoft.com/security

http://www.rsa.com External Link


Glossary

X.509 Certificate

A cryptographic certificate that contains a vendor's unique name and the vendor's public key.

PKCS #7 Signed Data

A Public Key Certificate Standard #7 (PKCS #7) signed-data object encapsulates the information used to sign a file. Typically, it includes the signer's certificate and the root certificate.

Certification Authority (CA)

A trusted entity that makes a statement (represented by an X.509 certificate) about the authenticity of another certificate.

Cryptographic Digest

A one-way hash function that takes a variable-length input string and converts it to a fixed-length output string (called a cryptographic digest.) This fixed-length output string is probabilistically unique for every different input string and thus can act as a fingerprint of a file. When a file with a cryptographic digest is downloaded, the receiver recomputes the digest. If the output string matches the digest contained in the file, the receiver has proof that the received file was not tampered with and is identical to the file originally sent.

Local Registration Authority (LRA)

An intermediary between a publisher and a CA. The LRA can, for example, verify a publisher's credentials before sending them to the CA.

Portable Executable (PE) Image

The standard Win32(r) executable format.

Software Publishing Certificate (SPC)

A PKCS #7 signed-data object containing X.509 certificates.

Trust Provider

The software that decides whether or not a given file is trusted. This decision is based on the certificate associated with the file.

WIN_CERTIFICATE

A Win32 data structure that contains either a PKCS #7 signed-data object or an X.509 certificate.


Introduction to Code Signing

One of the larger questions facing the software industry is this: How can users trust code that is published on the Internet? Currently, most Web pages contain only static information, but soon they will be filled with controls and applications that are downloaded and run locally, on the user's computer.

Packaged software uses branding and trusted sales outlets to assure users of its integrity, but these are not available when code is transmitted on the Internet. Additionally, there is no guarantee that the code hasn't been altered while being downloaded. Browsers typically exhibit a warning message explaining the possible dangers of downloading data, but do nothing to actually see whether the code is what it claims to be. A more active approach must be taken to make the Internet a reliable medium for distributing software.

Ensuring Integrity and Authenticity

There are two issues that must be addressed to make the Internet a reliable source for software:
Ensuring authenticity | Assures users that they know where the code came from.
Ensuring integrity | Verifies that the code hasn't been tampered with since its publication.

Microsoft's solution to these issues is Authenticode coupled with an infrastructure of trusted entities. A discussion of the infrastructure is included in the explanation of certification authorities later in this section. Authenticode, which is based on industry standards, allows developers to include information about themselves and their code with their programs through the use of digital signatures.

While Authenticode itself cannot guarantee that signed code is safe to run, Authenticode is the mechanism by which users can be informed of whether the software publisher is participating in the infrastructure of trusted entities. Thus, Authenticode serves the needs of both software publishers and users who rely upon the Internet for the downloading of software.

Digital Signatures

Use digital signatures when you want to distribute data, and you want to assure recipients that it does indeed come from you. Signing data does not alter it; it simply generates a digital signature string you can bundle with the data.

Digital signatures are created using a public-key signature algorithm such as the RSA public-key cipher. A public-key algorithm actually uses two different keys: the public key and the private key (called a key pair). The private key is known only to its owner, while the public key can be available to anyone. Public-key algorithms are designed so that if one key is used for encryption, the other is necessary for decryption. Furthermore, the decryption key cannot be reasonably calculated from the encryption key. In digital signatures, the private key generates the signature, and the corresponding public key validates it.

In practice, public-key algorithms are often too inefficient for signing long documents. To save time, digital signature protocols use a cryptographic digest, which is a one-way hash of the document. The hash is signed instead of the document itself. Both the hashing and digital signature algorithms are agreed upon beforehand. Here is a summary of the process:

  1. A one-way hash of the document is produced.
  2. The hash is encrypted with the private key, thereby signing the document.
  3. The document and the signed hash are transmitted.
  4. The recipient produces a one-way hash of the document.
  5. Using the digital signature algorithm, the recipient decrypts the signed hash with the sender's public key.

If the signed hash matches the recipient's hash, the signature is valid and the document is intact.

When software (code) is associated with a publisher's unique signature, distributing software on the Internet is no longer an anonymous activity. Digital signatures assure accountability, just as a manufacturer's brand name does on packaged software. If an organization or individual wants to use the Internet to distribute software, they should be willing to take responsibility for that software. This is based on the premise that accountability is a deterrent to the distribution of harmful code.

Digital Certificates

A certificate is a set of data that completely identifies an entity, and is issued by a certification authority (CA) only after that authority has verified the entity's identity. The data set includes the entity's public cryptographic key. When the sender of a message signs the message with its private key, the recipient of the message can use the sender's public key (retrieved from the certificate either sent with the message or possibly available elsewhere in the directory service) to verify the sender's identity.

Certificate Store Technology

In order to perform a code signing operation, both private key and signer identification information must be supplied. The digital certificate used in the signature usually supplies the signer identification information, however. Thus, the private key must be supplied through some other means. Additionally, the signature must include the certificate chain for the cryptographic service provider (CSP), up to a root certificate trusted by the user, in order for the signed file to be authenticated. So in all, there are several items that need to be provided in order to generate a digital signature.

Microsoft has developed a certificate store technology to reduce the above complexity. Using this technology, when a user enrolls to obtain a certificate, they specify the private key information, the CSP information, and the certificate store name for the certificate. The certificate will then be stored in the certificate store and be associated with the other items. When the user wants to sign a document, they only need to identify the certificate in the certificate store. The code signing tool will retrieve the certificate, the private key, and the certificate chain for the CSP, all based on the specified certificate.

Using Microsoft's certificate store technology, only one certificate is necessary to perform a digital code signing operation. This relieves users from having to manage private key and CSP information.

Digital Certification

One of the primary goals of a digital certificate is to confirm that the public key contained in a certificate is, in fact, the public key belonging to the person or entity to whom the certificate is issued. For example, a Certification authority (CA) might digitally sign a special message (the certificate information) containing the name of a user, Alice, and her public key in such a way that anyone can verify that the certificate information message was signed by no one other than the CA and thereby convey trust in Alice's public key.

The typical implementation of digital certification involves a signature algorithm for signing the certificate. The process goes something like this:

  1. Alice sends a certification request containing her name and her public key to a CA.
  2. The CA creates a special message (m) from Alice's request, which constitutes most of the data in the certificate. The CA signs the message with its private key, obtaining a separate signature (sig) in the process. Then the CA returns the message m and the signature sig to Alice; the two parts together form a certificate.
  3. Alice sends the certificate to Bob to convey trust in her public key.
  4. Bob verifies the signature sig using the CA's public key. If the signature is verified, he accepts Alice's public key.

As with any digital signature, anyone can verify, at any time, that the certificate was signed by the CA, without access to any secret information. Bob needs only to get a copy of the CA's certificate in order to access the CA's public key.

A certificate is valid only for the period of time specified by the CA that issued it. The certificate contains information about its beginning and expiration dates. The CA can also revoke any certificate it has issued and maintains a list of revoked certificates. This list is called a certificate revocation list (CRL), and is published by the CA so that anyone can determine the validity of any given certificate.

Certification Authorities

Certification authorities (CAs) are trustworthy persons or organizations that issue certificates to applicants whose identity has in some way been verified by the CA. Certificates are verified through a hierarchy of these CAs. Each certificate is linked to the certificate of the CA that signed it. By following this hierarchy, or verification path, to a known, trusted CA, you can be assured that a certificate is valid. An example of this is illustrated in the following diagram.

Sample certification hierarchy

In this example, Netwerks' certificate is certified by CA1, while Bob's is certified by CA3. Netwerks knows CA1's public key. CA2 has a certificate signed by CA1, so Netwerks can verify the CA2 certificate. The root also has a certificate signed by CA1. CA3 (Bob's CA) has a certificate signed by the root. By moving up the verification chain to a common point (in this case, the root), Netwerks can verify Bob's certificate.

Duties of Certification Authorities

Certification authorities have two main duties:

  • Publishing the criteria for granting certificates.
  • Granting certificates to applicants that meet the published criteria.

Other duties might include:

  • Managing certificates (for example, enrolling, renewing, and revoking them).
  • Storing root keys.
  • Verifying evidence submitted by applicants.
  • Providing tools for enrollment.
  • Accepting the liability associated with these responsibilities.

Obtaining Certification

To obtain a certificate from a CA, a software publisher must meet the criteria for either a commercial or an individual publishing certificate and submit these credentials to either a CA or a Local Registration Authority (LRA). The criteria discussed below have been proposed by Microsoft. Note that standards bodies, such as the World Wide Web Consortium (W3C), are reviewing these criteria and they are subject to change. A description of the overall process of obtaining a certificate for code signing ends this section of the document.

Criteria for Commercial Certification

Applicants for a commercial software publishing certificate must meet the following criteria:
Identification | Applicants must submit their name, address, and other material that proves their identity as a corporate representative. Proof of identify requires either personal presence or registered credentials.
The Pledge | Applicants must pledge that they will not distribute software that they know, or should have known, contains viruses or would otherwise harm a user's computer or code.
Dun & Bradstreet Rating | Applicants must achieve a level of financial standing as indicated by a D-U-N-S number (which indicates a company's financial stability) and any additional information provided by this service. This rating identifies the applicant as a corporation that is still in business. (Other financial rating services are being investigated.) Corporations that do not have a D-U-N-S number at the time of application (usually because of recent incorporation) can apply for one and expect a response in less than two weeks.

It is recommended that applicants generate and store their private key using a dedicated hardware solution. For example, this can be a magnetic stripe card, a plastic key with an embedded ROM chip (called a ROM key), or a smart card. For more information about storing keys, see Section 8.7 of Bruce Schneier's book, Applied Cryptography.

How do large software publishers determine who should apply for certificates and who should sign code? The answers depend on how the software publisher wants to control distribution of their software on the Internet.

In a centralized approach, where the company wants total control of what code is published, there may be only one certificate, and strict guidelines for releasing code through one source. In a decentralized approach, software publishers might allow each division, or even smaller groups or individuals within the company, to sign their own code using the corporate name. The point is that the software publisher must decide who can apply for a certificate and sign code, and who takes responsibility for any code signed using certificates that bear the corporate name.

Using the Dun & Bradstreet rating as a criterion draws a line between "commercial" and "individual" developers. The intended distinction is between commercial persons or entities (that is, sole proprietors, partnerships, corporations, or other organizations that develop software as a business) and noncommercial persons or entities (that is, individuals or nonprofit corporations).

Criteria for Individual Certification

Applicants for an individual software publishing certificate must meet the following criteria:
Identification | Applicants must submit their name, address, and other material that will be checked against an independent consumer database to validate their credentials.
The Pledge | Applicants must pledge that they cannot and will not distribute software that they know, or should have known, contains viruses or would otherwise maliciously harm the user's computer or code.

The value of an individual software publishing certificate is in the information it provides to users so they can decide whether or not to download the code. Knowing who authored the code, and that the bits have not been altered from the time the code was signed to the present, is reassuring information. Additionally, a browser could be used to access a publisher's Web pages so the user can obtain detailed information about the signed code, the author, and the certificate authority. After learning about this code and the author, the user might decide to run the code, or all future code, coming from this particular individual.

The Application Process

These are the steps to apply for and grant a certificate:

  1. Apply for a software publishing certificate.

    A software publisher's request for certification is sent to the local registration agency (LRA). (In a simpler model, it is sent to the CA.) It is expected that CAs and LRAs will have Web sites that walk the applicant through the application process. Applicants will be able to look at the entire policy and practices statements of the CA or LRA. The utilities an applicant needs to generate signatures, such as Microsoft Authenticode, should also be available.

    The applicant must generate a key pair using either hardware or software encryption technology. The public key is sent to the LRA during the application process. For individuals, all of the necessary information can be transferred online. For commercial publishers, because of the identity requirements, proof of identification must be sent by mail or courier.

  2. Verify the applicant's credentials.

    Depending on the contract between the CA and the LRA, these companies will examine the evidence to verify an applicant's credentials. To do this, they may employ external contractors such as Dun & Bradstreet.

  3. Generate and issue the software publisher X.509 certificate.

    After the CA has decided that the applicant meets the policy criteria, it generates a Software Publisher Certificate (SPC). The SPC contains multiple certificates conforming to the industry standard X.509 certificate format with Version 3 extensions. The SPC is distributed in a digital signature with the publisher's software file to identify the publisher and provide the publisher's public key. The digital signature is also used by the receiver of the file to verify that the file has not been modified since it was signed.

    The SPC is stored by the CA for reference, and a copy is returned to the applicant via electronic mail.

    The publisher should review the contents of the certificate and verify that the public key works with the private key. After accepting the certificate, the publisher should include a copy in all published software signed with the private key.

    Commercial developers can expect a response to their application in less than two weeks. While there is no limit to the number of certificates commercial software publishers can obtain, it is up to the publisher to determine who gets a certificate, and how code is signed and distributed.

  4. Distribute signed software.

    The publisher can now begin signing and distributing software on the Internet. Publishers use utility programs to sign the software they intend to publish. The utility programs use the private key to generate a digital signature on a digest of the binary file and create a signature file containing the signed content of a PKCS #7 signed-data object. (For more information about PKCS #7, see the RSA specification listed in Suggested Reading.) The PKCS #7 signed-data object also contains a copy of the SPC. For portable executable (PE) image format files, the PKCS #7 signature file contents are stored in the binary file itself, in an additional section.


Important Release Information

This release of Authenticode version 2.0 is coupled with Microsoft Internet Explorer version 4.0, and contains changes and enhancements over the previous version that was released with Internet Explorer version 3.02 UPD.

The version of Authenticode that was released with Internet Explorer 3.02 UPD added several new important code-signing features that improve on the initial implementation of Authenticode. Both the code-signing tools and browsers were updated with a new infrastructure that provides for these new features. The two most important features are:

  • The addition of a verifiable signature timestamp. When a software publisher's certificate expires, it is impossible to determine if the software was signed during the valid period of the certificate without incorporation of a verifiable signature timestamp. Authenticode version 2.0 incorporates timestamping support in both the signing and verification tools. In addition, VeriSign will be supporting a verifiable timestamping service for Authenticode signing purposes.
  • Inclusion of certificates in the certificate authority (CA) verification hierarchy which expire on June 30, 1997. Earlier versions of Internet Explorer will be unable to verify Authenticode signatures after that date. Internet Explorer version 3.02 UPD and future versions resolve this by eliminating these 'short lived' certificates. Signatures on certificates issued by VeriSign will properly verify until expiration of the VeriSign root certificate.

This release (with Internet Explorer 4.0) contains the same infrastructure and features as the Internet Explorer 3.02 UPD release. However, to provide a more consistent user interface, many of the command line option flags have been re-named or changed, and a few have been added.

As a result of these Authenticode improvements, the following steps need to be taken:

  • Software publishers need to re-sign their code using the Authenticode version 2.0 tools for Internet Explorer 3.02 UPD or Internet Explorer 4.0 in order for users to be able to verify their signed files after June 30, 1997.
  • Users need to upgrade to Internet Explorer version 3.02 UPD or Internet Explorer 4.0 in order to verify signed files after June 30, 1997.

Note that once files are re-signed, users of Internet Explorer versions earlier than 3.02 UPD will not be able to verify the re-signed files unless they upgrade to version 3.02 UPD or version 4.0. But after July 1, 1997, users of Internet Explorer versions earlier than 3.02 UPD will not be able to verify any signed files, whether the files have been re-signed with the new tools or not. It is clearly in the users' best interest to upgrade to Internet Explorer 3.02 UPD or version 4.0 to be able to continue to verify signed files. So software publishers should be able to re-sign their code using the new tools with confidence that users will be able to verify the files.

Additionally, by using the VeriSign service to timestamp the new signatures, software publishers gain the added benefit that the digital signatures will not need to be re-signed when their own software publishing certificate expires.


Signing and Checking Code with Authenticode

This section demonstrates how to sign code by creating digital signatures and associating them with files using Authenticode, which is provided with the Internet Client SDK. Creating a fully verifiable certificate might assume the existence of a complex hierarchy of CAs. A root certificate and a root private key are provided for testing purposes only. Independent software vendors must obtain a certificate from GTE, VeriSign, Inc., or another CA for signing code that will be distributed to the public.

Authenticode consists of programs to digitally sign files and programs to check that the files were, indeed, successfully signed. The programs are:

  • MakeCert, which creates a test X.509 certificate.
  • Cert2SPC, which creates a test SPC.
  • SignCode, which signs a file.
  • ChkTrust, which checks the validity of the file.
  • MakeCTL, which creates a certificate trust list.
  • CertMgr, which manages certificates, certificate trust lists, and certificate revocation lists.
  • SetReg, which sets registry keys that control the certificate verification process.

All user input to these programs is now case insensitive. Additionally, separate options now exist for the key-pair name and the private-key file.

MakeCert

Use the MakeCert test program to generate a test X.509 certificate. MakeCert performs the following tasks:

  1. Creates a public/private key pair for digital signatures and associates it with a name that you choose.
  2. Associates the key pair with a publisher's name that you choose.
  3. Creates an X.509 certificate, signed by the test root key or one you specify, that binds your name to the public part of the key pair. The certificate is output to a file, a system certificate store, or both.

The syntax for invoking MakeCert is:

MakeCert [basic options | extended options] outputFile

MakeCert's options consist of basic options and extended options. Basic options are the most commonly used ones to create a certificate. Extended options provide more flexibility. The options for MakeCert are also divided into three functional groups:

  1. Options applicable to SPC-file, private-key, and certificate store technology.
  2. Options specific to SPC-file and private-key technology only.
  3. Options specific to certificate store technology only.

Options in Groups 2 and 3 cannot be mixed, with the exception of the –ic option.

MakeCert Group 1 Options

The following Group 1 options may be applied in all cases.

Options are sorted alphabetically in the left (IE 4.0) column, and the corresponding IE 3.02 options are given in the middle column. IE 3.02 options that have no direct IE 4.0 equivalent will say either "N/A" or "(See -option)" in the IE 4.0 column, and are sorted alphabetically into the order of IE 4.0 options. For example, the IE 3.02 -C option follows the IE 4.0 -b option.
For IE 4.0 | For IE 3.02 UPD | Description
-a algorithm | -a | For IE3.02: Indicates the SHA1 hash algorithm should be used. MD5 is the default For IE4.0: The hash algorithm. Must be set to either SHA1 or MD5. The default is MD5.
-b dateStart | -B:dateStart | The date the certificate first becomes valid. The default is when the certificate is created. The format of dateStart is mm/dd/yyyy.
(See -$) | -C | The certificate will be used by commercial software publishers.
(See -$) | -C:f | The certificate will be used by commercial software publishers who have met the minimum financial criteria.
-cy certificateTypes | -t:types | For IE3.02: The certificate type. This parameter can be E for end-entity, C for certificate authority, or both. For IE4.0: The certificate type. Can be end, authority, or both. End stands for end-entity and authority stands for certificate authority.
-d displayName | -d:displayName | The display name of the subject.
-e dateEnd | -E:dateEnd | The date when the validity period ends. The default is the year 2039.
-eku OID1,OID2... | N/A | Inserts a list of one or more comma-separated enhanced key usage Object Identifiers (OIDs) into the certificate. For example, -eku 1.3.6.1.5.5.7.3.2 inserts the client authentication OID. See wincrypt.h in CryptoAPI 2.0 for definitions of allowable OIDs.
N/A | -g | Creates a glue certificate (IE 3.02 only.)
-h numChildren | -h:numChildren | The maximum height of the tree below this certificate.
(See -$) | -I | The certificate will be used by individual software publishers.
-l policyLink | -l:policyLink | A link to SPC agency policy information (for example, a URL).
-m nMonths | -D:nMonths | The duration of the validity period.
(See -a) | -m | The MD5 hash algorithm should be used. This is the default.
-n name | -n:name | The name for the publisher's certificate. This name must conform to the X.500 standard. The simplest method is to use "CN=MyName" format. For example: -n "CN=Test".
-nscp | -N | The Netscape client authentication extension should be included.
-r | -r | Creates a self-signed certificate.
-sc subjectCertFile -U:subjectCertFile | The certificate file name with the existing subject public key to be used.
-sk subjectKey | -u:subjectKey | The location of the subject's key container which holds the private key. If a key container does not exist, one is created. If neither of the -sk or -sv options are used, the JoeSoft key container is created and used by default.
-sky subjectKeySpec N/A The subject's key specification, which must be one of three possible values:

1. Signature, which stands for AT_SIGNATURE key specification.

2. Exchange, which stands for AT_KEYEXCHANGE key specification.

3. An integer, such as 3.

See notes on key specifications below.

-sp subjectProviderName | N/A | CryptoAPI provider for subject. The default is the user's provider. See the CryptoAPI 2.0 documentation for details on CryptoAPI providers.
-sr subjectCertStoreLocation | N/A | The registry location of the subject's certificate store. Must be either localMachine or currentUser. currentUser is the default. currentUser means that the certificate store is under the registry key HKEY_CURRENT_USER and localMachine means HKEY_LOCAL_MACHINE.
-ss subjectCertStoreName | N/A | The name of the subject's certificate store where the generated certificate will be stored.
-sv subjectKeyFile | -k:subjectKeyFile | The location of the subject's .pvk file. If neither of the -sk or -sv options are used, the JoeSoft key container is created and used by default.
-sy nSubjectProviderType | N/A | CryptoAPI provider type for subject. The default is PROV_RSA_FULL. See the CryptoAPI 2.0 documentation for details on CryptoAPI provider types.
-# serialNumber | -#:serialNumber | The serial number of the certificate. The maximum value is 2^31. The default is a value generated by the program that is guaranteed to be unique.
-$ certificateAuthority | (See -I, -C, -C:f) | The type of Certificate Authority. Must be set to either commercial or individual. Commercial means the certificate will be used by commercial software publishers. Individual means the certificate will be used by individual software publishers.
-? -? Displays the basic options.
-! N/A Displays the extended options.

If the -sky key specification option is used in IE 4.0, the specification must match the key specification indicated by the private key file or private key container. If the key specification option is not used, then the key specification indicated by the private key file or private key container will be used. If there is more than one key specification in the key container, MakeCert will first attempt to use the AT_SIGNATURE key specification. If that fails, MakeCert will then try to use AT_KEYEXCHANGE. Since most users have either an AT_SIGNATURE key or AT_KEYEXCHANGE key, this option does not need to be used in most cases.

MakeCert SPC-file and Private-key Technology Options

The following are Group 2 options for SPC-file and private-key technology only:
For IE 4.0 | For IE 3.02 UPD | Description
-ic issuerCertFile | -i:issuerCertFile | The location of the issuer's certificate.
-ik issuerKey | -s issuerKeyFile | The location of the issuer's key container. The default is the test root key.
-iky IssuerKeySpec -K:keySpec For IE3.02: The issuer's key specification. This parameter can be either S for a signature key (this is the default) or E for a key-exchange key.

For IE4.0: The issuer's key specification, which must be one of three possible values:

1. Signature, which stands for AT_SIGNATURE key specification.

2. Exchange, which stands for AT_KEYEXCHANGE key specification.

3. An integer, such as 3.

See notes on key specifications below.

-ip IssuerProviderName | -x:providerName | CryptoAPI provider for issuer. The default is the user's provider. See the CryptoAPI 2.0 documentation for details on CryptoAPI providers.
-iv issuerKeyFile | -s:issuerKeyFile | The issuer's private-key file. The default is the test root.
-iy nIssuerProviderType | -y:nProviderType | CryptoAPI provider type for issuer. The default is PROV_RSA_FULL. See the CryptoAPI 2.0 documentation for details on CryptoAPI provider types.

If the -iky key specification option is used in IE 4.0, the specification must match the key specification indicated by the private key file or private key container. If the key specification option is not used, then the key specification indicated by the private key file or private key container will be used. If there is more than one key specification in the key container, MakeCert will first attempt to use the AT_SIGNATURE key specification. If that fails, MakeCert will then try to use AT_KEYEXCHANGE. Since most users have either an AT_SIGNATURE key or AT_KEYEXCHANGE key, this option does not need to be used in most cases.

MakeCert Certificate Store Technology Options

The following are Group 3 options for certificate store technology only:
For IE 4.0 | For IE 3.02 UPD | Description
-ic issuerCertFile | NA | The file containing the issuer's certificate. For IE 4.0 only, MakeCert will search in the certificate store for a certificate with an exact match.
-in issuerNameString | N/A | The common name of the issuer's certificate. MakeCert will search in the certificate store for a certificate whose common name includes issuerNameString.
-ir IssuerCertStoreLocation | N/A | The registry location of the issuer's certificate store. Must be either localMachine or currentUser. currentUser is the default. currentUser means that the certificate store is under the registry key HKEY_CURRENT_USER and localMachine means HKEY_LOCAL_MACHINE.
-is issuerCertStoreName | N/A | The issuer's certificate store that includes the issuer's certificate and its associated private key information. If there is more than one certificate in the store, the user must uniquely identify it with the -ic or -in option. If the certificate in the certificate store is not uniquely identified, MakeCert will fail.

MakeCert Internet Explorer 3.02 UPD Example

The following is an example that creates a certificate using the Internet Explorer 3.02 UPD options:

MakeCert -k:c:\KeyStore\MyKey.pvk -n:CN=MySoftwareCompany Cert.cer

In this example, a certificate file called Cert.cer is created. The public part of the key pair called MyKey is bound to the publisher, MySoftwareCompany.

6.4 MakeCert Internet Explorer 4.0 Examples

The following are a series of examples for creating certificates with MakeCert using the Internet Explorer 4.0 options.

Make a certificate issued by the default test root. Save the certificate to a file.

MakeCert myNew.cer

Make a certificate issued by the default test root. Save it to a certificate store.

MakeCert -ss myNewStore

Make a certificate issued by the default test root. Create a .pvk file and output the certificate to both a store and a file.

MakeCert -sv myNew.pvk -ss myNewStore myNew.cer

Make a certificate issued by the default test root. Create a key container and output the certificate to both a store and a file.

MakeCert -sk myNewKey -ss myNewStore myNew.cer

Make a certificate using the default test root. Save the certificate to a store. Then make another certificate using the newly created certificate. Save the second certficate to another store.

MakeCert -sk myNewKey -ss myNewStore
MakeCert -is myNewStore -ss anotherStore

Make a certificate using the default test root. Save the certificate to my store. Then make another certificate using the newly created certificate. Since there is more than one certificate in my store, identify the first certificate using its common name.

MakeCert -sk myNewKey -n "CN=XXZZYY" -ss my
MakeCert -is my -in "XXZZYY" -ss anotherStore

Make a certificate using the default test root. Save the certificate to my store and to a file. Then make another certificate using the newly created myNew certificate. Since there is more than one certificate in my store, uniquely identify the first certificate using the certificate filename.

MakeCert -sk myNewKey -n "CN=XXZZYY" -ss my myNew.cer
MakeCert -is my -ic myNew.cer -ss anotherStore

Create a self-signed certificate named myNewRoot using the default test root. Then use SignCode with the certificate to sign a file.

MakeCert -sk myNewRootKey -r -ss myNewRoot
SignCode -s myNewRoot myControl.exe

Create a self-signed certificate named myNewRoot using the default test root. Save myNewRoot into a system certificate store ca . Then make a certificate from myNewRoot and sign some code with the certificate.

When SignCode uses a certificate in a store for signing, it will also build a certificate chain from the signing certificate to a root. All of the certificates in the certificate chain must be in any of the my, ca, spc, or root certificate stores. In this case, myNewRoot is in the ca certificate store.

MakeCert -sk myNewRootKey -r -ss ca myNewRoot.cer
MakeCert -is ca -ic myNewRoot.cer -ss myNewSign
SignCode -s myNewSign myControl.exe

Cert2SPC

After you have generated a certificate, you can create an SPC (Software Publisher Certificate) with the Cert2SPC program. This program wraps multiple X.509 certificates into a PKCS #7 signed-data object. Note that this program is for test purposes only. A valid SPC is obtained from a CA.

The syntax for Cert2SPC is:

Cert2SPC cert1.cer cert2.cer. . .certN.cer output.spc

where:

  • cert1. . .certN are the names of the X.509 certificates to include in the SPC.
  • output is the name of the PKCS #7 object containing the X.509 certificates.

Here is an example:

Cert2SPC MyCert.cer MyCert.spc

This wraps an X.509 certificate, MyCert.cer into a PKCS #7 SPC called MyCert.spc.

SignCode

The final step is to actually sign a file using the SignCode program. This program will:

  1. Create a cryptographic digest of the file.
  2. Sign the digest with your private key.
  3. Copy the X.509 certificates from the SPC into a new PKCS #7 signed-data object. The PKCS #7 object contains the serial numbers and issuers of the certificates used to create the signature, the certificates, and the signed digest information.
  4. Embed the object into the file.
  5. Optionally, it can add a timestamp to the file. A timestamp should always be added when signing a file. However, SignCode also has the ability to add a timestamp to a previously signed file subject to some restrictions (see the examples that follow the options table).

The syntax for signing is:

SignCode [options] [fileName]

where fileName is the name of the output file (Internet Explorer 4.0 only) and options are as described below.

The options for SignCode are divided into three groups:

  1. Basic options applicable in all cases
  2. Options specific to SPC-file and private-key technology
  3. Options specific to certificate store technology

    Options in groups 2 and 3 cannot be mixed in the same operation.

SignCode Basic Options

The following basic options (Group 1) may be applied in all cases:

Options are sorted alphabetically in the left (IE 4.0) column, and the corresponding IE 3.02 options are given in the middle column. IE 3.02 options that have no direct IE 4.0 equivalent will say either "N/A" or "(See -option)" in the IE 4.0 column, and are sorted alphabetically into the order of IE 4.0 options. For example, the IE 3.02 -individual option follows the IE 4.0 -i option.
For IE 4.0 | For IE 3.02 UPD | Description
-a algorithm | -sha, -md5 | The hashing algorithm to use. Must be set to either SHA1 or MD5. The default is MD5.
(See -$) -commercial | The code being signed was created by a commercial software publisher. The action SignCode will take depends upon both this setting and the SPC actually used. See table following these options for possible actions.
-i opusInfo | -info opusInfo | A location, such as a URL, for obtaining information about your program.
(See -$) | -individual | The code being signed was created by an individual software publisher. The action SignCode will take depends upon both this setting and the SPC actually used. See table following these options for possible actions.
-j dllName | N/A | The name of a DLL that returns an array of authenticated attributes for signing files. The user can specify more than one DLL by repeating the -j option. For example: -j dll1 -j dll2 -j dll3
-jp dllParam N/A A parameter to be passed for the preceding DLL. For example: -j DLL1 -jp DLL1Param.

Only one parameter is allowed per DLL. For a list of pre-defined DLLs and their parameters, see "-j and -jp SignCode Options".

(See -a) | -md5 | Specifies that the MD5 hashing algorithm should be used. This is the default hashing algorithm.
-n opusName | -name opusName | The friendly name given your program.
N/A | -nocerts | Specifies that no X.509 certificates should be embedded in the PKCS #7 signed-data object. In this case, the relevant certificates must already be stored on the client computer. In IE 4.0, all certificates will always be included in the message.
N/A | -prog filename | The output file name in IE 3.02 UPD. In IE 4.0 the file name is always placed as the last item on the command line.
(See -a) | -sha | Specifies that the SHA1 hashing algorithm should be used.
-t httpAddress | timestamper | Indicates that the file is to be timestamped. A URL specifying an address of a timestamping server must be provided (see -x for timestamping previously signed files).
-tr times | N/A | The maximum number of timestamping trials. The default is 1. SignCode will repeat the timestamping operation until it is successful or the limit on number of trials is reached.
-tw seconds | N/A | The number of seconds between each timestamping trial. The default is 0.
-x | -nosigning | Used when just timestamping a previously signed file. No signing is performed. Must be used in conjunction with -t.
-$ signingAuthority | -commercial, -individual | The type of publisher that created the code being signed. Must be either commercial or individual. The action SignCode will take depends upon both this setting and the signing certificate actually used. See table following these options for possible actions.
-? -? Displays all of the options.

The signature type (commercial or individual) used by SignCode depends on the signing option and certificate used. In some cases SignCode will fail the requested operation if there is a conflict. The possible signing actions are as follows:
Certificate Type | -$ commercial | -$ individual | no option
Commercial Only | commercial | fail | commercial
Individual Only | fail | individual | individual
Both | commercial | individual | commercial
None | fail | individual | individual

SignCode SPC-file and Private-key Technology Options

The following options are specific to SPC-file and private-key technology (group 2) only:

When upgrading from IE3.02 UPD to IE 4.0, the -pvk option should be mapped to either the -k option or to the -v option, depending on the storage location of the private key. If the private key is stored in a key container, use the -k option. If the private key is stored in a private key file, use the -v option.
For IE 4.0 | For IE 3.02 UPD | Description
-k privateKey | -pvk privateKey | The key container that holds the private key. Cannot be used with -v.
-ky keySpec N/A Indicates the key specification, which must be one of three possible values:

1. Signature, which stands for AT_SIGNATURE key specification.

2. Exchange, which stands for AT_KEYEXCHANGE key specification.

3. An integer, such as 3.

See notes on key specifications below.

-p providerName | -provider providerName | The CryptoAPI provider to use. The default is the user's default provider. (For more details, see the CryptoAPI 2.0 documentation.)
-spc credentials | -spc credentials | The file that contains the credentials. This is usually an .spc file.
-v privateKeyFile | -pvk privateKeyFile | The file containing the private key of the publisher (subject). This is usually a .pvk file. The -v option for IE 4.0 cannot be used with -k.
-y providerType | -providerType providerType | The CryptoAPI provider type to use. The default is PROV_RSA_FULL. (For more details, see the CryptoAPI 2.0 documentation.)

If the -ky key specification option is used in IE 4.0, the specification must match the key specification indicated by the private key file or private key container. If the key specification option is not used, then the key specification indicated by the private key file or private key container will be used. If there is more than one key specification in the key container, SignCode will first attempt to use the AT_SIGNATURE key specification. If that fails, SignCode will then try to use AT_KEYEXCHANGE. Since most users have either an AT_SIGNATURE key or AT_KEYEXCHANGE key, this option does not need to be used in most cases.

SignCode Certificate Technology Options

The following options are specific to certificate technology (group 3) only:
For IE 4.0 | For IE 3.02 UPD | Description
-c certificateFile | N/A | The file containing the encoded signing certificate. SignCode will search the certificate store for a matching certificate. Either -c or -cn can be used to identify the signing certificate in the certificate store to use.
-cn commonNameString | N/A | The common name of the encoded signing certificate. SignCode will search in the certificate store for a certificate whose common name includes commonNameString. If the common name of more than one certificate in the certificate store includes commonNameString, SignCode will fail and issue an error.
-r storeLocation | N/A | The registry location of the certificate store. Must be set to either currentUser or localMachine. The default is currentUser. CurrentUser means the certificate store is under the HKEY_CURRENT_USER registry key and localMachine means it is under HKEY_LOCAL_MACHINE.
-s storeName | N/A | The certificate store that includes the signing certificate and associated private key. The default is my. If there is more than one certificate in the store, the desired certificate must be uniquely identified using the -c or -cn options, or SignCode will fail.
-sp storePolicy N/A The certificate store policy. Must be set to either chain or spcStore. The default is spcStore. chain means to add to the signature all of the certificates in the chain located in the following certificate stores: spc, my, ca, and root.

spcStore means to add to the signature all of the certificates in the chain located in the following certificate stores: spc, my, ca, and root. Stop when the certificate is located in the spc store. This is the default.

The spc store is under the HKEY_LOCAL_MACHINE registry key. The my, ca, and root stores are all under the HKEY_CURRENT_USER registry key.

Once the file has been signed (assuming you have a valid certificate) and timestamped, the file can be distributed to your customers. Note that certificates generated with the test programs MakeCert and Cert2SPC are NOT valid for signing code that will be distributed to the public. Independent software vendors must obtain a certificate from GTE, VeriSign, Inc., or another CA for signing code that will be distributed to the public.

SignCode Examples for Internet Explorer 3.02 UPD

Here are two examples of how to sign and timestamp a file using the Internet Explorer 3.02 UPD options. The first uses a private-key name MyKey and the second uses a private-key file My.pvk:

SignCode -prog MyControl.exe -spc Cert.spc -pvk MyKey -timeStamper http://timestamp.verisign.com/scripts/timstamp.dll
SignCode -prog MyControl.exe -spc Cert.spc -pvk My.pvk -timeStamper http://timestamp.verisign.com/scripts/timstamp.dll

In both cases a PKCS #7 object, Cert.spc, is embedded into the digest of the file, MyControl.exe. In the first example, the digest is signed with the private key of the MyKey key pair, and a timestamp is added. In the second example, the digest is signed with the private-key file My.pvk, and a timestamp is added.

SignCode Examples for Internet Explorer 4.0

Here are two examples of how to sign and timestamp a file using the Internet Explorer 4.0 options. The first uses the MyKey key container and the second uses a private-key file My.pvk:

SignCode -spc Cert.spc -k MyKey -n "My control" -i http://www.my.com -$ commercial -t http://timestamp.verisign.com/scripts/timstamp.dll MyControl.exe

SignCode -spc Cert.spc -v My.pvk -n "My control" -i http://www.my.com -$ commercial -t http://timestamp.verisign.com/scripts/timstamp.dll MyControl.exe

In both cases a PKCS #7 object, Cert.spc, is embedded into the digest of the file, MyControl.exe. In the first example, the digest is signed with the private key of the MyKey key container, and a timestamp is added. In the second example, the digest is signed with the private-key file My.pvk, and a timestamp is added.

The following example shows how to sign and timestamp a file using a certificate in my store (the default certificate store). The certificate's common name is MyCert, and the program being signed has the friendly name My Control.

SignCode -cn "myCert" -n "My control" -i http://www.my.com -$ commercial -t http://timestamp.verisign.com/scripts/timstamp.dll MyControl.exe

The following example shows how to sign and timestamp a file using a certificate in theCert store. There is assumed to be only one certificate in the certificate store, so it is not necessary to identify the certificate. The certificate store is at the default registry location, HKEY_CURRENT_USER. My control is the friendly name for the program being signed.

SignCode -s "theCert" -n "My control" -i http://www.my.com -$ commercial -t http://timestamp.verisign.com/scripts/timstamp.dll MyControl.exe

Adding a Timestamp to a Previously Signed File

A timestamp should always be added when a file is signed. However, if a file was signed without a timestamp, a timestamp can be added to that file. Here is an example of how to add a timestamp to a previously signed file:

For Internet Explorer 3.02 UPD:

SignCode -prog MyControl.exe -nosigning -timeStamper http://timestamp.verisign.com/scripts/timstamp.dll

For Internet Explorer 4.0:

SignCode -t http://timestamp.verisign.com/scripts/timstamp.dll -x MyControl.exe

Notice the -x option is used in conjunction with the -t option to indicate that the file to be timestamped has already been signed. If you try to timestamp a file previously signed by Internet Explorer 3.0 tools, the timestamp may fail with an error saying you must re-sign. If you timestamp a previously signed file using the SignCode tool for Internet Explorer version 3.02 UPD or 4.0, it should successfully add the timestamp. The signing and timestamping concurrent operation should always work, even if the file was previously signed by Internet Explorer 3.0 tools, because if there is an old signature it is replaced.

-j and -jp SignCode Options

The -j and –jp options are provided for more advanced users of SignCode and Internet Explorer 4.0 only. The user can write a Dynamic Link Library (DLL) with predefined entry points that returns an array of authenticated or unauthenticated attributes for signing files. SignCode will take the following actions using these options:

  1. Load the DLL specified by the –j option.
  2. Pass the parameters specified by –jp option to the DLL.
  3. Retrieve an array of authenticated or unauthenticated attributes for signing Java files from the DLL.
  4. Add the attributes to the signature.

There are four pre-defined entry points for the DLL:

HRESULT WINAPI InitAttr(

LPWSTR pInitString); // IN: the initialization string

HRESULT WINAPI GetAttr(

PCRYPT_ATTRIBUTES *ppsAuthenticated, // OUT: Authenticated attributes added to signature

PCRYPT_ATTRIBUTES *ppsUnauthenticated); // OUT: Unauthenticated attributes added to signature

HRESULT WINAPI ReleaseAttr(

PCRYPT_ATTRIBUTES psAuthenticated, // OUT: Authenticated attributes to be released

PCRYPT_ATTRIBUTES psUnauthenticated); // OUT: Unauthenticated attributes to be released

HRESULT WINAPI ExitAttr( );

SignCode calls these entry points in the following order:

  1. InitAttr(initString); // (parameter specified by the –jp option)
  2. GetAttr();
  3. ExitAttr();
  4. InitAttr(initString); // (parameter specified by the –jp option)
  5. ReleaseAttr();
  6. ExitAttr();

ChkTrust

The ChkTrust program checks the validity of a signed file by:

  1. Extracting the PKCS #7 signed-data object.
  2. Extracting the X.509 certificates from the PKCS #7 signed-data object.
  3. Computing a new hash of the file and comparing it with the signed hash in the PKCS #7 object.

If the hashes agree, ChkTrust then verifies that the signer's X.509 certificate is traceable back to the root certificate and that the correct root key was used.

If all these steps are successful, it means that the file has not been tampered with, and that the vendor who signed the file was authenticated by the root authority.

Here is the syntax:

ChkTrust [options] signedFile

where the options are:
For IE 4.0 | For IE 3.02 UPD | Description
N/A | -c | Indicates that the signed file is a cabinet file.
N/A | -i | Indicates that the signed file is a PE image file. Includes .exe, .dll, and .ocx files.
-q | -n | Do not display user interface.
-? N/A Displays all of the options.

In the IE 4.0 version, ChkTrust can distinguish file types automatically, so the -c and -i switches used in the IE 3.02 UPD version are obsolete. Here is an example for the IE 3.02 UPD version:

ChkTrust -i MyProgram.exe

A successful response would be:

Result: 0

Here is an example for the IE 4.0 version:

ChkTrust MyProgram.exe

Note that versions of ChkTrust that are older than the one released with Internet Explorer 3.02 UPD cannot validate files signed with this release of Authenticode.

MakeCTL

The MakeCTL utility creates a certificate trust list (CTL) and outputs the encoded CTL to a file. MakeCTL is supported in IE 4.0 only.

The input to MakeCTL is an array of certificate stores. MakeCTL will build a CTL which includes the SHA1 hash of all of the certificates in the certificate stores. A certificate store can be one of the following:

  • A serialized store file
  • A PKCS#7
  • An encoded certificate file
  • A system store

The syntax for invoking MakeCTL is:

MakeCTL [-u subjectUsageID] [-s [-r registryLocation]] store1 [-s [-r registryLocation]] store2 ... [-s [-r registryLocation]] storeN output.ctl

where:

  • store1 store2 ... .storeN are the names of the certificate stores to make the certificate trust list for.
  • output.ctl is the name of the output file containing the certificate trust list.

The options are as follows:
-u subjectUsageID | The CTL subject usage identifier. The default identifier is szOID_TRUSTED_CODESIGNING_CA_LIST, which specifies that the CTL consists of root CAs for code signing.
-s | Indicates that the certificate store is a system store.
-r registryLocation The registry location of the system certificate store. Meaningful only when –s is set. Must be set to either currentUser or localMachine. The default setting is currentUser.

currentUser means that the certificate store is under the registry key HKEY_CURRENT_USER. localMachine means that the certificate store is under the registry key HKEY_LOCAL_MACHINE.

-? Lists command syntax and options.

An encoded CTL file must be signed before using. CTL files can be signed using the SignCode utility. Once the CTL file is signed, it can be moved to the trust system store by CertMgr. CertMgr can also move the CTL's signer certificate to the root store. If the subject usage identifier of the CTL is szOID_TRUSTED_CODESIGNING_CA_LIST (the default), all the files signed by certificates in the CTL will be trusted by ChkTrust and Authenticode.

The following example generates a CTL that includes all the certificates in a system certificate store named root:

MakeCTL -s root output.ctl

The following example generates a CTL that includes an array of certificates:

MakeCTL one.cer two.cer three.cer output.ctl

CertMgr

The CertMgr utility is a replacement for DumpCert and adds many new capabilities. CertMgr can manage certificates, certificate trust lists (CTLs), and certificate revocation lists (CRLs). The functionality of CertMgr has three parts:

  1. Display certificates, CTLs, and CRLs.
  2. Add certificates, CTLs, and CRLs from one certificate store to another.
  3. Delete certificates, CTLs, and CRLs from a certificate store.

Each functional part of CertMgr has its own syntax and options group. The syntax and options for different functional parts cannot be mixed.

CertMgr works with two kinds of certificate stores, StoreFile and system store. A StoreFile can be one of the following kinds of files:

  • Encoded CTL/CRL/certificate file (could be base64 encoded)
  • PKCS#7 file
  • Signed document
  • Serialized StoreFile

It is not necessary to specify the type of the StoreFile. CertMgr can determine the StoreFile type and take the appropriate actions.

A system store is located in the user's registry. The user can refer to a system store by providing just its name. It is not necessary to specify the certificate store provider type. Depending on the type of the StoreFile or system store, CertMgr will choose the corresponding store provider type.

Displaying Certificates, CTLs, and CRLs with CertMgr

The syntax for invoking CertMgr to display certificates, CTLs, and CRLs is as follows:

CertMgr [options] [-s [–r registryLocation]] StoreName

StoreName is the name of the certificate store containing the items to display. The store can be a serialized store (StoreFile) or a system store (in the registry). By default, CertMgr will display all the certificates, CTLs, or CRLs in the store, unless otherwise specified in the options.

The options are:
-v | Verbose mode. Displays detailed information about certificates, CTLs, and CRLs. The default is to display brief information.
-c | Only display certificates.
-CTL | Only display CTLs.
-CRL | Only display CRLs.
-e encodingType | Certificate encoding type.
-y storeProviderType | Store provider type.
-f dwFlags | Store open flag. This is the dwFlags parameter passed to CertOpenStore. The default value is CERT_SYSTEM_STORE_CURRENT_USER. Meaningful only if –y is set. For more information see the CryptoAPI 2.0 documentation.
-s | Indicates the store is a system store. If this option is not set, the store is a StoreFile.
-r registryLocation | Identifies the registry location of the system certificate store. Meaningful only when –s is set. Must be set to either currentUser or localMachine. CurrentUser is the default. currentUser means that the certificate store is under the registry key HKEY_CURRENT_USER, localMachine means HKEY_LOCAL_MACHINE.
-? Displays all the options.

Adding Certificates, CTLs, and CRLs with CertMgr

The syntax for invoking CertMgr to add certificates, CTLs, and CRLs is as follows:

CertMgr –add [options] [-s [–r registryLocation]] SourceStore [-s [–r registryLocation]] DestinationStore

SourceStore is the source certificate store that contains the existing certificates, CTLs, and CRLs. DestinationStore is the destination certificate store to which the certificates, CTLs, and CRLs will be added to. The destination store will be saved as a serialized store, unless the –7 option is used, which saves the store as a PKCS#7. Note that the –7 option can not be used when the destination store is a system store.

CertMgr can add either certificates, CTLs, or CRLs. If there is more than one item in one of these categories, the user has three options:

  1. Use the –all option to add all the items in the category.
  2. Use the –n and -sha1 options to uniquely identify the item.
  3. Do not specify any options, and CertMgr will prompt the user with a list of items to add. The user responds by entering the index of the item to add.

This functionality of CertMgr can be used to copy and move certificates, CTLs, and CRLs. See the examples following the options.

The options are:
-c | Add certificates.
-CTL | Add CTLs.
-CRL | Add CRLs.
-all | Add all entries.
-7 | Save the destination store as a PKCS#7.
-e encodingType | Certificate encoding type.
-y storeProviderType | Store provider type.
-f dwFlags | Store open flag. This is the dwFlags parameter passed to CertOpenStore. The default value is CERT_SYSTEM_STORE_CURRENT_USER. Meaningful only if –y is set. For more information see the CryptoAPI 2.0 documentation.
-n commonNameString | The common name of the certificate to add. Can be used only with certificates.
-s | Indicates the store is a system store. If this option is not set, the store is a StoreFile.
-sha1 sha1Hash | The SHA1 hash of the certificate, CTL, or CRL to add.
-r registryLocation | Identifies the registry location of the system certificate store. Meaningful only when –s is set. Must be set to either currentUser or localMachine. CurrentUser is the default. currentUser means that the certificate store is under the registry key HKEY_CURRENT_USER, localMachine means HKEY_LOCAL_MACHINE.
-? Displays all the options.

Deleting Certificates, CTLs, and CRLs with CertMgr

The syntax for invoking CertMgr to delete certificates, CTLs, and CRLs is as follows:

CertMgr –del [options] [-s [–r registryLocation]] SourceStore [-s [–r registryLocation] DestinationStore]

SourceStore is the source certificate store that contains the existing certificates, CTLs, and CRLs. DestinationStore is the destination certificate store which will contain copies of the remaining certificates, CTLs, and CRLs after the specified items have been deleted. If DestinationStore is not specified, SourceStore will also serve as the destination store (it will be modified.) The destination store will be saved as a serialized store, unless –7 option is used, which saves the store as a PKCS#7. Note that the –7 option cannot be used when the destination store is a system store.

CertMgr can delete either certificates, CTLs, or CRLs. If there is more than one item in one of these categories, the user has three options:

  1. Use the –all option to delete all the items in the category.
  2. Use the –n and -sha1 options to uniquely identify the item.
  3. Do not specify any options, and CertMgr will prompt the user with a list of items to delete. The user responds by entering the index of the item to delete.

The options are:
-c | Delete certificates.
-CTL | Delete CTLs.
-CRL | Delete CRLs.
-all | Delete all entries.
-7 | Save the destination store as a PKCS#7.
-n commonNameString | The common name of the certificate to delete. Can be used only with certificates.
-sha1 sha1Hash | The SHA1 hash of the certificate, CTL, or CRL to delete.
-e encodingType | Certificate encoding type.
-y storeProviderType | Store provider type.
-f dwFlags | Store open flag. This is the dwFlags parameter passed to CertOpenStore. The default value is CERT_SYSTEM_STORE_CURRENT_USER. Meaningful only if –y is set. For more information see the CryptoAPI 2.0 documentation.
-s | Indicates the store is a system store. If this option is not set, the store is a StoreFile.
-r registryLocation | Identifies the registry location of the system certificate store. Meaningful only when –s is set. Must be set to either currentUser or localMachine. CurrentUser is the default. currentUser means that the certificate store is under the registry key HKEY_CURRENT_USER, localMachine means HKEY_LOCAL_MACHINE.
-? Displays all the options.

CertMgr Examples

View certificates, CRLs, and CTLs from a file called myFile.ext. myFile can be one of the following files: an encoded CTL, CRL, or certificate file (could be base64 encoded), a PKCS#7 file, an SPC file, a signed document, or a serialized storeFile.

CertMgr myFile.ext

View a system store called my store:

CertMgr -s my

Add all the certificates in a file called myFile.ext to a new file, called newFile.ext:

CertMgr -add -all -c myFile.ext newFile.ext

Copy all the certificates in a system store to a file called newMy.ext:

CertMgr -add -all -c -s my newMy.ext

Move a certificate with common name myCert in my system store to a file called newCert.cer:

CertMgr -add -c -n myCert -s my newCert.cer

Delete all the certificates in my system store:

CertMgr -del -all -c  -s my

Delete all the CTLs in my system store and save the resulting store to a file called newStore.str:

CertMgr -del -all -ctl -s my newStore.str

The following example demonstrates how to build a CTL and move it to the root store:

// 1. Make a self-signed certificate called sign.cer.
MakeCert -sv sign.pvk -r -n "CN=THIS IS A TEST OF MAKECTL" sign.cer
// Make an SPC file using Cert2SPC.
Cert2SPC sign.cer sign.spc

// 2. Make another self-signed certificate called test.cer.
MakeCert -sv test.pvk -r -n "CN=THIS IS MY TEST CERT" test.cer
// Make an SPC file using Cert2SPC.
Cert2SPC test.cer test.spc

// 3. Make a test.ctl from test.cer.
MakeCTL test.cer test.ctl

// 4. Sign test.ctl with the sign.pvk and sign.spc made in step 1.
SignCode -v sign.pvk -spc sign.spc test.ctl

// 5. Move test.ctl to the trust system store.
CertMgr -add -ctl test.ctl -s trust

// 6. Move sign.cer to the root system store.
CertMgr -add -c sign.cer -s root

// 7. Sign something (test.exe) with test.pvk, and test.spc.
SignCode -v test.pvk -spc test.spc test.exe

// 8. Since test.cer is in the test.ctl, ChkTrust will succeed.
ChkTrust test.exe

SetReg

The SetReg utility is used to set the value of the registry keys controlling the behavior of the Authenticode certificate verification process. These keys are called the Software Publishing State Keys. When SetReg has completed the requested action, the current state of the Software Publishing State Keys is displayed.

The syntax for invoking SetReg is:

SetReg [options] [Choice # <True | False>]

The options can be one of the following values:
For IE 4.0 | For IE 3.02 UPD | Description
-q | -q | Suppresses the display of the Software Publishing State Key values after SetReg has completed the requested action. The values are displayed by default.
-? -h Lists command syntax and options.

Choice # must be one of the following values (valid for both IE 3.02 and IE 4.0, except 9 and 10, which are for IE 4.0 only):
1 | Trust the Test Root. Causes the test root to be a trusted root if set to TRUE. This is equivalent to running "regedit wvtston.reg" in Internet Explorer 3.x. The default is FALSE. Any code signed with a test root will not verify unless this flag is turned TRUE.
2 | Use expiration date on certificates. Causes the certificate expiration date to be checked if set to TRUE. To ignore expiration dates, set this flag to FALSE. The default is TRUE.
3 | Check the revocation list. Causes the revocation check to be performed if set to TRUE. To bypass revocation check, set this flag to FALSE. The default is FALSE in Internet Explorer 3.x and TRUE in Internet Explorer 4.x.
4 | Offline revocation server OK (Individual). Allows off-line approval for individual certificates if set to TRUE. The default is FALSE.
5 | Offline revocation server OK (Commercial). Allows off-line approval for commercial certificates if set to TRUE. The default is FALSE.
6 | Java offline revocation server OK (Individual). Allows off-line approval for individual certificates and does not display the user interface for bad certificates if set to TRUE. The default is FALSE.
7 | Java offline revocation server OK (Commercial). Allows off-line approval for commercial certificates and does not display the user interface for bad certificates if set to TRUE. The default is FALSE.
8 | Invalidate version 1 signed objects. Invalidates version 1 signed objects if set to TRUE. The default is FALSE.
9 | Perform the revocation check on the timestamp server's certificate if set to TRUE. The default is FALSE. For IE 4.0 only.
10 | Only allow downloads from publishers that are contained in the Personal Trust Database if set to TRUE. The default is FALSE. For IE 4.0 only.

Here is an example:

SetReg 1 TRUE

This turns on the capability to trust the test root.


IObjectSafety::GetInterfaceSafetyOptions

HRESULT  GetInterfaceSafetyOptions(
    /* [in]  */ REFIID riid,
    /* [out] */ DWORD __RPC_FAR *pdwSupportedOptions,
    /* [out] */ DWORD __RPC_FAR *pdwEnabledOptions);

Retrieves the safety options supported by an object as well as the safety options that are currently set for that object.

  • Returns S_OK if successful, or E_NOINTERFACE if riid specifies an interface that is unknown to the object.
riid
Specifies the interface ID for a given object.
pdwSupportedOptions
Specifies the options supported for the interface identified by riid.
pdwEnabledOptions
Specifies the options currently enabled for the interface identified by riid.

This method returns a set of bits in pdwSupportedOptions for each capability that the control knows about, and a set of bits in pdwEnabledOptions for each capability for which the control is currently safe.

For example, a control might say that it knows about INTERFACESAFE_FOR_UNTRUSTED_DATA and INTERFACESAFE_FOR_UNTRUSTED_CALLER, and is currently safe for just INTERFACESAFE_FOR_UNTRUSTED_DATA.


Reference

This section describes the methods of the IObjectSafety interface.

IObjectSafety::GetInterfaceSafetyOptions

IObjectSafety::SetInterfaceSafetyOptions


IObjectSafety::SetInterfaceSafetyOptions

HRESULT SetInterfaceSafetyOptions(
    /* [in] */ REFIID riid,
    /* [in] */ DWORD dwOptionSetMask,
    /* [in] */ DWORD dwEnabledOptions);

Makes an object safe for initialization or scripting.

  • Returns one of the following values:
    S_OK | Success,
    E_NOINTERFACE | riid specifies an interface that is unknown to the object.
    E_FAIL | dwOptionSetMask specifies an option that is not supported by the object.
riid
Specifies the interface ID for the object to be made safe.
dwOptionSetMask
Specifies the options to be changed.
dwEnabledOptions
Specifies the settings for the options that are to be changed. This can be one of the following values:
INTERFACESAFE_FOR_UNTRUSTED_CALLER | The interface identified by riid should be made safe for scripting.
INTERFACESAFE_FOR_UNTRUSTED_DATA | The interface identified by riid should be made safe for untrusted data during initialization.

Typically, a control client would call this method before attempting to script or initialize the object, in an attempt to require that the object is safe for the desired action. If SetInterfaceSafetyOptions returns failure, its client displays the user interface to the user to confirm whether the action should be allowed.

This method takes an interface (either IDispatch for scripting or IPersist* for initialization), a bitmask of options to change (dwOptionSetMask), and the new settings for those options (dwEnabledOptions). The currently supported capabilities are, as described above, INTERFACESAFE_FOR_UNTRUSTED_CALLER and INTERFACESAFE_FOR_UNTRUSTED_DATA.


ActiveX Scripting Engines

To implement an ActiveX™ Scripting engine, create an OLE COM object that supports the following interfaces.
Interface | Description
IActiveScript | Provides the basic scripting ability. Implementation of this interface is required.
IActiveScriptParse | Provides the ability to add script text, evaluate expressions, and so on. Implementation of this interface is optional; however, if it is not implemented, the script engine must implement one of the IPersist* interfaces in order to load a script.
IPersist* Provides persistence support. Implementation of at least one of the following interfaces is required if IActiveScriptParse is not implemented.
Interface | Description
IPersistStorage | Provides support for the DATA={url} attribute in the OBJECT tag.
IPersistStreamInit | Provides support for the same as IPersistStorage as well as the DATA="string-encoded byte stream" attribute in the OBJECT tag.
IPersistPropertyBag | Provides support for the PARAM= attribute in the OBJECT tag.

Note It is possible that the scripting engine will never be called upon to save or restore a script state through IPersist*. Instead, IActiveScriptParse is used by calling IActiveScriptParse::InitNew to create a blank script, then scriptlets are added and connected to events with IActiveScriptParse::AddScriptlet and general code is added with IActiveScriptParse::ParseScriptText. Nonetheless, a scripting engine should fully implement at least one IPersist* interface (preferably IPersistStreamInit), because other host applications may try to make use of them.

Registry Standard

Script Engine States

Scripting Engine Threading

Scripting Engine Reference

Registry Standard

An ActiveX Scripting engine can identify itself using component categories. ActiveX Scripting currently defines two component categories.
Category | Description
CATID_ActiveScript | Indicates that the class identifiers (CLSIDs) are ActiveX Scripting engines that support, at a minimum, the IActiveScript interface and a persistence mechanism (the IPersistStorage, IPersistStreamInit, or IPersistPropertyBag interface).
CATID_ActiveScriptParse | Indicates that the CLSIDs are ActiveX Scripting engines that support, at a minimum, the IActiveScript and IActiveScriptParse interfaces.

Although IActiveScriptParse is not a true persistence mechanism, it does support the IActiveScriptParse::InitNew method that is functionally equivalent to IPersist*::InitNew.

Script Engine States

At any given time, an ActiveX Scripting engine can be in one of several states.
State | Description
uninitialized | The script has not been initialized or loaded using an IPersist* interface, or does not have an IActiveScriptSite interface set. The scripting engine is generally not usable from this state until the script is loaded.
initialized The script has been initialized with an IPersist* interface and has an IActiveScriptSite interface set, but is not connected to host objects and sinking events. Note that this state simply means that the IPersist*::Load, IPersist*::InitNew, or IActiveScriptParse::InitNew method has been completed, and that the IActiveScript::SetScriptSite method has been called. The engine cannot run code in this mode. The engine queues code that the host passes to it through the IActiveScriptParse::ParseScriptText method, and executes the code after transitioning to the started state.

Because languages can vary widely in semantics, scripting engines are not required to support this state transition. Engines that support the IActiveScript::Clone method must, however, support this state transition. Hosts must prepare for this transition and take the appropriate action: release the current scripting engine, create a new scripting engine, and call IPersist*::Load, IPersist*::InitNew, or IActiveScriptParse::InitNew (and possibly also call IActiveScriptParse::ParseScriptText). Use of this transition should be considered an optimization of the above steps. Note that any information the scripting engine has obtained about the names of Named Items and the type information describing Named Items remains valid.

Because languages vary widely, defining the exact semantics of this transition is difficult. At a minimum, the scripting engine must disconnect from all events, and release all of the SCRIPTINFO_IUNKNOWN pointers obtained by calling the IActiveScriptSite::GetItemInfo method. The engine must re-obtain these pointers after the script is run again. The scripting engine should also reset the script back to an initial state that is appropriate for the language. VBScript, for example, resets all variables and retains any code added dynamically by calling IActiveScriptParse::ParseScriptText with the SCRIPTTEXT_ISPERSISTENT flag set. Other languages may need to retain current values (such as Lisp because there is no code/data separation) or reset to a well-known state (this includes languages with statically initialized variables).

Note that the transition to the started state should have the same semantics (that is, it should leave the scripting engine in the same state) as calling IPersist*::Save to save the scripting engine, and then calling IPersist*::Load to load a new scripting engine; these actions should have the same semantics as IActiveScript::Clone. Scripting engines that do not yet support IActiveScript::Clone or IPersist* should carefully consider how the transition to the started state should behave, so that such a transition would not violate the above conditions if IActiveScript::Clone or IPersist* support was later added.

During this transition to the started state, the scripting engine will disconnect from event sinks after the appropriate destructors, and so on, are executed in the script. To avoid having these destructors executed, the host can first move the script into the disconnected state before moving into the started state.

Use IActiveScript::InterruptScriptThread to cancel a running script thread without waiting for current events, and so on, to finish running.

started | The transition from the initialized state to the started state causes the engine to execute any code that was queued in the initialized state. The engine can execute code while in the started state, but it is not connected to any events added through the IActiveScript::AddNamedItem method. The engine can execute code by calling the IDispatch interface obtained from the IActiveScript::GetScriptDispatch method, or by calling IActiveScriptParse::ParseScriptText. It is possible that further background initialization (progressive loading) is still ongoing, and that calling the IActiveScript::SetScriptState method with the SCRIPTSTATE_CONNECTED flag set may cause the script to block until initialization is complete.
connected | The script is loaded and connected for sinking events from host objects. If this is a transition from the initialized state, the scripting engine should transition through the started state, performing the necessary actions, before entering the connected state and connecting to events.
disconnected | The script is loaded and has a run-time state, but is temporarily disconnected from sinking events from host objects. This can be done either logically (ignoring events received) or physically (calling IConnectionPoint::Unadvise on the appropriate connection points). If this is a transition from the initialized state, the scripting engine should transition through the started state, performing the necessary actions, before entering the disconnected state. Event sinks that are in progress are completed before the state changes (use IActiveScript::InterruptScriptThread to cancel a running script thread). This state is distinguished from the initialized state in that the transition to this state does not cause the script to reset, the run-time state of the script is not reset, and a script initialization procedure is not executed.
closed | The script has been closed. The scripting engine no longer works and returns errors for most methods.

The following illustration shows the relationships between the various scripting engine states, and shows the methods that cause transitions from one state to another.

The following illustration shows the actions that the scripting engine performs during the various state transitions.

Scripting Engine Threading

Because an ActiveX Scripting engine can be used in many environments, it is important to keep its execution model as flexible as possible. For example, a server-based host may need to preserve a multithreaded design while using ActiveX Scripting in an efficient manner. At the same time, a host that does not use threading, such as a typical application, should not be burdened with threading management. ActiveX Scripting achieves this balance by restricting the ways a free-threaded scripting engine can call back to the host, freeing hosts from this burden.

Scripting engines used on servers are typically implemented as free-threading COM objects. This means that methods on the IActiveScript interface and its associated interfaces can be called from any thread in the process, without marshaling. (Unfortunately, this also means that the scripting engine must be implemented as an in-process server, because OLE does not currently support interprocess marshaling of free-threaded objects.) Synchronization is the responsibility of the scripting engine. For scripting engines that are not internally reentrant, or for language models that are not multithreaded, synchronization could be as simple as serializing access to the scripting engine with a mutex. Of course certain methods, such as IActiveScript::InterruptScriptThread, should not be serialized in this way so that a stuck script can be terminated from another thread.

The fact that IActiveScript is typically free-threaded generally implies that the IActiveScriptSite interface and the host's object model should be free-threaded as well. This would make implementation of the host quite difficult, particularly in the common case where the host is a single-threaded Microsoft Windows®-based application with single-threaded or apartment-model ActiveX Controls in its object model. For this reason, the following constraints are placed on the scripting engine's use of IActiveScriptSite:

  • The script site is always called in the context of a host thread. That is, the scripting engine never calls the script site in the context of a thread that the scripting engine created, but only from within a scripting engine method that was called from the host through IActiveScript and its derivatives, through the exposed scripting engine's dispatch object, through a Windows message, or from an event source in the host's object model.
  • The script site is never called from within the context of a simple thread state control method (for example, the IActiveScript::InterruptScriptThread method) or from the IActiveScript::Clone method.


Enumerations

This section describes the enumerations used by ActiveX Scripting engines.

SCRIPTSTATE

SCRIPTTHREADSTATE


IActiveScript

The IActiveScript interface provides the methods necessary to initialize the scripting engine. The scripting engine must implement the IActiveScript interface.

Methods in Vtable Order
SetScriptSite | Informs the scripting engine of the IActiveScriptSite site provided by the host.
GetScriptSite | Retrieves the site object associated with the ActiveX Scripting engine.
SetScriptState | Places the scripting engine into the specified state.
GetScriptState | Retrieves the current state of the scripting engine.
Close | Causes the scripting engine to abandon any currently loaded script, lose its state, and release any interface pointers it has to other objects, thus entering a closed state.
AddNamedItem | Adds the name of a root-level item to the scripting engine's name space.
AddTypeLib | Adds a type library to the name space for the script.
GetScriptDispatch | Retrieves the IDispatch interface for the running script.
GetCurrentScriptThreadID | Retrieves a scripting-engine-defined identifier for the currently executing thread.
GetScriptThreadID | Retrieves a scripting-engine-defined identifier for the thread associated with the given Microsoft Win32® thread.
GetScriptThreadState | Retrieves the current state of a script thread.
InterruptScriptThread | Interrupts the execution of a running script thread.
Clone | Clones the current scripting engine (minus any current execution state), returning a loaded scripting engine that has no site in the current thread.


IActiveScript::AddNamedItem

HRESULT AddNamedItem(
    LPCOLESTR pstrName,  // address of item name
    DWORD dwFlags        // item flags
);

Adds the name of a root-level item to the scripting engine's name space. A root-level item is an object with properties and methods, an event source, or all three.

  • Returns one of the following values:
    S_OK | Success.
    E_INVALIDARG | An argument was invalid.
    E_POINTER | An invalid pointer was specified.
    E_UNEXPECTED | The call was not expected (for example, the scripting engine has not yet been loaded or initialized).
pstrName
[in] Address of a buffer that contains the name of the item as viewed from the script. The name must be unique and persistable.
dwFlags
[in] Flags associated with an item. Can be a combination of these values:
SCRIPTITEM_CODEONLY | Indicates that the named item represents a code-only object, and that the host has no IUnknown to be associated with this code-only object. The host only has a name for this object. In object-oriented languages such as C++, this flag would create a class. Not all languages support this flag.
SCRIPTITEM_GLOBALMEMBERS | Indicates that the item is a collection of global properties and methods associated with the script. Normally, a scripting engine would ignore the object name (other than for the purpose of using it as a cookie for the IActiveScriptSite::GetItemInfo method, or for resolving explicit scoping) and expose its members as global variables and methods. This allows the host to extend the library (run-time functions and so on) available to the script. It is left to the scripting engine to deal with name conflicts (for example, when two SCRIPTITEM_GLOBALMEMBERS items have methods of the same name), although an error should not be returned because of this situation.
SCRIPTITEM_ISPERSISTENT | Indicates that the item should be saved if the scripting engine is saved. Similarly, setting this flag indicates that a transition back to the initialized state should retain the item's name and type information (the scripting engine must, however, release all pointers to interfaces on the actual object).
SCRIPTITEM_ISSOURCE | Indicates that the item sources events that the script can sink. Child objects (properties of the object that are in themselves objects) can also source events to the script. This is not recursive, but it provides a convenient mechanism for the common case, for example, of creating a container and all of its member controls.
SCRIPTITEM_ISVISIBLE | Indicates that the item's name is available in the name space of the script, allowing access to the properties, methods, and events of the item. By convention the properties of the item include the item's children; therefore, all child object properties and methods (and their children, recursively) will be accessible.
SCRIPTITEM_NOCODE | Indicates that the item is simply a name being added to the script's name space, and should not be treated as an item for which code should be associated. For example, without this flag being set, VBScript will create a separate module for the named item, and C++ might create a separate wrapper class for the named item.


IActiveScript::AddTypeLib

HRESULT AddTypeLib(
    REFGUID guidTypeLib,  // CLSID of type library
    DWORD dwMaj,          // major version number
    DWORD dwMin,          // minor version number
    DWORD dwFlags         // option flags
);

Adds a type library to the name space for the script. This is similar to the #include directive in C/C++. It allows a set of predefined items such as class definitions, typedefs, and named constants to be added to the run-time environment available to the script.

  • Returns one of the following values:
    S_OK | Success.
    E_INVALIDARG | An argument was invalid.
    E_UNEXPECTED | The call was not expected (for example, the scripting engine has not yet been loaded or initialized).
    TYPE_E_CANTLOADLIBRARY | The specified type library could not be loaded.
guidTypeLib
[in] CLSID of the type library to add.
dwMaj
[in] Major version number.
dwMin
[in] Minor version number.
dwFlags
[in] Option flags. Can be the following:
SCRIPTTYPELIB_ISCONTROL The type library describes an ActiveX control used by the host.


IActiveScript::Clone

HRESULT Clone(
    IActiveScript **ppscript  // receives pointer to IActiveScript
);

Clones the current scripting engine (minus any current execution state), returning a loaded scripting engine that has no site in the current thread. The properties of this new scripting engine will be identical to the properties the original scripting engine would be in if it were transitioned back to the initialized state.

  • Returns one of the following values:
    S_OK | Success.
    E_NOTIMPL | This method is not supported.
    E_POINTER | An invalid pointer was specified.
    E_UNEXPECTED | The call was not expected (for example, the scripting engine has not yet been loaded or initialized).
ppscript
[out] Address of a variable that receives a pointer to the IActiveScript interface of the cloned scripting engine. The host must create a site and call the IActiveScript::SetScriptSite method on the new scripting engine before it will be in the initialized state and, therefore, usable.

The IActiveScript::Clone method is an optimization of IPersist*::Save, CoCreateInstance, and IPersist*::Load, so the state of the new scripting engine should be the same as if the state of the original scripting engine were saved and loaded into a new scripting engine. Named items are duplicated in the cloned scripting engine, but specific object pointers for each item are forgotten and are obtained with the IActiveScriptSite::GetItemInfo method. This allows an identical object model with per-thread entry points (an apartment model) to be used.

This method is used for multithreaded server hosts that can run multiple instances of the same script. The scripting engine may return E_NOTIMPL, in which case the host can achieve the same result by duplicating the persistent state and creating a new instance of the scripting engine with an IPersist* interface.

This method can be called from non-base threads without resulting in a non-base callout to host objects or to the IActiveScriptSite interface.


IActiveScript::Close

HRESULT Close(void);

Causes the scripting engine to abandon any currently loaded script, lose its state, and release any interface pointers it has to other objects, thus entering a closed state. Event sinks, immediately executed script text, and macro invocations that are already in progress are completed before the state changes (use IActiveScript::InterruptScriptThread to cancel a running script thread). This method must be called by the creating host before the interface is released to prevent circular reference problems.

  • Returns one of the following values:
    S_OK | Success.
    E_UNEXPECTED | The call was not expected (for example, the scripting engine was already in the closed state).
    OLESCRIPT_S_PENDING | The method was queued successfully, but the state hasn't changed yet. When the state changes, the site will be called back on the IActiveScriptSite::OnStateChange method.
    S_FALSE | The method succeeded, but the script was already closed.


IActiveScript::GetCurrentScriptThreadID

HRESULT GetCurrentScriptThreadID(
    SCRIPTTHREADID *pstidThread  // receives scripting thread identifier
);

Retrieves a scripting-engine-defined identifier for the currently executing thread. The identifier can be used in subsequent calls to script thread execution-control methods such as the IActiveScript::InterruptScriptThread method.

  • Returns S_OK if successful, or E_POINTER if an invalid pointer was specified.
pstidThread
[out] Address of a variable that receives the script thread identifier associated with the current thread. The interpretation of this identifier is left to the scripting engine, but it can be just a copy of the Windows thread identifier. If the Win32 thread terminates, this identifier becomes unassigned and can subsequently be assigned to another thread.

This method can be called from non-base threads without resulting in a non-base callout to host objects or to the IActiveScriptSite interface.


IActiveScript::GetScriptDispatch

HRESULT GetScriptDispatch(
    LPCOLESTR pstrItemName  // address of item name
    IDispatch **ppdisp      // receives IDispatch pointer
);

Retrieves the IDispatch interface for the methods and properties associated with the currently running script.

  • Returns one of the following values:
    S_OK | Success.
    E_INVALIDARG | An argument was invalid.
    E_POINTER | An invalid pointer was specified.
    E_UNEXPECTED | The call was not expected (for example, the scripting engine has not yet been loaded or initialized).
    S_FALSE | The scripting engine does not support a dispatch object; the ppdisp parameter is set to NULL.
pstrItemName
[in] Address of a buffer that contains the name of the item for which the caller needs the associated dispatch object. If this parameter is NULL, the dispatch object contains as its members all of the global methods and properties defined by the script. Through the IDispatch interface and the associated ITypeInfo interface, the host can invoke script methods or view and modify script variables.
ppdisp
[out] Address of a variable that receives a pointer to the object associated with the script's global methods and properties. If the scripting engine does not support such an object, NULL is returned.

Because methods and properties can be added by calling the IActiveScriptParse interface, the IDispatch interface returned by this method can dynamically support new methods and properties. Similarly, the IDispatch::GetTypeInfo method should return a new, unique ITypeInfo interface when methods and properties are added. Note, however, that language engines must not change the IDispatch interface in a way that is incompatible with any previous ITypeInfo interface returned. That implies, for example, that DISPIDs will never be reused.


IActiveScript::GetScriptSite

HRESULT GetScriptSite(
    REFIID iid,           // interface identifier
    void **ppvSiteObject  // address of host site interface
);

Retrieves the site object associated with the ActiveX Scripting engine.

  • Returns one of the following values:
    S_OK | Success.
    E_INVALIDARG | An argument was invalid.
    E_NOINTERFACE | The specified interface is not supported.
    E_POINTER | An invalid pointer was specified.
    S_FALSE | No site has been set; the ppvSiteObject parameter is set to NULL.
iid
[in] Identifier of the requested interface.
ppvSiteObject
[out] Address of the location that receives the interface pointer to the host's site object.


IActiveScript::GetScriptState

HRESULT GetScriptState(
    SCRIPTSTATE *pss  // address of structure for state information
);

Retrieves the current state of the scripting engine. This method can be called from non-base threads without resulting in a non-base callout to host objects or to the IActiveScriptSite interface.

  • Returns S_OK if successful, or E_POINTER if an invalid pointer was specified.
pss
[out] Address of a variable that receives a value defined in the SCRIPTSTATE enumeration. The value indicates the current state of the scripting engine associated with the calling thread.


IActiveScript::GetScriptThreadID

HRESULT GetScriptThreadID(
    DWORD dwWin32ThreadID,       // Win32 thread identifier
    SCRIPTTHREADID *pstidThread  // receives scripting thread identifier
);

Retrieves a scripting-engine-defined identifier for the thread associated with the given Win32 thread.

  • Returns one of the following values:
    S_OK | Success.
    E_POINTER | An invalid pointer was specified.
    E_UNEXPECTED | The call was not expected (for example, the scripting engine has not yet been loaded or initialized) and therefore failed.
dwWin32ThreadID
[in] Thread identifier of a running Win32 thread in the current process. Use the GetCurrentScriptThreadID function to retrieve the thread identifier of the currently executing thread.
pstidThread
[out] Address of a variable that receives the script thread identifier associated with the given Win32 thread. The interpretation of this identifier is left to the scripting engine, but it can be just a copy of the Windows thread identifier. Note that if the Win32 thread terminates, this identifier becomes unassigned and may subsequently be assigned to another thread.

The retrieved identifier can be used in subsequent calls to script thread execution control methods such as the IActiveScript::InterruptScriptThread method.

This method can be called from non-base threads without resulting in a non-base callout to host objects or to the IActiveScriptSite interface.


IActiveScript::GetScriptThreadState

HRESULT GetScriptThreadState(
    SCRIPTTHREADID stidThread,    // identifier of script thread
    SCRIPTTHREADSTATE *pstsState  // receives state flag
);

Retrieves the current state of a script thread.

  • Returns one of the following values:
    S_OK | Success.
    E_POINTER | An invalid pointer was specified.
    E_UNEXPECTED | The call was not expected (for example, the scripting engine has not yet been loaded or initialized).
stidThread
[in] Identifier of the thread for which the state is desired, or one of the following special thread identifiers:
SCRIPTTHREADID_BASE | The base thread; that is, the thread in which the scripting engine was instantiated.
SCRIPTTHREADID_CURRENT | The currently executing thread.
pstsState
[out] Address of a variable that receives the state of the indicated thread. The state is indicated by one of the named constant values defined by the SCRIPTTHREADSTATE enumeration. If this parameter does not identify the current thread, the state may change at any time.

This method can be called from non-base threads without resulting in a non-base callout to host objects or to the IActiveScriptSite interface.


IActiveScript::InterruptScriptThread

HRESULT InterruptScriptThread(
    SCRIPTTHREADID   stidThread,  // identifier of thread
    const EXCEPINFO *pexcepinfo,  // receives error information
    DWORD dwFlags
);

Interrupts the execution of a running script thread (an event sink, an immediate execution, or a macro invocation). This method can be used to terminate a script that is stuck (in an infinite loop, for example). It can be called from non-base threads without resulting in a non-base callout to host objects or to the IActiveScriptSite method.

  • Returns one of the following values:
    S_OK | Success.
    E_INVALIDARG | An argument was invalid.
    E_POINTER | An invalid pointer was specified.
    E_UNEXPECTED | The call was not expected (for example, the scripting engine has not yet been loaded or initialized).
stidThread
[in] Identifier of the thread to interrupt, or one of the following special thread identifier values:
SCRIPTTHREADID_ALL | All threads. The interrupt is applied to all script methods currently in progress. Note that unless the caller has requested that the script be disconnected, by calling the IActiveScript::SetScriptState method with the SCRIPTSTATE_DISCONNECTED or SCRIPTSTATE_INITIALIZED flag set, the next scripted event causes script code to run again.
SCRIPTTHREADID_BASE | The base thread; that is, the thread in which the scripting engine was instantiated.
SCRIPTTHREADID_CURRENT | The currently executing thread.
pexcepinfo
[in] Address of an EXCEPINFO structure that receives error information associated with the error condition.
dwFlags
[in] Option flags associated with the interruption. Can be one of these values:
SCRIPTINTERRUPT_DEBUG
If supported, enter the scripting engine's debugger at the current script execution point.
SCRIPTINTERRUPT_RAISEEXCEPTION
If supported by the scripting engine's language, let the script handle the exception. Otherwise, the script method is aborted and the error code is returned to the caller; that is, the event source or macro invoker.


IActiveScript::SetScriptSite

HRESULT SetScriptSite(
    IActiveScriptSite *pScriptSite  // address of host script site
);

Informs the scripting engine of the IActiveScriptSite interface site provided by the host. This method must be called before any other IActiveScript interface methods can be used.

  • Returns one of the following values:
    S_OK | Success.
    E_FAIL | An unspecified error occurred; the scripting engine was unable to finish initializing the site.
    E_INVALIDARG | An argument was invalid.
    E_POINTER | An invalid pointer was specified.
    E_UNEXPECTED | The call was not expected (for example, a site was already set).
pScriptSite
[in] Address of the host-supplied script site to be associated with this instance of the scripting engine. The site must be uniquely assigned to this scripting engine instance; it cannot be shared with other scripting engines.


IActiveScript::SetScriptState

HRESULT SetScriptState(
    SCRIPTSTATE ss  // identifier of new state
);

Puts the scripting engine into the given state. This method can be called from non-base threads without resulting in a non-base callout to host objects or to the IActiveScriptSite interface.

  • Returns one of the following values:
    S_OK | Success.
    E_FAIL | The scripting engine does not support the transition back to the initialized state. The host must discard this scripting engine and create, initialize, and load a new scripting engine to achieve the same effect.
    E_UNEXPECTED | The call was not expected (for example, the scripting engine has not yet been loaded or initialized) and therefore failed.
    OLESCRIPT_S_PENDING | The method was queued successfully, but the state has not changed yet. When the state changes, the site will be called back through the IActiveScriptSite::OnStateChange method.
    S_FALSE | The method succeeded, but the script was already in the given state.
ss
[in] Sets the scripting engine to the given state. Can be one of the values defined in the SCRIPTSTATE enumeration.

For more information about scripting engine states, see Script Engine States.

See also IActiveScript::Clone, IActiveScript::GetScriptDispatch, IActiveScript::InterruptScriptThread, IActiveScriptParse::ParseScriptText, IActiveScriptSite::GetItemInfo


IActiveScriptError

An object implementing this interface is passed to the IActiveScriptSite::OnScriptError method whenever the scripting engine encounters an unhandled error. The host then calls methods on this object to obtain information about the error that occurred.

Methods in Vtable Order
GetExceptionInfo | Retrieves information about an error.
GetSourcePosition | Retrieves the location in the source code where an error occurred.
GetSourceLineText | Retrieves the line in the source file where an error occurred.


IActiveScriptError::GetExceptionInfo

HRESULT GetExceptionInfo(
    EXCEPINFO *pexcepinfo  // structure for exception information
);

Retrieves information about an error that occurred while the scripting engine was running a script.

  • Returns S_OK if successful, or E_FAIL if an error occurred.
pexcepinfo
[out] Address of an EXCEPINFO structure that receives error information.


IActiveScriptError::GetSourceLineText

HRESULT GetSourceLineText(
    BSTR *pbstrSourceLine  // address of buffer for source line
);

Retrieves the line in the source file where an error occurred while a scripting engine was running a script.

  • Returns S_OK if successful, or E_FAIL if the line in the source file was not retrieved.
pbstrSourceLine
[out] Address of a buffer that receives the line of source code in which the error occurred.


IActiveScriptError::GetSourcePosition

HRESULT GetSourcePosition(
    DWORD *pdwSourceContext,  // context cookie
    ULONG *pulLineNumber,     // line number of error
    LONG *pichCharPosition    // character position of error
);

Retrieves the location in the source code where an error occurred while the scripting engine was running a script.

  • Returns S_OK if successful, or E_FAIL if the location was not retrieved.
pdwSourceContext
[out] Address of a variable that receives a cookie that identifies the context. The interpretation of this parameter depends on the host application.
pulLineNumber
[out] Address of a variable that receives the line number in the source file where the error occurred.
pichCharPosition
[out] Address of a variable that receives the character position in the line where the error occurred.


IActiveScriptParse

If the ActiveX Scripting engine allows raw text code scriptlets to be added to the script or allows expression text to be evaluated at run time, it implements the IActiveScriptParse interface. For interpreted scripting languages that have no independent authoring environment, such as VBScript, this provides an alternate mechanism (other than IPersist*) to get script code into the scripting engine, and to attach script fragments to various object events.

Methods in Vtable Order
InitNew | Initializes the scripting engine.
AddScriptlet | Adds a code scriptlet to the script.
ParseScriptText | Parses the given code scriptlet, adding declarations into the name space and evaluating code as appropriate.


IActiveScriptParse::AddScriptlet

HRESULT AddScriptlet(
    LPCOLESTR pstrDefaultName,   // address of default name of scriptlet
    LPCOLESTR pstrCode,          // address of scriptlet text
    LPCOLESTR pstrItemName,      // address of item name
    LPCOLESTR pstrSubItemName,   // address of subitem name
    LPCOLESTR pstrEventName,     // address of event name
    LPCOLESTR pstrDelimiter,     // address of end-of-scriptlet delimiter
    DWORD dwSourceContextCookie, // application-defined value for debugging
    ULONG ulStartingLineNumber,  // starting line of the script
    DWORD dwFlags,               // scriptlet flags
    BSTR *pbstrName,             // address of actual name of scriptlet
    EXCEPINFO *pexcepinfo        // address of exception information
);

Adds a code scriptlet to the script. This method is used in environments where the persistent state of the script is intertwined with the host document and the host is responsible for restoring the script, rather than through an IPersist* interface. The primary examples are HTML scripting languages that allow scriptlets of code embedded in the HTML document to be attached to intrinsic events (for instance, ONCLICK="button1.text='Exit'").

  • Returns one of the following values:
    S_OK | Success.
    DISP_E_EXCEPTION | An exception occurred in the parsing of the scriptlet; the pexcepinfo parameter contains information about the exception.
    E_INVALIDARG | An argument was invalid.
    E_NOTIMPL | This method is not supported; the scripting engine does not support adding event-sinking scriptlets.
    E_POINTER | An invalid pointer was specified.
    E_UNEXPECTED | The call was not expected (for example, the scripting engine has not yet been loaded or initialized) and therefore failed.
    OLESCRIPT_E_INVALIDNAME | The default name supplied is invalid in this scripting language.
    OLESCRIPT_E_SYNTAX | An unspecified syntax error occurred in the scriptlet.
pstrDefaultName
[in] Address of a default name to associate with the scriptlet. If the scriptlet does not contain naming information (as in the ONCLICK example above), this name will be used to identify the scriptlet. If this parameter is NULL, the scripting engine manufactures a unique name, if necessary.
pstrCode
[in] Address of the scriptlet text to add. The interpretation of this string depends on the scripting language.
pstrItemName
[in] Address of a buffer that contains the item name associated with this scriptlet. This parameter, in addition to pstrSubItemName, identifies the object for which the scriptlet is an event handler.
pstrSubItemName
[in] Address of a buffer that contains the name of a subobject of the named item with which this scriptlet is associated; this name must be found in the named item's type information. This parameter is NULL if the scriptlet is to be associated with the named item instead of a subitem. This parameter, in addition to pstrItemName, identifies the specific object for which the scriptlet is an event handler.
pstrEventName
[in] Address of a buffer that contains the name of the event for which the scriptlet is an event handler.
pstrDelimiter
[in] Address of the end-of-scriptlet delimiter. When the pstrCode parameter is parsed from a stream of text, the host typically uses a delimiter, such as two single quotation marks ("), to detect the end of the scriptlet. This parameter specifies the delimiter that the host used, allowing the scripting engine to provide some conditional primitive preprocessing (for example, replacing a single quotation mark ['] with two single quotation marks for use as a delimiter). Exactly how (and if) the scripting engine makes use of this information depends on the scripting engine. Set this parameter to NULL if the host did not use a delimiter to mark the end of the scriptlet.
dwSourceContextCookie
[in] Application-defined value that is used for debugging purposes.
ulStartingLineNumber
[in] Zero-based value that specifies which line the parsing will begin at.
dwFlags
[in] Flags associated with the scriptlet. Can be a combination of the following values:
SCRIPTTEXT_ISVISIBLE | Indicates that the script text should be visible (and, therefore, callable by name) as a global method in the name space of the script.
SCRIPTTEXT_ISPERSISTENT | Indicates that the code added during this call should be saved if the scripting engine is saved (for example, through a call to IPersist*::Save), or if the scripting engine is reset by way of a transition back to the initialized state. For more information about this state, see Script Engine States.
pbstrName
[out] Actual name used to identify the scriptlet. This will be, in order of preference: a name explicitly specified in the scriptlet text, the default name provided in pstrDefaultName, or a unique name synthesized by the scripting engine.
pexcepinfo
[out] Address of a structure containing exception information. This structure should be filled in if DISP_E_EXCEPTION is returned.


IActiveScriptParse::InitNew

HRESULT InitNew(void);

Initializes the scripting engine.

  • Returns S_OK if successful, or E_FAIL if an error occurred during initialization.

Before the scripting engine can be used, one of the following methods must be called: IPersist*::Load, IPersist*::InitNew, or IActiveScriptParse::InitNew. The semantics of this method are identical to IPersistStreamInit::InitNew, in that this method tells the scripting engine to initialize itself. Note that it is not valid to call both IPersist*::InitNew or IActiveScriptParse::InitNew and IPersist*::Load, nor is it valid to call IPersist*::InitNew, IActiveScriptParse::InitNew, or IPersist*::Load more than once.


IActiveScriptParse::ParseScriptText

HRESULT ParseScriptText(
    LPCOLESTR pstrCode,          // address of scriptlet text
    LPCOLESTR pstrItemName,      // address of item name
    IUnknown *punkContext,       // address of debugging context
    LPCOLESTR pstrDelimiter,     // address of end-of-scriptlet delimiter
    DWORD dwSourceContextCookie, // application-defined value for debugging
    ULONG ulStartingLineNumber,  // starting line of the script
    DWORD dwFlags,               // scriptlet flags
    VARIANT *pvarResult,         // address of buffer for results
    EXCEPINFO *pexcepinfo        // address of buffer for error data
);

Parses the given code scriptlet, adding declarations into the name space and evaluating code as appropriate.

  • Returns one of the following values:
    S_OK | Success.
    DISP_E_EXCEPTION | An exception occurred in the processing of the scriptlet. The pexcepinfo parameter contains information about the exception.
    E_INVALIDARG | An argument was invalid.
    E_POINTER | An invalid pointer was specified.
    E_NOTIMPL | This method is not supported. The scripting engine does not support run-time evaluation of expressions or statements.
    E_UNEXPECTED | The call was not expected (for example, the scripting engine is in the uninitialized or closed state, or the SCRIPTTEXT_ISEXPRESSION flag was set and the scripting engine is in the initialized state).
    OLESCRIPT_E_SYNTAX | An unspecified syntax error occurred in the scriptlet.
pstrCode
[in] Address of the scriptlet text to evaluate. The interpretation of this string depends on the scripting language.
pstrItemName
[in] Address of the item name that gives the context in which the scriptlet is to be evaluated. If this parameter is NULL, the code is evaluated in the scripting engine's global context.
punkContext
[in] Address of the context object. This object is reserved for use in a debugging environment, where such a context may be provided by the debugger to represent an active run-time context. If this parameter is NULL, the engine uses pstrItemName to identify the context.
pstrDelimiter
[in] Address of the end-of-scriptlet delimiter. When pstrCode is parsed from a stream of text, the host typically uses a delimiter, such as two single quotation marks ("), to detect the end of the scriptlet. This parameter specifies the delimiter that the host used, allowing the scripting engine to provide some conditional primitive preprocessing (for example, replacing a single quotation mark ['] with two single quotation marks for use as a delimiter). Exactly how (and if) the scripting engine makes use of this information depends on the scripting engine. Set this parameter to NULL if the host did not use a delimiter to mark the end of the scriptlet.
dwSourceContextCookie
[in] Application-defined value that is used for debugging purposes.
ulStartingLineNumber
[in] Zero-based value that specifies which line the parsing will begin at.
dwFlags
[in] Flags associated with the scriptlet. Can be a combination of these values:
SCRIPTTEXT_ISEXPRESSION | If the distinction between a computational expression and a statement is important but syntactically ambiguous in the script language, this flag specifies that the scriptlet is to be interpreted as an expression, rather than as a statement or list of statements. By default, statements are assumed unless the correct choice can be determined from the syntax of the scriptlet text.
SCRIPTTEXT_ISPERSISTENT | Indicates that the code added during this call should be saved if the scripting engine is saved (for example, through a call to IPersist*::Save), or if the scripting engine is reset by way of a transition back to the initialized state.
SCRIPTTEXT_ISVISIBLE | Indicates that the script text should be visible (and, therefore, callable by name) as a global method in the name space of the script.
pvarResult
[out] Address of a buffer that receives the results of scriptlet processing, or NULL if the caller expects no result (that is, the SCRIPTTEXT_ISEXPRESSION value is not set).
pexcepinfo
[out] Address of a structure that receives exception information. This structure is filled if IActiveScriptParse::ParseScriptText returns DISP_E_EXCEPTION.

If the scripting engine is in the initialized state, no code will actually be evaluated during this call; rather, such code is queued and executed when the scripting engine is transitioned into (or through) the started state. Because execution is not allowed in the initialized state, it is an error to call this method with the SCRIPTTEXT_ISEXPRESSION flag when in the initialized state.

The scriptlet can be an expression, a list of statements, or anything allowed by the script language. For example, this method is used in the evaluation of the HTML <SCRIPT> tag, which allows statements to be executed as the HTML page is being constructed, rather than just compiling them into the script state.

The code passed to this method must be a valid, complete portion of code. For example, in VBScript it is illegal to call this method once with Sub Function(x) and then a second time with End Sub. The parser must not wait for the second call to complete the subroutine, but rather must generate a parse error because a subroutine declaration was started but not completed.

For more information about script states, see Script Engine States.


Scripting Engine Reference

The following elements are specific to ActiveX Scripting Engines.
Interfaces
IActiveScript
IActiveScriptError
IActiveScriptParse
Enumerations
SCRIPTSTATE
SCRIPTTHREADSTATE


SCRIPTSTATE

typedef enum tagSCRIPTSTATE {
    SCRIPTSTATE_UNINITIALIZED = 0,
    SCRIPTSTATE_INITIALIZED   = 5,
    SCRIPTSTATE_STARTED       = 1,
    SCRIPTSTATE_CONNECTED     = 2,
    SCRIPTSTATE_DISCONNECTED  = 3,
    SCRIPTSTATE_CLOSED        = 4
} SCRIPTSTATE;

Contains named constant values that specify the state of a scripting engine. This enumeration is used by the IActiveScript::GetScriptState, IActiveScript::SetScriptState, and IActiveScriptSite::OnStateChange methods.

SCRIPTSTATE_UNINITIALIZED
Script has just been created, but has not yet been initialized using an IPersist* interface and IActiveScript::SetScriptSite.
SCRIPTSTATE_INITIALIZED
Script has been initialized, but is not running (connecting to other objects or sinking events) or executing any code. Code can be queried for execution by calling the IActiveScriptParse::ParseScriptText method.
SCRIPTSTATE_STARTED
Script can execute code, but is not yet sinking the events of objects added by the IActiveScript::AddNamedItem method.
SCRIPTSTATE_CONNECTED
Script is loaded and connected for sinking events.
SCRIPTSTATE_DISCONNECTED
Script is loaded and has a run-time execution state, but is temporarily disconnected from sinking events.
SCRIPTSTATE_CLOSED
Script has been closed. The scripting engine no longer works and returns errors for most methods.


SCRIPTTHREADSTATE

typedef enum tagSCRIPTTHREADSTATE {
    SCRIPTTHREADSTATE_NOTINSCRIPT  = 0,
    SCRIPTTHREADSTATE_RUNNING      = 1
} SCRIPTTHREADSTATE;

Contains named constant values that specify the state of a thread in a scripting engine. This enumeration is used by the IActiveScript::GetScriptThreadState method.

SCRIPTTHREADSTATE_NOTINSCRIPT
Specified thread is not currently servicing a scripted event, processing immediately executed script text, or running a script macro.
SCRIPTTHREADSTATE_RUNNING
Specified thread is actively servicing a scripted event, processing immediately executed script text, or running a script macro.


IDispatchEx

IDispatchEx, an extension of the IDispatch interface, supports features appropriate for dynamic languages such as scripting languages. This section describes the IDispatchEx interface itself, the differences between IDispatch and IDispatchEx, and the rationale for the extensions. It is expected that readers are familiar with IDispatch and have access to the IDispatch documentation.

Description

IDispatchEx Methods

IDispatch Methods

Examples

Description

IDispatch was developed essentially for Microsoft® Visual Basic®. The primary limitation of IDispatch is that it assumes objects are static, that is, they do not change during run time and thus can be fully described at compile time by type information. Dynamic run time models as found in scripting languages such as Visual Basic Scripting Edition (VBScript) and JScript and object models such as Dynamic HTML require a more flexible interface.

IDispatchEx was developed to provide all the services of IDispatch as well as some extensions that are appropriate for more dynamic late-bound languages such as scripting languages. The additional features of IDispatchEx beyond those provided by IDispatch are:

  • Add new members to an object ("expando")—use GetDispID with the fdexNameEnsure flag.
  • Delete members of an object—use DeleteMemberByName or DeleteMemberByDispID.
  • Case-sensitive dispatch operations—use fdexNameCaseSensitive or fdexNameCaseInsensitive.
  • Search for member with implicit name—use fdexNameImplicit.
  • Enumerate DISPIDs of an object—use GetNextDispID.
  • Map from DISPID to element name—use GetMemberName.
  • Obtain properties of object members—use GetMemberProperties.
  • Method invocation with this pointer—use InvokeEx with DISPATCH_METHOD.
  • Allow browsers that support the concept of name spaces to obtain the name space parent of an object—use GetNameSpaceParent.

Objects that support IDispatchEx might also support IDispatch for backward compatibility. The dynamic nature of objects that support IDispatchEx has a few implications for the IDispatch interface of those objects. For example, IDispatch assumes that "The member and parameter DISPIDs must remain constant for the lifetime of the object. This allows a client to obtain DISPIDs once, and cache them for later use." Since IDispatchEx allows the addition and deletion of members, the set of valid DISPIDs does not remain constant. However, IDispatchEx requires that the mapping between DISPID and member name remain constant. This means that if a member is deleted:

  • The DISPID cannot be reused unless a member with the same name is created.
  • The DISPID must remain valid for GetNextDispID.
  • The DISPID must be accepted gracefully by any of the IDispatch/IDispatchEx methods—they must recognize the member as deleted and return an appropriate error code (usually DISP_E_MEMBERNOTFOUND or S_FALSE).


Examples

This JScript code in the function test() does the following:

  • Create a new object by calling the "Object" constructor and assign a pointer to the new object to the variable "Obj".
  • Create a new element ("Elem") in the object and assign to this element a pointer to the function "foo".
  • Call this function. Since it is being called as a method, the "this" pointer refers to the object "Obj". The function adds a new element "Bar" to the object.
  <HTML>
   <BODY>
   <SCRIPT LANGUAGE="JScript">
   function foo()
   {
      // Create new element and assign the value 10
      this.Bar = 10;
   }

   function test()
   {
      // Construct new object
      Obj = new Object();

      // Create new element and assign function pointer
      Obj.Elem = foo;

      // Call Elem method ("this" == Obj)
      Obj.Elem();

      // Obj.Bar now exists
   }
   test();
   </SCRIPT>
   </BODY>
   </HTML>

A control placed on this same web page could obtain from the browser a dispatch pointer to the script engines. The control could then implement the function test():

  <HTML>
   <BODY>
   <SCRIPT LANGUAGE="JScript">
   function foo()
   {
      // Create new element and assign the value 10
      this.Bar = 10;
   }
   </SCRIPT>
   <OBJECT ID="test" <CLASSID="CLSID:9417DB5D-FA2A-11D0-8CB3-00C04FC2B085">>
   </OBJECT>
   </BODY>
   </HTML>

Code from the control "test" that does the same thing as the JScript function test(). Note that these dispatch calls are made into the 'running' JScript engine and change the state of the engine:

  • Obtain the dispatch pointer to the "foo" function using GetDispID().
  • Obtain the dispatch pointer to the "Object" function using GetDispID().
  • Construct an object by calling the "Object" function with InvokeEx() and obtain a dispatch pointer to the newly constructed object.
  • Create a new element "Elem" in the object using GetDispID() with the fdexNameEnsure flag.
  • Put the dispatch pointer to "foo" in the element using InvokeEx().
  • Call the dispatch pointer to "foo" as a method by calling InvokeEx() and passing in the dispatch pointer to the constructed object as the "this" pointer.
  • The "foo" method creates a new element "Bar" on the current "this" object.
  • Verify that the new element "Bar" was created in the constructed object by enumerating through the elements using GetNextDispID().
  BOOL test(IDispatchEx *pdexScript)
   {
      HRESULT hr;
      VARIANT var;
      BSTR bstrName;
      DISPID dispid, putid;
      IDispatchEx *pdexObj;
      IDispatch   *pdispObj, *pdispFoo;
      DISPPARAMS dispparams, dispparamsNoArgs = {NULL, NULL, 0, 0};

      // Get dispatch pointer for "foo"
      bstrName = SysAllocString(OLESTR("foo"));
      pdexScript->GetDispID(bstrName, 0, &dispid);
      SysFreeString(bstrName);
      pdexScript->InvokeEx(dispid, LOCALE_USER_DEFAULT,
         DISPATCH_PROPERTYGET, &dispparamsNoArgs,
         &var, NULL, NULL);
      pdispFoo = var.pdispVal;

      // Create object by calling "Object" constructor
      bstrName = SysAllocString(OLESTR("Object"));
      pdexScript->GetDispID(bstrName, 0, &dispid);
      SysFreeString(bstrName);
      pdexScript->InvokeEx(dispid, LOCALE_USER_DEFAULT,
         DISPATCH_CONSTRUCT, &dispparamsNoArgs,
         &var, NULL, NULL);
      pdispObj = var.pdispVal;
      pdispObj->QueryInterface(IID_IDispatchEx, (void **)&pdexObj);

      // Create new element in object
      bstrName = SysAllocString(OLESTR("Elem"));
      pdexObj->GetDispID(bstrName, fdexNameEnsure, &dispid);
      SysFreeString(bstrName);

      // Assign "foo" dispatch pointer to element
      putid = DISPID_PROPERTYPUT;
      var.vt = VT_DISPATCH;
      var.pdispVal = pdispFoo;
      dispparams.rgvarg = &var;
      dispparams.rgdispidNamedArgs = &putid;
      dispparams.cArgs = 1;
      dispparams.cNamedArgs = 1;
      pdexObj->InvokeEx(dispid, LOCALE_USER_DEFAULT,
         DISPATCH_PROPERTYPUTREF, &dispparams,
         NULL, NULL, NULL);

      // Invoke method with "this" pointer
      putid = DISPID_THIS;
      var.vt = VT_DISPATCH;
      var.pdispVal = pdispObj;
      dispparams.rgvarg = &var;
      dispparams.rgdispidNamedArgs = &putid;
      dispparams.cArgs = 1;
      dispparams.cNamedArgs = 1;
      pdexObj->InvokeEx(dispid, LOCALE_USER_DEFAULT,
         DISPATCH_METHOD, &dispparams,
      NULL, NULL, NULL);

      // Confirm that new element "Bar" is in object
      hr = pdexObj->GetNextDispID(fdexEnumAll, DISPID_STARTENUM, &dispid);
      while (hr != S_FALSE)
      {
         pdexObj->GetMemberName(dispid, &bstrName);
         if (!wcscmp(bstrName, OLESTR("Bar")))
            return TRUE;
         SysFreeString(bstrName);
         hr = pdexObj->GetNextDispID(fdexEnumAll, dispid, &dispid);
      }
      return FALSE;
   }


IDispatch Methods

IDispatchEx is a subclass of IDispatch – therefore, any object that supports the IDispatchEx interface also has implementations of the IDispatch methods:

  • IDispatch::GetTypeInfoCount
  • IDispatch::GetTypeInfo
  • IDispatch::GetIDsOfNames
  • IDispatch::Invoke

These methods behave as defined by IDispatch except that they might provide additional support as defined by IDispatchEx. For example, IDispatchEx::Invoke should support the same values as IDispatchEX::InvokeEx (for example, DISPID_THIS, DISPATCH_CONSTRUCT). This allows an implementation of IDispatchEx::Invoke to simply delegate calls to IDispatchEx::InvokeEx. An object that supports both IDispatch and IDispatchEx might also choose to provide this additional support in IDispatch::Invoke.


IDispatchEx Methods

DeleteMemberByDispID
DeleteMemberByName
GetDispID
GetMemberName
GetMemberProperties
GetNameSpaceParent
GetNextDispID
InvokeEx


IDispatchEx::DeleteMemberByDispID

HRESULT DeleteMemberByDispID(
    DISPID id
);

Deletes a member by DISPID.

  • Returns one of the following values:
    S_OK | Success.
    S_FALSE | Member exists but cannot be deleted.
id
Member identifier. Use GetDispID or GetNextDispID to obtain the dispatch identifier.

If the member is deleted, the DISPID needs to remain valid for GetNextDispID.

If a member with a given name is deleted and later a member with the same name is recreated, the DISPID should be the same. (Whether member names that differ only by case are the "same" is object-dependent.)

Example

BSTR bstrName;
DISPID dispid;
IDispatch *pdex;

// Assign to pdex and bstrName
pdex->GetDispID(bstrName, fdexNameCaseSensitive, &dispid);
pdex->DeleteMemberByDispID(dispid);


IDispatchEx::DeleteMemberByName

HRESULT DeleteMemberByName(
   BSTR bstrName,
   DWORD grfdex
);

Deletes a member by name.

  • Returns one of the following values:
    S_OK | Success.
    S_FALSE | Member exists but cannot be deleted.
bstrName
Name of member to be deleted.
grfdex
Determines if the member name is case sensitive. This can be one of the following values:
fdexNameCaseSensitive | Request that the name lookup be done in a case-sensitive manner. Can be ignored by object that does not support case-sensitive lookup.
fdexNameCaseInsensitive | Request that the name lookup be done in a case-insensitive manner. Can be ignored by object that does not support case-insensitive lookup.

If the member is deleted, the DISPID needs to remain valid for GetNextDispID.

If a member with a given name is deleted and later a member with the same name is recreated, the DISPID should be the same. (Whether members that differ only by case are the "same" is object-dependent.)

Example

BSTR bstrName;
IDispatch *pdex;

// Assign to pdex and bstrName
pdex->DeleteMemberByName(bstrName, fdexNameCaseSensitive);


IDispatchEx::GetDispID

 HRESULT GetDispID(
   BSTR bstrName,
   DWORD grfdex,
   DISPID *pid
);

Maps a single member name to its corresponding DISPID, which can then be used on subsequent calls to IDispatchEx::InvokeEx.

  • Returns one of the following values:
    S_OK | Success.
    E_OUTOFMEMORY | Out of Memory.
    DISP_E_UNKNOWNNAME | The name was not known.
bstrName
Passed in name to be mapped.
grfdex
Determines the options for obtaining the member identifier. This can be a combination of the following values:
fdexNameCaseSensitive | Request that the name lookup be done in a case-sensitive manner. May be ignored by object that does not support case-sensitive lookup.
fdexNameEnsure | Request that the member be created if it does not already exist. The new member should be created with the value VT_EMPTY.
fdexNameImplicit | Indicates that the caller is searching object(s) for a member of a particular name, when the base object is not explicitly specified.
fdexNameCaseInsensitive | Request that the name lookup be done in a case-insensitive manner. May be ignored by object that does not support case-insensitive lookup.
pid
Pointer to caller-allocated location to receive DISPID result. If an error occurs, pid contains DISPID_UNKNOWN.

GetDispID can be used instead of GetIDsOfNames to obtain the DISPID for a given member.

Because IDispatchEx allows the addition and deletion of members, the set of DISPIDs does not remain constant for the lifetime of an object.

The unused riid parameter in IDispatch::GetIDsOfNames has been removed.

Example

BSTR bstrName;
   DISPID dispid;
   IDispatch *pdex;

   // Assign to pdex and bstrName
   pdex->GetDispID(bstrName, fdexNameCaseSensitive, &dispid);
   // Use dispid


IDispatchEx::GetMemberName

HRESULT GetMemberName(
   DISPID id,
   BSTR *pbstrName
);

Retrieves the name of a member.

  • Returns one of the following values:
    S_OK | Success.
    DISP_E_MEMBERNOTFOUND | The requested member does not exist.
id
Identifies the member. Use GetDispID or GetNextDispID to obtain the dispatch identifier.
pbstrName
Address of a BSTR that receives the name of the member. The calling application is responsible for freeing this value.

Example

HRESULT hr;
   BSTR bstrName;
   DISPID dispid;
   IDispatch *pdex;

   // Assign to pdex
   hr = pdex->GetNextDispID(fdexEnumAll, DISPID_STARTENUM, &dispid);
   while (hr != S_FALSE)
   {
   pdex->GetMemberName(dispid, &bstrName);
   if (!wcscmp(bstrName, OLESTR("Bar")))
      return TRUE;
   SysFreeString(bstrName);
   hr = pdexObj->GetNextDispID(fdexEnumAll, dispid, &dispid);
}


IDispatchEx::GetMemberProperties

HRESULT GetMemberProperties(
   DISPID id,
   DWORD grfdexFetch,
   DWORD *pgrfdex
);

Retrieves a member's properties.

  • Returns one of the following values:
    S_OK | Success.
    DISP_E_MEMBERNOTFOUND | The requested member does not exist.
id
Identifies the member. Use GetDispID or GetNextDispID to obtain the dispatch identifier.
grfdexFetch
Determines which properties to retrieve. This can be a combination of the values listed under pgrfdex and/or a combination of the following values:
grfdexPropCanAll | Combines fdexPropCanGet, fdexPropCanPut, fdexPropCanPutRef, fdexPropCanCall, fdexPropCanConstruct and fdexPropCanSourceEvents.
grfdexPropCannotAll | Combines fdexPropCannotGet, fdexPropCannotPut, fdexPropCannotPutRef, fdexPropCannotCall, fdexPropCannotConstruct and fdexPropCannotSourceEvents.
grfdexPropExtraAll | Combines fdexPropNoSideEffects and fdexPropDynamicType.
grfdexPropAll | Combines grfdexPropCanAll, grfdexPropCannotAll and grfdexPropExtraAll.
pgrfdex
Address of a DWORD that receives the requested properties. This can be a combination of the following values:
fdexPropCanGet | The member can be obtained using DISPATCH_PROPERTYGET.
fdexPropCannotGet | The member cannot be obtained using DISPATCH_PROPERTYGET.
fdexPropCanPut | The member can be set using DISPATCH_PROPERTYPUT.
fdexPropCannotPut | The member cannot be set using DISPATCH_PROPERTYPUT.
fdexPropCanPutRef | The member can be set using DISPATCH_PROPERTYPUTREF.
fdexPropCannotPutRef | The member cannot be set using DISPATCH_PROPERTYPUTREF.
fdexPropNoSideEffects | The member does not have any side effects. For example, a debugger could safely get/set/call this member without changing the state of the script being debugged.
fdexPropDynamicType | The member is dynamic and can change during the lifetime of the object.
fdexPropCanCall | The member can be called as a method using DISPATCH_METHOD.
fdexPropCannotCall | The member cannot be called as a method using DISPATCH_METHOD.
fdexPropCanConstruct | The member can be called as a constructor using DISPATCH_CONSTRUCT.
fdexPropCannotConstruct | The member cannot be called as a constructor using DISPATCH_CONSTRUCT.
fdexPropCanSourceEvents | The member can fire events.
fdexPropCannotSourceEvents | The member cannot fire events.

Example

BSTR bstrName;
   DISPID dispid;
   IDispatch *pdex;
   DWORD dwProps;

   // Assign to pdex and bstrName
   pdex->GetDispID(bstrName, fdexNameCaseSensitive, &dispid);
   pdex->GetMemberProperties(dispid, grfdexPropAll, &dwProps);
   if (dwProps & fdexPropCanPut)
      // Assign to member


IDispatchEx::GetNameSpaceParent

HRESULT GetNameSpaceParent(
   IUnknown **ppunk
);

Retrieves the interface for the namespace parent of an object.

  • Returns S_OK if successful or an OLE-defined error code otherwise.
ppunk
Address of an IUnknown interface pointer that receives the namespace parent's interface.


IDispatchEx::GetNextDispID

HRESULT GetNextDispID(
   DWORD grfdex,
   DISPID id,
   DISPID *pid
);

Enumerates the members of the object.

  • Returns one of the following values:
    S_OK | Success.
    S_FALSE | Enumeration is done.
grfdex
Determines which set of item will be enumerated. This can be a combination of the following values:
fdexEnumDefault | Request that the object enumerate the default elements. The object is allowed to enumerate any set of elements.
fdexEnumAll | Request that the object enumerate all of the elements. The object is allowed to enumerate any set of elements.
id
Identifies the current member. GetNextDispID will retrieve the item in the enumeration after this one. Use GetDispID or a previous call to GetNextDispID to obtain this identifier. Use the DISPID_STARTENUM value to obtain the first identifier of the first item.
pid
Address of a DISPID variable that receives the identifier of the next item in the enumeration.

If a member is deleted by DeleteMemberByName or DeleteMemberByDispID, the DISPID needs to remain valid for GetNextDispID.

Example

HRESULT hr;
   BSTR bstrName;
   DISPID dispid;
   IDispatch *pdex;

   // Assign to pdex
   hr = pdex->GetNextDispID(fdexEnumAll, DISPID_STARTENUM, &dispid);
   while (hr != S_FALSE)
   {
      pdex->GetMemberName(dispid, &bstrName);
      if (!wcscmp(bstrName, OLESTR("Bar")))
      return TRUE;
      SysFreeString(bstrName);

      hr = pdexObj->GetNextDispID(fdexEnumAll, dispid, &dispid);
   }


IDispatchEx::InvokeEx

HRESULT InvokeEx(
   DISPID id,
   LCID lcid,
   WORD wFlags,
   DISPARAMS *pdp,
   VARIANT *pVarRes,
   EXCEPINFO *pei,
   IServiceProvider *pspCaller
);

Provides access to properties and methods exposed by an IDispatchEx object.

  • Returns one of the following values:
    S_OK | Success.
    DISP_E_BADPARAMCOUNT | The number of elements provided to DISPPARAMS is different from the number of arguments accepted by the method or property.
    DISP_E_BADVARTYPE | One of the arguments in rgvarg is not a valid variant type.
    DISP_E_EXCEPTION | The application needs to raise an exception. In this case, the structure passed in pei should be filled in.
    DISP_E_MEMBERNOTFOUND | The requested member does not exist, or the call to InvokeEx tried to set the value of a read-only property.
    DISP_E_NONAMEDARGS | This implementation of IDispatch does not support named arguments.
    DISP_E_OVERFLOW | One of the arguments in rgvarg could not be coerced to the specified type.
    DISP_E_PARAMNOTFOUND | One of the parameter DISPIDs does not correspond to a parameter on the method.
    DISP_E_TYPEMISMATCH | One or more of the arguments could not be coerced.
    DISP_E_UNKNOWNLCID | The member being invoked interprets string arguments according to the LCID, and the LCID is not recognized. If the LCID is not needed to interpret arguments, this error should not be returned.
    DISP_E_PARAMNOTOPTIONAL | A required parameter was omitted.
id
Identifies the member. Use GetDispID or GetNextDispID to obtain the dispatch identifier.
lcid
The locale context in which to interpret arguments. The lcid is passed to InvokeEx to allow the object to interpret its arguments specific to a locale.
wFlags
Flags describing the context of the InvokeEx call:
DISPATCH_METHOD | The member is invoked as a method. If a property has the same name, both this and the DISPATCH_PROPERTYGET flag may be set (defined by IDispatch).
DISPATCH_PROPERTYGET | The member is retrieved as a property or data member (defined by IDispatch).
DISPATCH_PROPERTYPUT | The member is changed as a property or data member (defined by IDispatch).
DISPATCH_PROPERTYPUTREF | The member is changed by a reference assignment, rather than a value assignment. This flag is valid only when the property accepts a reference to an object (defined by IDispatch).
DISPATCH_CONSTRUCT The member is being used as a constructor (this is a new value defined by IDispatchEx). The legal values for wFlags are:
DISPATCH_PROPERTYGET
DISPATCH_METHOD
DISPATCH_PROPERTYGET | DISPATCH_METHOD
DISPATCH_PROPERTYPUT
DISPATCH_PROPERTYPUTREF
DISPATCH_PROPERTYPUT | DISPATCH_PROPERTYPUTREF
DISPATCH_CONSTRUCT
pdp
Pointer to a structure containing an array of arguments, an array of argument DISPIDs for named arguments, and counts for the number of elements in the arrays. See the IDispatch documentation for a full description of the DISPPARAMS structure.
pVarRes
Pointer to the location where the result is to be stored, or Null if the caller expects no result. This argument is ignored if DISPATCH_PROPERTYPUT or DISPATCH_PROPERTYPUTREF is specified.
pei
Pointer to a structure that contains exception information. This structure should be filled in if DISP_E_EXCEPTION is returned. Can be Null. See the IDispatch documentation for a full description of the EXCEPINFO structure.
pspCaller
Pointer to a service provider object supplied by the caller which allows the object to obtain services from the caller. Can be Null.

IDispatchEx::InvokeEx provides all of the same features as IDispatch::Invoke and adds a few extensions:
DISPATCH_CONSTRUCT | Indicates that the item is being used as a constructor.
pspCaller | The pspCaller allows the object access to services provided by the caller. Specific services may be handled by the caller itself or delegated to callers further up the call chain. For example, if a script engine inside a browser makes an InvokeEx call to an external object, the object can follow the pspCaller chain to obtain services from the script engine or browser. (Note that the call chain is not the same as the creation chain – a.k.a. container chain or site chain – the creation chain may be available through some other mechanism such as IObjectWithSite.)
"this" pointer When DISPATCH_METHOD is set in wFlags, there may be a "named parameter" for the "this" value. The DISPID will be DISPID_THIS and it must be the first named parameter.

The unused riid parameter in IDispatch::Invoke has been removed.

The puArgArr parameter in IDispatch::Invoke has been removed.

See the IDispatch::Invoke documentation for the following examples:

  • "Calling a method with no arguments"
  • "Getting and setting properties"
  • "Passing parameters"
  • "Indexed Properties"
  • "Raising exceptions during Invoke"
  • "Returning errors"

Example

VARIANT var;
   BSTR bstrName;
   DISPID dispid;
   IDispatch *pdex;
   DISPPARAMS dispparamsNoArgs = {NULL, NULL, 0, 0};

   // Assign to pdex and bstrName
   pdex->GetDispID(bstrName, fdexNameCaseSensitive, &dispid);
   pdex->InvokeEx(dispid, LOCALE_USER_DEFAULT,
   DISPATCH_PROPERTYGET, &dispparamsNoArgs,
   &var, NULL, NULL);


IProvideMultipleClassInfo

IProvideMulitpleClassInfo, an extension of the IProvideClassInfo2 interface, provides access to the type information of the default interfaces that describe an extended object.

A container typically implements an extender object to add properties, methods, and events to an existing object, the extendee. This interface can be implemented to return the type information of the extender (as index 0) and the type information of the extendee (as index 1). If this extendee is itself an extension, this interface must also return the type information of what that object extends (as index 2 in this example). This process continues for all extended objects until the base object (the innermost object being extended) is reached.

Only the default interfaces are part of the logical merging. Other interfaces are simply ignored; nothing can be inferred by their presence or absence.

This interface is typically implemented by an Active Scripting host and requested by an Active Scripting engine.

Methods


Methods

The IProvideMultipleClassInfo interface consists of two methods (listed in vtable order):

  • GetMultiTypeInfoCount
  • GetInfoOfIndex


ActiveX Scripting Hosts

When implementing an ActiveX™ Scripting host, you can safely assume that a scripting engine will only call the IActiveScriptSite interface in the context of the base thread as long as the host does the following:

  • Chooses a base thread (generally the thread that contains the message loop).
  • Instantiates the scripting engine in the base thread.
  • Calls scripting engine methods only from the base thread, except where specifically allowed, as in the cases of IActiveScript::InterruptScriptThread and IActiveScript::Clone.
  • Calls the scripting engine's dispatch object only from the base thread.
  • Ensures that the message loop runs in the base thread if a window handle is provided.
  • Ensures that objects in the host's object model only source events in the base thread.

These rules are automatically followed by all single-threaded hosts. The restricted model described above is intentionally loose enough to allow a host to abort a stuck script by calling IActiveScript::InterruptScriptThread from another thread (initiated by a CTRL+BREAK handler or the like), or to duplicate a script in a new thread using IActiveScript::Clone.

Also, none of these restrictions apply to a host that chooses to implement a free-threaded IActiveScriptSite interface and a free-threaded object model. Such a host can use the IActiveScript interface from any thread, without restriction.

Scripting Host Reference


ActiveX Scripting

Microsoft® ActiveX™ Scripting introduces a new way for an application to add scripting and OLE Automation capabilities. With the advent of ActiveX Scripting, hosts can call upon disparate scripting engines from multiple sources and vendors to perform scripting between components. The implementation of the script itself—language, syntax, persistent format, execution model, and so on—is left to the script vendor. The designers have taken care to allow hosts that rely on ActiveX Scripting to use arbitrary language back ends.

ActiveX Scripting Hosts

ActiveX Scripting Engines

IDispatchEx

IProvideMultipleClassInfo

Active Script Debugging Interfaces

ActiveX Scripting Terms

This list contains definitions of the scripting-related terms used in this document.
Term | Definition
Code object | An instance created by the scripting engine that is associated with a named item, such as the module behind a form in Visual Basic®, or a C++ class associated with a named item. Preferably, this is an OLE Component Object Model (COM) object that supports OLE Automation so the host or other nonscript entity can manipulate the code object.
Named item | An OLE COM object (preferably one that supports OLE Automation) that the host deems interesting to the script. Examples include the HTML Page and Browser in a Web browser, and the Document and Dialogs in Microsoft Word.
Script | The data that makes up the program that the scripting engine runs. A script can be any contiguous executable data, including pieces of text, blocks of pcode, or even machine-specific executable byte codes. A host loads a script into the scripting engine through one of the IPersist* interfaces or through the IActiveScriptParse interface.
Scripting engine | The OLE object that processes scripts. A scripting engine implements the IActiveScript and, optionally, IActiveScriptParse interfaces.
Scripting host | The application or program that owns the ActiveX Scripting engine. The host implements the IActiveScriptSite and, optionally, IActiveScriptSiteWindow interfaces.
Scriptlet | A portion of a script that gets attached to an object through the IActiveScriptParse interface. The aggregate collection of scriptlets is the script.
Script language | The language in which a script is written (VBScript, for example) and the semantics of that language.

ActiveX Scripting Background

ActiveX Scripting components fall into two categories: ActiveX Scripting hosts and ActiveX Scripting engines. A host creates a scripting engine and calls on the engine to run the scripts. Examples of ActiveX Scripting hosts include:

  • Microsoft Internet Explorer
  • Internet authoring tools
  • Shell

ActiveX Scripting engines can be developed for any language or run-time environment, including:

  • Microsoft Visual Basic for Applications (VBA)
  • Microsoft Visual Basic Scripting Edition (VBScript)
  • Perl
  • Lisp

To make implementation of the host as flexible as possible, an OLE Automation wrapper for ActiveX Scripting is provided. However, a host that uses this wrapper object to instantiate the scripting engine does not have the degree of control over the run-time name space, the persistence model, and so on, that it would if it used ActiveX Scripting directly.

The ActiveX Scripting design isolates the interface elements required only in an authoring environment so that nonauthoring hosts (such as browsers and viewers) and script engines (for example, VBScript) can be kept lightweight.

ActiveX Scripting Basic Architecture

The following illustration shows the interaction between an ActiveX Scripting host and an ActiveX Scripting engine.

Following is a description of the steps involved in the interaction between the host and engine. The actual nesting of the function calls is omitted for clarity.

  1. Create a Project. The host loads a project or document. (This step is not particular to ActiveX Scripting, but is included here for completeness.)
  2. Create the ActiveX Scripting Engine. The host calls CoCreateInstance to create a new ActiveX Scripting engine, specifying the class identifier (CLSID) of the specific scripting engine to use. For example, the HTML browsing component of Internet Explorer receives the scripting engine's class identifier through the CLSID= attribute of the HTML <OBJECT> tag.
  3. Load the Script. If the script contents have been persisted, the host calls the script engine's IPersist*::Load method to feed it the script storage, stream, or property bag. Otherwise, the host uses either the IPersist*::InitNew or IActiveScriptParse::InitNew method to create a null script. A host that maintains a script as text can use IActiveScriptParse::ParseScriptText to feed the scripting engine the text of the script, after calling IActiveScriptParse::InitNew.
  4. Add Named Items. For each top-level named item (such as pages and forms) imported into the scripting engine's name space, the host calls the IActiveScript::AddNamedItem method to create an entry in the engine's name space. This step is not necessary if top-level named items are already part of the persistent state of the script loaded in step 3. A host does not use IActiveScript::AddNamedItem to add sublevel named items (such as controls on an HTML page); rather, the engine indirectly obtains sublevel items from top-level items by using the host's ITypeInfo and IDispatch interfaces.
  5. Run the Script. The host causes the engine to start running the script by setting the SCRIPTSTATE_CONNECTED flag in the IActiveScript::SetScriptState method. This call would likely perform any scripting engine construction work, including static binding, hooking up to events (see below), and executing code, in a way similar to a scripted main() function.
  6. Get Item Information. Each time the script engine needs to associate a symbol with a top-level item, it calls the IActiveScriptSite::GetItemInfo method, which returns information about the given item.
  7. Hook Up Event Advise. Before starting the actual script, the scripting engine connects to the events of all the relevant objects through the IConnectionPoint interface.
  8. Invoke Properties and Methods. As the script runs, the scripting engine realizes references to methods and properties on named objects through IDispatch::Invoke or other standard OLE binding mechanisms.


IActiveScriptSite

The host must create a site for the ActiveX Scripting engine by implementing the IActiveScriptSite interface. Usually, this site will be associated with the container of all the objects that are visible to the script (for example, the ActiveX Controls). Typically, this container will correspond to the document or page being viewed. Microsoft Internet Explorer, for example, would create such a container for each HTML page being displayed. Each ActiveX control (or other automation object) on the page, and the scripting engine itself, would be enumerable within this container.

Methods in Vtable Order
GetLCID | Retrieves the locale identifier that the host uses for displaying user-interface elements.
GetItemInfo | Obtains information about an item that was added to an engine through a call to the IActiveScript::AddNamedItem method.
GetDocVersionString | Retrieves a host-defined string that uniquely identifies the current document version from the host's point of view.
OnScriptTerminate | Called when the script has completed execution.
OnStateChange | Informs the host that the scripting engine has changed states.
OnScriptError | Informs the host that an execution error occurred while the engine was running the script.
OnEnterScript | Informs the host that the scripting engine has begun executing the script code.
OnLeaveScript | Informs the host that the scripting engine has returned from executing script code.


IActiveScriptSite::GetDocVersionString

HRESULT GetDocVersionString(
    BSTR *pbstrVersionString  // address of document version string
);

Retrieves a host-defined string that uniquely identifies the current document version. If the related document has changed outside the scope of ActiveX Scripting (as in the case of an HTML page being edited with NotePad), the scripting engine can save this along with its persisted state, forcing a recompile the next time the script is loaded.

  • Returns S_OK if successful, or E_NOTIMPL if this method is not supported.
pstrVersionString
[out] Address of the host-defined document version string.

If E_NOTIMPL is returned, the scripting engine should assume that the script is in sync with the document.


IActiveScriptSite::GetItemInfo

HRESULT IActiveScriptSite::GetItemInfo(
    LPCOLESTR pstrName,     // address of item name
    DWORD dwReturnMask,     // bit mask for information retrieval
    IUnknown **ppunkItem,   // address of pointer to item's IUnknown
    ITypeInfo **ppTypeInfo  // address of pointer to item's ITypeInfo
);

Allows the scripting engine to obtain information about an item added with the IActiveScript::AddNamedItem method.

  • Returns one of the following values:
    S_OK | Success.
    E_INVALIDARG | An argument was invalid.
    E_POINTER | An invalid pointer was specified.
    TYPE_E_ELEMENTNOTFOUND | An item of the specified name was not found.
pstrName
[in] The name associated with the item, as specified in the IActiveScript::AddNamedItem method.
dwReturnMask
[in] A bit mask specifying what information about the item should be returned. The scripting engine should request the minimum amount of information possible because some of the return parameters (for example, ITypeInfo) can take considerable time to load or generate. Can be a combination of the following values:
SCRIPTINFO_IUNKNOWN | Return the IUnknown interface for this item.
SCRIPTINFO_ITYPEINFO | Return the ITypeInfo interface for this item.
ppunkItem
[out] Address of a variable that receives a pointer to the IUnknown interface associated with the given item. The scripting engine can use the IUnknown::QueryInterface method to obtain the IDispatch interface for the item. This parameter receives NULL if dwReturnMask does not include the SCRIPTINFO_IUNKNOWN value. Also, it receives NULL if there is no object associated with the item name; this mechanism is used to create a simple class when the named item was added with the SCRIPTITEM_CODEONLY flag set in the IActiveScript::AddNamedItem method.
ppTypeInfo
[out] Address of a variable that receives a pointer to the ITypeInfo interface associated with the item. This parameter receives NULL if dwReturnMask does not include the SCRIPTINFO_ITYPEINFO value, or if type information is not available for this item. If type information is not available, the object cannot source events, and name binding must be realized with the IDispatch::GetIDsOfNames method. Note that the ITypeInfo interface retrieved describes the item's coclass (TKIND_COCLASS) because the object may support multiple interfaces and event interfaces. If the item supports the IProvideMultipleTypeInfo interface, the ITypeInfo interface retrieved is the same as the index zero ITypeInfo that would be obtained using the IProvideMultipleTypeInfo::GetInfoOfIndex method.

This method retrieves only the information indicated by the dwReturnMask parameter; this improves performance. For example, if an ITypeInfo interface is not needed for an item, it is simply not specified in dwReturnMask.


IActiveScriptSite::GetLCID

HRESULT GetLCID(
    LCID *plcid  // address of variable for language identifier
);

Retrieves the locale identifier associated with the host's user interface. The scripting engine uses the identifier to ensure that error strings and other user-interface elements generated by the engine appear in the appropriate language.

  • Returns one of the following values:
    S_OK | Success.
    E_NOTIMPL | This method is not implemented. Use the system-defined locale.
    E_POINTER | An invalid pointer was specified.
plcid
[out] Address of a variable that receives the locale identifier for user-interface elements displayed by the scripting engine.

If this method returns E_NOTIMPL, the system-defined locale identifier should be used.


IActiveScriptSite::OnEnterScript

HRESULT OnEnterScript(void);

Informs the host that the scripting engine has begun executing the script code.

  • Returns S_OK if successful.

The scripting engine must call this method on every entry or reentry into the scripting engine. For example, if the script calls an object that then fires an event handled by the scripting engine, the scripting engine must call IActiveScriptSite::OnEnterScript before executing the event, and must call the IActiveScriptSite::OnLeaveScript method after executing the event but before returning to the object that fired the event. Calls to this method can be nested. Every call to this method requires a corresponding call to IActiveScriptSite::OnLeaveScript.


IActiveScriptSite::OnLeaveScript

HRESULT IActiveScriptSite::OnLeaveScript(void);

Informs the host that the scripting engine has returned from executing script code.

  • Returns S_OK if successful.

The scripting engine must call this method before returning control to a calling application that entered the scripting engine. For example, if the script calls an object that then fires an event handled by the scripting engine, the scripting engine must call the IActiveScriptSite::OnEnterScript method before executing the event, and must call IActiveScriptSite::OnLeaveScript after executing the event before returning to the object that fired the event. Calls to this method can be nested. Every call to IActiveScriptSite::OnEnterScript requires a corresponding call to this method.


IActiveScriptSite::OnScriptError

HRESULT IActiveScriptSite::OnScriptError(
    IActiveScriptError *pase  // address of error interface
);

Informs the host that an execution error occurred while the engine was running the script.

  • Returns S_OK if the error was correctly handled, or an OLE defined error code otherwise.
pase
[in] Address of the error object's IActiveScriptError interface. A host can use this interface to obtain information about the execution error.


IActiveScriptSite::OnScriptTerminate

HRESULT OnScriptTerminate(
    VARIANT *pvarResult,   // address of script results
    EXCEPINFO *pexcepinfo  // address of structure with exception information
);

Informs the host that the script has completed execution.

  • Returns S_OK if successful.
pvarResult
[in] Address of a variable that contains the script result, or NULL if the script produced no result.
pexcepinfo
[in] Address of an EXCEPINFO structure that contains exception information generated when the script terminated, or NULL if no exception was generated.

The scripting engine calls this method before the call to the IActiveScriptSite::OnStateChange method, with the SCRIPTSTATE_INITIALIZED flag set, is completed. This method can be used to return completion status and results to the host. Note that many script languages, which are based on sinking events from the host, have life spans that are defined by the host. In this case, this method may never be called.


IActiveScriptSite::OnStateChange

HRESULT IActiveScriptSite::OnStateChange(
    SCRIPTSTATE ssScriptState  // new state of engine
);

Informs the host that the scripting engine has changed states.

  • Returns S_OK if successful.
ssScriptState
[in] Value that indicates the new script state. See the IActiveScript::GetScriptState method for a description of the states.


IActiveScriptSiteWindow

This interface is implemented by hosts that support a user interface on the same object as IActiveScriptSite. Hosts that do not support a user interface, such as servers, would not implement the IActiveScriptSiteWindow interface. The scripting engine accesses this interface by calling QueryInterface from IActiveScriptSite.

Methods in Vtable Order
GetWindow | Retrieves the window handle that can act as the owner of a pop-up window that the scripting engine must display.
EnableModeless | Causes the host to enable or disable its main window as well as any modeless dialog boxes.


IActiveScriptSiteWindow::EnableModeless

HRESULT IActiveScriptSite::EnableModeless(
    BOOL fEnable  // enable flag
);

Causes the host to enable or disable its main window as well as any modeless dialog boxes.

  • Returns S_OK if successful, or E_FAIL if an error occurred.
fEnable
[in] Flag that, if TRUE, enables the main window and modeless dialogs or, if FALSE, disables them.

This method is identical to the IOleInPlaceFrame::EnableModeless method.

Calls to this method can be nested.


IActiveScriptSiteWindow::GetWindow

HRESULT GetWindow(
    HWND *phwnd  // address of variable for window handle
);

Retrieves the handle to a window that can act as the owner of a pop-up window that the scripting engine must display.

  • Returns S_OK if successful, or E_FAIL if an error occurred.
phwnd
[out] Address of a variable that receives the window handle.

This method is similar to the IOleWindow::GetWindow method.


Scripting Host Reference

The following interfaces are specific to Microsoft® ActiveX™ Scripting hosts:

  • IActiveScriptSite
  • IActiveScriptSiteWindow


Component Library

The documentation in this section contains overview and reference material for various ActiveX™ Controls.

ActiveMovie Control

Microsoft ActiveX Data Objects

Microsoft Agent

Microsoft Chat Controls

NetMeeting API

Microsoft NetShow

Microsoft Remote Data Service

Tabular Data Control (TDC)


ActiveMovie Control

This section explains how to use the Microsoft® ActiveMovie™ Control, both in HTML pages and in Visual Basic applications. It contains a description of the control properties, methods, events, property sheet, and shortcut keys.

Introduction to DirectShow

About the DirectShow ActiveMovie Control

Using the ActiveMovie Control in HTML Pages

Using the ActiveMovie Control in Visual Basic

Control Properties

Control Methods

Control Events

Control Property Sheet

Control Shortcut Keys

Introduction to DirectShow

Microsoft® DirectShow™ is an extensible media architecture that delivers high-quality audio and video playback from the Internet or an intranet. DirectShow supports the most popular media types, including MPEG audio and video, AVI video, WAV audio, MIDI audio, and Apple® QuickTime® video. You can access the DirectShow-supported media types quickly and easily by using the Microsoft ActiveMovie™ Control.

The DirectShow architecture defines how applications can control and process time-stamped multimedia data using modular components called filters connected in a configuration called a filter graph. A complete filter graph consists of a number of filters, assembled in a logical progression from the data source to the media renderer or renderers.

Applications assemble the filter graph and control how data moves through it by accessing the filter graph manager through programming interfaces, as shown in the following illustration.

Diagram of how information moves between DirectShow and an application

For example, the Microsoft MPEG filter graph uses the following filters.

  • A source filter to read the data off the disk
  • A splitter transform filter to separate the video and audio
  • A video transform filter to decompress the video data
  • A video rendering filter to display the data on the screen
  • An audio transform filter to decompress the audio data
  • An audio rendering filter to send the audio data to the sound card

Default filter graphs are configured for you when you install the DirectShow software on your computer. You can also install additional filters and create your own filter graphs. For more information about creating and managing filter graphs, see Filter Graph Manager and Filter Graphs in the DirectShow SDK documentation.

About the DirectShow ActiveMovie Control

You can use the DirectShow ActiveMovie Control to quickly add support for multimedia to your applications. DirectShow supports the many media types, including MPEG audio and video, AVI video, WAV audio, MIDI audio, and Apple® QuickTime® video. The DirectShow SDK provides samples and examples that illustrate how to write programs that use the control with either Microsoft® Visual Basic® or Microsoft Visual C++®.

The ActiveMovie Control represents an easy-to-use programming interface that lets you manage multimedia using the control's properties, methods, and events. The control handles all video and audio rendering for you, which simplifies your programming tasks and makes it easy to add support for multimedia to your application. In addition to the ActiveMovie Control, you can use the DirectShow Component Object Model (COM) interfaces. (See Summary of DirectShow COM Interfaces in the DirectShow SDK documentation.)

Using the ActiveMovie Control in HTML Pages

Files on a Web page are referenced using URL names and various protocols, such as HTTP, file, FTP, or Gopher. These names can be either explicit or relative.

Following are two examples of explicit references. The first example uses the HTTP protocol to access the file. The second uses a network path and file name.

"http://directshow/samples/web/RoadRun.avi"

"file://directshow/samples/web/RoadRun.avi"

Here is an example of a relative reference:

"/samples/web/RoadRun.avi"

In the examples in this article, you can assume that either relative or explicit file names will work and any protocol for accessing these file names will also work.

Contents of this article:

  • Invoking Playback on HTML Pages
  • Using the OBJECT Tag
  • Using the OBJECT Tag with the CODEBASE Attribute
  • Using the EMBED Tag
  • Using the IMG tag with the DYNSRC= Attribute
  • Using the A Tag with the HREF Attribute
  • How Progressive Downloading Works
  • Setting ActiveMovie Control Properties on a Web Page

Invoking Playback on HTML Pages

You can play files in one of two ways: either embedded in a Web page, or externally in a window displayed outside or on top of the page. There are four ways of playing back media using HTML tags. Three of these result in embedded playback:

  • OBJECT
  • EMBED
  • IMG DYNSRC=

The fourth means of implementing playback results in an external window:

  • A HREF

Although not restricted to playback, you can use an attribute of the OBJECT tag to automatically download a file that contains required components for playback.

  • OBJECT CODEBASE

The following examples show how you use these tags to reference the file, but do not show all possible properties and attributes (width, height, color, and so on) that could be specified as well. See Setting ActiveMovie Control Properties on a Web Page for more information.

Using the OBJECT Tag

When you use the OBJECT tag, you must explicitly specify the class identifier (CLSID) for the playback control, as shown in the following example.

<OBJECT CLASSID="CLSID:05589FA1-C356-11CE-BF01-00AA0055595A">
<PARAM NAME="FileName" VALUE="http://www.microsoft.com//directshow/samples/web/RoadRun.avi">
</OBJECT>

The preceding CLSID is that of the ActiveMovie Control. The application loads the control and passes it the file name. The control parses the file name and downloads and plays the file. If the protocol is "file," the control instantiates the File Source (async) filter to play back the file. If the protocol is "http," the control instantiates the File Source (URL) filter instead. See the DirectShow SDK documentation for more information on these filters.

Using this tag, you can play back certain media types using "progressive downloading," which allows the user to play back the downloaded portion of the file as the data is downloading. See How Progressive Downloading Works for more information.

Using this tag along with the CODEBASE attribute, you can download components required for playback. See Using the OBJECT Tag with the CODEBASE Attribute for more information.

Using the OBJECT Tag with the CODEBASE Attribute

As the author of a Web page, you might find that using components such as specialized DirectShow filters can enhance playback of your media files on the user's machine. However, if the necessary components aren't already installed on the user's computer, you need a method to install those components. Internet Explorer supports using the CODEBASE attribute of the OBJECT tag for automatic file download, and cabinet (.cab) files for automatic installation. See http://www.microsoft.com/workshop/prog/cab/default.htm for information about the Cabinet SDK and .cab files.

The CODEBASE attribute works in conjunction with the OBJECT tag. See Using the OBJECT Tag for another example that uses the OBJECT tag.

An example of filter download using the CODEBASE attribute and a .cab file follows:

<OBJECT ID=GargleFilter1
CLASSID="CLSID:d616f350-d622-11ce-aac5-0020af0b99a3"
CODEBASE="http://directshow/samples/gargle.cab">
</OBJECT>

The preceding class identifier (CLSID) is the ID of the Gargle filter, which applies a "gargle" sound effect to a sound file. Internet Explorer checks the target computer's registry for the specified CLSID. If the specified CLSID is not present (indicating the filter is not installed on the machine), the browser attempts to find the file (Gargle.cab) at the site specified by the CODEBASE attribute and download it. Once downloaded, the .cab file provides the information to automatically install the filter.

Note: The .cab file must have been properly constructed for automatic installation to work. The .cab must include the filter (Gargle.ax in this case) and an .inf file that contains installation information. The .inf file should handle copying each filter to a specific directory (such as the Windows® System directory) on the user's computer and properly registering each filter. See the Platform SDK for information about .inf files.

Using the EMBED Tag

Netscape introduced this tag for embedding source. The following example uses this tag.

<EMBED autostart="FALSE" loop="FALSE" SRC="http://directshow/samples/web/RoadRun.avi">

This tag works identically to the OBJECT tag, except that you don't need to specify the CLSID. Internally, DirectShow examines the HKCR/MIME/Database/Content Type registry entries, retrieves the appropriate CLSID (DirectShow automatically registers all compatible data types at install time), and launches the control with that media type.

Using the IMG tag with the DYNSRC= Attribute

Internet Explorer can use the DYNSRC= attribute to play back audio-video interleaved (AVI) files. You can use this playback mechanism, but it is preferable to use the OBJECT tag. The following example demonstrates this HTML tag.

<IMG start=1 loop=0 DYNSRC="http://directshow/samples/web/RoadRun.avi">

Using the A Tag with the HREF Attribute

To play back a movie in an external movie, use the A tag with the HREF attribute. An example of this follows:

<A HREF="http://directshow/samples/web/dwad.cinepack.avi">AVI_CINEPACK</A>

The parsing steps that Internet Explorer 3.0 (or later) goes through are similar to the "EMBED SRC tag" case, in that it gets the file extension, maps it to a content type and looks in the HKCR/MIME/Database/Content Type area of the registry to get a CLSID to invoke. However, in this case the control plays in an external window. The ActiveMovie Control is in control of downloading the file.

How Progressive Downloading Works

The following series of steps describes what happens during progressive downloading.

  1. As soon as possible after activation, the ActiveMovie Control displays the first frame in the file (for movies). The filter graph remains in a paused state.
  2. The control does not start to play until it determines that it has enough data to play uninterrupted while the remaining amount downloads. At this time, playback starts and downloading will continue.
  3. The user can click the Play button during this time. In this case, the control will play until the play cursor reaches the end of the current amount downloaded and will automatically transition from the running state to the paused state.
  4. The download of the file will not stop if the user clicks Stop. The user can stop the download by closing the control.
  5. For most AVI or QuickTime files, you can't start playback until DirectShow has read the entire file (because the indexes are at the end of the file). However, the download bar is displayed to show how much of the file has been downloaded. The Play control button remains unavailable until the control downloads the file completely.

Setting ActiveMovie Control Properties on a Web Page

You can set any ActiveMovie Control property by using the PARAM tag inside an OBJECT container. For Boolean values, –1 is TRUE and 0 is FALSE. All other values are set as they would be in the Microsoft® Visual Basic® design environment.

The following example demonstrates playing a movie with most controls shown. If you have a video file and you want to try this, you can copy and paste this code onto your Web page and modify the parameters as you want. If you do this, be sure to change the movie's file name, perhaps using a relative path and file protocol (for example, PARAM NAME="FileName" VALUE="file://c:\mymovie.mpg") to play the movie from your hard drive.

<HTML>
<HEAD>
<TITLE>ActiveMovie Embedded MPG Object Test Page</TITLE>
</HEAD>
<BODY>
Scene from Stargate (MPG File)
<OBJECT ID="ActiveMovie1" WIDTH=357 HEIGHT=322
CLASSID="CLSID:05589FA1-C356-11CE-BF01-00AA0055595A">
<PARAM NAME="Version" VALUE="1">
<PARAM NAME="EnableContextMenu" VALUE="-1">
<PARAM NAME="ShowDisplay" VALUE="-1">
<PARAM NAME="ShowControls" VALUE="-1">
<PARAM NAME="ShowPositionControls" VALUE="0">
<PARAM NAME="ShowSelectionControls" VALUE="0">
<PARAM NAME="EnablePositionControls" VALUE="-1">
<PARAM NAME="EnableSelectionControls" VALUE="-1">
<PARAM NAME="ShowTracker" VALUE="-1">
<PARAM NAME="EnableTracker" VALUE="-1">
<PARAM NAME="AllowHideDisplay" VALUE="-1">
<PARAM NAME="AllowHideControls" VALUE="-1">
<PARAM NAME="MovieWindowSize" VALUE="0">
<PARAM NAME="FullScreenMode" VALUE="0">
<PARAM NAME="MovieWindowWidth" VALUE="353">
<PARAM NAME="MovieWindowHeight" VALUE="318">
<PARAM NAME="AutoStart" VALUE="0">
<PARAM NAME="AutoRewind" VALUE="-1">
<PARAM NAME="PlayCount" VALUE="1">
<PARAM NAME="SelectionStart" VALUE="0">
<PARAM NAME="SelectionEnd" VALUE="48.5151388">
<PARAM NAME="Appearance" VALUE="1">
<PARAM NAME="BorderStyle" VALUE="1">
<PARAM NAME="FileName" VALUE="http://DirectShow/samples/web/stargate1.mpg">
<PARAM NAME="DisplayMode" VALUE="0">
<PARAM NAME="AllowChangeDisplayMode" VALUE="-1">
<PARAM NAME="DisplayForeColor" VALUE="16777215">
<PARAM NAME="DisplayBackColor" VALUE="0">
</OBJECT>
</BODY>

Using the ActiveMovie Control in Visual Basic

This article describes how Microsoft® Visual Basic® applications can use the ActiveMovie Control. The ActiveMovie Control is a high-level interface that meets the needs of most multimedia application developers. Additional lower-level interfaces are also available to Visual Basic programmers.

Contents of this article:

  • Quick Start: Insert and Use the ActiveMovie Control
  • The Visual Basic Ocxvb01 Sample
  • Opening and Running DirectShow Source Files
  • Managing the User Interface of the ActiveMovie Control
  • Monitoring ActiveMovie Control Events

Quick Start: Insert and Use the ActiveMovie Control

This section describes how to insert the ActiveMovie Control and use it in a Visual Basic application. It is a simple example to get you started, and implements only playing and stopping a movie.

Follow these steps to insert the ActiveMovie Control into a Visual Basic form and play a movie:

  1. Install Internet Explorer to install the ActiveMovie Control.
  2. Open a project or create a new project in Visual Basic.
  3. Choose Components from the Projects menu. Choose the Controls tab. If the ActiveMovie Control does not appear in the list of Controls, click the Browse button. In the Add ActiveX Control dialog box that appears, navigate to the directory containing the control (by default, the \Windows\System or \Winnt\System32 directory). Double-click the Amovie.ocx file to add the ActiveMovie Control to the Controls list.
  4. Add the ActiveMovie Control to the Visual Basic toolbox by selecting the check box next to Microsoft ActiveMovie Control in the Controls list.
  5. Add the ActiveMovie Control to your form and size the control to the screen size you want for your movie. (Click the control in the Toolbox, and then draw its size on the form.)
  6. In the Properties list for the ActiveMovie Control, initialize the FileName property to the movie file you want to play. The FileName property should contain the full path. For example:
    c:\movies\mymovie.avi
  7. Set the ShowControls and ShowDisplay properties to FALSE.
  8. Add code to start and stop the movie to two events the ActiveMovie Control supports. For example:
    Private Sub ActiveMovie1_Click()
    ActiveMovie1.Run
End Sub
Private Sub ActiveMovie1_KeyPress(KeyAscii As Integer)
     ActiveMovie1.Stop
End Sub
  9. Compile the application.
  10. Run the application. In this example, click anywhere on the movie screen to start the movie. Press any key to stop the movie.

Follow these steps to use the ActiveMovie Control to play a movie controlled by Visual Basic controls:

  1. Follow steps 1-6 as shown earlier in this section.
  2. Add Visual Basic controls (such as a CommandButton or ListBox) to your form to play and stop the movie.
  3. Add code to play and stop the movie. For example:
    Private Sub Command1_Click()
ActiveMovie1.Run
End Sub
Private Sub Command2_Click()
ActiveMovie1.Stop
End Sub
  4. Compile the application.
  5. Run the application. In this example, Click the Command1 button to start the movie. Click the Command2 button to stop the movie.

The Visual Basic Ocxvb01 Sample

This section describes some of the features of the DirectShow Visual Basic sample application called Ocxvb01 in the VB\OCX directory of the DirectShow samples. The ActiveMovie Control manages most of the details of the display and playback of DirectShow files, while giving the Visual Basic developer control over the image size, playback rate, volume, balance, and position. With the control, the developer can manage a variety of standard user interface controls, such as rewind and fast forward, and a trackbar control to set positions within the media file.

The Visual Basic sample application Ocxvb01 consists of two forms: the main control form frmMain (Ocxvb01.frm) and the display form frmViewer (Viewer.frm).

The frmMain form's menu commands call ActiveMovie Control methods to run, pause, and stop multimedia playback, set and retrieve the control's properties, and enable and disable different parts of the user interface.

The frmMain form contains two command buttons that change the CurrentPosition property of the IMediaPosition object; you can use these buttons to move forward or backward through the multimedia source file, if the multimedia source type supports this functionality. The frmMain form's trackbar control sets the Playback property; its valid range is 0.5 to 1.5. This value is used as a multiplier; 1.0 is the authored speed, so 0.5 is half the authored speed and 2.0 is twice the authored speed. You can set this property to values outside this range, but the audio portion tends to become incomprehensible.

The main control form also contains option buttons that set the display configuration to half size, full size (default), and double size. The main control form appears as shown in the following illustration.

Main control form

The display form, frmViewer, contains the ActiveMovie Control that is displayed when the DirectShow multimedia source file is active or when the source is playing. The application resizes the display form to correspond to the selected source. The display form, with all ActiveMovie Control user interface elements visible and enabled, appears as shown in the following illustration.

Display form with all ActiveMovie Control elements visible and enabled

The following sections describe how to use some of the properties, methods, and events.

Opening and Running DirectShow Source Files

To load and play a DirectShow file, set the ActiveMovie Control's FileName property. Depending on your application's requirements, you can play the file from your code by using methods like Run and Stop, or you can let the user interact with the user interface elements offered by the control.

The FileName property specifies the name of the multimedia source file. When you set the FileName property, several other properties are updated to indicate characteristics of that source file.

Once the FileName property contains a valid file name, you can call the control's Run method to play the multimedia file. Or, you can enable the control buttons on the display form and let the user play the file.

The sample application contains an Open command on the File menu that sets the value of the FileName property. It invokes the File Open common dialog box to obtain a file name:

   Private Sub mnu_File_Open_Click()

      CommonDialog1.Filter = "All files (*.*)|*.*|DirectShow files
(*.mpg;*.mpa;*.mpv;*.mov;*.mpeg;*.enc;*.m1v;*.mp2)|*.mpg;*.mpa;*.mpv;*.mov;*.mpeg;*.enc;*.m1v;*.
mp2|Audio files (.wav)|*.wav|Video for Windows files
(.avi)|*.avi"
      CommonDialog1.Flags = 4 'Hide read-only check box
      CommonDialog1.ShowOpen
      ' only set the property if the user selected a filename from the common dialog
      If CommonDialog1.filename <> "" Then
         frmViewer.ActiveMovie1.filename = CommonDialog1.filename
         g_FileOpened = True
         g_FileExtension = Right$(CommonDialog1.filename, Len(CommonDialog1.filename) -
InStr(CommonDialog1.filename, "."))
      Else
         GoTo err_FileOpen
      End If
      Call ResizeViewer
      ...

First, the subroutine prepares the common dialog box to display only movie files. After the common dialog box returns, the subroutine checks to determine if a file name was returned.

If a file name was returned, the subroutine sets the FileName property of the ActiveMovie Control, in addition to some other global variables: gFileOpened to determine whether or not a file has been opened, and gFileExtension to determine the type of the file.

Finally, the subroutine calls the ResizeViewer subroutine to make the dimensions of the viewer form match those of the DirectShow file. The dimensions of the Visual Basic form are expressed in twips, while the dimensions of the multimedia source are expressed in pixels. The ResizeViewer subroutine considers these differences to size the form by using the form's ScaleHeight and ScaleWidth properties:

' Resize form to dimensions of ActiveMovie Control + nonclient region.
    With frmViewer
        .Visible = False
        .Height = .ActiveMovie1.Height + (.Height - .ScaleHeight)
        .Width = .ActiveMovie1.Width + (.Width - .ScaleWidth)
        .Visible = True
    End With

After the file is loaded successfully, you can play it by clicking Play on the control, or by using the Run method. The sample application provides a Run command on its File menu that calls the Run method:

   Private Sub mnu_File_Run_Click()

      If g_FileOpened = True Then
         frmViewer.ActiveMovie1.Run
         frmViewer.ZOrder 0
      End If

Managing the User Interface of the ActiveMovie Control

The display form of the sample application (Viewer.frm) contains the ActiveMovie Control. The following illustration shows the control with the status bar visible and the control bar hidden.

ActiveMovie Control with status bar visible and control bar hidden

You can use the ActiveMovie Control properties to show or hide and enable or disable user interface elements of the ActiveMovie Control. The sample application includes selected menu commands that enable you to individually control each of the user interface elements. The commands on the View menu enable you to control whether the element is visible. The commands on the Enable menu enable you to control whether the element is enabled.

When the sample application loads a new file, it resets the ActiveMovie Control properties to default values and initializes the values of these selected menu commands. This fragment is from the mnu_File_Open_Click procedure:

   With frmViewer.ActiveMovie1
      .EnablePositionControls = False              'Disable/Enable controls.
      .EnableSelectionControls = False
      .EnableTracker = False
      .ShowPositionControls = False                'Show/don't show controls.
      .ShowSelectionControls = False
      .ShowTracker = True
      mnu_Enable_PositionControls.Checked = False  'Check/uncheck menus to match
      mnu_Enable_SelectionControls.Checked = False 'controls.
      mnu_Enable_Tracker.Checked = False
      mnu_View_Tracker.Checked = True
      mnu_View_PositionControls.Checked = False
      mnu_View_SelectionControls.Checked = False
      ...
   End With

Many of the control elements have two properties associated with them: one to enable them and another to make them visible. To use the position controls, set both the EnablePositionControls and ShowPositionControls properties. The following illustration shows the display controls and all position controls with all elements of the user interface both visible and enabled.

Display form with all ActiveMovie Control elements visible and enabled

Monitoring ActiveMovie Control Events

The ActiveMovie Control automatically monitors certain events and calls event procedures accordingly. To handle one of these events, you provide only the event handling code. For example, the StateChange event indicates a change in the state of the multimedia source, such as the change from running to stopped, or the change from paused to running. To take some action when this event occurs, the application provides code as part of the control's StateChange event.

To demonstrate these event handlers, the sample application provides trivial code that increments a variable. The variable represents a count of the number of times the event has occurred. The current values for these counter variables are displayed at the bottom of the main form. The following example shows the code for the StateChange event.

   Private Sub ActiveMovie1_StateChange(ByVal oldState As Long, ByVal newState As Long)

      g_cStateChange = g_cStateChange + 1
      UpdateStatusBar

Each event procedure passes some informational parameters too. For the StateChange event, you can determine the previous state, in addition to the control's current state, by examining the oldState and newState parameters.


Control Property Sheet

A property sheet is a dialog box with tabbed pages that you can use to set properties on a control. You can access the ActiveMovie Control Properties property sheet at either design or run time.

To activate a property page at design time, select the control, press F4, then click Custom in the Properties page. To activate a property page at run time, right-click, and then click Properties on the shortcut menu that appears. The following is a list of the tabs in the ActiveMovie Control Properties property sheet.

  • Playback
  • Movie Size
  • Controls
  • Advanced

Playback Tab

Use the controls on the Playback tab at run time to set options such as volume, rate of play, and the number of times you want the current video to play.

The Playback tab
Property | Description
Volume | Adjusts the control's volume. For information about how to set this property in code, see Volume.
Balance | Adjusts balance for the control.
Start Time | Identifies the start time for the current file.
Stop Time | Identifies the stop time for the current file. For information about how to set this property in code, see the AllowChangeDisplayMode property.
Play Count | Specifies the number of times to play the current file consecutively. For information about how to set this property in code, see the PlayCount property.
Auto Repeat | Causes the ActiveMovie Control to play the current file repeatedly. For information about how to set this property in code, see the AutoStart property.
Auto Rewind | Indicates whether to rewind the multimedia stream automatically and reposition at the beginning after playing stops. For information about how to set this property in code, see the AutoRewind property.

Movie Size Tab

Use the controls on the Movie Size tab at run time to specify the size of the window in which you want to play video.

The Movie Size tab
Property | Description
Movie Size | Use this option list to specify the movie's size. For information about how to set this property in code, see the MovieWindowSize property.
Run Full Screen | Select this option to maximize the ActiveMovie Control so that it fills the entire screen. For information about how to set this property in code, see the FullScreenMode property.

Controls Tab

Use the controls on the Controls tab at run time to specify which ActiveMovie controls you want to be visible.

The Controls tab
Property | Description
Display Panel | Select this check box if you want the display panel to be visible at run time. For information about how to set this property in code, see the ShowDisplay property.
Control Panel | Select this check box if you want the control panel to be visible at run time. For more information about how to set this property in code, see the ShowControls property.
Position Controls | Select this check box if you want the video stream position to be displayed at run time. For information about how to set this property in code, see the DisplayMode property.
Selection Controls | Select this check box to make the selection controls visible. For information about how to set this property in code, see the SelectionStart property.
Show Trackbar | Select this check box to toggle the visibility of the trackbar. For information about how to set this property in code, see the ShowTracker property.
Foreground Color | Use this control to show and set the foreground color of the ActiveMovie Control. For information about how to set this property in code, see the DisplayForeColor property.
Background Color | Use this control to show and set the background color of the ActiveMovie Control. For information about how to set this property in code, see the DisplayBackColor property.

Advanced Tab

Use the Advanced tab to run a filter on the currently playing video.

The Advanced tab
Property | Description
Filter Properties | Selects the filter property page to display when the Properties button is clicked.
Properties | Displays the property page of the filter selected in the Filter Properties list. Property pages allow you to change parameters on individual filters in the DirectShow filter graph. For more information about properties of DirectShow filters, see Filters in the DirectShow SDK documentation.


Control Shortcut Keys

You can use the following key combinations to activate ActiveMovie Control commands.
Key(s) | Result
CTRL+D | Toggle display
CTRL+LEFT ARROW | Rewind
CTRL+P | Pause
CTRL+R | Run
CTRL+RIGHT ARROW | Forward
CTRL+S | Stop
CTRL+SHIFT+LEFT ARROW | Previous
CTRL+SHIFT+RIGHT ARROW | Next
CTRL+T | Toggle control panel
ALT+ENTER | Toggle between full-screen and windowed modes
SHIFT+window resize | Stretches video to fill the control window


AboutBox Method AboutBox Method *
  * Previous Topic: Control Methods
  * Next Topic: IsSoundCardEnabled Method

AboutBox Method

Displays version and copyright information about the ActiveMovie Control.

Syntax

object.AboutBox


AllowChangeDisplayMode Property

Indicates whether the end-user can change the display mode at run time between time and frames.

Syntax

[form.]object.AllowChangeDisplayMode [ = { True | False } ]

Settings

True | (Default) The end-user can change the type of display at run time.
False | The end-user cannot change the type of display at run time.

Data Type

Boolean

Remarks

This property controls run-time access to the DisplayMode property, which specifies whether to show the multimedia file's current position in time or frames. If you set this property to True, the end-user can change how the control displays the current position by right-clicking the control window and choosing Time or Frames from the shortcut menu.

Run-time access: read-only. Design-time access: read/write.


AllowHideControls Property

Indicates whether the end-user can control the visibility of the controls panel at run time.

Syntax

[form.]object.AllowHideControls [ = { True | False } ]

Settings

True | (Default) The end-user can hide or show the controls panel.
False | The end-user cannot hide or show the controls panel.

Data Type

Boolean

Remarks

This property controls run-time access to the ShowControls property, which hides and displays the controls panel. If you set this property to True, the end-user can show or hide the controls panel by right-clicking the control window and choosing Controls from the shortcut menu.

Run-time access: read-only. Design-time access: read/write.


AllowHideDisplay Property

Indicates whether the end-user can hide the display panel at run time.

Syntax

[form.]object.AllowHideDisplay [ = { True | False } ]

Settings

True | (Default) The end-user can hide or show the display panel.
False | The end-user cannot hide or show the display panel.

Data Type

Boolean

Remarks

This property controls run time access to the ShowDisplay property, which hides and displays the display panel. If you set this property to True, the end-user can show or hide the display panel by right-clicking the control window and choosing Display from the shortcut menu.

Run-time access: read-only. Design-time access: read/write.


Appearance Property

Specifies the appearance of the display panel's border.

Syntax

[form.]object.Appearance [ = long ]

Settings

1 | (Default) The display panel has an inset border, which gives the illusion of depth. This value is the same as 3D.
0 | The display panel has no border. This value is the same as Flat.

Data Type

Long

Remarks

This property is identical to the standard Visual Basic Appearance property.

Run-time access: read-only. Design-time access: read/write.


AutoRewind Property

Indicates whether the multimedia stream should automatically return to the selection's starting point when it reaches the end of the selection.

Syntax

[form.]object.AutoRewind  [ = { True  | False  } ]

Settings

True | (Default) Reposition the multimedia stream to the start of the selection after playback stops.
False | Do not reposition the multimedia stream to the start of the selection after playback stops.

Data Type

Boolean

Remarks

If you set this property to True, DirectShow sets CurrentPosition to the position specified by SelectionStart when it reaches the position specified by SelectionEnd.

To retain the current position within the multimedia stream, set AutoRewind to False or use the Pause method.

Run-time access: read/write. Design-time access: read/write.

See Also

AutoStart


AutoStart Property

Indicates whether to automatically start playing the multimedia stream.

Syntax

[form.]object.AutoStart  [ = { True  | False  } ]

Settings

True | Automatically start playing the multimedia stream.
False | (Default) Do not automatically start the multimedia stream.

Data Type

Boolean

Remarks

If you set this property to False, you must make an explicit call to the Run method to play the stream.

Run-time access: read-only. Design-time access: read/write.

See Also

PlayCount


Balance Property

Specifies the stereo balance.

Syntax

[form.]object.Balance [ = long ]

Settings

long Numeric expression that specifies the balance value. The number ranges from –10,000 to 10,000 and defaults to 0.

Data Type

Long

Remarks

The value 0 indicates that the sound is balanced equally between the left and right speakers. A value of –10,000 indicates that all sound is going to the left speaker and 10,000 that all sound is going to the right speaker.

Run-time access: read/write. Design-time access: read/write.

See Also

Volume Property


BorderStyle Property

Specifies the control's border style.

Syntax

[form.]object.BorderStyle [ = long ]

Settings

0 | No border.
1 | (Default) Fixed, single-line border.

Data Type

Integer (Enumerated)

Remarks

Run-time access: read-only. Design-time access: read/write.


CurrentPosition Property

Specifies the current position within the multimedia stream, in seconds.

Syntax

[form.]object.CurrentPosition [ = double ]

Settings

double New position within the stream, in seconds.

Data Type

double

Remarks

The new value must be within the range specified by the SelectionStart and SelectionEnd properties.

The current position value displayed by the control's user interface can represent either seconds or frames. The DisplayMode property determines the units shown.

Setting the CurrentPosition property at run time is similar to a seek operation and changes the position to the specified point in the multimedia stream.

Run-time access: read/write. Design-time access: not applicable.


CurrentState Property

Describes the playback file's current state.

Syntax

[form.]object.CurrentState

Settings

Setting | Value | Description
amvStopped | 0 | The player is stopped.
amvPaused | 1 | The player is paused.
amvRunning | 2 | The player is playing the multimedia file.

Data Type

Long

Remarks

You cannot assign a value to this property. You can change it by calling the Stop, Run, or Pause method, and DirectShow notifies the application of the change by sending the StateChange event.

The amv settings are available only to C/C++ programmers; scripters and other programmers should use the numerical values.

Run-time access: read-only. Design-time access: not applicable.


DisplayBackColor Property

Specifies the display panel's background color.

Syntax

[form.]object.DisplayBackColor [ = color ]

Settings

Normal RGB colors | Colors specified by using the color palette or by using the Visual Basic RGB or QBColor functions in code.
System default colors | Colors specified by system color constants listed in the Object Browser's object library. The Windows® operating environment substitutes the user's choices as specified in the Control Panel settings.

Remarks

At design time, the default setting is black (0x0).

The valid range for a normal RGB color is 0 to 16,777,215 (&HFFFFFF). The high byte of a number in this range equals 0; the lower 3 bytes, from least to most significant byte, determine the amount of red, green, and blue, respectively. The red, green, and blue components are each represented by a number between 0 and 255 (&HFF). If the high byte is not 0, Visual Basic uses the system colors, as defined in the user's Control Panel settings and by constants listed in the Object Browser's object library.

Run-time access: read/write. Design-time access: read/write.

See Also

DisplayForeColor


DisplayForeColor Property

Specifies the display panel's foreground color.

Syntax

[form.]object.DisplayForeColor [ = color ]

Settings

Normal RGB colors | Colors specified by using the color palette or by using the Visual Basic RGB or QBColor functions in code.
System default colors | Colors specified by system color constants listed in the Object Browser's object library. The Windows operating environment substitutes the user's choices as specified in the Control Panel settings.

Remarks

At design time, the default setting is white (&HFFFFFF).

The valid range for a normal RGB color is 0 to 16,777,215 (&HFFFFFF). The high byte of a number in this range equals 0; the lower 3 bytes, from least to most significant byte, determine the amount of red, green, and blue, respectively. The red, green, and blue components are each represented by a number between 0 and 255 (&HFF). If the high byte is not 0, Visual Basic uses the system colors, as defined in the user's Control Panel settings and by constants listed in the Object Browser's object library.

Run-time access: read/write. Design-time access: read/write.

See Also

DisplayBackColor


DisplayMode Property

Indicates whether the display panel shows the current position in seconds or frames.

Syntax

[form.]object.DisplayMode [ = setting ]

Settings

0 | (Default) Display the current position in seconds.
1 | Display the current position in frames.

Data Type

Integer (Enumerated)

Remarks

Run-time access: read/write. Design-time access: read/write.

See Also

AllowHideDisplay, ShowDisplay


DisplayModeChange Event

Indicates changes to the DisplayMode property, such as from full-screen to half. The current display mode appears in the DisplayMode property. State flags are listed under DisplayMode property.

Syntax

Private Sub object_DisplayModeChange()


EnableContextMenu Property

Indicates whether to enable the control's shortcut menu.

Syntax

[form.]object.EnableContextMenu  [ = { True | False } ]

Settings

True | (Default) The shortcut menu is enabled.
False | The shortcut menu is disabled.

Data Type

Boolean

Remarks

The shortcut menu appears when the end-user right-clicks anywhere on the control.

Run-time access: read/write. Design-time access: read/write.

See Also

ShowDisplay


Enabled Property

Specifies whether the control is enabled.

Syntax

[form.]object.Enabled [ = setting ]

Settings

-1 | (Default) The control is enabled.
0 | The control is disabled.

Data Type

Integer (Enumerated)

Remarks

This property is identical to the standard Visual Basic Enabled property.

A disabled control remains visible (if it already was) and will continue to play, if it was already playing. When a control is disabled, none of the commands or menus respond to user input.

Disabling a control at design time is useful if you want to control the media stream from an external source, such as a custom group of controls on a Web page, instead of from the built-in controls panel.

Run-time access: read/write. Design-time access: read/write.


EnablePositionControls Property

Indicates whether or not to show the position buttons in the controls panel.

Syntax

[form.]object.EnablePositionControls  [ = { True | False } ]

Settings

True | (Default) The position controls are visible.
False | The position controls are not visible.

Data Type

Boolean

Remarks

Run-time access: read/write. Design-time access: read/write.

See Also

ShowPositionControls


EnableSelectionControls Property

Indicates whether or not to show the selection controls in the controls panel.

Syntax

[form.]object.EnableSelectionControls  [ = { True  | False  } ]

Settings

True | (Default) The selection controls are visible.
False | The selection controls are not visible.

Data Type

Boolean

Remarks

Run-time access: read/write. Design-time access: read/write.

See Also

ShowSelectionControls


EnableTracker Property

Indicates whether or not to show the trackbar control.

Syntax

[form.]object.EnableTracker [ = { True | False } ]

Settings

True | (Default) The trackbar is visible.
False | The trackbar is not visible.

Data Type

Boolean

Remarks

Run-time access: read/write. Design-time access: read/write.

See Also

ShowTracker


Error Event

Indicates that an error occurred.

The Error event is sent when DirectShow reports an error during playback. By default, the ActiveMovie Control displays a message box containing the description string. To avoid displaying this box, set the CancelDisplay parameter of the Error event to False.

Syntax

Private Sub object_Error(ByVal SCode As Integer, ByVal Description As String, ByVal Source As String, CancelDisplay As Boolean)

object | Object expression that evaluates to an ActiveMovie Control.
SCode | Error code.
Description | String describing the error that occurred.
Source | String containing the ActiveMovie Control's name.
CancelDisplay | Value that the client can set to cancel the default error messages.


Control Events

The ActiveMovie Control supports the following events.
DisplayModeChange | Indicates changes to the DisplayMode property.
Error | Indicates that an error occurred.
OpenComplete | Specifies the state of readiness for this ActiveMovie Control, based on how completely the source file has loaded.
PositionChange | Indicates changes to the current media position, such as when the user selects (or seeks to) a new media position.
ReadyStateChange | Indicates changes to the control's state of readiness.
StateChange | Indicates player state changes.
Timer | Handles timer events.

The ActiveMovie Control also supports several events common to other controls: Click, DblClick, KeyDown, KeyPress, KeyUp, MouseDown, MouseMove, and MouseUp. For information about these events, see the event documentation for Visual Basic.


FileName Property

Specifies the name of the source data file.

Syntax

[form.]object.FileName  [ = string ]

Settings

string Name of the file that contains the multimedia stream.

Data Type

String

Remarks

The ActiveMovie Control asynchronously opens the file specified by this property at run time. This means that an application must receive the ReadyStateChange event with an amvInteractive or amvComplete value before attempting to call the Run method.

When designing an application using Microsoft® Visual Basic® that uses the ActiveMovie Control, you can choose the media source file at design time. After you add a control to the application, fill in the full path to the media file as the value for the FileName property in Properties. You can also double-click the "..." value in the uninitialized FileName property and its property page will appear. If you click the Browse button, you can pick the desired source file from the Open dialog box.

Run-time access: read/write. Design-time access: read/write.


FilterGraph Property

Contains the IUnknown interface pointer to the current filter graph object.

Syntax

[form.]object.FilterGraph [ = punk ]

Settings

punk IUnknown pointer for the filter graph object.

Data Type

Integer (IUnknown*)

Remarks

The filter graph represents a specific configuration of source, transform, and rendering filters. The filter graph is the complete set of software components needed to process a given multimedia stream within the DirectShow architecture.

You can set this property to change the current filter graph.

The IDispatch interface pointer for the filter graph object is contained in the FilterGraphDispatch property.

Run-time access: read/write. Design-time access: read-only.

See Also

IFilterGraph Interface in the DirectShow SDK documentation.


FilterGraphDispatch Property

Contains an IDispatch interface pointer to the current filter graph object.

Syntax

[form.]object.FilterGraphDispatch [ = pdisp ]

Settings

pdisp IDispatch pointer to the current filter graph object.

Data Type

Integer (IDispatch*)

Remarks

The filter graph represents a specific configuration of source, transform, and rendering filters. The filter graph represents the complete set of software components needed to process a given multimedia stream within the DirectShow architecture.

Run-time access: read-only. Design-time access: read-only.

See Also

FilterGraph


FullScreenMode Property

Expands the area of the playback panel to fill the entire screen.

Syntax

[form.]object.FullScreenMode [ = { True | False } ]

Settings

True | Use full-screen mode.
False | Do not use full-screen mode.

Data Type

Boolean

Remarks

Run-time access: read-only. Design-time access: read/write.

See Also

MovieWindowSize


IsSoundCardEnabled Method

Determines whether the computer has one or more sound cards enabled.

Syntax

object.IsSoundCardEnabled [ = { True | False } ]

Settings

True | Sound card is enabled.
False | No sound cards are enabled.

Data Type

Boolean

Remarks

Run-time access: read. Design-time access: read.


Control Methods

The ActiveMovie Control supports the following methods.
AboutBox | Displays version and copyright information about the ActiveMovie Control.
IsSoundCardEnabled | Determines whether the computer's sound card is enabled.
Pause | Suspends a play operation without changing the current position.
Run | Starts a multimedia stream from the specified starting position or continues playing a paused stream.
Stop | Stops playback and resets the position as indicated by the AutoRewind and SelectionStart properties.

The ActiveMovie Control also supports several methods that are common to other controls: Drag, Move, SetFocus, ShowWhatsThis, and ZOrder.

For information about these methods, see documentation for Visual Basic.


MovieWindowSize Property

Specifies the size of the playback panel.

Syntax

[form.]object.MovieWindowSize [ = setting ]

Settings

Setting | Value | Description
amvOriginalSize | 0 | (Default) Uses the authored size.
amvDoubleOriginalSize | 1 | Increases the image projection size to twice the authored size.
amvOneSixteenthScreen | 2 | Projects the images onto an area the size of one-sixteenth of the screen.
amvOneFourthScreen | 3 | Projects the images onto an area the size of one-quarter of the screen.
amvOneHalfScreen | 4 | Projects the images onto an area the size of half of the screen.

Data Type

Long

Remarks

The amv settings are available only to C/C++ programmers; scripters and other programmers should use the numerical values.

Run-time access: read/write. Design-time access: read/write.


OpenComplete Event

Indicates the control finished opening the media file and is ready for playback.

Syntax

Private Sub object_OpenComplete()

Parameters

object Object expression that evaluates to an ActiveMovie Control.

Remarks

This event is provided for backward compatibility; use the ReadyStateChange event instead.


Pause Method

Suspends a play operation without changing the current position.

Syntax

object.Pause

Remarks

The Pause method pauses the multimedia stream at the current position. To continue playing the multimedia stream, use the Run method.

To stop the multimedia stream, use the Stop method.


PlayCount Property

Specifies the number of times to play the multimedia stream.

Syntax

[form.]object.PlayCount [ = long ]

Settings

long Numeric expression that specifies the number of times to play the multimedia stream.

Data Type

Long

Remarks

If you set this property to zero, the control will play the multimedia stream repeatedly, restarting as soon as it reaches the end.

Run-time access: read/write. Design-time access: read/write.

See Also

AutoStart


PositionChange Event

Indicates changes to the current media position, such as when the user selects (or seeks to) a new media position.

Syntax

Private Sub object_PositionChange(ByVal oldPosition As Double, ByVal newPosition As Double)

Parameters

object | Object expression that evaluates to an ActiveMovie Control.
oldPosition | Position before it changed, in seconds.
newPosition | Current position, in seconds, after the position change occurred.

Remarks

Changes made directly to the CurrentPosition property do not trigger this event.


Control Properties

The ActiveMovie Control supports the following properties.
AllowChangeDisplayMode | Indicates whether or not the end-user can change the display mode at run time between seconds and frames.
AllowHideControls | Indicates whether or not the end-user can hide the control panel at run time.
AllowHideDisplay | Indicates whether or not the end-user can hide the display panel at run time.
Appearance | Specifies the appearance of the display panel's border.
AutoRewind | Indicates whether or not the multimedia stream should automatically return to the selection's starting point when it reaches the end of the selection.
AutoStart | Indicates whether or not to automatically start playing the multimedia stream.
Balance | Specifies the stereo balance.
BorderStyle | Specifies the control's border style.
CurrentPosition | Specifies the current position within the playback file, in seconds.
CurrentState | Specifies the playback file's current state: stopped, paused, or running.
DisplayBackColor | Specifies the display panel's background color.
DisplayForeColor | Specifies the display panel's foreground color.
DisplayMode | Indicates whether or not the display panel shows the current position in seconds or frames.
EnableContextMenu | Indicates whether or not to enable the shortcut menu.
Enabled | Specifies whether or not the control is enabled.
EnablePositionControls | Indicates whether or not to show the position buttons in the controls panel.
EnableSelectionControls | Indicates whether or not to show the selection buttons in the controls panel.
EnableTracker | Indicates whether or not to show the trackbar control in the controls panel.
FileName | Specifies the name of the source data file.
FilterGraph | Contains the IUnknown interface pointer to the current filter graph object.
FilterGraphDispatch | Contains the IDispatch interface pointer to the current filter graph object.
FullScreenMode | Expands the area of the playback panel to fill the entire screen.
MovieWindowSize | Specifies the size of the playback panel.
PlayCount | Specifies the number of times to play the multimedia stream.
Rate | Specifies the playback rate for the stream.
ReadyState | Specifies the state of readiness for this ActiveMovie Control, based on how completely the source file has loaded.
SelectionEnd | Specifies the ending position in this multimedia stream, in seconds, relative to the stream's beginning.
SelectionStart | Specifies the starting position in this multimedia stream, in seconds, relative to the stream's beginning.
ShowControls | Indicates whether or not the controls panel is visible.
ShowDisplay | Indicates whether or not the display panel is visible.
ShowPositionControls | Indicates whether or not the position controls are visible.
ShowSelectionControls | Indicates whether or not the selection controls are visible.
ShowTracker | Indicates whether or not the trackbar is visible.
Volume | Specifies the volume, in hundredths of decibels.

The ActiveMovie Control supports the following properties that are common to other controls: Appearance, BorderStyle, Enabled, and hWnd. For information about these properties, see the documentation for Visual Basic.


Rate Property

Specifies the playback rate for the multimedia stream.

Syntax

[form.]object.Rate [ = double ]

Settings

double Numeric expression that represents the playback rate; 1.0 corresponds to the authored rate and is the default value.

Data Type

double

Remarks

This property acts as a multiplier value that allows you to play the stream at a faster or slower rate. The value 1.0 indicates the authored speed. Note that the audio track becomes difficult to understand at rates lower than 0.5 and higher than 1.5.

Run-time access: read/write. Design-time access: read/write.


ReadyState Property

Specifies the control's state of readiness.

Syntax

[form.]object.ReadyState

Settings

Setting | Value | Description
amvUninitialized | 1 | The FileName property has not been initialized.
amvLoading | 0 | The ActiveMovie Control is asynchronously loading a file.
amvInteractive | 3 | The control loaded a file, and has downloaded enough data to play the file, but has not yet received all data.
amvComplete | 4 | All data has been downloaded.

Data Type

Long

Remarks

The ActiveMovie Control changes this property at run time, and its value is passed as a parameter to the ReadyStateChange event. The run method will only work on the control after the ReadyState property has reached the amvInteractive or amvComplete state.

Run-time access: read-only. Design-time access: read-only.


ReadyStateChange Event

Indicates changes to the control's state of readiness.

Syntax

Private Sub object_ReadyStateChange(ByVal ReadyState As Long)

Parameters

object | Object expression that evaluates to an ActiveMovie Control.
ReadyState | Current state of readiness, after the change occurred.

Settings

Following are possible settings for the ReadyState parameter.
Setting | Value | Description
amvUninitialized | 1 | The FileName property has not been initialized.
amvLoading | 0 | The ActiveMovie Control is asynchronously loading a file.
amvInteractive | 3 | The control loaded a file, and downloaded enough data to play the file, but has not yet received all data.
amvComplete | 4 | All data has been downloaded.

Remarks

When you change the FileName property, applications should check the control's state of readiness before attempting to call the Run method on the newly opened file. Applications should call the Run method only if the ReadyState parameter equals amvInteractive or amvComplete.


Run Method

Starts a multimedia stream from the specified starting position or continues playing a paused stream.

Syntax

object.Run

Remarks

The Run method starts the multimedia stream at the starting position specified by the SelectionStart property. In the absence of other user or application input, the Run method continues playing the stream to the position specified by the SelectionEnd property.

The Run method is also used to resume playing a paused multimedia stream.

To pause playing, call the Pause method. To stop playing, call the Stop method.


SelectionEnd Property

Specifies the ending position in this multimedia stream, in seconds, relative to the stream's beginning.

Syntax

[form.]object.SelectionEnd [ = double ]

Settings

double Numeric expression that specifies the position in the multimedia stream that represents the end of the playback sequence.

Data Type

double

Remarks

The default value for SelectionEnd is the length of the multimedia stream; this value is not accessible until the file is loaded completely. When DirectShow sends the ReadyStateChange event with a value of Complete, you can access the value of this property.

Run-time access: read/write. Design-time access: none.

See Also

SelectionStart


SelectionStart Property

Specifies the starting position in this multimedia stream, in seconds, relative to the stream's beginning.

Syntax

[form.]object.SelectionStart [ = double ]

Settings

double Numeric expression that specifies the position within the multimedia stream that represents the beginning of the playback sequence.

Data Type

double

Remarks

The default value for SelectionStart is zero; this value is not accessible until the file is loaded completely. When DirectShow sends the ReadyStateChange event with a value of Complete, you can access the value of this property.

Run-time access: read/write. Design-time access: none.

See Also

SelectionEnd


ShowControls Property

Indicates whether or not the controls panel is visible.

Syntax

[form.]object.ShowControls [ = { True | False } ]

Settings

True | (Default) The controls panel is visible.
False | The controls panel is not visible.

Data Type

Boolean

Remarks

Run-time access: read/write. Design-time access: read/write.

See Also

ShowDisplay


ShowDisplay Property

Indicates whether or not the display panel is visible.

Syntax

[form.]object.ShowDisplay [ = { True | False } ]

Settings

True | (Default) The display panel is visible.
False | The display panel is not visible.

Data Type

Boolean

Remarks

Run-time access: read/write. Design-time access: read/write.

See Also

ShowControls


ShowPositionControls Property

Indicates whether the position controls are visible.

Syntax

[form.]object.ShowPositionControls [ = { True  | False  } ]

Settings

True | The position controls are visible.
False | (Default) The position controls are not visible.

Data Type

Boolean

Remarks

The position controls consist of four buttons: Previous, Rewind, Forward, and Next. Rewind and Forward move the media position rapidly backward and forward. If the current media position is after the position specified in SelectionStart, Previous sets the media position to the value of SelectionStart. If not, Previous sets the media position to the start of the data stream. If the current media position is before the position specified in SelectionStart, Next sets the media position to the value of SelectionStart. If not, Next sets the media position to the end of the data stream.

Run-time access: read/write. Design-time access: read/write.

See Also

EnablePositionControls


ShowSelectionControls Property

Indicates whether the selection controls are visible.

Syntax

[form.]object.ShowSelectionControls  [ = { True  | False  } ]

Settings

True | The selection controls are visible.
False | (Default) The selection controls are not visible.

Data Type

Boolean

Remarks

There are two selection buttons—Start Selection and End Selection. Start Selection sets the SelectionStart property to the current media position and End Selection sets the SelectionEnd property to the current media position. If you choose an invalid selection, such as an end time that is earlier than the start time, DirectShow automatically sets SelectionStart to the start of the data stream and SelectionEnd to the end.

Run-time access: read/write. Design-time access: read/write.

See Also

EnableSelectionControls


ShowTracker Property

Indicates whether or not the trackbar is visible.

Syntax

[form.]object.ShowTracker  [ = { True | False } ]

Settings

True | (Default) The trackbar is visible.
False | The trackbar is not visible.

Data Type

Boolean

Remarks

Run-time access: read/write. Design-time access: read/write.

See Also

EnableTracker


StateChange Event

Indicates that the player state changed, such as from running to stopped.

Syntax

Private Sub object_StateChange(ByVal oldState As Long, ByVal newState As Long)

Parameters

object | Object expression that evaluates to an ActiveMovie Control.
oldState | Previous state, before the change occurred.
newState | Current state, after the change occurred.

Settings

Following are possible settings for the oldState or newState parameters.
Setting | Value | Description
amvStopped | 0 | The player is stopped.
amvPaused | 1 | The player is paused.
amvRunning | 2 | The player is playing the multimedia file.

Remarks

The ActiveMovie Control raises the StateChange event when the player state changes, such as from stopped to running. The current player state appears in the CurrentState property. You can find the player state flags in the CurrentState property documentation.


Stop Method

Stops playback and resets the position as indicated by the AutoRewind and SelectionStart properties.

Syntax

object.Stop

Remarks

The Stop method changes the CurrentState property.

When the Stop method halts a play operation, you can reset the current position to the starting point for the multimedia stream, as indicated by the SelectionStart property. The AutoRewind property determines whether the position is reset to this starting position.

To halt a play operation without changing the current position, use the Pause method.

See Also

Run Method


Timer Event

Provides the rate at which DirectShow refreshes the control panel's display.

Syntax

Private Sub object_Timer( )

Parameters

object Object expression that evaluates to an ActiveMovie Control.

Remarks

The Timer event is raised at the intervals specified by the control's timer.


Volume Property

Specifies the volume, in hundredths of decibels.

Syntax

[form.]object.Volume [ = long ]

Settings

long Numeric expression that specifies the audio volume, in hundredths of decibels. The default value is zero.

Data Type

Long

Remarks

The value ranges from –10,000 to 0. The value 0 is full volume and –10,000 is no volume. Not all devices support 10,000 discrete steps of volume.

Run-time access: read/write. Design-time access: read/write.

See Also

Balance Property


Microsoft Chat Controls

Microsoft provides three reusable components that allow developers and content providers to add Internet functionality to their applications:

Microsoft Chat Control 1.1

Microsoft Chat Protocol Control 2.0

Microsoft Chat 1.0j Java Applet

The following list outlines the differences between these three components. It is provided to help developers and Web authors decide which component to use in their applications.

  • The Chat 1.1 control and Chat 1.0j applet offer customizable default user interfaces; the Chat Protocol Control 2.0 control requires the developer to design the user interface.
  • The Chat 1.1 control communicates with the server through either MIC or IRC protocols. The Chat 1.0j applet communicates with the server through the IRC protocol only. The Chat Protocol Control 2.0 communicates with the server through either IRC or IRCX protocols.
  • Since the Chat 1.0j applet is written in Java, it can be used in browsers that support Java. The Chat 1.1 and Chat Protocol Control 2.0 must be hosted by an ActiveX™ control container such as Internet Explorer or Visual Basic®.
  • The Chat Protocol Control 2.0 permits multiple concurrent conversations. The Chat 1.1 control and Chat 1.0j applet are limited to chatting in only one room at a time.
  • The Chat Protocol Control 2.0 exposes a much greater set of features than the Chat 1.1 control or Chat 1.0j.


Microsoft Chat 1.0j

Microsoft® Chat 1.0j is a Java applet that provides the Web designer with a simple, customizable user interface and programmability for the applet. With this applet, the page can be coded to join or create an existing room on the chat server with a nickname selected by the user. Other options include the ability to customize or hide the toolbar, and hide the member list and/or input field. The applet provides the Web designer with a default user interface that includes dialog boxes to view the room list, create and join a room, change the nickname, change fonts, and connect to the server. The default user interface is customizable by the Web designer.

Microsoft Chat 1.0j does not provide event notification and does not display the user list on the chat server.

Setting Up Microsoft Chat 1.0j

Optional Parameters

Public Applet Methods

Setting Up Microsoft Chat 1.0j

The following steps show how to set up Microsoft Chat 1.0j to work with your chat server:

  1. Set up a Web server and IRC chat server on the same computer to use the Chat applet. Chat 1.0j should work with any IRC chat server but has been tested mainly with the IRC chat server available from http://backoffice.microsoft.com/product/chat/.

  2. After you set up the Web server and chat server, copy Mschat1j.exe in the \bin directory to your Web server. You can obtain Mschat1j.exe by installing the Component Library section of the Internet Client SDK.

  3. Unzip the self-extracting executable file by running Mschat1j.exe from the \bin directory of the Internet Client SDK.

  4. To use Microsoft Chat 1.0j, after running Mschat1j.exe, you will need to use all *.class, *.gif, *.cab, *.properties, and *.files files. You will also need an HTML file that points to the applet. You can use the sample HTML files or create your own.

Optional Parameters

The following is a list of optional parameters that can be applied to a Chat applet embedded on a Web page by using the <PARAM> tag.

Name | Value(s) | Default | Description
port | [number] | 6667 | Specifies the port on which the chat server is running, usually 6667.
nickname | [user nickname] | "Anonymous" | Specifies the default name, used for autoconnect.
room [roomname] - Specifies the default room to join.
toolbar | true | false | true | Determines if the toolbar should be visible.
memberlist | true | false | true | Determines if the member list should be visible.
observer | true | false | false | Determines if the user can participate in a conversation.
banner [imagename] - Specifies a welcome image that should be displayed when the applet loads.
autoconnect | true | false | false | Determines if the applet will automatically connect when loaded. If true, room and nickname must be specified.
autodisconnect | true | false | false | Determines if the applet will automatically disconnect when the page is exited.
motd | true | false | true | Determines if the applet will display the Message of the Day after connecting.
stats | true | false | true | Determines if the applet will display server statistics after connecting.
id | [unique string] | "null" | Indicates that unique identifiers must be supplied if multiple chat applets will be on the same page.
font | fontname, style, size | Helvetica, 0, 11 | Helvetica | Dialog | TimesRoman | Courier, 0(plain), 1(bold), 2(italic), 3(bold + italic), 8 - 20
bgcolor | ffffff | c0c0c0 | Specifies the color, using hexadecimal notation same as in the HTML body tag.

Example

The following example shows HTML code for embedding an applet in a page. The sample shows the main user interface for Chat 1.0j. The user can use the toolbar to choose a nickname, connect to the chat server, and join or create a chat room to chat in.

<applet code=MSChat archive=mschat.jar name=Chat width=500 height=400>
    <param name=cabbase value=mschat.cab>
    <param name=room value=#newbies>
    <param name=port value=6667>
</applet>

Public Applet Methods

The following methods are exposed by the Chat applet. They can be called from any script language supported by the client browser.

Method | Returns | Description
connect(string nickname) | void | Connects to the server with the specified nickname.
connect(string nickname, string room) | void | Connects to the server with the specified nickname and joins the specified room, overriding any present room parameter.
disconnect() | void | User leaves all rooms and closes the connection with the server.
getNick() | String | Returns the user nickname, or null if the user hasn't yet logged on.
getRoom() | String | Returns the name of the room the user is currently in, or null if the user hasn't yet logged on.
join(string room, string password) | void | Leaves any current room, joins a specified room. Password is ignored if null or "".
showRoomList() | void | Displays the room list window.
showEnterRoomDialog() | void | Displays the dialog box that prompts user to enter a chat room.
showFontDialog() | void | Displays the dialog box that prompts user to change the current font.
showConnectDialog() | void | Displays the dialog box that prompts user to connect to a server.
showAboutDialog() | void | Displays the Microsoft Chat dialog box.

Example

The following example calls the connect method.

<FORM NAME="form1">
<INPUT TYPE="button" VALUE="Connect" onClick="document.Chat.connect(document.form1.nickname.value, document.form1.room.value)">
</FORM>
<applet code=MSChat archive=mschat.jar
                name=Chat width=500 height=400>
    <param name=cabbase value=mschat.cab>
    <param name=room value=#newbies>
    <param name=port value=6667>
</applet>


Microsoft Chat Control 1.1

The Microsoft® Chat Control 1.1 is an ActiveX™ control that allows you to participate in a chat, or conversation using text and data between two or more users connected to a chat server. The Chat Control 1.1 communicates with the chat server through either the MIC or IRC protocols.

Microsoft Chat Control 1.1 Visual Basic Overview

Microsoft Chat Control 1.1 Visual Basic Reference


Microsoft Chat Control 1.1 Visual Basic Overview

The Microsoft® Chat control, an ActiveX™-based control, exports most of the ChatSock API features. The control has an optional user interface (UI) that is very flexible. This UI can include a Send button, Whisper button, Participant list box, History text box, and Send text box. This overview covers the use of the Chat control with Visual Basic® Scripting Edition and with a Visual Basic application.

Introduction

The Chat Control

Dependencies

Licensing and Distribution

Using the Chat Control

Introduction

The Microsoft Chat control allows the user to participate in a chat, or conversation, that can communicate both text and data, including arrays, Booleans, errors, currencies, and dates, between two or more users connected to a chat server. Stand-alone Microsoft Visual Basic applications containing the Chat control or HTML pages that utilize the Chat control are referred to as chat clients. These chat clients communicate with a chat server through either the MIC (Microsoft Internet Chat) or IRC (Internet Relay Chat) protocols. Developers can design and implement their own user interface for a Chat control client, or use the customizable default user interface provided with the Chat control.

The Chat Control

The Chat control is an ActiveX™ control that can be hosted by a Microsoft Visual Basic application program to create a chat client. Web authors can also insert the Chat control into an HTML file with the <OBJECT> tag, and use Microsoft Visual Basic Scripting Edition (VBScript) to manipulate the control's properties, methods, and events. Both implementations enable conversations between multiple users on client computers accessing a common chat server over the Internet.

HTML-based chat pages require the user to view the page with a browser that supports the HTML <SCRIPT> tag and the VBScript scripting engine that is implemented in the Vbscript.dll file. Browser applications, such as Microsoft Internet Explorer, that use the scripting engine are called scripting hosts.

The architecture that supports conversations on the Web using the Chat control and Chat server is shown below.

Microsoft Chat control data flow diagram

This diagram shows three users browsing the Web. Two users (on Web Clients 1 and 2) have already found the Chat control on a Web page and have entered a chat room to have a conversation. The user on Web Client 3 has just encountered the Web page with the Chat control. The numbers on the diagram represent the direction of the data flow. Each step in the process is described by the following actions:

  1. First-time user on Web Client 3 makes a request to join the conversation, using the Chat control's user interface that is displayed on a Web page.
  2. The Web browser downloads the Chat control software to Web Client 3.
  3. The user on Web Client 3 types the message "Hello." The Chat control sends the message to the chat room.
  4. The chat room sends the message "Hello" to all participants in the chat. They see "Hello" on their Chat History text boxes.
  5. Some server and channel information is transmitted from the Web page to the chat room.

User Interface Elements

The Chat control allows a variety of user interface options. You can configure the control's user interface with the UIOption property. The user interface includes a History text box for displaying previously sent messages. You can directly access the text that is displayed in the History text box with the History property. The text appearing in the History text box can be limited to the maximum number of characters specified in the MaxHistoryLength property. The ClearHistory method should be invoked to clear the History text box when the OnHistoryFull event is triggered, indicating the History text box is 90 percent full.

Another user-interface feature is a Participant list box that allows users to see the alias names of all chat room members. Information about a chat room member, such as alias name, identifier, and Windows® user name, can be obtained by using the ThisParticipantAlias, ThisParticipantID, and ThisParticipantName properties, respectively. Using the information obtained from these properties will also allow you to invite a member of another chat room into a different chat room by using the InviteParticipant method, which triggers the OnParticipantInvited event. You can also obtain a chat room member's real name with the GetParticipantRealName method. If the attempt to get the member's real name was successful, this method triggers the OnParticipantRealName event.

A Send text box is included in the user interface so that the user can type outgoing messages. A Send button for broadcasting messages to all chat room members, and a Whisper button for sending private messages to a specific chat room member, are located at the bottom of the Chat control.

The following picture shows the default user interface provided with the Microsoft Chat control.

Microsoft Chat control user interface

In addition to the default user interface, you can create a custom user interface using the control's automation interface with the supported properties, methods, and events.

Chat Rooms

Users running chat client applications can enter or create chat rooms to communicate with other users. A chat room is entered or created using the EnterRoom method with the desired options. Using these options, you can modify existing chat rooms or create a number of different types of new ones. For example, auditorium rooms can be created to prevent chat room members from communicating with any other chat room member who is not a host. If the room type is changed, users can be notified through the OnRoomTypeChanged event. It is also possible to allow the user to cancel the request to enter a chat room with the CancelEntering method. This may be especially helpful if network problems arise, or if the response from the chat server is slower than the user can tolerate. In any chat client application or Web page, you should include a button that invokes the ExitRoom method to allow a chat room member to leave the chat room at any time. When creating a custom user interface, you should utilize the OnEnterParticipant and OnExitParticipant events to notify all chat room members when someone has joined or left the room. As a precaution, the user's State property should always be checked before entering, canceling, or exiting a chat room to make sure the desired method will be valid. The example included at the end of this chapter illustrates this concept.

There are several properties associated with chat rooms that you can use to control users' access to a room, or to let them decide which room they want to enter. The current number of members in a chat room can be checked with the MemberCount property, and the maximum number of members allowed in a chat room can be restricted with the MaxMembers property. Chat rooms are usually labeled with the topic being discussed by setting the RoomTopic property. The OnRoomTopicChanged event is triggered when the RoomTopic property has changed, and should be used to notify all chat room members of the new topic. In certain cases, it may also be desirable to use the Rating property to label chat rooms that contain potentially offensive subject matter. The ratings associated with a chat room must be based on the World Wide Web Consortium (W3C) standard for content ratings, known as PICS (http://www.w3.org/PICS/ External link), or Platform for Internet Content Selection.

Chat Members

Hosts, participants, and spectators are the three different types of members in a chat room. When a user creates a chat room, that member becomes the host of that room by default. After the OnEndEnumeration event is triggered, indicating that the list of a chat room's members has been retrieved, those members with a host status can perform certain administrative tasks. For example, a host can prevent specific users from entering the chat room with the BanParticipant method or eject members currently in a chat room with the KickParticipant method. When kicking a chat member out of the chat room, the OnParticipantKicked event can be used as an opportunity to notify or warn other chat room members (with a SendMessage) about acceptable behaviors within the current chat room. You can implement the SetParticipantStatus method to allow hosts to change the status of another chat room member. The associated OnParticipantStatusChanged event is triggered when the chat room member's status changes, and can be used as a mechanism to notify other chat room members. This can be especially useful in moderated rooms where a host wants to select a new host before leaving the chat room.

Chat room members with a participant status can send and receive messages from other chat room members, including hosts. Chat room spectators can see broadcast messages, but they are not allowed to send any type of message to other members of the chat.

Messages

When a chat room host or participant sends a message, it is broadcast to all other members in the room. A chat room member can also whisper a message to a specific member of the chat with the SendMessage method. Hosts can disable whisper messages for a specific chat member or the entire chat room with the SetParticipantStatus and EnterRoom methods, respectively. Chat room members can use the SetParticipantStatus method to ignore messages from specific members other than a chat room host.

General Chat Control Rules

The following rules apply to the use of the Chat control:

  • A chat room member will not receive the OnMessage event if the message was sent by that user. However, if the internal user interface is used, the OnTextMessageSent event will be triggered.
  • If a critical error occurs while in a chat room, the chat room member will automatically be ejected from the chat room. For example, if the network a chat room member was using to access the chat server suddenly became unavailable during a chat session, that user would be dropped from the list of participants. For more information on errors, look at the section on error codes.
  • The BorderStyle and Appearance properties should be set only at startup time. They should not be changed in the middle of a conversation, because the content of the controls (text boxes and list boxes) would be lost.
  • Chat room members cannot ignore themselves or a chat room host.
  • Only a host can change a member into a spectator, participant, or host.
  • The host cannot change an ignored member into a host (the ignore status must be removed first).
  • Participants and spectators cannot change the no-whisper status of another chat room member.
  • Chat room members cannot change themselves into spectators, participants, or hosts.

Dependencies

The Chat control requires the presence of the Mschat.ocx and Chatsock.dll files on the user's computer. These files can be obtained by installing the Internet Client SDK. To implement Web pages that use the Chat control, the Web server must have access to a chat server. If the Chat control is implemented as a stand-alone client application, the computer running this application must have access to a chat server. The Chat control enables the connection from the user's computer to a chat channel, or chat room, on the chat server.

Licensing and Distribution

The Microsoft Chat control is an ActiveX control that can be hosted by any ActiveX control container. This control is available for installation and redistribution on all computers with validly licensed copies of Microsoft operating system products (for example, Windows NT®, Windows® 95, and so on). For further information on licensing issues, refer to the License.txt file distributed with the Internet Client SDK.

Using the Chat Control

Web pages can be created to automatically download the Chat control with the <OBJECT> tag and allow the browser client to join a chat room using the default user interface with scripting. The following image shows how a sample HTML page looks when it is loaded by the browser.

Microsoft Chat control in an HTML page

To use the chat control shown above, the user viewing this HTML page would simply type an alias name in the Nickname field and click the Join The Chat button. Once connected, the frame on the right side of the control would show all chat room members. To broadcast a message, the user clicks in the Send text box, types the text of the message, and clicks the Send button. To whisper to specific members of the chat room, a user can select the names of the members in the Participant list box, click in the Send text box, type the message, and click the Whisper button. Whenever a message is sent in the chat room, the History text box is updated with the message and the chat member who sent it.

To implement this control, create an HTML page similar to the following example that uses VBScript. Detailed explanations of the HTML tags and VBScript code are provided below.

<HTML>
<HEAD>
<TITLE>MSChat OCX Simple Demo Page</TITLE>
</HEAD>
<BODY TOPMARGIN=4 BGCOLOR=#003B00 LINK=#FFFFDD VLINK=33FFFF TEXT=#FFFFFF>
<PRE>
        - Microsoft Chat Control Demo Page -
</PRE>
<P>
<OBJECT
    STANDBY="Dowloading the Microsoft MSChat ActiveX Control"
    CODETYPE="application/x-oleobject"
    CLASSID="clsid:D6526FE0-E651-11CF-99CB-00C04FD64497"
    CODEBASE="MSChatOCX.Cab#Version=4,71,413,0"
    WIDTH=600
    HEIGHT=350
    ID=Chat
    >
    <PARAM NAME="UIOption"   VALUE="2047">
    <PARAM NAME="Appearance" VALUE="3">
    <PARAM NAME="BackColor"  VALUE="255">
</OBJECT>
<FORM NAME = "WEBChat">
<PRE>
Room Path    <INPUT TYPE = "TEXT" NAME="Room" VALUE = "mic:\\ChatSvr\#Demo" SIZE = "40">
    Nickname    <INPUT TYPE = "TEXT" NAME="Alias" VALUE="" SIZE = "40">
<P>
    <INPUT TYPE = "BUTTON" NAME="FluxBtn" VALUE = "   Join the chat   " OnClick = "FluxBtn_OnClick">
</PRE>
</FORM>
<SCRIPT LANGUAGE="VBScript">
SUB FluxBtn_OnClick        'Event triggered when button is pressed
    Dim ChatForm
    Set ChatForm = Document.WEBChat
    If (Chat.State = 1) Then
        Chat.EnterRoom ChatForm.Room.Value, "", ChatForm.Alias.Value, "", 1, 1
    Else
        If (Chat.State = 2) Then
            Chat.CancelEntering
            Chat.ClearHistory
        Else
            If (Chat.State = 3) Then
                Chat.ExitRoom
                Chat.ClearHistory
            End If
        End If
    End If
END SUB
SUB Chat_OnStateChanged(ByVal NewState)    'Chat control event triggered when the chat's state is changed
    Dim ChatForm
    Set ChatForm = Document.WEBChat
    If (NewState = 1) Then
        ChatForm.FluxBtn.Value = "   Join the chat   "
        Chat.BackColor = 255    'UI Frame is red
    Else
        If (NewState = 2) Then
            ChatForm.FluxBtn.Value = "Cancel Entering"
            Chat.BackColor = 33023    'UI Frame is yellow
        Else
            If (NewState = 3) Then
                ChatForm.FluxBtn.Value = "Leave the chat"
                Chat.BackColor = 49152    'UI Frame is green
            End If
        End If
    End If
END SUB
</SCRIPT>
</BODY>
</HTML>

Note The version in the codebase line is subject to change and should be updated to the current version of the control that is available.

The <OBJECT> Tag

The <OBJECT> tag is required to download the Chat control that the unique CLASSID parameter value specifies. If the ActiveX control specified is not already on the computer, it will be downloaded from the URL value in the CODEBASE parameter. The ID parameter indicates the name of the MSChat object that the VBScript code will reference.

The <PARAM> tags are used within the <OBJECT> tag to specify default values for any property the object supports. In the previous example, the UIOption property bitmask is set to enable all options except History text box hyperlinked URLs (value 2048). The Appearance parameter causes the Chat control to appear as a 3-D object, and the BackColor parameter displays the user interface border in red. For information on other <OBJECT> parameters, see the HTML element reference for OBJECT.

The <FORM> Tag

The <FORM> tag is used to place objects such as buttons and text boxes on the HTML page. This is similar to using a Form in Microsoft Visual Basic or Microsoft Visual Basic for Applications. The example above creates a form with two text boxes and a button. The <INPUT TYPE = "TEXT"> tag is used to allow the user to specify a chat server room path and the user's nickname to be used in the chat room. The <INPUT TYPE = "BUTTON"> tag creates a button that can be clicked to join the chat, cancel entering the chat, and leave the chat.

The "TEXT" and "BUTTON" input types are included in the set of intrinsic HTML controls built into the Internet Explorer browser itself, and therefore do not require the use of the <OBJECT> tag to make them available. For further information on intrinsic HTML controls and their associated properties, methods, and events, refer to Inside Microsoft Visual Basic, Scripting Edition (Scot Hillier, Microsoft Press).

The <SCRIPT> Tag

The <SCRIPT> tag selects the scripting language to be used until the browser reaches the </SCRIPT> tag. In the previous example, VBScript code is used to execute when either of two events occur, including a button click (OnClick) event and a state change (OnStateChanged) event. The FluxBtn_OnClick subprocedure is executed whenever the button is clicked by the user. When this occurs, the procedure checks the current state of the user's HTML Chat client by retrieving the value of the State property. Based on the current Chat state, the procedure either connects to the specified Chat room with the EnterRoom method, cancels the request to join the Chat with the CancelEntering method, or disconnects from the Chat with the ExitRoom method. After responding to the button click, the Chat_OnStateChanged subprocedure is executed because the Chat control's state has been changed. This procedure simply checks the new state of the Chat control, and sets the appropriate button text with the Value property; the control's background color is changed with the BackColor property.

Note The Value property and OnClick event are associated with the set of intrinsic HTML controls mentioned previously.


Microsoft Chat Control 1.1 Visual Basic Reference

The Microsoft® Chat control is an ActiveX™-based control that can be used with any OLE container. This control provides users with the capability to create a chat, or conversation, that communicates text and/or data with other users connected through the Internet or an intranet. This reference describes the properties, methods, events, and error codes associated with the Chat control.

  • Properties
  • Methods
  • Events
  • Error Codes

MSChat Object

Properties

Appearance, BackColor, BorderStyle, Height, History, LastMessageReceived, LastMessageSent, MaxHistoryLength, MaxMembers, MaxMessageLength, MemberCount, Rating, RoomPath, RoomTopic, State, ThisParticipantAlias, ThisParticipantID, ThisParticipantName, UIOption, Width

Methods

AboutBox, BanParticipant, CancelEntering, ClearHistory, EnterRoom, ExitRoom, GetParticipantRealName, InviteParticipant, KickParticipant, MoveSplitBar, SelectParticipants, SendMessage, SetParticipantStatus

Events

OnBeginEnumeration, OnEndEnumeration, OnEnterParticipant, OnError, OnExitParticipant, OnHistoryFull, OnMessage, OnParticipantAliasChanged, OnParticipantInvited, OnParticipantKicked, OnParticipantRealName, OnParticipantStatusChanged, OnRoomTopicChanged, OnRoomTypeChanged, OnStateChanged, OnTextMessageSent


AboutBox Method

Displays the About message dialog box.

Syntax

object.AboutBox

Parameters

object Required. An object expression that evaluates to a Chat control.


Appearance Property

Retrieves or sets the appearance of the Chat control. This property is persistent and is read-only when connected to a chat room. This property has meaning only if the internal user interface is displayed.

Syntax

object.Appearance[=value]

Parameters

object | Required. An object expression that evaluates to a Chat control.
value | Optional. A short integer expression that determines the appearance of the Chat control. Can be set to one of the return values listed below.

Return Value

Returns a short integer value that indicates the current appearance of the Chat control. Can be one of the following values.
0 | All flat
1 | 3-D children only
2 | 3-D control frame only
3 | All 3-D

See Also

BorderStyle, UIOption


BackColor Property

Retrieves or sets the color of the background behind the text panes and the toolbar. This property is persistent and has meaning only if the internal user interface is displayed.

Syntax

object.BackColor[=value]

Parameters

object | Required. An object expression that evaluates to a Chat control.
value | Optional. An OLE_COLOR expression that determines the background color. The default value is the system's default window background color.

Return Value

Returns the OLE_COLOR value of the current background behind the text panes and toolbar.

See Also

UIOption


BanParticipant Method

Bans a member from or reinstates a member to a chat room.

Syntax

object.BanParticipant Name, Set

Parameters

object | Required. An object expression that evaluates to a Chat control.
Name | Required. A BSTR value that contains the alias of the member to be banned or reinstated.
Set | Required. A Boolean value that determines whether the member is banned or reinstated. If the value is set to TRUE, the member is banned from the chat room and cannot rejoin it. If the value is set to FALSE, the member is reinstated and can join the chat at any time.

Remarks

This method only prevents the member from rejoining or allows the member to rejoin the chat room after leaving or being kicked. It does not kick the member from the chat room. BanParticipant cannot be called before the OnEndEnumeration event has been triggered.

See Also

KickParticipant


BorderStyle Property

Retrieves or sets the appearance of the border. This property is read-only when connected to a chat room and has meaning only if the internal user interface is displayed. This property is persistent.

Syntax

object.BorderStyle[=value]

Parameters

object | Required. An object expression that evaluates to a Chat control.
value | Optional. A short integer expression that determines the border appearance. Can be set to one of the return values listed below.

Return Value

Returns the current border style. Can be one of the following values.
0 | None
1 | Single fixed for children only
2 | Single fixed for control frame only
3 | All single fixed

See Also

Appearance, UIOption


CancelEntering Method

Cancels an EnterRoom operation

Syntax

object.CancelEntering

Parameters

object Required. An object expression that evaluates to a Chat control.

Remarks

This method should be called only when the control's State property is equal to 2 (Connecting).

See Also

EnterRoom


ClearHistory Method

Empties the History text box.

Syntax

object.ClearHistory

Parameters

object Required. An object expression that evaluates to a Chat control.

Remarks

This method has an effect only if the value of the UIOption property includes a History text box (value=8).

See Also

History, OnHistoryFull


EnterRoom Method

Allows the user to enter the specified chat room.

Syntax

object.EnterRoom RoomPath, RoomPwd, ThisParticipantAlias, SecurityPackage, Flags, Type

Parameters

object | Required. An object expression that evaluates to a Chat control.
RoomPath Required. A string value containing the location of the chat room. The format of the string should be:

[prefix]://server-name[:port-number]/[[#]|[&]]room-name

The prefix is optional and can be either mic or irc. The server-name is the host name of the chat server computer. The optional number sign (#) indicates that the chat room can be a global IRC room. The optional ampersand (&) indicates that the room can be a local IRC or MIC room. The room-name is the name of the chat room.

RoomPwd | Required. A string containing either the room password or the host key used when creating or joining a password-protected room.
ThisParticipantAlias | Required. A string containing the alias that the user will be known by in the chat room.
SecurityPackage | Required. A string containing a list of security packages that are separated by semicolons and ordered by preference. If SecurityPackage is set to an empty string, the control asks the server for a list of security packages it provides. If the server replies no packages at all, an anonymous connection is tried. If the server replies with a list of packages, the first package on the list is tried. If the string is set to "ALL", all the server's security packages are tried in an order defined by the server. The control will stop looping through the security packages as soon as one package succeeds or an error not related to the account information occurs. If all packages fail, the control will try to connect the user anonymously. The "ANON" string can be used to request anonymous connections.
Flags Required. A combination of values used when creating or joining a room. These values characterize the room type and cannot change dynamically once the room is created. Set to zero to use no flags. Can be any combination of the following values.
1 | Join an existing chat room or create a chat room if one does not exist. If this flag is not set, the EnterRoom method will create a chat, but will not join an existing chat.
2 | The chat room will not be exposed to other servers on the Internet.
4 | The chat room is set up as read-only for news feeds, stock quotes, and so on.
8 | The chat room will allow only MIC clients to join it. IRC users will not be able to join the chat room.
16 | The server will accept only authenticated members in this chat room.
32 | Only authenticated members can talk in the chat room.
Type Required. A combination of values to set the type of chat room. Set to zero to use no flags. The chat room type can dynamically vary during its lifetime. The user is notified when the room type changes through the OnRoomTypeChanged event. Can be any combination of the following values.
1 | Allows any user into the chat room.
2 | Allows only hosts to change the topic of the chat room.
4 | Allows only users who logged on to this server to enter the chat room.
8 | Disables whispering in the chat room.
16 | Creates an auditorium room. The member list shows only the user and the hosts. Participants cannot whisper, but hosts can whisper to anybody, regardless of whether the no-whisper (Type=8) flag is set. Messages coming from participants are sent only to the hosts.
32 | Creates a moderated room. Members join the chat room as spectators by default.

Remarks

This method should be called only when the control's State property is equal to 1 (Disconnected).

See Also

CancelEntering, ExitRoom, OnRoomTypeChanged, RoomPath


Error Codes

The following list contains the error codes and their associated error messages. These error messages are subject to change and may not be exactly as they appear below.
Error code | Error message
5 | Illegal function call.
6 | Overflow error.
7 | Out of memory.
70 | Permission is denied.
380 | Invalid property value.
382 | Property is read-only at run time.
383 | Property is read-only.
394 | Property is write-only.
1000 | An error occurred. Please leave the application and try again.
1001 | Could not load the RICHED32.DLL library.
1002 | The room could not be found.
1003 | You are already trying to enter a room.
1004 | You are not trying to enter a room.
1005 | You are already in a chat room.
1006 | The room is full. Please try again later.
1007 | You cannot create this room, it already exists.
1008 | Could not make the room unique.
1009 | Too many rooms are already open on this server.
1010 | This is a room for which you need an invitation.
1011 | This is a password protected room. The room password specified is invalid.
1012 | The operation is denied.
1013 | The chat room path specified is invalid.
1014 | Can't connect to the chat server.
1015 | User unknown. Please verify your entries.
1016 | The alias specified is already in use.
1017 | The name specified is too long.
1018 | The user password specified is too long.
1019 | The room password specified is too long.
1020 | The alias specified is too long.
1021 | The room name specified is too short. Please enter a longer name.
1022 | The room name specified is too long. Please enter a shorter name.
1023 | The server name specified is too long.
1024 | The chat room topic specified is too long. Please enter a shorter topic.
1025 | A string specified is too long.
1026 | The Flags parameter specified is invalid.
1027 | The Type parameter specified is invalid.
1028 | The room name specified contains illegal characters.
1029 | The alias specified contains illegal characters.
1030 | For MIC and IRC local rooms, the first character has to be &. For IRC global rooms, the first character has to be #.
1031 | This chat has a bad name. The server cannot create it.
1032 | This user is unknown. The authentication failed.
1033 | Select the name of the member you want to ignore, and try again. You cannot ignore yourself or a host.
1034 | The participant ID specified is invalid.
1035 | Please select exactly one member and try the operation again.
1036 | You cannot kick yourself!
1037 | You cannot ban or reinstate yourself!
1038 | The status specified is invalid.
1039 | The mask specified is invalid.
1040 | The status change was denied.
1041 | Only a host can complete this operation.
1042 | You can only complete this operation on yourself.
1043 | This operation cannot be attempted on a host.
1044 | This operation cannot be attempted on an ignored member.
1045 | You cannot whisper to yourself.
1046 | Could not send the message.
1047 | The Receive text box limitation is too small to display the message. You might want to increase this limitation.
1048 | The destination list specified is invalid.
1049 | The message type specified is invalid.
1050 | The message format is invalid.
1051 | You are trying to whisper to too many recipients.
1052 | The message is empty.
1053 | The message to send is too long and could not be sent.
1054 | Only a system operator can complete this operation.
1055 | You are currently not connected to a chat server.
1056 | The chat server specified could not be found.
1057 | You are currently not in a room.
1058 | The connection to the chat server was lost.
1059 | A host of this chat room closed the room. You are no longer in the room.
1060 | Property is read-only when you're in a chat room.
1061 | The authentication could not be performed.
1062 | The password provided is invalid.
1063 | You are not allowed to whisper in this chat room.
1064 | This member does not accept whispers.
1065 | All the recipients refuse whispers.
1066 | The member name specified is blank or invalid.
1067 | This server does not allow IRC clients.
1068 | You have been banned from this chat room.
1069 | This chat room only allows authenticated members.
1070 | This server is full and does not allow additional members. Please try again later.
1071 | The server does not recognize the security package specified.
1072 | The SecurityPackage parameter specified is too long.
1073 | An MIC operation was attempted on an IRC channel
1074 | The PICS rating of this channel doesn't allow you to complete this operation.
1075 | No member with the alias specified could be found.
1076 | Couldn't get the real name of the member.
1077 | An error occurred on the chat server.
1078 | You cannot put carriage returns in a message sent to an IRC room.
1079 | A security-related error occurred on the server.
1080 | This MSN account is unknown.
1081 | This NT account is unknown.
1082 | The authenticated login failed.
1083 | Could not log you in successfully.
1084 | This chat program cannot join this type of room. Please try another room.
1085 | The chat room could not be created.
1086 | The operation could not be performed successfully.
1087 | Only administrators can perform this operation.
1088 | The server and client protocols in use are not compatible.
1089 | A member is trying to flood you.
1090 | You are not allowed to talk in this room.
1091 | The member is already in this room.
1092 | The member you specified is currently unknown on this chat server.


Events

This section describes the events associated with the Microsoft Chat control.

OnBeginEnumeration Event
OnEndEnumeration Event
OnEnterParticipant Event
OnError Event
OnExitParticipant Event
OnHistoryFull Event
OnMessage Event
OnParticipantAliasChanged Event
OnParticipantInvited Event
OnParticipantKicked Event
OnParticipantRealName Event
OnParticipantStatusChanged Event
OnRoomTopicChanged Event
OnRoomTypeChanged Event
OnStateChanged Event
OnTextMessageSent Event


ExitRoom Method

Disconnects the user from the current chat room.

Syntax

object.ExitRoom

Parameters

object Required. An object expression that evaluates to a Chat control.

Remarks

This method should be called only when the control's State property is equal to 3 (Connected).

See Also

CancelEntering, EnterRoom


GetParticipantRealName Method

Gets the real name of a participant by using the member's participant ID or alias (nickname).

Syntax

object.GetParticipantRealName ParticipantID, Alias, Synchronous, RealName

Parameters

object | Required. An object expression that evaluates to a Chat control.
ParticipantID | Required. A long integer value that indicates which member's real name is being requested. If ParticipantID is set to -1, the method uses the selected member's participant ID in the Participant list box. If ParticipantID is not set to -1, the participant ID must have come from an OnEnterParticipant event. This value must be set to zero if the application is requesting the real name by using the member's alias.
Alias | Required. A BSTR value that contains the requested member's alias. This value must be set to an empty string if the application is requesting the real name by using the member's ParticipantID.
Synchronous | Required. A Boolean value that indicates whether this method is executed synchronously or asynchronously. If Synchronous is set to TRUE, the real name is put into the string that is pointed to by RealName for a Visual Basic or C/C++ application. If Synchronous is set to FALSE, the answer to the query comes back asynchronously. If the query is successful, the OnParticipantRealName event returns the information. If the query is not successful, the OnError event is triggered. VBScript does not support pointers, so Synchronous must be set to FALSE.
RealName | Required. An address of a string where the real name of the member will be stored if the method is executed synchronously.

Remarks

When using ParticipantID, the scope of the search is limited to members currently in the chat room. When using Alias, the entire server is searched.

See Also

ThisParticipantID, ThisParticipantAlias


Height Property

Retrieves or sets the height of the control in HiMetrics. Each HiMetrics unit corresponds to 0.01 millimeters. This property is persistent.

Syntax

object.Height[=value]

Parameters

object | Required. An object expression that evaluates to a Chat control.
value | Optional. A HiMetrics value that indicates the height of the Chat control.

Return Value

Returns the current height of the Chat control in HiMetrics units.

See Also

Width


History Property

Retrieves the current content of the History text box. This property is read-only and has meaning only if the internal user interface is displayed.

Syntax

object.History

Parameters

object Required. An object expression that evaluates to a Chat control.

Return Value

Returns a BSTR value that contains the current contents of the History text box. If UIOption does not include the History text box (value=8), this property returns an empty string.

Remarks

The length of this string is limited by the MaxHistoryLength property.

See Also

ClearHistory


InviteParticipant Method

Invites a member to the user's current chat room.

Syntax

object.InviteParticipant Alias

Parameters

object | Required. An object expression that evaluates to a Chat control.
Alias | Required. A string value that contains the alias of the member to invite.

Remarks

The member must be on the same chat server as the user.

See Also

OnParticipantInvited, ThisParticipantAlias


KickParticipant Method

Kicks a member from the chat room.

Syntax

object.KickParticipant ParticipantID, KickComment

Parameters

object | Required. An object expression that evaluates to a Chat control.
ParticipantID | Required. A long integer value that indicates which member will be kicked. If ParticipantID is set to -1, the method uses the participant ID of the member selected in the Participant list box. If ParticipantID is not set to -1, the participant ID must have come from an OnEnterParticipant event.
KickComment | Required. A BSTR value that contains a text message with the host's reason for kicking the member. If the kicked member uses the Chat control and has the value 128 (inform about member status changes) set in the UIOption property, the member will see a message box with this reason.

Remarks

This method cannot be called before the OnEndEnumeration event has been triggered.

See Also

BanParticipant, OnParticipantKicked, ThisParticipantID


LastMessageReceived Property

Retrieves the last message the user received from the channel. This property is read-only.

Syntax

object.LastMessageReceived

Parameters

object Required. An object expression that evaluates to a Chat control.

Return Value

Returns a BSTR value that contains the last message received by the user.

Remarks

This property is updated whenever the user receives a text message.

See Also

LastMessageSent


LastMessageSent Property

Retrieves the last message sent by the user. This property is read-only.

Syntax

object.LastMessageSent

Parameters

object Required. An object expression that evaluates to a Chat control.

Return Value

Returns a BSTR value that contains the last text message sent by the user.

Remarks

This property is updated whenever the user sends a text message.

See Also

LastMessageReceived


MaxHistoryLength Property

Retrieves or sets the maximum number of characters allowed in the History text box. This property has meaning only if the internal user interface is displayed.

Syntax

object.MaxHistoryLength[=value]

Parameters

object | Required. An object expression that evaluates to a Chat control.
value | Optional. A long integer value that sets the maximum number of characters allowed in the History text box.

Return Value

Returns the maximum number of characters allowed in the History text box. If the UIOption property does not include the History text box (value=8), this property is equal to zero. The default value of MaxHistoryLength is 32K.

See Also

ClearHistory, History


MaxMembers Property

Retrieves or sets the maximum number of members in a chat room.

Syntax

object.MaxMembers[=value]

Parameters

object | Required. An object expression that evaluates to a Chat control.
value | Optional. A long integer expression that determines the maximum number of members allowed in the room. Only a host of the chat room can change this property.

Return Value

Returns zero if the limit is the server's default limit, or the maximum number of members otherwise.

See Also

MemberCount


MaxMessageLength Property

Retrieves or sets the maximum number of characters allowed in the Send text box.

Syntax

object.MaxMessageLength[=value]

Parameters

object | Required. An object expression that evaluates to a Chat control.
value | Optional. A long integer value that determines the maximum number of characters allowed in the Send text box. The default value is 2040 characters, which is the maximum message length on an MIC server.

Return Value

Returns the maximum number of characters allowed in the Send text box. If the UIOption property does not include the Send text box (value=16), this property is equal to zero.

See Also

SendMessage


MemberCount Property

Retrieves the number of members currently in the user's chat room. This property is read-only.

Syntax

object.MemberCount

Parameters

object Required. An object expression that evaluates to a Chat control.

Return Value

Returns zero if the user is not in a chat room, or the number of members in the chat room otherwise.

See Also

MaxMembers


Methods

This section describes the methods associated with the Microsoft Chat control.

AboutBox Method
BanParticipant Method
CancelEntering Method
ClearHistory Method
EnterRoom Method
ExitRoom Method
GetParticipantRealName Method
InviteParticipant Method
KickParticipant Method
MoveSplitBar Method
SelectParticipants Method
SendMessage Method
SetParticipantStatus Method


MoveSplitBar Method

Changes the appearance of the cursor to a cross hair so the user can resize the control by using the arrow keys or the mouse.

Syntax

object.MoveSplitBar

Parameters

object Required. An object expression that evaluates to a Chat control.


OnBeginEnumeration Event

Occurs when a user enters a chat room, before the list of members already in the conversation appears in the Participant list box.

Syntax

object_OnBeginEnumeration

Value | Description
object | Required. An object expression that evaluates to a Chat control.

See Also

EnterRoom, OnEndEnumeration, UIOption


OnEndEnumeration Event

Occurs after getting the initial list of members in the conversation, including the user.

Syntax

object_OnEndEnumeration

Value | Description
object | Required. An object expression that evaluates to a Chat control.

Remarks

The user can start to use the ThisParticipantID property or the SetParticipantStatus, KickParticipant, BanParticipant, and SendMessage methods once this event is triggered.


OnEnterParticipant Event

Occurs when either the list of members already in the conversation first appears when entering a chat room or when a new participant joins the conversation.

Syntax

object_OnEnterParticipant(ParticipantID, Name, Status)

Value | Description
object | Required. An object expression that evaluates to a Chat control.
ParticipantID | A long integer value that contains the participant ID of the member entering the chat room.
Name | A BSTR value that contains the alias of the member joining the chat room.
Status A short integer value indicating the status of the member entering the room. Can be one of the following values.
1 | Member is a host.
2 | Member is a participant.
4 | Member is a spectator.

See Also

EnterRoom


OnError Event

Occurs when there is an error in the control. If the display dialog boxes flag (value=512) is set in the UIOption property, the error message is displayed to the user.

Syntax

object_OnError(ErrorCode, Description)

Value | Description
object | Required. An object expression that evaluates to a Chat control.
ErrorCode | A short integer value that contains the numeric value of the error code.
Description | A BSTR value that contains the error message that is associated with the error code.


OnExitParticipant Event

Occurs when a member leaves the chat room.

Syntax

object_OnExitParticipant(ParticipantID)

Value | Description
object | Required. An object expression that evaluates to a Chat control.
ParticipantID | A long integer value that contains the participant ID of the member exiting the chat room.

See Also

ExitRoom


OnHistoryFull Event

Occurs each time a message is added to the History text box, when the total number of characters in the History text box is at least 90 percent of the MaxHistoryLength property (which is the maximum number of characters allowed in the History text box).

Syntax

object_OnHistoryFull(Percent)

Value | Description
object | Required. An object expression that evaluates to a Chat control.
Percent | The exact percentage of the History text box's maximum length that has been used.

Remarks

If the History text box gets too full to contain an incoming message, the top 20 percent of the text box's contents are removed. If this does not give enough space to fit the incoming message, more text is removed.

See Also

ClearHistory, History, UIOption


OnMessage Event

Occurs when a user gets a message from a member or the chat room.

Syntax

object_OnMessage(SenderID, Message, MessageType)

Value | Description
object | Required. An object expression that evaluates to a Chat control.
SenderID | A long integer that contains the participant ID of the member who sent the message, or zero if the message comes from the chat room.
Message | A VARIANT value that contains the message. The incoming message can be a text message (BSTR) or data (an array of bytes, shorts, longs, floats, doubles, Booleans, errors, currencies, or dates).
MessageType Can be a combination of the following values.
0 | A text or data message that is broadcast to all members.
1 | A text or data message that is whispered to one or more members.
2 | A ComicChat thought, which is text only.
4 | An action, which is text only.

See Also

SendMessage, OnTextMessageSent, ThisParticipantID


OnParticipantAliasChanged Event

Occurs when the member's alias is changed. Also, if the display notifications flag (value=128) is set in the UIOption property, a dialog box is displayed that says: "<OldAlias> is now known as <NewAlias>."

Syntax

object_OnParticipantAliasChanged(ParticipantID, OldAlias, NewAlias)

Value | Description
object | Required. An object expression that evaluates to a Chat control.
ParticipantID | A long integer value that contains the participant ID of the member whose alias is changing.
OldAlias | A BSTR value that contains the old alias.
NewAlias | A BSTR value that contains the new alias.

See Also

ThisParticipantAlias


OnParticipantInvited Event

Occurs when a member invites the user to the member's chat room.

Syntax

object_OnParticipantInvited(RoomName, Alias)

Value | Description
object | Required. An object expression that evaluates to a Chat control.
RoomName | A string value containing the name of the member's chat room.
Alias | A string value containing the name of the member who invited the user to the member's chat room.

See Also

InviteParticipant, ThisParticipantAlias


OnParticipantKicked Event

Occurs when the user is kicked from the chat room.

Syntax

object_OnParticipantKicked(ParticipantID, Reason)

Value | Description
object | Required. An object expression that evaluates to a Chat control.
ParticipantID | A long integer value that contains the participant ID of the host who kicked the user from the chat room.
Reason | A BSTR value that contains the reason given for kicking the user from the chat room. This value can be an empty string, if no reason was given.

See Also

KickParticipant, ThisParticipantID


OnParticipantRealName Event

Occurs when a successful call is made to GetParticipantRealName with the Synchronous parameter set to FALSE.

Syntax

object_OnParticipantRealName(Alias, RealName)

Value | Description
object | Required. An object expression that evaluates to a Chat control.
Alias | A BSTR value that contains the current alias of the member.
RealName | A BSTR value that contains the real name of the member.

See Also

ThisParticipantName


OnParticipantStatusChanged Event

Occurs when a member changes status.

Syntax

object_OnParticipantStatusChanged(ParticipantID, Status)

Value | Description
object | Required. An object expression that evaluates to a Chat control.
ParticipantID | A long integer value that contains the participant ID of the member whose status is changing.
Status A short integer value that indicates the new status of the member. The new status is a combination of the following values.
1 | Member has become a host.
2 | Member has become a participant.
4 | Member has become a spectator.
8 | Member does not allow whispers.
16 | Member is ignored, so all incoming messages from this member are discarded.

Remarks

Any member is either a host (Status=1), participant (Status=2), or spectator (Status=4), so a valid status must include one of these values.

See Also

SetParticipantStatus, ThisParticipantID


OnRoomTopicChanged Event

Occurs when the room topic property changes.

Syntax

object_OnRoomTopicChanged(NewRoomTopic)

Value | Description
object | Required. An object expression that evaluates to a Chat control.
NewRoomTopic | A BSTR value that contains the description of the new topic of conversation.

See Also

RoomTopic


OnRoomTypeChanged Event

Gives the value of the new room type.

Syntax

object_OnRoomTypeChanged(NewRoomType)

Value | Description
object | Required. An object expression that evaluates to a Chat control.
NewRoomType A short integer value that equals the sum of the room type settings. Can be a combination of the following values.
1 | Allows any user into the chat room.
2 | Allows only hosts to change the topic of the chat room.
4 | Allows only users who logged on to this server to enter the chat room.
8 | Disables whispering in the chat room.
16 | Creates an auditorium room. The member list shows only the user and the hosts. Participants cannot whisper, but hosts can whisper to anybody, regardless of whether the no-whisper (NewRoomType=8) flag is set. Messages coming from participants are sent only to the hosts.
32 | Creates a moderated room. Members join the chat room as spectators by default.

Remarks

For example, if NewRoomType=10, it means that only hosts can change the room topic (NewRoomType=2), and no whispers are allowed in the room (NewRoomType=8).

See Also

EnterRoom


OnStateChanged Event

Occurs when the user's state changes.

Syntax

object_OnStateChanged(NewState)

Value | Description
object | Required. An object expression that evaluates to a Chat control.
NewState A short integer that indicates the user's new state. Can be one of the following values.
1 | Disconnected from any chat rooms.
2 | Connecting to a chat room.
3 | Connected to a chat room.

See Also

State


OnTextMessageSent Event

Occurs whenever the user sends a text message by using the internal Send button or Whisper button.

Syntax

object_OnTextMessageSent(TextMessage, MessageType)

Value | Description
object | Required. An object expression that evaluates to a Chat control.
TextMessage | A BSTR value that contains the text sent by the user.
MessageType A short integer value that indicates the type of message sent. Can be one of the following values.
0 | The user sent some text as a broadcast to all members.
1 | The user sent some text as a whisper to one or more members.

Remarks

This event is not triggered when using the SendMessage method.

See Also

UIOption


Properties

This section describes the properties associated with the Microsoft Chat control.

Appearance Property
BackColor Property
BorderStyle Property
Height Property
History Property
LastMessageReceived Property
LastMessageSent Property
MaxHistoryLength Property
MaxMembers Property
MaxMessageLength Property
MemberCount Property
Rating Property
RoomPath Property
RoomTopic Property
State Property
ThisParticipantAlias Property
ThisParticipantID Property
ThisParticipantName Property
UIOption Property
Width Property


Rating Property

Retrieves the rating of a chat room. This property is read-only.

Syntax

object.Rating

Parameters

object Required. An object expression that evaluates to a Chat control.

Return Value

Returns a BSTR value that contains the Platform for Internet Content Selection (PICS) rating if the chat room is on an MIC server. Otherwise, this property returns an empty string. For more information on PICS ratings, see Internet Ratings.


RoomPath Property

Retrieves the location of the chat room to which the user is currently connected. This property is read-only.

Syntax

object.RoomPath

Parameters

object Required. An object expression that evaluates to a Chat control.

Return Value

Returns a BSTR expression that evaluates to the server location of the chat room. If the user is not connected to a chat room, an empty string is returned.

Remarks

The format of the server location returned is:

prefix://server-name[:port-number]/[[#]|[&]]room-name

The prefix can be mic or irc. The server-name is the host name of the chat server computer. The optional number sign (#) indicates that the chat room can be a global IRC room. The optional ampersand (&) indicates that the room can be a local IRC or MIC room. The room-name is the name of the chat room.

See Also

EnterRoom


RoomTopic Property

Retrieves or sets the chat room's topic. This property can be used to set the topic when creating a chat room, to change the topic when the user is in the room, or to get the current topic of the room that the user is in.

Syntax

object.RoomTopic[=value]

Parameters

object | Required. An object expression that evaluates to a Chat control.
value | Optional. A BSTR value that indicates the topic name to be set.

Return Value

Returns a BSTR value that contains the topic name of the chat room that the user is currently in.

Remarks

The user cannot set or modify the topic if the chat room was created with the value in the EnterRoom method set to (Type=2), which allows only the host to change the topic, and the user is not the host.

See Also

OnRoomTopicChanged


SelectParticipants Method

Selects, deselects, or inverts the selection of members in the Participant list box.

Syntax

object.SelectParticipants value

Parameters

object Required. An object expression that evaluates to a Chat control.
value Required. A short integer value that determines which members are selected. Can be set to one of the following values.
0 | Deselects any highlighted member.
1 | Selects all the members.
2 | Deselects the highlighted members and selects the members that were not highlighted.

Remarks

This method has an effect only if the UIOption property includes a Participant list box (value=4).

See Also

SendMessage


SendMessage Method

Sends a message.

Syntax

object.SendMessage DestinationList, Count, Message

Parameters

object | Required. An object expression that evaluates to a Chat control.
DestinationList Required. A VARIANT value that indicates how this message should be distributed. The message can be broadcast to all members, whispered to one member, or whispered to a group of members:
  • To broadcast the message to all members, the value must be set by an integer, a long integer, or an array of long integers (limited to one element) equal to -1.
  • To whisper to one member (unicast), the value must be set by a long integer equal to the member's participant ID.
  • To whisper to a group of members (multicast), the value must be set by an array of long integers corresponding to the member's participant ID.
Count | Required. A short integer that determines the number of recipients that will receive the message. To broadcast a message to all members, set the value of Count to zero. Otherwise, set Count to the number of members that will receive the message.
Message Required. A VARIANT value that contains the message being distributed:
  • To distribute a text message to be displayed in the History text box of the selected members, the data type must be a BSTR value that contains the text to be displayed.
  • To distribute a data message being sent to the selected members, the data can be an array of bytes, shorts, longs, floats, doubles, Booleans, errors, currencies, or dates that correspond to the following VARIANT types: VT_UI1, VT_I2, VT_I4, VT_R4, VT_R8, VT_BOOL, VT_ERROR, VT_CY, VT_DATE.

Remarks

This method cannot be called before the OnEndEnumeration event has been triggered.

See Also

History, OnMessage, SelectParticipants, ThisParticipantID


SetParticipantStatus Method

Changes the status of the member in a chat room.

Syntax

object.SetParticipantStatus ParticipantID, Mask, Status

Parameters

object | Required. An object expression that evaluates to a Chat control.
ParticipantID | Required. If ParticipantID=-1, the member selected in the Participant list box will be affected. Only one member can be selected for this method to work. Otherwise, the value of ParticipantID has to come from an OnEnterParticipant event.
Mask Required. A short integer indicating the types of status changes that the user wants to make. Set to zero if no masks are wanted. Can be set to one of the following values or a combination of 1 and one other value.
1 | Mask to set a member's privileges. Must be set if Status is 1, 2, or 4.
2 | Mask to set the whisper status of the user. Must be set if Status is changed to 8 or zero (to allow whispers).
4 | Mask to set the ignored status of a member. Must be set if Status is changed to 16 or zero (to allow the user to receive messages from the member again).
Status Required. A short integer setting the participant's status changes. Set to zero if the user wants to allow the member to whisper to the user (if Mask includes 2) or allow the user to receive messages from the member (if Mask includes 4). Can be set to any combination of the following values.
1 | Changes the privileges of the member to a host. The value of Mask must include 1.
2 | Changes the privileges of the member to a participant. The value of Mask must include 1.
4 | Changes the privileges of the member to a spectator. The value of Mask must include 1.
8 | Changes the status of the user to not allow whispers. The value of Mask must include 2.
16 | Changes the status of the member to be ignored so the user will not receive any messages from that member. The value of Mask must include 4.

Remarks

This method cannot be called before the OnEndEnumeration event. The following are the rules that apply to status changes:

  • The user cannot ignore herself or himself or the hosts.
  • The user can set the flag for no whispers (Status=8) only on herself or himself.
  • Only a host can change another user's privileges.
  • The user cannot set both the no-whisper and ignored values (or masks), since users cannot ignore themselves and the user cannot set the whisper value of another member.

See Also

OnParticipantStatusChanged, ThisParticipantID


State Property

Retrieves whether the user is currently disconnected from, connected to, or in the process of connecting to a chat room. This property is read-only.

Syntax

object.State

Parameters

object Required. An object expression that evaluates to a Chat control.

Return Value

Returns the current user state. Can be one of the following values.
1 | Disconnected from any chat rooms
2 | Connecting to a chat room
3 | Connected to a chat room

See Also

CancelEntering, EnterRoom, ExitRoom, OnStateChanged


ThisParticipantAlias Property

Retrieves the user's alias. This property is read-only.

Syntax

object.ThisParticipantAlias

Parameters

object Required. An object expression that evaluates to a Chat control.

Return Value

Returns a BSTR value that contains the user's nickname used when the EnterRoom method was called, if the user is currently in a chat room. If the user is not in a chat room, an empty string is returned.

See Also

OnParticipantAliasChanged, ThisParticipantID, ThisParticipantName


ThisParticipantID Property

Retrieves the user's numeric identifier. This property is read-only.

Syntax

object.ThisParticipantID

Parameters

object Required. An object expression that evaluates to a Chat control.

Return Value

Returns a long integer value that contains the user's numeric identifier, if the user is currently in a chat room. If the user is not in a chat room, the value is zero.

See Also

ThisParticipantAlias, ThisParticipantName


ThisParticipantName Property

Returns the user's Microsoft Windows® user name. This property is read-only.

Syntax

object.ThisParticipantName

Parameters

object Required. An object expression that evaluates to a Chat control.

Return Value

Returns a BSTR value that contains the user's Windows user name, if the user is currently in a chat room. If the user is not in a chat room, an empty string is returned.

See Also

ThisParticipantAlias, ThisParticipantID


UIOption Property

Contains flags that control the appearance of the default user interface. This property is a bitmask.

Syntax

object.UIOption[=value]

Parameters

object Required. An object expression that evaluates to a Chat control.
value Optional. A short integer expression that equals the sum of the desired user interface option values. Can include the following option values.
1 | Set this value to display the Send button. Must set the Send text box (value=16) in order to set the Send button.
2 | Set this value to display the Whisper button. Must set the Send button (value=1) in order to set the Whisper button.
4 | Set this value to display the Participant list box.
8 | Set this value to display the History text box. This window displays all messages that have been received.
16 | Set this value to display the Send text box. The user composes messages in this text box before sending them.
32 | Set this value to notify members in the History text box when a new user joins the chat.
64 | Set this value to notify members in the History text box when a user leaves the chat.
128 | Set this value to allow the Chat control to display a dialog box that notifies the user when a member's status (host, participant, or spectator) changes, when a member's alias (nickname) changes, and when the user has been kicked by a host.
256 | Set this value to insert a blank line between messages in the History text box.
512 | Set this value to allow the Chat control to display error dialog boxes. When an OnError event is triggered, a dialog box containing the error message will appear.
1024 | Set this value to allow the user to resize the control.
2048 | Set this value to allow any URLs appearing in the History text box to be clickable.

Return Value

Returns the sum of the option values currently selected.

Remarks

To set a Chat control's user interface so that it includes a Send text box, Send button, Whisper button, History text box, and Participant list box, this property must be set to the sum of the option values. In this case, the sum would equal 31 (16 + 1 + 2 + 8 + 4 = 31). To set the control to have all options, the sum would equal 4095 (1 + 2 + 4 + 8 + 16 + 32 + 64 + 128 + 256 + 512 + 1024 + 2048 = 4095).

See Also

Appearance, BackColor, BorderStyle, History, MaxHistoryLength, MaxMessageLength


Width Property

Returns or sets the width of the control in HiMetrics. Each HiMetrics unit corresponds to 0.01 millimeters. This property is persistent.

Syntax

object.Width[=value]

Parameters

object | Required. An object expression that evaluates to a Chat control.
value | Optional. A HiMetrics value that indicates the width of the Chat control.

Return Value

Returns the current width of the Chat control in HiMetrics units.

See Also

Height


Microsoft Chat Protocol 2.0

The Microsoft® Chat Protocol Control 2.0 is an ActiveX™ control that allows you to participate in a chat, or conversation using text and data between two or more users connected to a chat server. The Chat Protocol Control 2.0 communicates with the chat server through either the IRC or IRCX protocols.

Microsoft Chat Protocol Control 2.0 Visual Basic Overview (Beta1 Release)

Microsoft Chat Protocol Control 2.0 Visual Basic Reference (Beta1 Release)


Microsoft Chat Protocol Control 2.0 Visual Basic Overview (Beta1 Release)

The Microsoft® Chat Protocol Control 2.0 is an ActiveX™ control that allows the user to participate in a chat, or conversation, between two or more users connected to a chat server.

The Chat Protocol control allows the user to communicate both text and data, including arrays, Booleans, errors, currencies, and dates.

Stand-alone Microsoft Visual Basic® or Microsoft Visual C++® applications containing the Chat Protocol control or HTML pages that utilize the Chat Protocol control are referred to as chat clients. These chat clients communicate with a chat server through either the IRC (Internet Relay Chat) or IRCX (Extended Internet Relay Chat) protocols. The Chat Protocol control abstracts the IRC/IRCX protocols by the heavy use of objects and properties, thus insulating the developer from unnecessary knowledge of these protocols.

Because the Microsoft Chat Protocol Control 2.0 does not implement a user interface, developers are free to design and implement their own.

The Chat Protocol Control

Dependencies

Licensing and Distribution

Using the Chat Protocol Control

The Chat Protocol Control

The Chat Protocol control is an ActiveX control that can be hosted by Microsoft Visual Basic or Microsoft Visual C++ applications. Web authors can also insert the Chat Protocol control into an HTML file with the <OBJECT> tag, and use Microsoft Visual Basic Scripting Edition (VBScript) to manipulate the control's properties, methods, and events. Web pages can be designed to query the user list, query the room lists, monitor the chat for specific events such as language type, notify when friends are online, and assign them specific privileges in a chat room.

Dependencies

The Chat Protocol control requires the presence of the Mschatpr.ocx on the user's computer. These files can be obtained by installing the Internet Client SDK. To implement Web pages that use the Chat Protocol control, the Web server must have access to a chat server. If the Chat Protocol control is implemented as a stand-alone client application, the computer running this application must have access to a chat server. The Chat Protocol control enables the connection from the user's computer to a chat channel, or chat room, on the chat server.

Licensing and Distribution

The Chat Protocol control is an ActiveX control that can be hosted by any ActiveX control container. This control is available for installation and redistribution on all computers with validly licensed copies of Microsoft operating system products (for example, Windows NT®, Windows® 95, and so on). For further information on licensing issues, refer to the License.txt file distributed with the Internet Client SDK.

Using the Chat Protocol Control

To use the Chat Protocol control, you can either directly log on to the chat server, or connect to the server prior to logging on.

You can connect to the server first to determine what security packages are available on the server. The following method is used to do this.

object.Connect ServerName

The following method is used to log on to a chat server.

object.Login ServerName, Nickname [, UserName] [, RealName] [, Password] [, SecurityPackages]

After logging on, you can add a Channel object to the Channels collection with the Add method. The Channels collection object is a standard Visual Basic collection object that uses the standard Add and Remove methods and the Item and Count properties.

Add method:

value=object.Add[(Index] [, Key)]

After the Channel object is created, you can join a channel with the JoinChannel or CreateChannel method. The CreateChannel method can be used only on an IRCX server.

JoinChannel method:

object.JoinChannel [ChannelName] [, ChannelKeyword]

CreateChannel method:

object.CreateChannel [ChannelName] [, ChannelKeyword] [, ChannelModes] [, MaxMemberCount]

Example

The following example adds Channel objects to the Channels collection with the Add method, and then joins the "Questions" Channel with the JoinChannel method:

Dim chan1, chan2 As Channel
Set chan1 = MsChatPr1.Channels.Add(1, "Questions")
Set chan2 = MsChatPr1.Channels.Add(2, "Answers")
MsChatPr1.Channels(1).JoinChannel "Questions"

All the channel methods and properties are available after the channel has been joined. For example, the SendMessage method sends text or data to the channel or a selective set of channel members.

object.SendMessage MessageType, Message [, RecipientNicknames] [, DataMessageTag]

Example

The following example sends a regular string to the channel.

MsChatPr1.Channels(1).SendMessage msgtNormal, "How are you?"

For incoming messages, the OnMessage event is fired. You can use this event to update the user interface of the chat client.

object_OnMessage(Channel, SenderNickname, MessageType, Message, RecipientNicknames, DataMessageTag)

To leave the channel, the LeaveChannel method closes the current channel.

object.LeaveChannel

The Remove method removes a Channel object from the Channels collection.

object.Remove Index

Querying the Server for Information

Information regarding the server, a channel, a user, or a member can be obtained asynchronously or synchronously.

The Chat Protocol control supports sophisticated querying by the use of the ChatItems object. These queries relate to the server, a channel, a user, or a member. Generally, the information provided by the server is exposed to you through a ChatItems object.

The following example shows how to construct a ChatItems object to query the server for all users whose nicknames start with the letter 'a'.

Dim UserQueryItems As ChatItems
Set UserQueryItems = New ChatItems
UserQueryItems.AssociatedType = "Query"
UserQueryItems.Item("Nickname") = "a"
UserQueryItems.Item("NicknameOp") = "StartsWith"
MsChatPr1.ListUsers UserQueryItems
Set UserQueryItems = Nothing

Note: Because VBScript does not have a New operator, you need to use the control's NewChatItems property to create a new ChatItems object. Therefore, in VBScript, the first two lines of the preceding example would be:

Dim UserQueryItems
Set UserQueryItems = MsChatPr1.NewChatItems

Information can also be queried synchronously using the object properties. However, the control will be blocked until the server returns the required information. If the server has not returned the required information within a customizable period, the control throws a time-out error and unblocks. If the server sends the information later, the information will be exposed to the user through an event. You can alter this time-out period through the PropertyAccessTimeOut property.

The OBJECT Tag for HTML Pages

The following example uses the OBJECT tag to implement the Chat Protocol control.

<OBJECT ID=MsChatPr1
STANDBY="Downloading the Microsoft Chat Protocol Control"
CODETYPE="application/x-oleobject"
CLASSID="CLSID:039397C0-46DF-11D0-99CB-00C04FD64497"
CODEBASE="MsChatPr.Cab">
</OBJECT>


Microsoft Chat Protocol Control 2.0 Visual Basic Reference (Beta1 Release)

This section provides a reference for the objects and the associated methods, properties, and events of the Microsoft® Chat Protocol Control 2.0.

Objects

MsChatPr Object

Channel Object

Channels Collection Object

ChatItems Object

Enumerations

Error Codes

Object Properties

Objects

The objects that comprise the Microsoft Chat Protocol Control 2.0 are:

  • MsChatPr
  • Channel
  • Channels
  • ChatItems


AboutBox Method

Displays the About message dialog box.

Syntax

object.AboutBox

Parameters

object Required. An object expression that evaluates to an MsChatPr object.


Add Method

Adds a Channel object to the Channels collection.

Syntax

value=object.Add[(Index][, Key)]

Parameters

value | Required. An object expression that evaluates to a Channel object. This will contain the newly added Channel object.
object | Required. An object expression that evaluates to a Channels collection object.
Index | Optional. A variant. If specified, it must be empty or a valid index that is a number between 1 and the current collection Count + 1.
Key | Optional. A variant. If specified, it must be empty or a unique string that will identify the new Channel object.

Examples

Dim chan1, chan2 As Channel
Set chan1 = MsChatPr1.Channels.Add(1, "Questions")
Set chan2 = MsChatPr1.Channels.Add(2, "Answers")
MsChatPr1.Channels.Add
MsChatPr1.Channels.Add , "Aud"
MsChatPr1.Channels.Add 5

See Also

Index


AssociatedType Property

Defines whether the object is used to describe a query, server, user, member, or channel.

Syntax

object.AssociatedType=value

Parameters

object Required. An object expression that evaluates to a ChatItems object.
value Required. A string containing one of these valid values:
Query
Server
User
Member
Channel

Remarks

Access is read/write.

See Also

Item


BanMembers Method

Bans a member(s) and reinstates a member(s).

Syntax

object.BanMembers MemberItems, Set

Parameters

object | Required. An object expression that evaluates to a Channel object.
MemberItems Required. An object expression that evaluates to a ChatItems object. Specifies which members are to be banned or reinstated. The valid item names for constructing the MemberItems object are:
IPAddress
IPAddressOp
Nickname
NicknameOp
UserName
UserNameOp
Set | Required. A Boolean variable. This parameter must be TRUE to ban the member from the channel, or FALSE to reinstate the member to the channel.

Examples

1. Ban all the users with an IP address that ends with ".net":

Dim mi As ChatItems
Set mi = New ChatItems
mi.AssociatedType = "Query"
mi.Item("IPAddressOp") = "EndsWith"
mi.Item("IPAddress") = ".net"
chan.BanMembers mi, True
Set mi = Nothing

2. Ban all the users with the username "ProutZ":

Dim mi As ChatItems
Set mi = New ChatItems
mi.AssociatedType = "Query"
mi.Item("UserName") = "ProutZ"
chan.BanMembers mi, True
Set mi = Nothing

3. Reinstate all the users with a username that contains "regis" and an IP address that starts with "ms":

Dim mi As ChatItems
Set mi = New ChatItems
mi.AssociatedType = "Query"
mi.Item("UserNameOp") = "Contains"
mi.Item("UserName") = "regis"
mi.Item("IPAddressOp") = "StartsWith"
mi.Item("IPAddress") = "ms"
chan.BanMembers mi, False
Set mi = Nothing

See Also

NewChatItems


BanUsers Method

Bans users from the server and reinstates users to the server.

Syntax

object.BanUsers UserItems, Set[, Reason][, Duration]

Parameters

object | Required. An object expression that evaluates to an MsChatPr control.
UserItems Required. An object expression that evaluates to a ChatItems object. Defines which users are banned or reinstated. The item names that can be used to construct the ChatItems object are:
Nickname
NicknameOp
UserName
UserNameOp
IPAddress
IPAddressOp
Set | Required. A Boolean variable that determines whether the users are banned or reinstated.
Reason | Optional. A variant that is used if Set is TRUE to contain the reason for banishing users.
Duration | Optional. A variant that is used if Set is TRUE to indicate, in minutes, the length of time a user or users will be banned.

Remarks

This feature is reserved for administrators and system operators only. Banned users will not be able to log on to the server. Some IRC servers do not provide this feature and will return an error code.

Examples

These examples illustrate methods of using BanUsers to ban users from the server and to reinstate users to the server.

1. Ban a specific user:

Dim chatitemobj As ChatItems
Set chatitemobj = New ChatItems
chatitemobj.AssociatedType  = "Query"
chatitemobj.Item("UserName") = "RebeccaH"
chatitemobj.Item("IPAddressOp") = "EndsWith"
chatitemobj.Item("IPAddress") = ".microsoft.com"
MsChatPr1.BanUsers chatitemobj, True, "Abusive behavior"
Set chatitemobj = Nothing

2. Ban all the users with an IP address that ends with .edu, for the duration of one hour:

Dim chatitemobj As ChatItems
Set chatitemobj = New ChatItems
chatitemobj.AssociatedType  = "Query"
chatitemobj.Item("IPAddressOp") = "EndsWith"
chatitemobj.Item("IPAddress") = ".edu"
MsChatPr1.BanUsers chatitemobj, True, , 60
Set chatitemobj = Nothing

3. Stop banning the same group:

Dim chatitemobj As ChatItems
Set chatitemobj = New ChatItems
chatitemobj.AssociatedType  = "Query"
chatitemobj.Item("IPAddressOp") = "EndsWith"
chatitemobj.Item("IPAddress") = ".edu"
MsChatPr1.BanUsers chatitemobj, False
Set chatitemobj = Nothing


CancelConnectLogin Method

Cancels a Connect or Login call.

Syntax

object.CancelConnectLogin

Parameters

object Required. An object expression that evaluates to an MsChatPr control.

Remarks

This method can be called when the connection state is csConnecting or csLogging.

Example

MsChatPr1.Connect "comicsrv1.microsoft.com"
    'OnConnectionState(csConnecting) event is fired
MsChatPr1.CancelConnectLogin
MsChatPr1.Login "irc.mtv.com", "JB007", "JamesB", "James Bond"
    'OnConnectionState(csConnecting) event is fired
MsChatPr1.CancelConnectLogin
MsChatPr1.Login "irc.univ-lyon1.fr", "Vette"
    'OnConnectionState(csConnecting) event is fired
    'OnConnectionState(csLogging) event is fired
MsChatPr1.CancelConnectLogin

See Also

Connect, Login


Channels Collection Object

The Chat Protocol control Channels collection object is a standard Visual Basic collection object and uses the standard Add and Remove methods and the Item and Count properties.

This section lists the methods and properties supported by the Channels collection object.

Methods

Add, Remove

Properties

Count, Item


Methods

This section describes the methods associated with the Channels collection object.

Add Method

Remove Method


Properties

This section describes the properties associated with the Channels collection object.

Count Property

Item Property


ChangeChannelProperty Method

Asynchronously modifies a channel property.

Syntax

object.ChangeChannelProperty ChannelPropertyName, NewChannelProperty

Parameters

object | Required. An object expression that evaluates to a Channel object.
ChannelPropertyName Required. A string expression. The following table shows the valid channel property names.
IRCX | IRC/IRCX
protocol only | protocols
Account Keyword
ClientData MaxMemberCount
ClientGuid Modes
HostKey Topic
Language
Lag
OnJoin
OnPart
OwnerKey
Rating
ServicePath
Subject
NewChannelProperty | Required. A variant, the type of which depends on the new channel property.

Remarks

A successful call results in an OnChannelPropertyChanged event.

Examples

chanobj.ChangeChannelProperty "HostKey", "SecretHost"
chanobj.ChangeChannelProperty "Lag", 2
chanobj.ChangeChannelProperty "Modes", cmPublic + cmKnock + cmTopicop

See Also

enumChannelMode, OnChannelPropertyChanged


ChangeMemberProperty Method

Asynchronously changes a member property.

Syntax

object.ChangeMemberProperty MemberPropertyName, NewMemberProperty[, MemberNickname]

Parameters

object | Required. An object expression that evaluates to a Channel object.
MemberPropertyName | Required. A string expression. The only valid member property name value is "Modes".
NewMemberProperty Required. A variant. This property must represent a valid member Modes value. A valid member modes value is a combination of these enumMemberMode values:
mmClientIgnored | = &H1.
mmNotClientIgnored | = &H2.
mmOwner | = &H100.
mmNotOwner | = &H200.
mmHost | = &H400.
mmNotHost | = &H800.
mmVoice | = &H1000.
mmNoVoice | = &H2000.
MemberNickname | Optional. If specified, it must be an empty variant or a valid channel member nickname. If omitted or empty, the nickname of the caller is used.

Remarks

A successful call results in an OnMemberPropertyChanged event.

Examples

1. Change your own modes (giving up your host privileges in the channel):

chan1.ChangeMemberProperty "Modes", mmNotHost

2. Change another user's member modes (turning a member into a host):

chan1.ChangeMemberProperty "Modes", mmHost, "JamesB"

3. Ignore a member:

chan1.ChangeMemberProperty "Modes", mmClientIgnored, "AustinP"

Note You cannot ignore a channel host or owner, or a server system operator or administrator.


ChangeNickname Method

Asynchronously changes the user's Nickname.

Syntax

object.ChangeNickname NewNickname

Parameters

object | Required. An object expression that evaluates to an MsChatPr control.
NewNickname | Required. A string expression containing the user's new nickname.

Remarks

A successful call to ChangeNickname results in an OnUserPropertyChanged event.

Example

MsChatPr1.ChangeNickname "NaomiH"
'This is a shortcut for:
MsChatPr1.ChangeUserProperty "Nickname", "NaomiH"

See Also

ChangeUserProperty


ChangeUserProperty Method

Asynchronously modifies a user property.

Syntax

object.ChangeUserProperty UserPropertyName, NewUserProperty[, Nickname]

Parameters

object | Required. An object expression that evaluates to an MsChatPr control.
UserPropertyName | Required. A string that must contain one of these two valid values: "Modes" or "Nickname".
NewUserProperty | Required. A variant, the type of which depends on the new user property.
Nickname | Optional. A variant. Can be omitted or empty, in which case the call concerns the control user. Otherwise, the Nickname must be a current server user.

Remarks

This method can be used to change nicknames, user Modes, or ignore/stop ignoring other users. Callers can change only their own nickname or user modes.

A successful call to ChangeUserProperty results in an OnUserPropertyChanged event.

You cannot ignore a server system operator or administrator.

Examples

1. Change the nickname:

MsChatPr1.ChangeUserProperty "Nickname", "ElisabethH", "Moi"
'or
MsChatPr1.ChangeUserProperty "Nickname", "ElisabethH"
    'This is equivalent to MsChatPr1.ChangeNickname "ElisabethH"

2. Become invisible:

MsChatPr1.ChangeUserProperty "Modes", umInvisible

3. Give up the system operator privileges and become visible:

MsChatPr1.ChangeUserProperty "Modes", umNotSysop + umNotInvisible

4. Ignore a user:

MsChatPr1.ChangeUserProperty "Modes", umClientIgnored, "Maja"

5. Stop ignoring a user:

MsChatPr1.ChangeUserProperty "Modes", umNotClientIgnored, "Maja"

See Also

ChangeNickname


ChannelName Property

Synchronously reads or writes the Name of the channel.

Syntax

value=object.ChannelName

Parameters

value | Required. A string containing the Name of the channel.
object | Required. An object expression that evaluates to a Channel object.

Remarks

Access is read/write or read-only depending on the ChannelState value:

  • If the ChannelState is chsClosed, the property is read/write.
  • If the ChannelState is chsOpening or chsOpen, the property is read-only.
  • If the ChannelName property is set while the channel is closed, the CreateChannel and JoinChannel methods use its value if their ChannelName parameter is not specified.

After joining a channel, the ChannelName property is not necessarily the string you specified in CreateChannel, JoinChannel, or ChannelName because of the cloned channels.

For example, you could call:

MsChatPr1.Channels(1).JoinChannel "#Chat"

and, in fact, join "#Chat3", which will be the value returned by the ChannelName property.

The ChannelName property is not cleared when the user leaves the channel and the ChannelState becomes chsClosed.

The user can also synchronously get the channel Name using:

<channel>.ChannelProperty("Name")

But the ChannelName property is simpler and more efficient.

The asynchronous method of accessing the channel Name is:

<channel>.QueryChannelProperty "Name"

See Also

CreateChannel, ChannelProperty, JoinChannel, QueryChannelProperty


ChannelProperty Property

Synchronously accesses a channel property.

Syntax

value=object.ChannelProperty(ChannelPropertyName[, ChannelName])

Parameters

value | Required. An object expression that evaluates to a ChatItems object.
object | Required. An object expression that evaluates to an MsChatPr control.
ChannelPropertyName Required. A string that contains one of the valid channel property name values in the following table.
IRCX | IRC/IRCX
protocol only | protocols
Account BannedList
ClientData Keyword
ClientGuid MaxMemberCount
CloneList MemberCount
CreationTime Modes
HostKey Name
Lag Topic
Language
ObjectId
OnJoin
OnPart
OwnerKey
Rating
ServicePath
Subject
ChannelName | Optional. A string expression that can be omitted or empty if there is exactly one open channel in the collection. In this case, the call concerns that uniquely open channel. Otherwise ChannelName must be the Name of an existing channel on the server.

Remarks

Access is read-only.

If the property could not be retrieved within the number of milliseconds specified in the PropertyAccessTimeOut property, an OnChannelProperty event is fired with the requested property.

Example

Dim chatitemobj As ChatItems
Set chatitemobj = MsChatPr1.ChannelProperty("Rating", "#MyRoom")
Set chatitemobj = MsChatPr1.ChannelProperty("Modes") 'There is only one open channel
Set chatitemobj = Nothing

See Also

OnUserProperty, PropertyAccessTimeOut, QueryChannelProperty


ChannelProperty Property

Synchronously accesses a channel property.

Syntax

value=object.ChannelProperty(ChannelPropertyName)

Parameters

value | Required. An object expression that evaluates to a ChatItems object.
object | Required. An object expression that evaluates to Channel object.
ChannelPropertyName Required. A string that contains one of the valid values shown in the following table.
IRCX | IRC/IRCX
protocol only | protocols
Account BannedList
ClientData Keyword
ClientGuid MaxMemberCount
CloneList MemberCount
CreationTime Modes
HostKey Name
Lag Topic
Language
ObjectId
OnJoin
OnPart
OwnerKey
Rating
ServicePath
Subject

Remarks

Access is read-only.

When the client asks for this property, the server might return more information than was requested. Because of this, all answers are packaged into a ChatItems object and exposed to the caller.

Generally, all the information known by the client at the time of the ChannelProperty call is exposed to the caller in the ChatItems object.

The ChannelState must be chsOpen for the ChannelProperty property access to succeed.

Example

The following are asynchronous methods of accessing a channel property.

<channel>.QueryChannelProperty <ChannelPropertyName>
'and
<control>.QueryChannelProperty <ChannelPropertyName>, <ChannelName>

See Also

ChannelName, QueryChannelProperty


Channels Property

Returns the Channels collection of the control.

Syntax

value=object.Channels

Parameters

value | Required. An object expression that evaluates to a Channels object.
object | Required. An object expression that evaluates to an MsChatPr control.

Remarks

Access is read-only.

Example

Dim chancoll As Channels
Set chancoll = MsChatPr1.Channels


ChannelState Property

Returns the current channel state of the control.

Syntax

value=object.ChannelState

Parameters

value | Required. A variable of enumChannelState type.
object | Required. An object expression that evaluates to a Channel object.

Remarks

Access is read-only.

At creation, the state of a channel is chsClosed. When calling its JoinChannel or CreateChannel method, the state becomes asynchronously chsOpening and chsOpen. It becomes chsClosed again when the user leaves the channel or is kicked from the channel, or when a server disconnection occurs.

If the Channel object is removed from the collection, attempts to access any of its properties or methods will cause an occurrence of the Channels collection error 3172, "The channel is no more part of the collection."

The asynchronous channel state changes are exposed through the OnChannelState event.


ChannelTopic Property

Synchronously reads the Topic of the channel.

Syntax

value=object.ChannelTopic

Parameters

value | Required. A string expression that contains the Topic of the channel.
object | Required. An object expression that evaluates to a Channel object.

Remarks

Access is read-only.

The ChannelTopic property is not cleared when the user leaves the channel and the channel state becomes chsClosed.

The user can also synchronously get the Topic of the channel by using:

<channel>.ChannelProperty("Topic")
'or
<control>.ChannelProperty("Topic", <channelname>)

But the ChannelTopic property is simpler and more efficient.

The asynchronous methods to access the Topic of the channel are:

<channel>.QueryChannelProperty "Topic"
'and
<control>.QueryChannelProperty "Topic", <channelname>

See Also

ChannelProperty, QueryChannelProperty


Channel Object

After logging in to a chat server, the Channel object is added to the Channels collection with the Add method.

This section lists the methods and properties supported by the Channel object.

Properties

ChannelName, ChannelProperty, ChannelState, ChannelTopic, Index, MemberCount, MemberIdentity, MemberModes, MemberProperty

Methods

BanMembers, ChangeChannelProperty, ChangeMemberProperty, CreateChannel, JoinChannel, KickMember, LeaveChannel, ListMembers, QueryChannelProperty, QueryMemberProperty, SendInvitation, SendMessage


Methods

This section describes the methods associated with the Channel object.

BanMembers Method

ChangeChannelProperty Method

ChangeMemberProperty Method

CreateChannel Method

JoinChannel Method

KickMember Method

LeaveChannel Method

ListMembers Method

QueryChannelProperty Method

QueryMemberProperty Method

SendInvitation Method

SendMessage Method


Properties

This section describes the properties associated with the Channel object.

ChannelName Property

ChannelProperty Property

ChannelState Property

ChannelTopic Property

Index Property

MemberCount Property

MemberIdentity Property

MemberModes Property

MemberProperty Property


Channel Properties

The following table contains the channel properties supported by Chat Protocol Control 2.0.

Note All the properties that have a name that ends in "Op" are used for querying only and can have one of only three values: "StartsWith", "EndsWith", and "Contains".

Note RO: Read-only RW: Read/write QO: Query-only WO: Write-only

Name | Type | IRCX only | Access | Description
Account | String | Y | RW or RO | Implementation-dependent string for attaching a security account.
BannedList | Variant | N | RO | List of banned members.
ChannelAgeMax | Long | Y | QO | Used when listing channels.
ChannelAgeMin | Long | Y | QO | Used when listing channels.
ClientData | String | Y | RW or RO | Client-defined information.
ClientGuid | String | Y | RW or RO | GUID that defines the client protocol to be used within the channel.
CloneList | Variant | Y | RO | List of clone channel names created after the user joined the original channel. (See Remarks)
CreationTime | Long | Y | RO | The time that the channel was created, in number of seconds elapsed since midnight, January 1, 1970.
HostKey | String | Y | WO | The host key that will provide host access when entering the channel.
Keyword | String | N | WO | The keyword required to enter the channel.
Lag | Long | Y | RW or RO | Numeric value between 0 and 2 seconds that will add an artificial lag to any message sent from the same member within the specified lag settings.
Language | String | Y | RW or RO | The preferred language type.
LanguageOp | String | Y | QO | Used when listing channels.
ListCount | Long | Y | QO | Used when listing channels.
MaxMemberCount | Long | N | RW or RO | Maximum number of members allowed in the channel.
MemberCount | Long | N | RO | Current number of members in the channel.
MemberCountMax | Long | Y | QO | Used when listing channels.
MemberCountMin | Long | Y | QO | Used when listing channels.
Modes | Long | N | RW or RO | The channel modes (cmAuditorium, cmPrivate, and so on.)
Name | String | N | RO | The channel name.
NameOp | String | N | QO | Used when listing channels.
ObjectId | Long | Y | RO | Internal object identifier for the channel. If set to "0", this feature is not supported on the server.
OnJoin | String | Y | RW or RO | A string to be sent as a private message to a user after the user joined the channel. (See Remarks)
OnPart | String | Y | RW or RO | A string to be sent as a private message to a user after the user leaves the channel. (See Remarks)
OwnerKey | String | Y | WO | The Owner keyword that will provide owner access when entering the channel.
Rating | String | Y | RW or RO | The current PICS rating of the channel.
Registered | Boolean | Y | QO | Used when listing channels.
ServicePath | String | Y | RW or RO | The path of a server side extension that is used to control the channel operation. Details are implementation-dependent.
Subject | String | Y | RW | String that can contain subject keywords.
SubjectOp | String | Y | QO | Used when listing channels.
Topic | String | N | RW or RO | The topic of the conversation in the channel.
TopicAgeMax | Long | Y | QO | Used when listing channels.
TopicAgeMin | Long | Y | QO | Used when listing channels.
TopicOp | String | Y | QO | Used when listing channels.

Remarks

CloneList: The latest clone created has the highest index in the array of clone names. When a clone is closed, the hosts of the original channel don't get notified. Later, when the clone is recreated, it is repositioned to the end of the array of clones.

OnJoin and OnPart: The sender of the message is the channel Name. Only the user joining the channel will see this message. Multiple lines can be generated by embedding a backslash followed by the lowercase letter 'n' (\n) at the point in the string where it wraps to the next line.

See Also

Note


Member Properties

The following table contains the member properties supported by Chat Protocol Control 2.0.

Note RO: Read-only RW: Read/write QO: Query-only WO: Write-only

Name | Type | Access | Description
Identity | String | RO | Yields the user name and IP address of the member.
IPAddress | String | RO | IP address of the user. (Host name in IRC terminology.)
IPAddressOp | String | QO | Used when listing, banning, or ignoring members.
Modes | Long | RW or RO | The member modes (mmAway, mmNotClientIgnored, and so on).
Nickname | String | RO | The member's nickname.
NicknameOp | String | QO | Used when listing, banning, or ignoring members.
ObjectId | Long | RO | IRCX specific. Internal object identifier for the member. If set to "0", this feature is not supported on the server.
UserName | String | RO | The member's user name.
UserNameOp | String | QO | Used when listing, banning, or ignoring members.

See Also

Note


Object Properties

This section describes the properties associated with the Microsoft Chat Protocol 2.0.

Server, Channel, User, Member


Server Properties

The following table contains the server properties supported by Chat Protocol Control 2.0.

Note RO: Read-only RW: Read/write QO: Query-only WO: Write-only

Name | Type | Access | Description
AnonymousAllowed | Boolean | RO | Are anonymous connections allowed?
ChannelCount | Long | RO | How many open channels on the server?
IgnoredUsers | Variant: array of variants that are ChatItems objects or empty | RO | List of ignored users.
Info | Variant: array of variants that are strings or empty | RO | Information strings about the server.
MaxMessageLength | Long | RO | Maximum server message length in bytes.
Name | String | RO | Server name.
NetInvisibleCount | Long | RO | Number of invisible users on the network.
NetServerCount | Long | RO | Number of nodes on the network.
NetUserCount | Long | RO | Number of users on the network.
NodeServerCount | Long | RO | Number of node connections to this node.
NodeUserCount | Long | RO | Number of user connections to this node.
SecurityPackages | String | RO | Security packages provided by this server.
SysopCount | Long | RO | Number of system operators on this server.
UnknownConnectionCount | Long | RO | Number of users logging on to the server.


User Properties

The following table contains the user properties supported by Chat Protocol Control 2.0.

Note RO: Read-only RW: Read/write QO: Query-only WO: Write-only

Name | Type | Access | Description
Away | String | RO | Away text message.
Channels | String or variant: array of variants that are strings | QO or RO | Used when listing users or yields the channels the user is currently in.
HostInChannels | Variant | RO | Lists the channels where the user is currently a host.
Identity | String | RO | Yields the user name and IP address.
IdleTime | Long | RO | Idle time of the user in seconds.
IPAddress | String | RO | IP address of the user. (Host name in IRC terminology.)
IPAddressOp | String | QO | Used when listing, banning, or ignoring users.
Mask | String | QO | Used when listing users.
MaskOp | String | QO | Used when listing users.
Modes | Long | RW or RO | The user modes (Invisible, Sysop, and so on).
Nickname | String | RW or RO | The user's nickname.
NicknameOp | String | QO | Used when listing, banning, or ignoring users.
OwnerOfChannels | Variant: array of Variants that are Strings | RO | Lists the channels for which the user is an owner.
RealName | String | RO | The user's real name.
ServerInfo | String | RO | Some server information.
ServerName | String | RO | The server that the user is connected to.
SignOnTime | Long | RO | The time the user logged on to the server.
UserName | String | RO | The user's user name.
UserNameOp | String | QO | Used when listing, banning, or ignoring users.
VoiceInChannel | Variant: array of Variants that are strings | RO | Lists the channels where the user has a voice.

See Also

Note


Connect Method

Creates a connection between the user's computer and the server.

Syntax

object.Connect ServerName

Parameters

object | Required. An object expression that evaluates to an MsChatPr control.
ServerName | Required. A string expression that contains the ServerName. This parameter can include the socket port to be used. The port 6667 is used by default.

Remarks

A successful Connect call results in an OnConnectionState event for which the ConnectionState parameter is csConnecting. Next, an OnConnectionState event is fired for which the ConnectionState parameter is csConnected. The server properties accessible at the csConnected point are:
Name
MaxMessageLength
SecurityPackages
AnonymousAllowed
IgnoredUsers

All the other server properties can be accessed once the user is logged on.

Examples

'ServerName only, port 66667 by default
MsChatPr1.Connect "comicsrv1.microsoft.com"
'ServerName and socket port
MsChatPr1.Connect "irc.eskimo.com:6668"

See Also

Login


ConnectionState Property

Returns the current connection state of the control.

Syntax

value=object.ConnectionState

Parameters

value | Required. A variable of enumConnectionState type.
object | Required. An object expression that evaluates to an MsChatPr control.

Remarks

Access is read-only.

This property is always accessible. After successfully calling the Connect method, ConnectionState switches from csDisconnected to csConnecting to csConnected.

After successfully calling the Login method, ConnectionState switches from csConnected to csLogging to csLogged, or from csDisconnected to csConnecting to csLogging to csLogged.

When calling Disconnect, ConnectionState switches from csConnected to csDisconnecting to csDisconnected, or from csLogged to csDisconnecting to csDisconnected.

Example

Dim cs As enumConnectionState
cs = MsChatPr1.ConnectionState

See Also

Connect, Disconnect, Login


ConnectionType Property

Returns the type of connection (IRC or IRCX) established with the chat server.

Syntax

value=object.ConnectionType

Parameters

value | A variable of enumConnectionType type. The enumConnectionType is made of the values ctIRC = 0 and ctIRCX = 1.
object | Required. An object expression that evaluates to an MsChatPr control.

Remarks

Access is read-only.

If a server is an IRCX server, the control automatically switches to the IRCX mode at connection time.

The ConnectionType property is accessible as soon as the OnConnectionState event is fired after calling the Connect method, or as soon as the OnConnectionState event is fired after calling the Login method.

Example

Dim ct As enumConnectionType
ct = MsChatPr1.ConnectionType

See Also

Connect, Login, OnConnectionState


ConvertedString Property

Returns a converted version of the source string.

Syntax

value=object.ConvertedString(ConversionType, ConversionSource, Source, PostProcess)

Parameters

value | Required. A string variable to contain the converted version of the source string.
object | Required. An object expression that evaluates to an MsChatPr control.
ConversionType Required. A variable of enumConversionType type. When ConversionType is set to cvtToUTF8, the property returns the UTF8 version of the source string. The source string must be a regular Unicode BSTR.

When ConversionType is set to cvtToUnicode, the property returns the Unicode version of the source string. The source string must be a UTF8 BSTR.

ConversionSource Required. A variable of enumConversionSource type. When ConversionSource is set to cvsNormal, the source parameter can represent any string. For example, an incoming or outgoing text message or a topic can be represented by the source parameter.

When ConversionSource is set to cvsNickname, the source parameter represents a nickname.

When ConversionSource is set to cvsChannelName, the source parameter represents a channel Name.

Source | Required. A string variable. Because the IRCX protocol uses UTF8 modified strings for extended nicknames and channel names, the control exposes a method to convert strings from Unicode to UTF8 and vice-versa.
PostProcess Required. A Boolean value. When set to TRUE, the postprocessing mechanism shown in the following table is used when converting from Unicode to UTF8.
Character | Becomes string
'\0' | "\0"
'\' "\\"
'\n' | "\n"
'\r' | "\r"
'\t' | "\t"
' ' "\b"
',' "\c"

When converting from UTF8 to Unicode, the postprocessing mechanism shown in the following table is used.
String | Becomes Character
"\0" | '\0'
"\\" '\'
"\n" | '\n'
"\r" | '\r'
"\t" | '\t'
"\b" ' '
"\c" ','

Remarks

Access is read-only.

Examples

MsChatPr1.ConvertedString(cvtToUTF8, cvsNormal, "Hi Régis, how are you?", FALSE)
'returns "Hi RÃ©gis, how are you?"
MsChatPr1.ConvertedString(cvtToUnicode, cvsNormal, "TouchÃ©\c\bcoulÃ©!", TRUE)
'returns "Touché, coulé!"
MsChatPr1.ConvertedString(cvtToUTF8, cvsNickname, "The Säïnt",  TRUE)
'returns "'The\bSÃ¤Ã¯nt"
MsChatPr1.ConvertedString(cvtToUnicode, cvsNickname, "'La\bBellÃ¤\bXena", TRUE)
'returns "La Bellä Xena"
MsChatPr1.ConvertedString(cvtToUTF8, cvsChannelName, "%#Les Français parlent aux Français", TRUE)
'returns "%#Les\bFranÃ§ais\bparlent\baux\bFranÃ§ais"
MsChatPr1.ConvertedString(cvtToUnicode, cvsChannelName, "%&ZÃ»lÃ»", TRUE)
'returns "%&Zûlû"


Count Property

Accesses the number of Channel objects in the Channels collection.

Syntax

value=object.Count

Parameters

value | Required. A long integer that contains the number of Channel objects in the Channels collection.
object | Required. An object expression that evaluates to a Channels collection object.

Remarks

Access is read-only.

Examples

Dim lChannelCount As Long
lChannelCount = MsChatPr1.Channels.Count
Dim coll As Channels
Set coll = MsChatPr1.Channels
lChannelCount = coll.Channels.Count

See Also

Item


CreateChannel Method

Creates a channel on IRCX servers only.

Syntax

object.CreateChannel [ChannelName][, ChannelKeyword][, ChannelModes][, MaxMemberCount]

Parameters

object | Required. An object expression that evaluates to a Channel object.
ChannelName | Optional. A variant. If specified, must be empty or contain a valid channel Name. If the parameter is empty or not specified, the current value of the ChannelName property is used instead.
ChannelKeyword | Optional. A variant. If specified, must be empty or a string. If the parameter is empty or not specified, the channel will be created with no Keyword set.
ChannelModes Optional. A variant. If specified, must be empty or a number (integer or long) that is a valid channel Modes value. A valid ChannelModes parameter is a combination of some of the values from the enumChannelMode enumeration. The valid components of a ChannelModes value are:
cmPublic | &H0.
cmPrivate | &H1.
cmHidden | &H2.
cmSecret | &H4.
cmModerated | &H8.
cmNoExtern | &H10.
cmTopicop | &H20.
cmInvite | &H40.
cmKnock | &H80.
cmNoWhisper | &H100.
cmService | &H400.
cmAuthOnly | &H800.
cmCloneable | &H1000.
cmAuditorium | &H4000.
cmNoFormat | &H8000.
cmCreateOnly | &H10000000.

The cmPrivate, cmHidden, and cmSecret values are mutually exclusive. If the cmCreateOnly flag is set, the CreateChannel call will fail if the channel already exists. If this flag is not set, the caller will join the channel if it already exists.

If the ChannelModes parameter is empty or not specified, the channel Modes value will be defined by the server's default settings.

MaxMemberCount | Optional. A variant. If specified, the MaxMemberCount parameter must be empty or a number (integer or long) that is a valid maximum member count. If the parameter is empty or not specified, the maximum member count of the channel will be defined by the server's default settings.

Remarks

The channel state must be chsClosed for the call to succeed, and the channel must belong to the collection for the call to be successful.

A successful CreateChannel calls results in an OnChannelState event in which the channel state is chsOpening, then an OnChannelState event is fired with the channel state chsClosed or the following suite of events.
Event | Parameters
OnChannelState | (Channel, chsOpening)
OnChannelState | (Channel, chsOpen)
OnBeginEnumeration | (Channel, etInitialMembers)
OnAddMember | (Channel, Nickname, MemberItems)
OnEndEnumeration | (Channel, etInitialMembers)
OnChannelProperty | (Channel, ChannelItems)

Examples

1. Specify all the parameters:

MsChatPr1.Channels(1).CreateChannel "#MyRoom", "SecretPassword", cmTopicop +  cmCreateOnly, 20

2. Omit the ChannelKeyword and MaxMemberCount parameters:

MsChatPr1.Channels(1).CreateChannel "#MyRoom", , cmCreateOnly

3. Use empty variants:

MsChatPr1.Channels(1).CreateChannel "#MyRoom", Empty,
cmCreateOnly, Empty

See Also

ChannelName, ChannelState, enumChannelMode, JoinChannel, OnChannelState


Disconnect Method

Disconnects from the chat server.

Syntax

object.Disconnect

Parameters

object Required. An object expression that evaluates to an MsChatPr control.

Remarks

The Disconnect method can be called when the connection state is csConnected or csLogged.

A successful call results in an OnConnectionState event for which the connection state is csDisconnecting, and another OnConnectionState event for which the ConnectionState parameter is csDisconnected.

Examples

MsChatPr1.Connect "comicsrv1.microsoft.com"
    'OnConnectionState(csConnecting) event is fired
    'OnConnectionState(csConnected) event is fired
MsChatPr1.Disconnect

MsChatPr1.Login "irc.mtv.com", "JB007", "JamesB", "James Bond"
    'OnConnectionState(csConnecting) event is fired
    'OnConnectionState(csLogging) event is fired
    'OnConnectionState(csLogged) event is fired
MsChatPr1.Disconnect

See Also

Connect, Login, OnConnectionState


enumChannelMode Enumeration

Used in OnChannelProperty and OnChannelPropertyChanged events, CreateChannel, ChangeChannelProperty, and QueryChannelProperty methods, and ChannelProperty property to contain the channel mode.

Value | Description
cmNone | Value = &H0. No particular mode is set.
cmPublic | Value = &H0. The channel is public and all information about the channel (except for text messages) can be queried by nonmembers. The cmPublic mode is mutually exclusive with the cmPrivate, cmHidden, and cmSecret modes.
cmPrivate | Value = &H1. The channel is private and only the name, number of members, and PICS rating property can be queried by nonmembers. The cmPrivate mode is mutually exclusive with the cmPublic, cmHidden, and cmSecret modes.
cmHidden | Value = &H2. The channel is hidden and cannot be located through enumeration queries by nonmembers. The cmHidden mode is mutually exclusive with the cmPublic, cmPrivate, and cmSecret modes. The purpose of the new cmHidden channel mode is to permit the existence of channels that cannot be found using the standard LIST IRC command, but whose properties can be queried if the exact channel name is known. Thus a hidden channel is like a public channel except that it cannot be enumerated by using a ListChannels method call.
cmSecret | Value = &H4. The channel is secret and cannot be located by any query from nonmembers. The cmSecret mode is mutually exclusive with the cmPublic, cmPrivate, and cmHidden modes.
cmModerated | Value = &H8. Normally, new channel members may speak. In cmModerated mode, however, by default, new channel members may not speak. This is achieved by designating the no voice mode to all new members for that channel. Although the no voice mode usually has no effect, it does affect a moderated channel.
cmNoExtern | Value = &H10. Blocks messages from nonmembers to the channel. An administrator can still send a message to the channel.
cmTopicop | Value = &H20. Permits only channel owners and hosts to change the channel topic property.
cmInvite | Value = &H40. Permits only invited users to enter the channel. Only owners and hosts can issue an invitation when this mode is on.
cmKnock | Value = &H80. The cmKnock extended mode causes an OnKnock event to be fired for owners and hosts of the channel if a user attempts to join a channel and is denied entrance by the server.
cmNoWhisper | Value = &H100. Prevents whisper messages from being sent to the channel.
cmRegistered | Value = &H200. The channel is registered by the administrator of the chat network. The registration procedure is not defined here and is implementation-dependent. Only the server or administrator can set this mode.
cmService | Value = &H400. A service is monitoring/controlling the channel. This is an indication to the client that message traffic sent to the channel is being monitored by a chat service that does not appear as a member in the channel. The cmService flag can be set only by the chat server.
cmAuthOnly | Value = &H800. Permits channel access only to users who have been authenticated by the server. Note that an authenticated user is any user who was successfully authenticated by the Password parameter or SecurityPackages parameter during the Login method.
cmCloneable | Value = &H1000. Defines a channel that creates new clone channels if the parent channel is full. A clone channel is created with the same name as the parent cloneable channel with a numeric suffix starting at 1 and ranging to 99. It is not valid to set the cmCloneable channel mode of a parent channel that ends with a numeric character. The clone channel inherits modes and properties from the parent channel when it is set up. When a clone channel is created, any channel that has the same name is removed. This prevents channel takeover of a clone channel. It is advised that only administrators be allowed to set cmCloneable mode on a channel.
cmClone | Value = &H2000. Defines a channel that was created by the server when a parent cloneable channel becomes full. Users should usually join the parent channel, although a user can join a clone channel that is not full. Only the server can set up a clone channel and set this mode.
cmAuditorium | Value = &H4000. Restricts visibility and messaging within a channel. Members will only see themselves and the hosts/owners in the channel. Any message sent by a member will be received only by the hosts and owners. Hosts and owners will see all members in the channel. Messages from a host or owner are seen by all channel members. Ordinary members will not receive OnAddMember and OnDelMember events for other members. This mode is designed for channels with such a large membership that the members do not want to see each other.
cmNoFormat Value = &H8000. Indicates to the client application not to format text received from the channel. Normally, clients will prefix text messages with "x said y" or "x whispers to y and x". If the cmNoFormat mode is set, just the raw text is displayed, wrapping to the next line at the end of the message. The client should not echo text sent by the client. This is to permit custom applications to control the formatting to clients.

Because cmNoFormat is a channel mode and could be abused by the channel host, clients may want to inform users that messages can be spoofed or imitated with this mode. With MIC 2.0, only the administrator can enable this mode on persistent channels. This is the IRCX +f channel mode. The concept does not exist on other IRC servers. Clients can choose to ignore the flag.

cmCreateOnly | Value = &H10000000. Only used in a CreateChannel call. If set, the channel is opened only if it does not yet exist.


enumChannelState Enumeration

OnChannelState event and ChannelState property values.

Value | Description
chsClosed | Value = 0. The state of a channel when created. It becomes chsClosed again when the user leaves the channel or is kicked from the channel, or when a server disconnection occurs.
chsOpening | Value = 1. When calling its JoinChannel or CreateChannel method, the state becomes asynchronously chsOpening and chsOpen.
chsOpen | Value = 2. When calling its JoinChannel or CreateChannel method, the state becomes asynchronously chsOpening and chsOpen.


enumConnectionState Enumeration

OnConnectionState event and ConnectionState property values.

Value | Description
csDisconnected | Value = 0. Used to indicate that the connection state of the channel is currently disconnected.
csConnecting | Value = 1. Used to indicate that the connection state of the channel is currently in the process of connecting.
csConnected | Value = 2. Used to indicate that the connection state of the channel is currently connected.
csLogging | Value = 3. Used to indicate that the connection state of the channel is currently in the process of logging.
csLogged | Value = 4. Used to indicate that the connection state of the channel is currently logged.
csDisconnecting | Value = 5. Used to indicate that the connection state of the channel is currently in the process of disconnecting.


enumConnectionType Enumeration enumConnectionType Enumeration *
  * Previous Topic: enumConnectionState Enumeration
  * Next Topic: enumConversionSource Enumeration

enumConnectionType Enumeration

ConnectionType property value.

Value | Description
ctIRC | Value = 0. For IRC connections.
ctIRCX | Value = 0. For IRCX connections.


enumConversionSource Enumeration

ConvertedString property access.

Value | Description
cvsNormal | Value = 0. For regular text.
cvsNickname | Value = 1. For user nicknames.
cvsChannelName | Value = 2. For channel names.


enumConversionType Enumeration

ConvertedString property access.

Value | Description
cvtToUTF8 | Value = 0. Used to convert to UTF8 format.
cvtToUnicode | Value = 1. Used to convert to Unicode format.


enumEnumType Enumeration

OnBeginEnumeration and OnEndEnumeration events parameter.

Value | Description
etMessageOfTheDay | Value = 0. Used when exposing the message of the day at login.
etUsers | Value = 1. Used when listing users with the ListUsers method.
etChannels | Value = 2. Used when listing channels with the ListChannels method.
etChannelsTruncated | Value = 3. Used when channel listing is truncated during a ListChannels call.
etMembers | Value = 4. Used when listing members with the ListMembers method.
etInitialMembers | Value = 5. Used when initial channel members are exposed when joining a channel.


enumMemberMode Enumeration

Used in OnMemberProperty and OnMemberPropertyChanged events, QueryMemberProperty and ChangeMemberProperty methods, and MemberProperty and MemberModes properties.

Value | Description
mmNone | Value = &H0. No specific member mode is set.
mmClientIgnored | Value = &H1. At the client level, incoming messages from specific members will be ignored and not exposed by an OnMessage event. This is ignoring at the client level, not the server level.
mmNotClientIgnored | Value = &H2. At the client level, incoming messages from specific members will not be ignored and will be exposed by an OnMessage event.
mmAuthMember | Value = &H4. The member was authenticated by the server by the use of a password or authentication package.
mmNotAuthMember | Value = &H8. The member was not authenticated by the server.
mmAway | Value = &H10. The member has an away text message, and the away flag is set.
mmNotAway | Value = &H20. The member does not have an away text message, and the away flag is not set.
mmSysop | Value = &H40. The member is a system operator.
mmNotSysop | Value = &H80. The member is not a system operator.
mmOwner | Value = &H100. The member is an owner of the channel.
mmNotOwner | Value = &H200. The member is not an owner of the channel.
mmHost | Value = &H400. The member is a host of the channel.
mmNotHost | Value = &H800. The member is not a host of the channel.
mmVoice | Value = &H1000. The member is able to speak even if the channel is moderated.
mmNoVoice | Value = &H2000. The member cannot speak if the channel is moderated.


enumMessageType Enumeration

Used in OnMessage event and SendMessage method parameters.

Value | Description
msgtNormal | Value = &H0. Sends a regular text message to the channel.
msgtNotice | Value = &H1. Similar to msgtNormal, but the client does not expect an answer from the recipient(s).
msgtData | Value = &H2. IRCX servers only. Sends data instead of text.
msgtDataRequest | Value = &H4. IRCX servers only. Similar to msgtData except the sender expects a msgtDataReply response from the recipient(s).
msgtDataReply | Value = &H8. IRCX servers only. Similar to msgtData except the sender does not expect a reply.
msgtDataRaw | Value = &H10. IRCX servers only. Sends raw bytes to the server without using an internal message header. This flag must be combined with msgtData, msgtDataRequest, or msgtDataReply.
msgtWhisper | Value = &H20. Used to whisper to some channel members instead of sending out to the entire channel. The recipients receive the whole list of recipients.
msgtThought | Value = &H40. Incoming messages only. Indicates that the message is a thought.
msgtAction | Value = &H80. Sends an action CTCP.
msgtSound | Value = &H100. Sends a sound CTCP.
msgtCTCP | Value = &H200. Sends a regular CTCP.
msgtInfo | Value = &H400. Incoming messages from Microsoft Chat Control 1.1 only. Used to indicate what kind of visual character and what type of gesture to display.


enumPrivateMessageType Enumeration

Used in the OnPrivateMessage event and the SendPrivateMessage method parameters.

Value | Description
pmtNormal | Value = &H0. Used in the OnPrivateMessage event and the SendPrivateMessage method to send a regular text message.
pmtNotice | Value = &H1. Sends a regular text message to the users, like pmtNormal, but the client does not expect an answer from the recipients.
pmtData | Value = &H2. Can be used only on IRCX servers. Sends data instead of text.
pmtDataRequest | Value = &H4. Can be used only on IRCX servers. Sends data instead of text, like pmtData, but the sender expects a pmtDataReply reply from the recipient(s).
pmtDataReply | Value = &H8. Can be used only on IRCX servers. Similar to pmtData, but the sender does not want a reply from the recipient(s).
pmtDataRaw | Value = &H10. Can be used only on IRCX servers. Sends raw bytes to the server without using an internal message header. This flag must be combined with pmtData, pmtDataRequest, or pmtDataReply.
pmtAway | Value = &H20. For incoming away messages.
pmtVersion | Value = &H40. Requests or sends version information.
pmtLagTime | Value = &H80. Requests or gets the lag time with a user or users.
pmtLocalTime | Value = &H100. Requests or gets the local time of a user or users.
pmtAction | Value = &H200. Sends or receives an action CTCP (Client to Client Protocol) to a user or users.
pmtSound | Value = &H400. Sends or receives a sound CTCP to a user or users.
pmtCTCP | Value = &H800. Sends or receives a regular CTCP to a user or users.
pmtInfo | Value = &H1000. Same as msgtInfo, used to indicate what kind of avatar and what type of gesture to display.


Enumerations

This section describes the enumerations supported by the Chat Protocol Control 2.0.

enumChannelMode, enumChannelState, enumConnectionState, enumConnectionType, enumConversionSource, enumConversionType, enumEnumType, enumMemberMode, enumMessageType, enumPrivateMessageType, enumServerMessageType, enumStringType, enumUserMode

Note Microsoft Visual Basic 4.0 does not support the use of enumerations as variable types.


enumServerMessageType Enumeration

OnServerTextMessage event parameter.

Value | Description
smtNormal | Value = &H0. Used for regular incoming server messages.
smtNotice | Value = &H1. Used for incoming NOTICE message from the server.
smtMessageOfTheDay | Value = &H2. Used for the message of the day incoming text at login time.
smtServerInfo | Value = &H3. Used for server information messages.
smtError | Value = &H4. Used for incoming server error messages.


enumStringType Enumeration

MaxStringLength property access.

Value | Description
stServerMessage | Value = 1. Used when querying the maximum length of the incoming and outgoing server messages.
stChannelAccount | Value = 2. Used when querying the maximum length of the incoming and outgoing channel Account properties.
stChannelClientData | Value = 3. Used when querying the maximum length of the incoming and outgoing channel ClientData properties.
stChannelHostKey | Value = 4. Used when querying the maximum length of the incoming and outgoing channel HostKey properties.
stChannelKeyword | Value = 5. Used when querying the maximum length of the incoming and outgoing channel Keyword properties.
stChannelLanguage | Value = 6. Used when querying the maximum length of the incoming and outgoing channel Language properties.
stChannelName | Value = 7. Used when querying the maximum length of the incoming and outgoing channel Name properties.
stChannelOnJoin | Value = 8. Used when querying the maximum length of the incoming and outgoing channel OnJoin properties.
stChannelOnPart | Value = 9. Used when querying the maximum length of the incoming and outgoing channel OnPart properties.
stChannelOwnerKey | Value = 10. Used when querying the maximum length of the incoming and outgoing channel OwnerKey properties.
stChannelRating | Value = 11. Used when querying the maximum length of the incoming and outgoing channel Rating properties.
stChannelSubject | Value = 12. Used when querying the maximum length of the incoming and outgoing channel Subject properties.
stChannelTopic | Value = 13. Used when querying the maximum length of the incoming and outgoing channel Topic properties.


enumUserMode Enumeration

Used in the OnUserProperty, OnUserPropertyChanged, OnInvitation, and OnKnock events, the QueryUserProperty and ChangeUserProperty methods, and the UserProperty property.

Value | Description
umNone | Value = &H0.
umClientIgnored | Value = &H1. The user is ignored by the caller.
umNotClientIgnored | Value = &H2. The user is not ignored by the caller.
umAuthUser | Value = &H4. The user is authenticated.
umNotAuthUser | Value = &H8. The user is not authenticated.
umAway | Value = &H10. The user is currently away.
umNotAway | Value = &H20. The user is not currently away.
umSysop | Value = &H40. The user is a system operator.
umNotSysop | Value = &H80. The user is not a system operator.
umAdmin | Value = &H100. The user is an administrator.
umNotAdmin | Value = &H200. The user is not an administrator.
umInvisible | Value = &H400. The user is invisible.
umNotInvisible | Value = &H800. The user is not invisible.
umNotices | Value = &H1000. The user accepts server notices.
umNoNotices | Value = &H2000. The user does not receive server notices.
umWallops | Value = &H4000. The user receives wallops. A wallops is an IRC feature that will send a message to all operators online that have +w set on their user mode. Different IRC servers have various restrictions on who can send and read wallops.
umNoWallops | Value = &H8000. The user does not receive wallops.


Error Codes

The following lists contain the error codes supported by Chat Protocol Control 2.0 and the associated error messages. These error messages are subject to change and may not be exactly as they appear here.

Access Rights-Related, Channel-Related, Channels Collection-Related, ChatItems-Related, Connection-Related, Generic, Login-Related, Member-Related, Property-Related, Protocol-Related, Sending-Related, User-Related

Access Rights-Related Errors

Value | Description
3140 | Only a system operator can perform this operation.
3141 | You are not an owner of the channel '<ChannelName>'.
3142 | You are not a host in the channel '<ChannelName>'.
3143 | You don't have the rights to view this content.
3144 | You are banned from this channel '<ChannelName>'.
3145 | You are banned from this server.
3146 | You will be banned.
3147 | You cannot ignore a system operator or your channel host, or owner.
3148 | You cannot join a MIC-only channel with IRCX client.
3149 | You cannot join this channel from a remote server.
3150 | You cannot join dynamic channels due to admin restriction.
3151 | You cannot create dynamic channels due to admin restriction.
3152 | Only authenticated users may join this channel '<ChannelName>'.
3153 | The listing is too large and is aborted.

Channel-Related Errors

Value | Description
3060 | The channel is already open.
3061 | The channel is already opening.
3062 | The channel is not open.
3063 | The channel is not closed.
3064 | There is not exactly one open channel.
3065 | The channel Name is invalid.
3066 | The channel Topic is invalid.
3067 | The Keyword is invalid for channel '<ChannelName>'.
3068 | The channel HostKey is invalid.
3069 | The channel OwnerKey is invalid.
3070 | The channel Modes parameter is invalid.
3071 | The channel MaxMemberCount parameter is invalid.
3072 | The channel '<ChannelName>' is full.
3073 | You cannot join channel '<ChannelName>' because too many channels are already open.
3074 | You are not in the channel '<ChannelName>'.
3075 | The member '<Nickname>' is already in the channel '<ChannelName>'.
3076 | The channel '<ChannelName>' does not exist.
3077 | You need an invitation to join this channel '<ChannelName>'.
3078 | The key for this channel '<ChannelName>' has already been set.

Channels Collection-Related Errors

Value | Description
3170 | The channel index specified is invalid.
3171 | The channel index specified is out of bounds.
3172 | The channel is no more part of the collection.
3173 | The channel key specified is invalid.
3174 | The channel key specified is not unique.

ChatItems-Related Errors

Value | Description
3160 | This property is not available.
3161 | This property cannot be used in this context.
3162 | The associated type is invalid.
3163 | This property name is invalid.
3164 | A property value is invalid.
3165 | Unknown query operator.
3166 | A time-out condition occurred.

Connection-Related Errors

Value | Description
3020 | You are already connecting to a server.
3021 | You are already connected to a server.
3022 | You are already disconnecting from the server.
3023 | There is no operation in progress to be canceled.
3024 | You must disconnect first before logging on to that server.
3025 | You are not connected to a server.
3026 | The server could not be found.
3027 | Could not connect to the server.
3028 | Could not connect to the server.
3029 | A connection error occurred.
3030 | The connection to the server was lost.
3031 | The connection to the server was lost.
3032 | The server network is down.
3033 | The server dropped the connection.

Generic Errors

Value | Description
5 | Illegal function call.
6 | Overflow error.
7 | Out of memory. Please close some applications and try again.
70 | You don't have the right privileges to perform this command.
380 | Invalid property value.
382 | Property is read-only at run time.
383 | Property is read-only.
394 | Property is write-only.
3000 | An error occurred. Please leave the application and try again.
3001 | You specified an invalid argument.

Login-Related Errors

Value | Description
3040 | You are already logging on to a server.
3041 | You are already logged on to the server.
3042 | You are not logged on to a server.
3043 | You are already registered on the server.
3044 | You are not registered on the server.
3045 | The SecurityPackages parameter is invalid.
3046 | The login failed.
3047 | The authentication failed.
3048 | The authentication is not available.
3049 | Only authenticated users can login.

Member-Related Errors

Value | Description
3090 | The member '<Nickname>' does not exist in channel '<ChannelName>'.
3091 | The member modes parameter is invalid.

Property-Related Errors

Value | Description
3080 | The property name you specified for the object '<ObjectName>' is invalid.
3081 | The property value you specified for the object '<ObjectName>' is invalid.
3082 | This property is not readable.
3083 | This property is read-only.
3084 | This property is not writeable.

Protocol-Related Errors

Value | Description
3130 | A server error occurred.
3131 | This operation can only be performed when connected to an IRCX server.
3132 | The mode specified is unknown.
3133 | The server could not open the MOTD file.
3134 | This feature is not implemented on this chat server.

Sending-Related Errors

Value | Description
3110 | The message you are trying to send is too large.
3111 | Couldn't send the message to the channel '<ChannelName>'.
3112 | The recipient list is invalid.
3113 | The reason parameter is invalid.
3114 | The Away message parameter is invalid.
3115 | You cannot send an empty message.
3116 | The message type is invalid.
3117 | You are not allowed to whisper in the channel '<ChannelName>'.
3118 | The data tag is invalid.

User-Related Errors

Value | Description
3100 | The nickname parameter is invalid.
3101 | The user name parameter is invalid.
3102 | The real name parameter is invalid.
3103 | The password parameter is invalid or wrong.
3104 | The nickname '<Nickname>' is already in use.
3105 | There was a nickname collision for '<Nickname>'.
3106 | There is no user with the nickname '<Nickname>'.
3107 | The user modes parameter is invalid.
3108 | You are trying to change your nickname too quickly.
3109 | Nickname changes are not permitted at this time, try again later.


IgnoreUsers Method

Allows the caller to ignore or stop ignoring users.

Syntax

object.IgnoreUsers UserItems, Set

Parameters

object | Required. An object expression that evaluates to an MsChatPr control.
UserItems Required. An object expression that evaluates to a ChatItems object. Allows the caller to set criteria on the user's Nickname, UserName, or IPAddress. The item names that can be used to construct the ChatItems object are:
Nickname
NicknameOp
UserName
UserNameOp
IPAddress
IPAddressOp
Set | Required. A Boolean value used to indicate if a user should be ignored. If set to TRUE, the user is ignored. If set to FALSE, the user is no longer ignored.

Remarks

Ignoring a user means that the caller will no longer receive private messages from the ignored user.

Administrators and system operators are never ignored, even if the caller ignores a group of users that includes an administrator or system operator.

The IgnoredUsers server property returns the list of ignored users in the form of an array of ChatItems objects and is updated each time the user calls the IgnoreUsers method.

Examples

1. Ignore one specific user:

Dim chatitemobj As ChatItems
Set chatitemobj = New ChatItems
chatitemobj.AssociatedType  = "Query"
chatitemobj.Item("Nickname") = "Justin"
chatitemobj.Item("UserName") = "ArthurB"
chatitemobj.Item("IPAddress") = "foo.microsoft.com"
MsChatPr1.IgnoreUsers chatitemobj, True
Set chatitemobj = Nothing

2. Ignore all the users with an IP address that ends with .edu:

Dim chatitemobj As ChatItems
Set chatitemobj = New ChatItems
chatitemobj.AssociatedType  = "Query"
chatitemobj.Item("IPAddressOp") = "EndsWith"
chatitemobj.Item("IPAddress") = ".edu"
MsChatPr1.IgnoreUsers chatitemobj, True
Set chatitemobj = Nothing

3. Stop ignoring the same group:

Dim chatitemobj As ChatItems
Set chatitemobj = New ChatItems
chatitemobj.AssociatedType  = "Query"
chatitemobj.Item("IPAddressOp") = "EndsWith"
chatitemobj.Item("IPAddress") = ".edu"
MsChatPr1.IgnoreUsers chatitemobj, False
Set chatitemobj = Nothing

4. Stop ignoring everybody:

Dim vIgnoredUsers As Variant
Dim chatitemobj As ChatItems
Dim iIndex As Integer
Set chatitemobj = MsChatPr1.ServerProperty("IgnoredUsers")
If (chatitemobj.ItemValid("IgnoredUsers")) Then
    vIgnoredUsers = chatitemobj.Item("IgnoredUsers")
    If (Not IsEmpty(vIgnoredUsers)) Then
        For iIndex = LBound(vIgnoredUsers) To UBound(vIgnoredUsers)
        MsChatPr1.IgnoreUsers vIgnoredUsers(iIndex), False
        Next iIndex
    End If
End If
Set chatitemobj = Nothing


Index Property

Uniquely identifies the Channel object in the Channels collection.

Syntax

value=object.Index

Parameters

value | Required. A long integer that will receive the index of the Channel object.
object | Required. An object expression that evaluates to a Channel object.

Remarks

Access is read-only.

The index of a channel is not fixed; it can vary during the lifetime of the object. If a channel with a smaller index is removed from the collection, the index is decremented. If a channel with a smaller or equal index is added to the collection, the index is incremented.

Example

Dim lIndex As Long
Set c=MsChatPr1.Channels.Add(1, "Key1")
lIndex=chanobj.Index    'lIndex now contains 1
MsChatPr1.Channels.Add 1, "Key2"
lIndex=chanobj.Index    'lIndex now contains 2

See Also

Add, Item, Remove


InvalidateItem

Removes an item previously set in the object with the Item property.

Syntax

object.InvalidateItem(ItemName)

Parameters

object | Required. An object expression that evaluates to a ChatItems object.
ItemName | Required. A string expression.


Item Property

Accesses a channel in the collection. This is the default property of the Channels collection.

Syntax

value=object.Item[(Index)]

Parameters

value | Required. An object expression that evaluates to a Channel object.
object | Required. An object expression that evaluates to a Channels collection object.
Index Optional. A variant. The channel index is 1-based. If no Index parameter is specified or if it is an empty variant, the channel with the highest index is returned by the Item property.

The Index parameter can also be a string that represents the unique channel key specified at creation time in the Add method.

Remarks

Access is read-only.

Because Item is the default property of the Channels collection, the keyword "Item" can be omitted.

Examples

MsChatPr1.Channels.Add 1, "One"
MsChatPr1.Channels.Add 2, "Two"
MsChatPr1.Channels.Add 3, "Three"
MsChatPr1.Channels.Add 4, "Four"
Dim c As Channel
Set c = MsChatPr1.Channels.Items(4)
    'is equivalent to
Set c = MsChatPr1.Channels(4)
    'is equivalent to
Set c = MsChatPr1.Channels("Four")
    'is equivalent to
Set c = MsChatPr1.Channels.Item
Dim coll As Channels
Dim chan1, chan2 As Channel
Set coll = MsChatPr1.Channels
Set chan1 = coll.Add(1, "Foo")
Set chan2 = coll.Item(1)

See Also

Add


Item Property

Reads or writes an item in the object.

Syntax

object.Item(ItemName)=value

Parameters

object | Required. An object expression that evaluates to a ChatItems object.
ItemName | Required. A string expression.
value | Required. A variant that can be a string, number, or array of variants.

Remarks

Access is read/write.

The number of items set in a ChatItems object is unlimited. Items with a given name are unique in the object. An Item that was previously set can be overwritten by setting a new Item with the same ItemName.

Example

Dim chatitemobj as ChatItems
Set chatitemobj = New ChatItems
chatitemobj.AssociatedType = "Query"
chatitemobj.Item("Name") = "#Room"
chatitemobj.Item("Name") = "#Rhum"  'the last assignment is kept

See Also

AssociatedType


ChatItems Object

The Chat Protocol control supports sophisticated querying through the ChatItems object. These queries relate to the Server, Channel, a Member, or a User. Usually the information provided by the server is exposed to the developer through the ChatItems object.

This section lists the properties and method supported by the ChatItems object.

Properties

AssociatedType, Item, ItemValid, ValidItems

Method

InvalidateItem


Method

This section describes the method associated with the ChatItems object.

InvalidateItem


Properties

This section describes the properties associated with the ChatItems object.

AssociatedType Property

Item Property

ItemValid Property

ValidItems Property


ItemValid Property

Determines if a specific ItemName is valid in the object.

Syntax

value=object.ItemValid(ItemName)

Parameters

value | Required. A Boolean variable that determines if an ItemName is valid.
object | Required. An object expression that evaluates to a ChatItems object.
ItemName | Required. A string expression.

Remarks

Access is read-only.

Examples

The OnServerProperty event has a ServerItems parameter that is a ChatItems object. This event occurs in the following example:

MsChatPr1.QueryServerProperty "Info"

To extract the data attached to the "Info" ItemName, the following example is valid, given that the "Info" property is an array of strings.

If(ServerItems.ItemValid("Info")) Then
    Dim vInfo As Variant
    Dim strInfo As String
    Dim iIndex As Integer
    vInfo = ServerItems.Item("Info")
    strInfo = " "
    If(Not IsEmpty(vInfo)) Then
        For iIndex = LBound(vInfo) To UBound(vInfo)
            strInfo = strInfo + "<" + CStr(vInfo(iIndex)) + ">"
        Next iIndex
    End If
End If

See Also

Item, ValidItems


JoinChannel Method

Allows the user to join an existing channel or create a new channel.

Syntax

object.JoinChannel [ChannelName][, ChannelKeyword]

Parameters

object | Required. An object expression that evaluates to a Channel object.
ChannelName | Optional. A variant that contains the Name of the channel. If specified, the ChannelName variant must be empty or a string that is a valid channel Name. If the parameter is empty or not specified, the current value of the ChannelName property is used instead.
ChannelKeyword | Optional. A variant. If specified, this variant must be empty or a string. If the parameter is empty or not specified, the control tries to join the channel without using a Keyword.

Remarks

The channel state must be chsClosed for the call to succeed, and the channel must belong to the collection for the call to be successful.

A JoinChannel call results in the same kind of events as a CreateChannel call.

At creation time, the state of the created channel is chsClosed. Then, when calling its JoinChannel or CreateChannel method, the state becomes asynchronously chsOpening and chsOpen. It becomes chsClosed again when the user leaves the channel or is kicked from the channel, or when a server disconnection occurs.

Example

'Specifies the ChannelName and ChannelKeyword
MsChatPr1.Channels(lIndex).JoinChannel "#MyRoom", "SecretPassword"
'Specifies only the ChannelName
MsChatPr1.Channels(lIndex).JoinChannel "#MyRoom"

See Also

ChannelName, ChannelState, enumChannelState, OnChannelState, OpeningChannels


KickMember Method

Kicks a member from the channel.

Syntax

object.KickMember MemberNickname[, Reason]

Parameters

object | Required. An object expression that evaluates to a Channel object.
MemberNickname | Required. A string expression that must be a valid member nickname from the channel.
Reason | Optional. A string expression containing the reason for kicking the user from the channel.

Example

MsChatPr1.Channels(2).KickMember "WadeR", "Bad behavior!"
chan11.KickMember "WadeR"

See Also

Nickname, OnMemberKicked


KickUser Method

Disconnects a user from the server.

Syntax

object.KickUser Nickname[, Reason]

Parameters

object | Required. An object expression that evaluates to an MsChatPr control.
Nickname | Required. A string expression that contains an existing user Nickname.
Reason | Optional. Can be an empty value or a string containing the reason for user disconnection.

Remarks

This feature is reserved for administrators and system operators only.

Examples

MsChatPr1.KickUser "Rousseau", "You talk too much!"
MsChatPr1.KickUser "Voltaire"


KillChannel Method

Terminates a channel on the server.

Syntax

object.KillChannel ChannelName[, Reason]

Parameters

object | Required. An object expression that evaluates to an MsChatPr control.
ChannelName | Required. A string expression that must be an existing channel Name.
Reason | Optional. Can be empty, missing, or a string containing the reason for channel termination.

Remarks

The caller must be an administrator or system operator to successfully perform this operation.

All channel members are kicked out of the channel and the channel is closed.

Examples

MsChatPr1.KillChannel "#TheirChannel"
MsChatPr1.KillChannel "#BadChannel", "Bad language is used in this channel."


LeaveChannel Method

Closes the current channel.

Syntax

object.LeaveChannel

Parameters

object Required. An object expression that evaluates to a Channel object.

Remarks

The channel state must be chsOpen for the call to be successful.

Leaving a channel does not remove it from the Channels collection. The user can reuse the same Channel object to join and leave several channels sequentially.

A successful LeaveChannel call results in an OnChannelState event.

Example

MsChatPr1.Channels(iIndex).LeaveChannel

See Also

JoinChannel


ListChannels Method

Lists channels on the chat server.

Syntax

object.ListChannels ChannelQueryItems

Parameters

object | Required. An object expression that evaluates to an MsChatPr control.
ChannelQueryItems | Required. An object expression that evaluates to a ChatItems object.

Remarks

The ChannelQueryItems parameter can restrict the listing to a subset of channels.

The IRC protocol is limited to listing all the server channels or only one specific channel. On an IRC server, the valid item name for ChannelQueryItems is "Name".

For an IRCX server, the valid item names are listed in the following table.

See Note for an explanation of the "Op" endings.
Item name | Type | Usage
Name | String | Sets listing criteria based on the name of the channel.
NameOp | String | Sets listing criteria based on the name of the channel.
Topic | String | Sets listing criteria based on the topic of the channel.
TopicOp | String | Sets listing criteria based on the topic of the channel.
Language | String | Sets listing criteria based on the language of the channel.
LanguageOp | String | Sets listing criteria based on the language of the channel.
Subject | String | Sets listing criteria based on the subject of the channel.
SubjectOp | String | Sets listing criteria based on the subject of the channel.
ChannelAgeMax | Long | Sets listing criteria based on the creation time of the channel.
ChannelAgeMin | Long | Sets listing criteria based on the creation time of the channel.
ListCount | Long | Limits the number of listed channels to a certain value.
MemberCount | Long | Sets listing criteria based on the member count of the channel.
MemberCountMax | Long | Sets listing criteria based on the member count of the channel.
MemberCountMin | Long | Sets listing criteria based on the member count of the channel.
TopicAgeMax | Long | Sets listing criteria based on the latest topic change of the channel.
TopicAgeMin | Long | Sets listing criteria based on the latest topic change of the channel.
Registered | Boolean | Limits the listed channels to registered channels only.

The channels are filtered depending on their PICS rating and the user's ratings settings. For example, if the user cannot view unrated content, the ListChannels call fails on an IRC connection or shows only the rated channels on an IRCX connection. If the user has some specific PICS ratings settings, only the channels that are appropriately rated are exposed to the user.

A successful ListChannels call results in a succession of events. First, an OnBeginEnumeration event to mark the beginning of the channel listing is fired. Then, one OnChannelProperty event for each channel listed transpires and the ChannelItems parameter exposes all the known channel properties. Finally, an OnEndEnumeration with the etChannels parameter event is fired to mark the end of the channel listing.

If a listing is stopped because of a limitation set by the ListCount item, an OnEndEnumeration with the etChannelsTruncated parameter event is fired instead.

The IRC protocol is limited to listing all the server channels or only one specific channel.

Examples

1. On an IRC/IRCX server:

'List all the channels:
Dim chatitemobj As ChatItems
Set chatitemobj = New ChatItems
chatitemobj.AssociatedType = "Query"
MsChatPr1.ListChannels chatitemobj
Set chatitemobj = Nothing
'List one specific channel:
Dim chatitemobj As ChatItems
Set chatitemobj = New ChatItems
chatitemobj.AssociatedType = "Query"
chatitemobj.Item("Name") = "#Comic_Chat"
MsChatPr1.ListChannels chatitemobj
Set chatitemobj = Nothing

2. On an IRCX server, list all the channels that have been created in the last hour, and limit the listing to 100 channels:

Dim chatitemobj As ChatItems
Set chatitemobj = New ChatItems
chatitemobj.AssociatedType = "Query"
chatitemobj.Item("ChannelAgeMax") = 60
chatitemobj.Item("ListCount") = 100
MsChatPr1.ListChannels chatitemobj
Set chatitemobj = Nothing

3. On an IRCX server, list all the channels that have between 10 and 50 members, in which the Topic includes the word "Corvette":

Dim chatitemobj As ChatItems
Set chatitemobj = New ChatItems
chatitemobj.AssociatedType = "Query"
chatitemobj.Item("MemberCountMin") = 10
chatitemobj.Item("MemberCountMax") = 50
chatitemobj.Item("TopicOp") = "Contains"
chatitemobj.Item("Topic") = "Corvette"
MsChatPr1.ListChannels chatitemobj
Set chatitemobj = Nothing

4. On an IRCX server, list all the registered channels that start with "#F" and have a Language property that contains "FR":

Dim chatitemobj As ChatItems
Set chatitemobj = New ChatItems
chatitemobj.AssociatedType = "Query"
chatitemobj.Item("Registered") = True
chatitemobj.Item("NameOp") = "StartsWith"
chatitemobj.Item("Name") = "#F"
chatitemobj.Item("LanguageOp") = "Contains"
chatitemobj.Item("Language") = "FR"
MsChatPr1.ListChannels chatitemobj
Set chatitemobj = Nothing

5. On an IRCX server, list all the channels that have "real estate" in their Subject property:

Dim chatitemobj As ChatItems
Set chatitemobj = New ChatItems
chatitemobj.AssociatedType = "Query"
chatitemobj.Item("SubjectOp") = "Contains"
chatitemobj.Item("Subject") = "real estate"
MsChatPr1.ListChannels chatitemobj
Set chatitemobj = Nothing


ListMembers Method

Lists the members of the channel.

Syntax

object.ListMembers MemberQueryItems

Parameters

object Required. An object expression that evaluates to a Channel object.
MemberQueryItems Required. An object expression that evaluates to a ChatItems object.

The MemberQueryItems parameter is currently unused. It is present for backward compatibility in the future.

Remarks

Future releases of the protocol might include some method of narrowing the member listing. In this case the MemberQueryItems parameter would come into use. Currently neither the IRC nor the IRCX protocols offer any member-listing criteria.

Example

Dim mqi As ChatItems
chan.ListMembers mqi

See Also

OnMemberProperty, QueryMemberProperty


ListUsers Method

Lists users on the server.

Syntax

object.ListUsers UserQueryItems

Parameters

object Required. An object expression that evaluates to an MsChatPr control.
UserQueryItems Required. An object expression that evaluates to a ChatItems object. Restricts the user listing to a subset of users. The following table lists the item names that can be used to construct the ChatItems object.
IRC/IRCX | IRCX
protocols | protocol only
Channels IPAddress
Mask IPAddressOp
MaskOp
Nickname
NicknameOp

Remarks

The caller can set criteria on the user's nickname, IP address, or channel. Also, when using the Mask and optionally the MaskOp item names, the user can list the users for which the nickname, IP address, server name, real name, or channel name matches the mask given.

When using the Mask and optionally the MaskOp item names, the call maps to a WHO command; otherwise, it maps to a WHOIS command.

A successful ListUsers call results in a suite of events. First, an OnBeginEnumeration event is fired to mark the beginning of the user listing. Next, one OnUserProperty event occurs for each user listed, where UserItems exposes all the known user properties. Finally, an OnEndEnumeration event is fired to mark the end of the user listing.

Examples

1. List all users on the server:

Dim chatitemobj As ChatItems
Set chatitemobj = New ChatItems
chatitemobj.AssociatedType = "Query"
MsChatPr1.ListUsers chatitemobj
Set chatitemobj = Nothing

(On an IRC server this call maps to a WHO command. On an IRCX server it maps to a WHOIS command.)

2. On an IRCX server, list all users with an IP address that finishes with ".edu":

Dim chatitemobj As ChatItems
Set chatitemobj = New ChatItems
chatitemobj.AssociatedType = "Query"
chatitemobj.Item("IPAddressOp") = "EndsWith"
chatitemobj.Item("IPAddress") = ".edu"
MsChatPr1.ListUsers chatitemobj
Set chatitemobj = Nothing

3. On an IRCX server, list all users with an IP address that contains "microsoft":

Dim chatitemobj As ChatItems
Set chatitemobj = New ChatItems
chatitemobj.AssociatedType = "Query"
chatitemobj.Item("IPAddressOp") = "Contains"
chatitemobj.Item("IPAddress") = "microsoft"
MsChatPr1.ListUsers chatitemobj
Set chatitemobj = Nothing

4. On an IRCX server, list all users with a nickname that contains "joe":

Dim chatitemobj As ChatItems
Set chatitemobj = New ChatItems
chatitemobj.AssociatedType = "Query"
chatitemobj.Item("NicknameOp") = "Contains"
chatitemobj.Item("Nickname") = "joe"
MsChatPr1.ListUsers chatitemobj
Set chatitemobj = Nothing

5. On an IRCX server, list all users in the channel "#newbies":

Dim chatitemobj As ChatItems
Set chatitemobj = New ChatItems
chatitemobj.AssociatedType = "Query"
chatitemobj.Item("Channels") = "#newbies"
MsChatPr1.ListUsers chatitemobj
Set chatitemobj = Nothing

6. On an IRCX server, list all users for which the nickname, IP address, server name, or real name contains "nath":

Dim chatitemobj As ChatItems
Set chatitemobj = New ChatItems
chatitemobj.AssociatedType = "Query"
chatitemobj.Item("MaskOp") = "Contains"
chatitemobj.Item("Mask") = "nath"
MsChatPr1.ListUsers chatitemobj
Set chatitemobj = Nothing

7. On an IRCX server, list all users for which the nickname, IP address, server name, or real name starts with "Re":

Dim chatitemobj As ChatItems
Set chatitemobj = New ChatItems
chatitemobj.AssociatedType = "Query"
chatitemobj.Item("MaskOp") = "StartsWith"
chatitemobj.Item("Mask") = "Re"
MsChatPr1.ListUsers chatitemobj
Set chatitemobj = Nothing


Login Method

Logs a user on to the chat server.

Syntax

object.Login ServerName, Nickname[, UserName][, RealName][, Password][, SecurityPackages]

Parameters

object | Required. An object expression that evaluates to an MsChatPr control.
ServerName | Required. A string expression that contains the server Name. Can optionally include the port number.
Nickname | Required. A string expression containing the user Nickname. Must be a valid IRC/IRCX user Nickname.
UserName | Optional. A string expression that contains the UserName. If empty or missing, the control uses the Microsoft® Windows® login name as the UserName.
RealName | Optional. A string expression containing the user's RealName. Can be empty or missing, in which case the Username is used as the RealName.
Password | Optional. A string expression containing the user's password. If empty or missing, no password is used to log in to the server.
SecurityPackages Optional. A string expression that contains the name of the security package.

If empty or missing, the first authentication package provided by the server is used. If the server doesn't provide an authentication package, an anonymous login is tried.

The SecurityPackages parameter is a list of authentication packages that are successively tried during login. The packages must be separated by a semicolon and can include the ANON (not case sensitive) keyword for anonymous logins.

IRC servers do not implement user authentication; all logins are anonymous.

Remarks

The Login method can be called at two different stages—when the control is in the csDisconnected state, or after calling the Connect method and the control is in the csConnected state.

In this last case the ServerName and optional port number given in Login have to be the same as in the Connect call. After reaching the csConnected state, the csLogging and csLogged states are achieved.

Examples

1. Use Connect and Login:

MsChatPr1.Connect "comicsrv1.microsoft.com"
MsChatPr1.Login "comicsrv1.microsoft.com", "JB",_
"JamesB", ,MsChatPr1.SecurityPackages

2. Use Login alone:

MsChatPr1.Login "irc.mtv.com", "JB007", "JamesB", "James Bond", ,"ANON"
MsChatPr1.Login "irc.univ-lyon1.fr", "Arthur"
MsChatPr1.Login "chat.msn.com", "Norbert", , , ,"DPA;NTLM;ANON"

See Also

Connect, Disconnect


MaxStringLength Property

Returns the maximum length of some string properties.

Syntax

value=object.MaxStringLength(StringType)

Parameters

value | Required. A long integer that receives the maximum length of some string properties.
object | Required. An object expression that evaluates to an MsChatPr control.
StringType Required. A variable of enumStringType type. If the StringType parameter is set to stServerMessage, MaxStringLength returns the maximum length, in bytes, of any message sent to the server. For regular IRC servers, this value is 512 bytes. This variable is customizable on IRCX servers and could, for example, be 2048 bytes.

The following list itemizes the other values defined by the servers. These values might change in future server versions.
MaxStringLength(stChannelAccount) | = 31
MaxStringLength(stChannelClientData) | = 255
MaxStringLength(stChannelHostKey) | = 31
MaxStringLength(stChannelKeyword) | = 31
MaxStringLength(stChannelLanguage) | = 31
MaxStringLength(stChannelName) | = 200
MaxStringLength(stChannelOnJoin) | = 255
MaxStringLength(stChannelOnPart) | = 255
MaxStringLength(stChannelOwnerKey) | = 31
MaxStringLength(stChannelRating) | = 255
MaxStringLength(stChannelSubject) | = 31
MaxStringLength(stChannelTopic) | = 160

Remarks

Access is read-only.

Example

Dim lMaxMessageLen As Long
lMaxMessageLen = MsChatPr1.MaxStringLength(stServerMessage)


MemberCount Property

Synchronously returns the current number of members in the channel.

Syntax

value=object.MemberCount

Parameters

value | Required. A long integer that will receive the current number of members in the channel.
object | Required. An object expression that evaluates to a Channel object.

Remarks

Access is read-only.

If the Channel object is not open, attempts to access its MemberCount property will cause an occurrence of the Channel Error 3062, "The channel is not open."

Examples

The user can also synchronously obtain the member count of the channel by using:

ChannelProperty("MemberCount")

But the MemberCount property is simpler and more efficient.

The asynchronous methods of accessing the member count of the channel are:

&lt:channel>.QueryChannelProperty "MemberCount"
'and
&lt:control>.QueryChannelProperty "MemberCount", &lt:channelname>

See Also

ChannelProperty, QueryChannelProperty


MemberIdentity Property

Synchronously accesses the Identity of a channel member.

Syntax

value.object.MemberIdentity [MemberNickname]

Parameters

value | Required. A string expression containing the Identity of a member.
object | Required. An object expression that evaluates to a Channel object.
MemberNickname | Optional. A variant. When specified, the variant must be a string and represent the nickname of a channel member. If not specified, the Identity of the caller is returned.

Remarks

Access is read-only.

The member's Identity is composed of the member's UserName and IPAddress separated by the @ sign.

Examples

RegisB@REGISB1.dns.microsoft.com
RegisB@zorg.microsoft.com

The Identity of a member is fixed. The identity cannot vary, unlike a member's Nickname.

The user can also synchronously get a member's Identity by using:

<channel>.MemberProperty("Identity", <nickname>)

But the MemberIdentity call is simpler and more efficient.

The asynchronous method to access a member's identity is:

<channel>.QueryMemberProperty "Identity", <nickname>

See Also

MemberProperty, Nickname, QueryMemberProperty


MemberModes Property

Synchronously accesses a channel member's Modes.

Syntax

value=object.MemberModes[, MemberNickname]

Parameters

value | Required. A variable of enumMemberMode type.
object | Required. An object expression that evaluates to a Channel object.
MemberNickname | Optional. A variant. When specified, the variant must be a string and represent the nickname of a channel member. If not specified, the Modes of the caller are returned.

Remarks

Access is read-only.

The member modes expose eight Booleans, each Boolean taking two values that are mutually exclusive. For example, the mmClientIgnored and mmNotClientIgnored values are mutually exclusive.

If the MemberModes property returns 0x000AA41 = mmClientIgnored + mmAway + mmNotSysop + mmNotOwner + mmNotHost + mmNoVoice, the control is certain that this member is ignored by the caller, currently away, not a system operator, not a channel host, and has no voice.

However, in this example, because mmAuthMember and mmNotAuthMember are not part of the returned modes, the control is not aware of member authentication.

See Also

Nickname


MemberProperty Property

Synchronously accesses a channel member's property.

Syntax

value=object.MemberProperty MemberPropertyName[, MemberNickname]

Parameters

value | Required. An object expression that evaluates to a ChatItems object.
object | Required. An object expression that evaluates to a Channel object.
MemberPropertyName | Required. A string containing a valid member property name value.
MemberNickname | Optional. A variant. When specified, the variant must be a string and represent the nickname of a channel member. If not specified, the property of the caller is returned.

Remarks

Access is read-only.

See Also

Nickname


MsChatPr Object

MsChatPr is the top-level object in the Chat Protocol control object model. This section describes the methods, properties, and events supported by the MsChatPr object.

Properties of MsChatPr Object

ChannelProperty, Channels, ConnectionState, ConnectionType, ConvertedString, MaxStringLength, NewChatItems, Nickname, OpeningChannels, ProcessProtocolMessages, PropertyAccessTimeOut, ServerName, ServerProperty, UserProperty

Methods of MsChatPr Object

AboutBox, BanUsers, CancelConnectLogin, ChangeNickname, ChangeUserProperty, Connect, Disconnect, IgnoreUsers, KickUser, KillChannel, ListChannels, ListUsers, Login, QueryChannelProperty, QueryServerProperty, QueryUserProperty, SendInvitation, SendPrivateMessage, SendProtocolMessage, SetAway

Events of MsChatPr Object

OnAddMember, OnBeginEnumeration, OnChannelError, OnChannelProperty, OnChannelPropertyChanged, OnChannelState, OnConnectionError, OnConnectionState, OnDelMember, OnEndEnumeration, OnInvitation, OnKnock, OnMemberKicked, OnMemberProperty, OnMemberPropertyChanged, OnMessage, OnPrivateMessage, OnProtocolMessage, OnServerProperty, OnServerTextMessage, OnUserProperty, OnUserPropertyChanged


Events

This section describes the events associated with the MsChatPr object.

OnAddMember Event

OnBeginEnumeration Event

OnChannelError Event

OnChannelProperty Event

OnChannelPropertyChanged Event

OnChannelState Event

OnConnectionError Event

OnConnectionState Event

OnDelMember Event

OnEndEnumeration Event

OnInvitation Event

OnKnock Event

OnMemberKicked Event

OnMemberProperty Event

OnMemberPropertyChanged Event

OnMessage Event

OnPrivateMessage Event

OnProtocolMessage Event

OnServerProperty Event

OnServerTextMessage Event

OnUserProperty Event

OnUserPropertyChanged Event


Methods

This section lists the methods supported by the MsChatPr object.

AboutBox Method

BanUsers Method

CancelConnectLogin Method

ChangeNickname Method

ChangeUserProperty Method

Connect Method

Disconnect Method

IgnoreUsers Method

KickUser Method

KillChannel Method

ListChannels Method

ListUsers Method

Login Method

QueryChannelProperty Method

QueryServerProperty Method

QueryUserProperty Method

SendInvitation Method

SendPrivateMessage Method

SendProtocolMessage Method

SetAway Method


Properties

This section describes the properties associated with the MsChatPr object.

ChannelProperty Property

Channels Property

ConnectionState Property

ConnectionType Property

ConvertedString Property

MaxStringLength Property

NewChatItems Property

Nickname Property

OpeningChannels Property

ProcessProtocolMessages Property

PropertyAccessTimeOut Property

ServerName Property

ServerProperty Property

UserProperty Property


NewChatItems Property

Returns a newly allocated ChatItems object.

Syntax

value=object.NewChatItems

Parameters

value | Required. An object expression that evaluates to a ChatItems object.
object | Required. An object expression that evaluates to an MsChatPr control.

Remarks

Access is read-only.

This property exists for Visual Basic® Scripting Edition (VBScript) users. The following syntax does not work in VBScript.

Dim chatitemobj
Set chatitemobj=New ChatItems

Users must use the NewChatItems property instead, as in the following:

Dim chatitemobj
Set chatitemobj=MsChatPr1.NewChatItems
'...use chatitemobj
Set chatitemobj=Nothing  'releases chatitemobj

Dynamic allocation of a ChatItems object is necessary in order to perform some server queries, such as ListChannels or BanMembers.

Example

Dim mi
Set mi = MsChatPr1.NewChatItems
mi.AssociatedType = "Query"
mi.Item("IPAddressOp") = "EndsWith"
mi.Item("IPAddress") = ".com"
MsChatPr1.Channels(1).BanMembers mi, True
Set mi = Nothing


Nickname Property

Returns the control user's Nickname for the current connection, or an empty string if there is no live connection.

Syntax

value=object.Nickname

Parameters

object | Required. An object expression that evaluates to an MsChatPr control.
value | Required. A string expression to contain the control user's Nickname for the current connection, or an empty string if there is no live connection.

Remarks

Access is read-only.

Example

Dim strMyNickname As String
strMyNickname=MsChatPr1.Nickname
'or
Sub MsChatPr1_OnMemberKicked(Channel* Channel,
        BSTR KickedNickname,
        BSTR KickerNickname,
        BSTR Reason)
    If (KickedNickname = MsChatPr1.Nickname) Then
        MsgBox "You were kicked by " + KickerNickname + " because: " + Reason
    End If
End Sub


OnAddMember Event

Fires when entering a channel or when a new member joins an open channel.

Syntax

object_OnAddMember(Channel, Nickname, MemberItems)

Parameters

object | Required. An object expression that evaluates to an MsChatPr control.
Channel | Required. An object expression that evaluates to a Channel object.
Nickname | Required. A string expression that contains the user's Nickname.
MemberItems | Required. An object expression that evaluates to a ChatItems object.

Remarks

When entering a channel, the control user receives the initial member list through OnAddMember events. One OnAddMember event also occurs for each incoming new member.


OnBeginEnumeration Event

Fires at the beginning of an enumeration, when entering a channel or listing users, members, or channels.

Syntax

object_OnBeginEnumeration(Channel, EnumType)

Parameters

object | Required. An object expression that evaluates to an MsChatPr control.
Channel | Required. An object expression that evaluates to a Channel object.
EnumType | Required. A variable of enumEnumType type.

See Also

CreateChannel, ListChannels, ListUsers


OnChannelError Event

Fires when an asynchronous error related to a channel occurs.

Syntax

object_OnChannelError(Channel, ErrorCode, Description)

Parameters

object | Required. An object expression that evaluates to an MsChatPr control.
Channel | Required. An object expression that evaluates to a Channel object.
ErrorCode | Required. A long integer value that indicates the channel error code.
Description | Required. A string expression that contains the description of the error.

See Also

CreateChannel


OnChannelProperty Event

Fires after a ListChannels or QueryChannelProperty call.

Syntax

object_OnChannelProperty(Channel, ChannelItems)

Parameters

object | Required. An object expression that evaluates to an MsChatPr control.
Channel | Required. An object expression that evaluates to a Channel object.
ChannelItems | Required. An object expression that evaluates to a ChatItems object.

Remarks

This event can also be fired after a time-out occurs while accessing a ChannelProperty property.


OnChannelPropertyChanged Event

Fires when a channel property changes, such as after calling ChangeChannelProperty.

Syntax

object_OnChannelPropertyChanged(Channel, ModifierNickname, ChannelPropertyName, OldChannelProperty, NewChannelProperty)

Parameters

object | Required. An object expression that evaluates to an MsChatPr control.
Channel | Required. An object expression that evaluates to a Channel object.
ModifierNickname | Required. A string expression containing the modifier nickname.
ChannelPropertyName | Required. A string expression containing the name of the channel property that changed.
OldChannelProperty | Required. A variant, the type of which depends on the old channel property.
NewChannelProperty | Required. A variant, the type of which depends on the new channel property.

See Also

ChangeChannelProperty


OnChannelState Event

Fires after a CreateChannel, JoinChannel, or LeaveChannel call or after an asynchronous event, such as being kicked out of the room or being disconnected.

Syntax

object_OnChannelState(Channel, NewChannelState)

Parameters

object | Required. An object expression that evaluates to an MsChatPr control.
Channel | Required. An object expression that evaluates to a Channel object.
NewChannelState | Required. A short integer of enumChannelState type.

See Also

CreateChannel, JoinChannel, LeaveChannel


OnConnectionError Event

Fires when an asynchronous error occurs.

Syntax

object_OnConnectionError(ErrorCode, Description, ChannelName)

Parameters

object | Required. An object expression that evaluates to an MsChatPr control.
ErrorCode | Required. A long integer containing the value of the error code.
Description | Required. A string expression containing the description of the error code.
ChannelName | Required. A variant, the type of which depends on the name of the channel.


OnConnectionState Event

Fires after Connect, Login, CancelConnectLogin, and Disconnect calls or when an asynchronous disconnection occurs.

Syntax

object_OnConnectionState(NewConnectionState)

Parameters

object | Required. An object expression that evaluates to an MsChatPr control.
NewConnectionState | Required. A variable of enumConnectionState type.

Example

Dim NewConnectionState As enumConnectionState
NewConnectionState = MsChatPr1.ConnectionState


OnDelMember Event

Fires when a member leaves an open channel or is kicked out of the channel.

Syntax

object_OnDelMember(Channel, Nickname)

Parameters

object | Required. An object expression that evaluates to an MsChatPr control.
Channel | Required. An object expression that evaluates to a Channel object.
Nickname | Required. A string expression that contains the Nickname of the user who is leaving the channel.

See Also

KickMember, OnMemberKicked


OnEndEnumeration Event

Fires at the end of an enumeration, when entering a channel or listing users, members, or channels.

Syntax

object_OnEndEnumeration(Channel, EnumType)

Parameters

object | Required. An object expression that evaluates to an MsChatPr control.
Channel | Required. An object expression that evaluates to a Channel object.
EnumType | Required. A variable of enumEnumType type.

See Also

CreateChannel, ListChannels, ListUsers


OnInvitation Event

Fires when the control user is invited to a channel.

Syntax

object_OnInvitation(ChannelName, InviterItems)

Parameters

object | Required. An object expression that evaluates to an MsChatPr control.
ChannelName | Required. A string expression that represents the channel to which the user is invited.
InviterItems | Required. An object expression that evaluates to a ChatItems object. Gives all the known information about the user who is performing the inviting.

See Also

SendInvitation


OnKnock Event

Fires when a user failed to enter a channel.

Syntax

object_OnKnock(Channel, KnockerItems, ErrorCode)

Parameters

object | Required. An object expression that evaluates to an MsChatPr control.
Channel | Required. An object expression that evaluates to a Channel object.
KnockerItems | Required. An object expression that evaluates to a ChatItems object.
ErrorCode | Required. A long integer value that indicates why the user could not join the channel. Examples are that the channel is full, the channel is invite-only, or a channel Keyword is set.

Remarks

Only the hosts of the channel receive this notification. Also, the notification occurs only if the cmKnock flag is set for that channel.


OnMemberKicked Event

Fires when a member is kicked out of the channel.

Syntax

object_OnMemberKicked(Channel, KickedNickname, KickerNickname, Reason)

Parameters

object | Required. An object expression that evaluates to an MsChatPr control.
Channel | Required. An object expression that evaluates to a Channel object.
KickedNickname | Required. A string expression containing the Nickname of the member who is being kicked.
KickerNickname | Required. A string expression containing the Nickname of the member who is doing the kicking.
Reason | Required. A string expression containing the reason the member is being kicked, or it can be empty.

Remarks

This event can result from a KickMember method call and is immediately followed by an OnDelMember event.


OnMemberProperty Event

Fires after a ListMembers or QueryMemberProperty call.

Syntax

object_OnMemberProperty(Channel, MemberItems)

Parameters

object | Required. An object expression that evaluates to an MsChatPr control.
Channel | Required. An object expression that evaluates to a Channel object.
MemberItems | Required. An object expression that evaluates to a ChatItems object.

Remarks

This event can also be fired after a time-out occurs while accessing the MemberProperty property.


OnMemberPropertyChanged Event

Fires when a member property changes, such as after a ChangeMemberProperty or ChangeNickname call.

Syntax

object_OnMemberPropertyChanged(Channel, ModifiedNickname, ModifierNickname, MemberPropertyName, OldMemberProperty, NewMemberProperty)

Parameters

object | Required. An object expression that evaluates to an MsChatPr control.
Channel | Required. An object expression that evaluates to a Channel object.
ModifiedNickname | Required. A string expression containing the Nickname of the member that is being modified.
ModifierNickname | Required. A string expression containing the Nickname of the modifier.
MemberPropertyName | Required. A string containing a valid member property name value. Can be Modes or Nickname.
OldMemberProperty | Required. A variant, the data type of which is dependent on the old member property.
NewMemberProperty | Required. A variant, the data type of which is dependent on the new member property.

See Also

MemberProperty, QueryMemberProperty


OnMessage Event

Fires when a member sends a message to the channel or members of the channel including the control user.

Syntax

object_OnMessage(Channel, SenderNickname, MessageType, Message, RecipientNicknames, DataMessageTag)

Parameters

object | Required. An object expression that evaluates to an MsChatPr control.
Channel | Required. An object expression that evaluates to a Channel object.
SenderNickname | Required. A string expression that contains the Nickname of the sender.
MessageType | Required. A long integer of enumMessageType type.
Message Required. A variant. When the data message is received and the msgtDataRaw flag is not set, the Message parameter can be a number, a string, an array of numbers, an array of strings, or an array of variants that are strings or numbers. This is exactly like the Message parameter used in the SendMessage method.

However, when the msgtDataRaw flag is set, the Message parameter is an array of these three variants:
Message[0] | The postprocessed string that represents the array of bytes received.
Message[1] | An array of bytes.
Message[2] | An array of variants that are bytes.

RecipientNicknames Required. An array of variants that are strings when the incoming message is a whisper (that is, that originates from the SendMessage call that uses the msgtWhisper type).

RecipientNicknames is a string containing the user's nickname when the message is a multicasted data message (that is, a data message that was sent to one or more channel members including the control user). This differentiates the data messages that were sent to the channel where RecipientNicknames is an empty variant and those that were sent to channel member(s). RecipientNicknames is an empty variant in all other cases.

DataMessageTag | Required. A variant. Empty when the Message parameter is a string, and must be a string expression when Message is data.


OnPrivateMessage Event

Fires when a user sends a private message to the control user.

Syntax

object_OnPrivateMessage(SenderNickname, PrivateMessageType, Message, DataMessageTag)

Parameters

object | Required. An object expression that evaluates to an MsChatPr control.
SenderNickname | Required. A string expression containing the Nickname of the sender.
PrivateMessageType | Required. A long integer.
Message Required. A variant. When a data message is received and the pmtDataRaw flag is not set, the Message parameter can be a number, a string, an array of numbers, an array of strings, or an array of variants that are strings or numbers. This is exactly like the Message parameter used in the SendPrivateMessage method.

However, when the pmtDataRaw flag is set, the Message parameter is an array of these three variants:
Message[0] | The postprocessed string that represents the array of bytes received.
Message[1] | An array of bytes.
Message[2] | An array of variants that are bytes.

DataMessageTag | Required. A variant. This parameter is empty when the Message parameter is a string, and is a string when Message is data.


OnProtocolMessage Event

Fires for any incoming server message when the ProcessProtocolMessages property is set to FALSE.

Syntax

object_OnProtocolMessage(MessagePrefix, MessageCommand, MessageParameters, EnableDefault)

Parameters

object | Required. An object expression that evaluates to an MsChatPr control.
MessagePrefix | Required. A string expression.
MessageCommand | Required. A string expression.
MessageParameters | Required. An array of string variants.
EnableDefault | Required. An OLE_ENABLEDEFAULTBOOL.

Remarks

If the ProcessProtocolMessages property is set to TRUE, this event is fired for incoming messages that are not internally treated by the control.


OnServerProperty Event

Fires after a QueryServerProperty call.

Syntax

object_OnServerProperty(ServerItems)

Parameters

object | Required. An object expression that evaluates to an MsChatPr control.
ServerItems | Required. An object expression that evaluates to a ChatItems object.

Remarks

This event can also be fired after a time-out occurs while accessing the ServerProperty property.

See Also

ItemValid


OnServerTextMessage Event

Fires for incoming server text messages.

Syntax

object_OnServerTextMessage(ServerMessageType, Text)

Parameters

object | Required. An object expression that evaluates to an MsChatPr control.
ServerMessageType | Required. A variable of enumServerMessageType type.
Text | Required. A string expression that contains the text message.


OnUserProperty Event

Fires after a ListUsers or QueryUserProperty call.

Syntax

object_OnUserProperty(UserItems)

Parameters

object | Required. An object expression that evaluates to an MsChatPr control.
UserItems | Required. An object expression that evaluates to a ChatItems object.

Remarks

This event can also be fired after a time-out occurs while accessing the UserProperty property.


OnUserPropertyChanged Event

Fires when a user property changes.

Syntax

object_OnUserPropertyChanged(ModifiedNickname, ModifierNickname, UserPropertyName, OldUserProperty, NewUserProperty)

Parameters

object | Required. An object expression that evaluates to an MsChatPr control.
ModifiedNickname | Required. A string expression that contains the Nickname being modified.
ModifierNickname | Required. A string expression that contains the Nickname of the modifier, or it can be empty.
UserPropertyName | Required. A variant, the type of which depends on the user property name.
OldUserProperty | Required. A variant, the type of which depends on the old user property.
NewUserProperty | Required. A variant, the type of which depends on the new user property.

Remarks

This event can occur after calling ChangeUserProperty or ChangeNickname, for example.


OpeningChannels Property

Returns the number of opening channels in the Channels collection.

Syntax

value=object.OpeningChannels

Parameters

value | Required. A long integer value that receives the number of opening channels in the Channels collection.
object | Required. An object expression that evaluates to an MsChatPr control.

Remarks

Access is read-only.

Example

Dim lOpeningChannels As Long
MsChatPr1.Channels.Add
MsChatPr1.Channels.JoinChannel "#Foo"
lOpeningChannels = MsChatPr1.OpeningChannels	'returns 1


ProcessProtocolMessages Property

Determines whether the OnProtocolMessage event is fired for each incoming server message.

Syntax

object.ProcessProtocolMessages=value

Parameters

object | Required. An object expression that evaluates to an MsChatPr control.
value | Required. A Boolean value.

Remarks

Access is read/write.

When ProcessProtocolMessages is set to TRUE, the incoming server messages are immediately treated internally and exposed through some event. The OnProtocolMessage event is fired only when the incoming server message cannot be properly interpreted by the control.

However, when ProcessProtocolMessages is set to FALSE, the control first exposes the incoming server messages through the OnProtocolMessage event.

In the OnProtocolMessage event handler, the control user can set the EnableDefault parameter to TRUE or FALSE. The parameter is set to TRUE by default.

If set to TRUE, the control treats the incoming server message normally and fires the usual event. If set to FALSE, however, the control will not treat the message internally.

Tip Only experts should set the ProcessProtocolMessages property to FALSE. If the incoming messages are not treated internally by the control, the control might end up in an unstable state. This mode must be handled with extreme caution.

Example

MsChatPr1.ProcessProtocolMessages = False


PropertyAccessTimeOut Property

Reads or writes the time-out value when synchronously accessing a property.

Syntax

object.PropertyAccessTimeOut=value

Parameters

object | Required. An object expression that evaluates to an MsChatPr control.
value | Required. A long integer value that contains the time-out expressed in milliseconds. This unique property is used for all the synchronous property accesses being performed in the control.

Remarks

Access is read/write.

If a time-out condition occurs when trying to synchronously access a property, an error is returned. An OnChannelProperty, OnServerProperty, OnMemberProperty, or OnUserProperty event might be fired after a time-out error occurs. This event exposes the property that could not be accessed in time.

Example

Dim chatitemobj As ChatItems
MsChatPr1.PropertyAccessTimeOut = 10000    '10 seconds
Set chatitemobj = MsChatPr1.ChannelProperty("MaxMemberCount", "#MyRoom")
'... use chatitemobj
Set chatitemobj = MsChatPr1.Channels(2).MemberProperty("Identity", "Mila")
'... use chatitemobj
Set chatitemobj = Nothing

In the following example, a time-out condition has caused an error. An OnChannelProperty event is fired, in which the ChannelItems parameter exposes the MaxMemberCount property and all other known properties.

Dim chatitemobj As ChatItems
MsChatPr1.PropertyAccessTimeOut = 10    '10 milliseconds
Set chatitemobj = MsChatPr1.ChannelProperty("MaxMemberCount", "#MyRoom")

See Also

ChannelProperty, MemberProperty, OnChannelProperty, OnMemberProperty, OnUserProperty, OnServerProperty, ServerProperty


QueryChannelProperty Method

Asynchronously accesses a channel property.

Syntax

object.QueryChannelProperty ChannelPropertyName[, ChannelName]

Parameters

object | Required. An object expression that evaluates to an MsChatPr control.
ChannelPropertyName Required. A string that contains one of the valid values shown in the following table.
IRCX | IRC/IRCX
protocol only | protocols
Account BannedList
ClientData Keyword
ClientGuid MaxMemberCount
CreationTime MemberCount
HostKey Modes
Lag Name
Language Topic
ObjectId
OnJoin
OnPart
OwnerKey
Rating
ServicePath
Subject
ChannelName | Optional. A string that contains the channel Name. This parameter can be omitted or empty if there is exactly one open channel in the collection. In this case the call concerns that uniquely open channel. Otherwise, ChannelName must be the Name of an existing channel on the server.

Remarks

A successful QueryChannelProperty call results in an OnChannelProperty event in which the ChannelItems parameter exposes all the known channel properties.

Example

'Specifies the name of an existing server channel
MsChatPr1.QueryChannelProperty "Rating", "#MyRoom"
'There is exactly one channel open
MsChatPr1.QueryChannelProperty "Modes"


QueryChannelProperty Method

Asynchronously accesses a channel property.

Syntax

object.QueryChannelProperty ChannelPropertyName

Parameters

object Required. An object expression that evaluates to a Channel object.
ChannelPropertyName Required. A string that contains one of the valid values shown in the following table.
IRCX | IRC/IRCX
protocol only | protocols
Account BannedList
ClientData Keyword
ClientGuid MaxMemberCount
CloneList MemberCount
CreationTime Modes
HostKey Name
Lag Topic
Language
ObjectId
OnJoin
OnPart
OwnerKey
Rating
ServicePath
Subject

Remarks

A successful QueryChannelProperty call results in an OnChannelProperty event where the ChannelItems parameter exposes all the known channel properties.

Examples

chan.QueryChannelProperty "Account"
chan.QueryChannelProperty "MaxMemberCount"

See Also

ChannelName, ListChannels, MemberCount


QueryMemberProperty Method

Asynchronously requests a member property.

Syntax

object.QueryMemberProperty MemberPropertyName[, MemberNickname]

Parameters

object | Required. An object expression that evaluates to a Channel object.
MemberPropertyName Required. A string containing one of the following valid member property name values.
Identity
IPAddress
Modes
Nickname
ObjectId (IRCX protocol only)
UserName
MemberNickname | Optional. A string expression. If specified, this parameter must be an empty variant or a valid channel member nickname. If omitted or empty, the nickname of the caller is used.

Remarks

A successful call results in an OnMemberProperty event where the MemberItems parameter exposes all the known member properties.

Examples

MsChatPr1.Channels.Item(3).QueryMemberProperty "Identity", "DerrickL"
MsChatPr1.Channels.Item(3).QueryMemberProperty "Modes"

See Also

enumMemberMode, MemberIdentity, MemberProperty


QueryServerProperty Method

Asynchronously accesses a server property.

Syntax

object.QueryServerProperty ServerPropertyName

Parameters

object Required. An object expression that evaluates to an MsChatPr control.
ServerPropertyName Required. A string containing one of the following valid server property name values.
AnonymousAllowed
ChannelCount
IgnoredUsers
Info
MaxMessageLength
Name
NetInvisibleCount
NetServerCount
NetUserCount
NodeServerCount
NodeUserCount
SecurityPackages
SysopCount
UnknownConnectionCount

Remarks

A successful QueryServerProperty call results in an OnServerProperty event, in which ServerItems exposes the known server properties.

The connection state must be at least csConnected to access the AnonymousAllowed, IgnoredUsers, MaxMessageLength, and Name properties. The state must be at least csLogged to access all other server properties.

Example

MsChatPr1.QueryServerProperty "Info"
MsChatPr1.QueryServerProperty "SysopCount"

See Also

ItemValid


QueryUserProperty Method

Asynchronously accesses a user property.

Syntax

object.QueryUserProperty UserPropertyName[, Nickname]

Parameters

object | Required. An object expression that evaluates to an MsChatPr control.
UserPropertyName Required. A string expression. Must be one of the following valid user property name values.
Away
Channels
HostInChannels
Identity
IdleTime
IPAddress
Modes
Nickname
OwnerOfChannels
RealName
ServerInfo
ServerName
SignOnTime
UserName
VoiceInChannel
Nickname | Optional. A string expression. Can be omitted or empty, in which case the call concerns the control user. If used, the Nickname must be a current server user.

Remarks

A successful QueryUserProperty call results in an OnUserProperty event where UserItems exposes all the known user properties.

Examples

'UserPropertyName and Nickname
MsChatPr1.QueryUserProperty "Away", "Mila"
'UserPropertyName only
MsChatPr1.QueryUserProperty "SignOnTime"


Remove Method

Removes a Channel object from the Channels collection.

Syntax

object.Remove Index

Parameters

object | Required. An object expression that evaluates to a Channels collection object.
Index | Required. A variant. Index can be a number between 1 and the current collection Count, or the unique channel key.

Examples

MsChatPr1.Channels.Remove 4
MsChatPr1.Channels.Remove "Aud"

See Also

Item


SendInvitation Method

Invites a user to a channel.

Syntax

object.SendInvitation Nickname[, ChannelName]

Parameters

object | Required. An object expression that evaluates to an MsChatPr control.
Nickname | Required. A string expression containing the Nickname of an existing user on the server.
ChannelName | Optional. A variant that does not need to be an existing channel on the server. If the ChannelName parameter is not specified or is empty, there must be exactly one open channel in the collection, and the user is invited to that channel.

Remarks

The invited user will get an OnInvitation event as notification of the invitation.

Examples

'ChannelName is specified
MsChatPr1.SendInvitation "Momo", "#MyRoom"
'There is exactly one open channel in the collection
MsChatPr1.SendInvitation "Mila"


SendInvitation Method

Invites a user to the channel.

Syntax

object.SendInvitation Nickname

Parameters

object | Required. An object expression that evaluates to a Channel object.
Nickname | Required. A string expression that contains the invited user's Nickname.

Remarks

The invited user gets an OnInvitation event.

Example

MsChatPr1.Channels(5).SendInvitation "EuniceM"

The previous example is equivalent to:

MsChatPr1.SendInvitation("EuniceM",MsChatPr1.Channels(5).ChannelName)


SendMessage Method

Sends text or data messages to the channel or members of the channel.

Syntax

object.SendMessage MessageType, Message[, RecipientNicknames][, DataMessageTag]

Parameters

object | Required. An object expression that evaluates to a Channel object.
MessageType Required. A long integer that is a combination of some of the enumMessageType enumeration values. The valid MessageType values are:
msgtNormal
msgtNotice
msgtData
msgtDataRequest
msgtDataReply
msgtWhisper
msgtData + msgtDataRaw
msgtDataRequest + msgtDataRaw
msgtAction + msgtNormal
msgtSound + msgtNormal
msgtCTCP + msgtNormal
msgtAction + msgtNotice
msgtSound + msgtNotice
msgtCTCP + msgtNotice
msgtAction + msgtWhisper
msgtSound + msgtWhisper
msgtCTCP + msgtWhisper

The msgtNotice, msgtData, msgtDataRequest, msgtDataReply, and msgtWhisper values are mutually exclusive.

The msgtData, msgtDataRequest, msgtDataReply, msgtAction, msgtSound, and msgtCTCP values are mutually exclusive.

The msgtDataRaw, msgtAction, msgtSound, and msgtCTCP values are mutually exclusive.

Message Required. A variant containing the actual message to send. It can be a string, a number, an array of strings, an array of numbers, or an array of variants that can be strings and numbers. The variant types allowed for those numbers are:
VT_UI1
VT_I2
VT_I4
VT_R4
VT_R8
VT_BOOL
VT_ERROR
VT_CY
VT_DATE

When sending data and the msgtDataRaw flag is not set, the control packages the Message variant into an array of bytes. An internal header is used to notify the recipient(s) that the message originates from an MsChatPr control.

When the msgtDataRaw flag is also set, the Message variant can only be a postprocessed string, a byte, an array of bytes, or an array of variants that are bytes.

A postprocessed string is a string that was modified using the regular conversion scheme, as shown in the following table.
Character | Becomes string
'\0' | "\0"
'\' "\\"
'\n' | "\n"
'\r' | "\r"
'\t' | "\t"
' ' "\b"
',' "\c"

When sending raw data, the control simply converts the Message parameter into a postprocessed string without using an internal header. This way all clients can handle the data message.

RecipientNicknames Optional. A variant. Can be missing, an empty variant, or an empty string to send the message to the channel. Otherwise it can be a string, an array of strings, or an array of variants that are strings to send the message to designated channel members.

On IRC servers, there is no method to send a message to specific channel members, so the RecipientNicknames parameter must always be empty or missing.

On IRCX servers, the RecipientNicknames parameter can always specify one or more recipients, or it can be empty.

When msgtWhisper is used, the parameter must specify one or more recipients. The recipient list is exposed to the recipients only when using the msgtWhisper type.

DataMessageTag | Optional. A variant. For IRCX servers only. This parameter is used only when sending data (that is, the msgtData, msgtDataRequest, or msgtDataReply flag is set). If sending data, this parameter must be a non-empty string. In all other cases, this parameter must be empty or missing.

Examples

1. Send a regular string to the channel:

MsChatPr1.Channels(4).SendMessage msgtNormal, "Hi there!"

2. Send a notice to the channel:

chan3.SendMessage msgtNotice, "Bye now!"

3. Send an action to the channel (CTCP action):

chanobj.SendMessage msgtAction, "is eating couscous...."

4. Send a sound to the channel (CTCP sound):

MsChatPr1.Channels.Item(2).SendMessage msgtSound, "couscous.wav Isn't that cool?"

5. Send a CTCP message to the channel:

MsChatPr1.Channels(3).SendMessage msgtCTCP, "FINGER"

6. Send text to a channel member:

chanobj.SendMessage msgtNormal, "I'm an alien spy, and U?", "SharonL"

7. Send a notice to several channel members:

Dim strRecipients(1 To 3) As String
strRecipients(1) = "ColeenS"
strRecipients(2) = "DerrickL"
strRecipients(3) = "EuniceM"
chanobj.SendMessage msgtNotice, "I'm a spy, too...", strRecipients
'or
Dim vRecipients(1 To 3) As Variant
vRecipients(1) = "ColeenS"
vRecipients(2) = "DerrickL"
vRecipients(3) = "EuniceM"
chanobj.SendMessage msgtNotice, "I'm a spy, too...", vRecipients

8. Send an action to several channel members:

Dim strRecipients(1 To 3) As String
strRecipients(1) = "ColeenS"
strRecipients(2) = "DerrickL"
strRecipients(3) = "EuniceM"
chanobj.SendMessage msgtAction, "is eating macaroni and cheese....", strRecipients
'or
Dim vRecipients(1 To 3) As Variant
vRecipients(1) = "ColeenS"
vRecipients(2) = "DerrickL"
vRecipients(3) = "EuniceM"
chanobj.SendMessage msgtAction, "is eating macaroni and cheese....", vRecipients

9. Whisper text to a channel member:

chanobj.SendMessage msgtWhisper, "I'm an alien spy, and U?", "SharonL"

10. Whisper text to channel members:

Dim strRecipients(1 To 3) As String
strRecipients(1) = "SteveL"
strRecipients(2) = "WadeR"
strRecipients(3) = "Eldon"
chanobj.SendMessage msgtWhisper, "I'm a spy, too...", strRecipients
'or
Dim vRecipients(1 To 3) As Variant
vRecipients(1) = "Charlotte"
vRecipients(2) = "Zorg"
vRecipients(3) = "Arthur"
chanobj.SendMessage msgtWhisper, "I'm a cook, too...", vRecipients

11. Send a string as data to the channel:

chanobj.SendMessage msgtData, "And a painter as well.", , "_FOO_"

12. Send a number to channel members:

Dim vRecipients(1 To 3) As Variant
vRecipients(1) = "Charlotte"
vRecipients(2) = "Zorg"
vRecipients(3) = "Arthur"
chanobj.SendMessage msgtData, 1156, vRecipients, "X"

13. Send an array of numbers to the channel:

Dim iValues(1 To 4) As Integer
iValues(1) = 10
iValues(2) = -22
iValues(3) = 123
iValues(4) = 0
chanobj.SendMessage msgtData, iValues, , "COORD"
'or
Dim vValues(1 To 4) As Variant
vValues(1) = 10
vValues(2) = -22
vValues(3) = 123
vValues(4) = 0
chanobj.SendMessage msgtData, vValues, , "COORD"

14. Send an array of strings to a channel member:

Dim strValues(1 To 4) As String
strValues(1) = "Blue"
strValues(2) = "Green"
strValues(3) = "Red"
strValues(4) = "White"
chanobj.SendMessage msgtData, strValues, "Arthur", "COLORS"
'or
Dim vValues(1 To 4) As Variant
vValues(1) = "Blue"
vValues(2) = "Green"
vValues(3) = "Red"
vValues(4) = "White"
chanobj.SendMessage msgtData, vValues, "Arthur", "COLORS"

15. Send an array of variants to the channel:

Dim vValues(5 To 10) As Variant
vVariant(5) = Now
vVariant(6) = "Your turn to play...."
vVariant(7) = -10
vVariant(8) = 5
vVariant(9) = -12.689
vVariant(10) = 9876582146
chanobj.SendMessage msgtData, vValues, , "TheHugeOne"

16. Send raw data to the channel:

'A postprocessed string
chanobj.SendMessage msgtData+msgtDataRaw,_
      "dhe\rotk\\nsk\0k45v\0zxa\\v", , "ProcessedString"
'One byte
Dim byt As Byte
byt = 56
chanobj.SendMessage msgtData+msgtDataRaw, byt, , "OneByte"
'An array of bytes
Dim rgBytes(1 To 3) As Byte
rgBytes(1) = 15
rgBytes(2) = 98
rgBytes(3) = 2
chanobj.SendMessage msgtData+msgtDataRaw,_
    rgBytes, , "ArrayOfBytes"
'An array of Variants that are bytes
Dim vByt(1 To 3) As Variant
vByt(1) = CByte(15)
vByt(2) = CByte(98)
vByt(3) = CByte(2)
chanobj.SendMessage msgtData+msgtDataRaw,_
      vByt, , "ArrayOfVariants"

See Also

enumMessageType, OnMessage


SendPrivateMessage Method

Sends a private text or data message to one or several users.

Syntax

object.SendPrivateMessage PrivateMessageType, Message, RecipientNicknames[, DataMessageTag]

Parameters

object | Required. An object expression that evaluates to an MsChatPr control.
PrivateMessageType Required. A long value that is a combination of some of the enumPrivateMessageType enumeration values. The values that can be used are:
pmtNormal | &H0.
pmtNotice | &H1.
pmtData | &H2.
pmtDataRequest | &H4.
pmtDataReply | &H8.
pmtDataRaw | &H10.
pmtVersion | &H40.
pmtLagTime | &H80.
pmtLocalTime | &H100.
pmtAction | &H200.
pmtSound | &H400.
pmtCTCP | &H800.

Except for pmtNormal, all the above values are mutually exclusive.

The valid PrivateMessageType values are:
pmtNormal
pmtNotice
pmtData
pmtDataRequest
pmtDataReply
pmtData + pmtDataRaw
pmtDataRequest + pmtDataRaw
pmtDataReply + pmtDataRaw
pmtVersion + pmtNormal
pmtLagTime + pmtNormal
pmtLocalTime + pmtNormal
pmtAction + pmtNormal
pmtSound + pmtNormal
pmtCTCP + pmtNormal
pmtVersion + pmtNotice
pmtLagTime + pmtNotice
pmtLocalTime + pmtNotice
pmtAction + pmtNotice
pmtSound + pmtNotice
pmtCTCP + pmtNotice

Message Required. A variant that can be a string, a number, an array of strings, an array of numbers, or an array of variants that can be strings and numbers. The variant types allowed for these numbers are:
VT_UI1
VT_I2
VT_I4
VT_R4
VT_R8
VT_BOOL
VT_ERROR
VT_CY
VT_DATE

Message is the actual message to send.

RecipientNicknames | Required. A variant that can be a string, an array of strings, or an array of variants that are strings that represent the recipients' nicknames.
DataMessageTag | Optional. This variant will be a non-empty string when sending data (that is, the pmtData, pmtDataRequest, or pmtDataReply flag is set). This parameter must be empty or missing in all other cases.

Remarks

When sending data and the pmtDataRaw flag is not set, the control packages the Message parameter into an array of bytes and uses an internal header to tell the recipients that the message comes from an MsChatPr control. However, when the pmtDataRaw flag is also set, the Message parameter can only be a postprocessed string, a byte, an array of bytes, or an array of variants that are bytes. A postprocessed string is a string that was modified using the regular conversion scheme.
Character | Becomes string
'\0' | "\0"
'\' "\\"
'\n' | "\n"
'\r' | "\r"
'\t' | "\t"
' ' "\b"
',' "\c"

When sending raw data, the control simply converts the Message parameter into a postprocessed string without using an internal header. This way all clients can handle the data message.

Examples

1. Send a regular string to a user:

MsChatPr1.SendPrivateMessage pmtNormal, "Hi there!", "Mila"

2. Send a notice to a user:

MsChatPr1.SendPrivateMessage pmtNotice, "Bye now!", "Zorg"

3. Request version information:

MsChatPr1.SendPrivateMessage pmtVersion, " ", "Mila"

4. Send version information:

MsChatPr1.SendPrivateMessage pmtVersion,"MsChatPr ActiveX Control V2.0
    used in VB 5.0 Application Chat-oh", "Mila"

5. Request lag time:

MsChatPr1.SendPrivateMessage pmtLagTime, CStr(Timer), "Mila"

6. Request local time:

MsChatPr1.SendPrivateMessage pmtLocalTime, " ", "Mila"

7. Send an action to a user (CTCP action):

MsChatPr1.SendPrivateMessage pmtAction, "is eating couscous....", "Kimmy"

8. Send a sound to a user (CTCP sound):

MsChatPr1.SendPrivateMessage pmtSound, "couscous.wav Isn't that cool?", "Kimmy"

9. Send a CTCP message to a user:

MsChatPr1.SendPrivateMessage pmtCTCP, "FINGER", "Mila"

10. Send text to several users:

Dim strRecipients(1 To 3) As String
strRecipients(1) = "Charlotte"
strRecipients(2) = "Zorg"
strRecipients(3) = "Arthur"
MsChatPr1.SendPrivateMessage pmtNormal, "I'm a cook too...", strRecipients
'or
Dim vRecipients(1 To 3) As Variant
vRecipients(1) = "Charlotte"
vRecipients(2) = "Zorg"
vRecipients(3) = "Arthur"
MsChatPr1.SendPrivateMessage pmtNormal, "I'm a cook too...", vRecipients

11. Send a string as data to a user:

MsChatPr1.SendPrivateMessage pmtData, "And a painter as well.", "Mila", "_FOO_"

12. Send a number to a user:

MsChatPr1.SendPrivateMessage pmtData, 1156, "Charlotte", "X"

13. Send an array of numbers to users:

Dim iValues(1 To 4) As Integer
iValues(1) = 10
iValues(2) = -22
iValues(3) = 123
iValues(4) = 0
Dim strRecipients(1 To 3) As String
strRecipients(1) = "Charlotte"
strRecipients(2) = "Zorg"
strRecipients(3) = "Arthur"
MsChatPr1.SendPrivateMessage pmtData, iValues, strRecipients, "COORD"
'or
Dim vValues(1 To 4) As Variant
vValues(1) = 10
vValues(2) = -22
vValues(3) = 123
vValues(4) = 0
Dim vRecipients(1 To 3) As Variant
vRecipients(1) = "Charlotte"
vRecipients(2) = "Zorg"
vRecipients(3) = "Arthur"
MsChatPr1.SendPrivateMessage pmtData, vValues, vRecipients, "COORD"

14. Send an array of strings to a user:

Dim strValues(1 To 4) As String
strValues(1) = "Blue"
strValues(2) = "Green"
strValues(3) = "Red"
strValues(4) = "White"
MsChatPr1.SendPrivateMessage pmtData, strValues, "Prout", "COLORS"
'or
Dim vValues(1 To 4) As Variant
vValues(1) = "Blue"
vValues(2) = "Green"
vValues(3) = "Red"
vValues(4) = "White"
MsChatPr1.SendPrivateMessage pmtData, vValues, "Prout", "COLORS"

15. Send an array of variants to a user:

Dim vValues(5 To 10) As Variant
vVariant(5) = Now
vVariant(6) = "Your turn to play...."
vVariant(7) = -10
vVariant(8) = 5
vVariant(9) = -12.689
vVariant(10) = 9876582146
MsChatPr1.SendPrivateMessage pmtData, vValues, "Zoulou", "TheHugeOne"

16. Send raw data to a user:

'A postprocessed string
MsChatPr1.SendPrivateMessage pmtData + pmtDataRaw, "dhe\rotk\\nsk\0k45v\0zxa\\v",
    "Arthur", "ProcessedString"
'One byte
Dim byt As Byte
byt = 56
MsChatPr1.SendPrivateMessage pmtData + pmtDataRaw,byt, "Arthur", "OneByte"
'An array of bytes
Dim rgBytes(1 To 3) As Byte
rgBytes(1) = 15
rgBytes(2) = 98
rgBytes(3) = 2
MsChatPr1.SendPrivateMessage pmtData + pmtDataRaw,
    rgBytes, "Arthur", "ArrayOfBytes"
'An array of Variants that are bytes
Dim vByt(1 To 3) As Variant
vByt(1) = CByte(15)
vByt(2) = CByte(98)
vByt(3) = CByte(2)
MsChatPr1.SendPrivateMessage pmtData + pmtDataRaw, vByt, "Arthur",
    "ArrayOfVariants"


SendProtocolMessage Method

Sends a text message directly to the server.

Syntax

object.SendProtocolMessage TextMessage

Parameters

object | Required. An object expression that evaluates to an MsChatPr control.
TextMessage | Required. A string containing the text message.

Remarks

This method enables the user to use an IRC/IRCX command even if the command is not exposed by the MsChatPr control. The returned messages from the server might not be understood by the control and therefore be exposed to the user through the OnProtocolMessage event.

Examples

1. The user wants to become a system operator. This operation is not exposed by the protocol control:

MsChatPr1.SendProtocolMessage "OPER " + MsChatPr1.Nickname + " " + strPassword + vbCrLf

2. List servers linked to the server:

MsChatPr1.SendProtocolMessage "LINKS" + vbCrLf


ServerName Property

Returns the server name of the current connection, or an empty string if there is no live connection.

Syntax

value=object.ServerName

Parameters

object | Required. An object expression that evaluates to an MsChatPr control.
value | Required. A string expression to contain an empty string or the name of the server if there is a live connection.

Remarks

Access is read-only.

Example

Dim strServerName As String
strServerName = MsChatPr1.ServerName


ServerProperty Property

Synchronously accesses a server property.

Syntax

value.object.ServerProperty(ServerPropertyName)

Parameters

value | Required. An object expression that evaluates to a ChatItems object.
object | Required. An object expression that evaluates to an MsChatPr control.
ServerPropertyName Required. A string that contains one of these valid server property name values:
AnonymousAllowed
ChannelCount
IgnoredUsers
Info
MaxMessageLength
Name
NetInvisibleCount
NetServerCount
NetUserCount
NodeServerCount
NodeUserCount
SecurityPackages
SysopCount
UnknownConnectionCount

Remarks

Access is read-only.

If the property could not be retrieved within the number of milliseconds specified by the PropertyAccessTimeOut property, a time-out error is thrown and an OnServerProperty event might be fired later with the requested property.

The connection state must be at least csConnected to access the following properties:
AnonymousAllowed
IgnoredUsers
MaxMessageLength
Name

The state must be at least csLogged to access all other server properties.

Example

Dim chatitemobj As ChatItems
Set chatitemobj = MsChatPr1.ServerProperty("AnonymousAllowed")
'...use chatitemobj
Set chatitemobj = MsChatPr1.ServerProperty("NodeUserCount")
'...use chatitemobj
Set chatitemobj = Nothing

See Also

PropertyAccessTimeOut


SetAway Method

Sets and resets the Away flag and away message.

Syntax

object.SetAway Away[, TextMessage]

Parameters

object | Required. An object expression that evaluates to an MsChatPr control.
Away | Required. A Boolean value used to indicate if the user is away. When a user is marked as being away, the away message is sent to any caller sending a private message to the away user. This automatic replay stops when the user resets the away flag.
TextMessage | Optional. If the away flag is set to TRUE, this parameter is used to set the away text message. If the away flag is set to FALSE, this parameter is useless.

Examples

'Setting the Away flag
MsChatPr1.SetAway True, "Out with the dog, back at 4:00 p.m. local time."
'Resetting the Away flag
MsChatPr1.SetAway False


UserProperty Property

Synchronously accesses a user property.

Syntax

value=object.UserProperty(UserPropertyName[, Nickname])

Parameters

value | Required. An object expression that evaluates to a ChatItems object.
object | Required. An object expression that evaluates to an MsChatPr control.
UserPropertyName Required. A string containing one of these valid user property name values:
Away
Channels
HostInChannels
Identity
IdleTime
IPAddress
Modes
Nickname
OwnerOfChannels
RealName
ServerInfo
ServerName
SignOnTime
UserName
VoiceInChannel
Nickname | Optional. A variant parameter that can be omitted or empty, in which case the call concerns the control user. Otherwise the Nickname must be a current server user.

Remarks

Access is read-only.

If the property could not be retrieved within the number of milliseconds specified by the PropertyAccessTimeOut property, an OnUserProperty event is fired with the requested property.

Example

Dim chatitemobj As ChatItems
Set chatitemobj = MsChatPr1.UserProperty("Away", "Mila")
'. . . use chatitemobj
Set chatitemobj = MsChatPr1.UserProperty("SignOnTime")
'. . . use chatitemobj
Set chatitemobj = Nothing

See Also

OnUserProperty, PropertyAccessTimeOut


ValidItems Property

Defines the valid item names of the object.

Syntax

object.ValidItems=value

Parameters

object | Required. An object expression that evaluates to a ChatItems object.
value | Required. A variant that is an array of variants that are strings. When the ChatItems object has no valid items set, the Empty keyword as a variant is valid. (The Empty keyword is used as a variant subtype. It indicates an uninitialized variable value.)

Remarks

Access is read-only.

See Also

Item


Microsoft Tabular Data Control

The Tabular Data Control (TDC) is a Microsoft® ActiveX™ control that can be hosted by Microsoft® Internet Explorer 4.0 to display data stored in a delimited text file. Using the TDC, a Web author can display data either within tables or within controls found in a form. (Extensions in Internet Explorer 4.0 allow you to bind data to HTML elements on the page as well as to repeat the content of an HTML <TABLE> for each record of a data set. The latter can be thought of as using the table as a template for the data, where the template is repeated once for each record.)

One of the primary features of the TDC is that it brings filtering and sorting operations to the client side (there are no server-side operations).

The TDC exposes the OLE-DB simple provider interfaces. For more information about these interfaces, see OLE-DB Simple Provider: A Data Binding API for IE4/MSHTML.

Source Availability

Licensing and Distribution

Dependencies

Understanding the Tabular Data Control Object Model

Using the Tabular Data Control

Summary

Source Availability

To aid developers in creating their own data source objects, the Tabular Data Control is provided as a sample that ships with the Internet Client SDK. The source code can be found in \inetsdk\samples\tdc.

Licensing and Distribution

The Microsoft Tabular Data Control is automatically installed as part of the base installation of Microsoft Internet Explorer version 4.0.

Dependencies

The TDC is found in the file Tdc.ocx, which is automatically installed and registered with all versions of Internet Explorer 4.0.

Understanding the Tabular Data Control Object Model

The TDC supports properties and methods that can be divided into these categories:

  • Elements that describe the data file.
  • Elements that support data filtering.
  • Elements that support data sorting.

File Properties

Most of the properties supported by the TDC are data-file properties. These properties specify the location of the data file, the language used to create the data file, the character used to delimit fields, and so on. The following list describes each property:
Property | Description
CharSet | Identifies the character set used by the data file. The default character set is latin1.
DataURL | Specifies the location of the data file as a URL.
EscapeChar | Identifies the character to be used as an escape character in the data file. There is no default escape character.
FieldDelim | Identifies the character that is used to mark the end of a field in the data file. The default character is the comma (,).
Language | Specifies the language used to generate the data file (this specifier uses the HTML standard codes based on ISO 369). The default specifier is eng-us.
TextQualifier | Specifies the optional character that surrounds a field.
RowDelim | Identifies the character used to mark the end of each row of data. The default character is the newline (NL) character.
UseHeader | Specifies whether the first line of the data file contains header information. The default value is FALSE.

Filtering Properties

One TDC property and one method apply to data filtering.

Set the Filter property to an expression that includes the name of the column to be filtered, the criteria for filtering, and the value that will be compared against the specified column using the given value. The default value is an empty string ("").

Call the Reset method to apply the filter and refresh the contents of the HTML elements bound to the data supplied by the TDC.

Sorting Properties

One TDC property and a single TDC method apply to data sorting.

Set the Sort property to a semicolon-delimited list of column names by which the bound HTML elements should be sorted. Prefixing a column name with a plus (+) symbol indicates ascending order. The minus (-) symbol indicates descending order. The default sort order is ascending.

Call the Reset method to apply the new sort order and to refresh the contents of the HTML elements bound to the data supplied by the TDC.

Using the Tabular Data Control

This section demonstrates how you can incorporate the TDC into your Web pages.

Note The TDC examples in this section require Internet Explorer 4.0.

A Simple Before-and-After Example

This section contains a very simple example demonstrating how you can replace a static table in your HTML page with a dynamic table that is generated using the TDC. When this replacement occurs, you'll no longer need to modify your HTML source file each time your data changes; instead, you can simply modify the data file or regenerate it from a database.

Adding data to your Web page

The Tabular Data Control (TDC) has many uses, but perhaps the easiest way to get a feel for its capabilities is to see a short example. If you have a data file containing some of the elements of the periodic table, it might look like this:

Element,Symbol
Hydrogen,H
Helium,He
Lithium,Li
Beryllium,Be
Boron,B
Carbon,C
Nitrogen,N
Oxygen,O
Flourine,F
Neon,Ne

Each line contains the name of the element followed by a comma, then its scientific abbreviation. If you wanted to display this table in a Web page without using the TDC, you would add the table tags around each word, as shown in the following example:

<TABLE>
<THEAD><TR><TD>Element</TD><TD>Symbol</TD></TR></THEAD>
<TBODY>
<TR><TD>Hydrogen</TD> <TD>H</TD></TR>
<TR><TD>Helium</TD> <TD>He</TD></TR>
<TR><TD>Lithium</TD> <TD>Li</TD></TR>
<TR><TD>Beryllium</TD> <TD>Be</TD></TR>
<TR><TD>Boron</TD> <TD>B</TD></TR>
<TR><TD>Carbon</TD> <TD>C</TD></TR>
<TR><TD>Nitrogen</TD> <TD>N</TD></TR>
<TR><TD>Oxygen</TD> <TD>O</TD></TR>
<TR><TD>Flourine</TD> <TD>F</TD></TR>
<TR><TD>Neon</TD> <TD>Ne</TD></TR>
</TBODY>
</TABLE>

Click the Show Me button to see how the previous table appears when viewed in your browser.

A static table is not only tedious to create, but it also makes it inconvenient to edit or update the data. This especially applies if you want to use the raw data file in other applications. Using the TDC, you can instead tell the Web page where to find the text file, and it will read the data directly from the file (plus optionally sort it, filter it, and skip columns). The previous table coding is replaced with the following coding:

<TABLE datasrc=#elements>
<THEAD><TR><TD>Element</TD><TD>Symbol</TD></TR></THEAD>
<TBODY>
<TR><TD><DIV datafld="Element"></DIV></TD><TD><DIV datafld="Symbol"></DIV></TD></TR>
</TBODY>
</TABLE>

Click the Show Me button to see how databinding can be used to replace a static table in Internet Explorer 4.0.

If you look more closely at these changes, you will note that the first line uses the DATASRC attribute to identify the TDC. (This identifier corresponds to the ID attribute that was specified for the <OBJECT> tag that loaded the control.)

<TABLE datasrc=#elements>

The prepended # symbol is always required by the DATASRC attribute.

You can include multiple linked tables and objects in each Web page; each table should specify a DATASRC attribute that can be unique to that table or shared between tables or other elements on the page, such as forms.

The second line of the table definition is unchanged. As you can see, it provides the table heading.

<THEAD><TR><TD>Element</TD><TD>Symbol</TD></TR></THEAD>

The fourth line is the most interesting. Instead of providing the actual data, you specify the name of a column in the data file using the new DATAFLD attribute.

<TR><TD><DIV datafld="Element"></DIV></TD><TD><DIV datafld="Symbol"></DIV></TD></TR>

Because the original data file had a header that specified the name of each column, these column names can be used. If no header is provided in your data file, you should use the default names of Column1, Column2, and so on.

As part of the header that specifies column names, a type specifier can be included indicating the data type of the column. Since the TDC reads its data from a text file, this indicates the appropriate type conversion to do upon reading the data from the file. The TDC uses this to perform accurate sorting and filtering. Consider the case where you have integers in a column and you request the column to be sorted. Without the type specification, the sort would be done using string (lexicographic) ordering, which would give the wrong result. For more information on specifying data types for columns, see Microsoft Tabular Data Control Reference.

With this information encoded in the table, Internet Explorer 4.0 will ask the TDC for data to put into the table. It will then create one new row for each row of data. Notice how all the other table encoding tags remain unchanged. In fact, you can treat the incoming data exactly as if it were text that you hard-coded into your Web page. For example, if you wanted the symbols in the table to be bold and centered in their column, you could change the table entry to the following:

<TD><CENTER><B><DIV datafld="Symbol"></DIV></B></CENTER></TD>

You could also choose to completely leave out the symbol information from the table just by removing the <DIV> entry where it is specified. Although this might not necessarily be appropriate for this example, it's often convenient to omit some fields because that allows you to reuse the same data file in many different Web pages rather than maintaining multiple copies of almost identical data.

Declaring the TDC object

The only other new entry in your Web page is the TDC object declaration. The above examples use the following:

<OBJECT id=elements CLASSID="clsid:333C7BC4-460F-11D0-BC04-0080C7055A83">
    <PARAM NAME="DataURL" VALUE="minielts.txt">
    <PARAM NAME="UseHeader" VALUE="True">
</OBJECT>

The ID attribute identifies the TDC and its associated data for later use by elements such as tables, forms, and scripting. The ID attribute can be any arbitrary name, but it's best to start with a letter and avoid spaces and punctuation characters.

The DataURL property tells the TDC where to find the data file. You can provide any valid URL, or, as in this example, use a relative URL that will cause the TDC to look in the same place your Web page was found. Other valid DataURL settings include the following:

<PARAM NAME="DataURL" VALUE="data/elements.txt">
<PARAM NAME="DataURL" VALUE="http://www.mycoolsite.com.au/elements.txt">
<PARAM NAME="DataURL" VALUE="file://\\intranet\server\buried\down\a\long\path\elements.txt">

DataURL is the only property required by the TDC to access data. To delay the binding, omit the specification of the DataURL property in the object declaration, and set it later in script code.

The UseHeader property indicates whether the first line of the data file identified by DataURL lists the names of the fields. In the example text file above, the first line was:

Element,Symbol

This isn't part of the data. Instead, it identifies the names of the columns in the data set. Because the default value of this property is FALSE, the UseHeader property must be set to TRUE.

Relaxing TDC Security

By default, if the DataURL property specifies a URL on a different domain than that of the Web page, the TDC will silently fail to load the data. This feature prevents unauthorized pages or untrusted scripts from using the TDC to access private data. To allow content providers to create pages that access data on a different domain, providers can insert a domain string in the data. The string begins with "@!allow_domains" and is followed by a semicolon-delimited list of domain names and/or IP addresses. The string must appear exclusively at the beginning of the first line in the data set with no preceding white-space. The exact specification for the format string is as follows:

   domain_string: header_string "=" domain_list
   header_string: "@!allow_domains"
   domain_list: domain_spec [; domain_list ]
   domain_spec: * | [*.] domain | ipaddr

Observe that while wildcards may be used in domain names (*.microsoft.com), they are not supported in IP addresses.

The following is an example of a domain string that could be embedded in a data set to enable a page hosted on all microsoft.com and investor.msn.com servers to access the data.

   @!allow_domains=*.microsoft.com; investor.msn.com

A More Advanced Example: Sorting and Filtering

The example behind the following Show Me button demonstrates how you can automate the sorting and filtering of data in a table. Using the chemistry theme, the example displays a table that contains the first five periods of the periodic table. You can sort the data by clicking any of the three table headings (Position, Element, or Symbol); you can filter the data by choosing a specific period and group from the Period or Group list box.

Sorting data

Dynamic sorting is enabled using the Sort property and the Reset method on the TDC. In the previous example, a VBScript function supports the onclick event for each column heading in the table. When the user clicks a given heading, the corresponding function is called and the Sort property is assigned a value prior to calling the Reset method. The following example shows the function that handles sorting for the Symbol column.

function symbol_onclick()
    elem_list.Sort = "+Symbol"
    elem_list.Reset()
end function

In this example, the Sort property is assigned the name of the third column (Symbol), and then the Reset method is called. The "+" indicates an ascending sort. A "-" prefix indicates a descending sort.

The following excerpt from the HTML source file for this example demonstrates how the column headings were set up using the HTML <DIV> tag.

<THEAD><TR>
     <TD><DIV ID=position><B><U><FONT COLOR=BLUE>Position</FONT></U></B></DIV></TD>
     <TD><DIV ID=element><B><U><FONT COLOR=BLUE>Element</FONT></U></B></DIV></TD>
     <TD><DIV ID=symbol><B><U><FONT COLOR=BLUE>Symbol</FONT></U></B></DIV></TD>
</TR></THEAD>

Filtering data

Dynamic filtering is enabled using the Filter property and the Reset method of the TDC. In the example, a VBScript function supports the onchange event for each drop-down list box that appears above the table. When this function is invoked, a filter expression is constructed from the selected values in the Period and Group combo boxes, the expression is assigned to the Filter property, and the Reset method is called to synchronize the table displaying the data.

The following excerpt from the HTML source file shows the definition of the Period drop-down list box.

<SELECT ID=cboPeriod>
  <OPTION SELECTED VALUE=0>ALL
  <OPTION VALUE=1>1
  <OPTION VALUE=2>2
  <OPTION VALUE=3>3
  <OPTION VALUE=4>4
  <OPTION VALUE=5>5
</SELECT>

When a user selects a different value from either the Period drop-down or the Group drop-down, the following VBScript function handles the resulting onchange event.

function FilterGroupAndPeriod()
   cFilterExpr = ""
   if cboPeriod.selectedIndex > 0 then
      cFilterExpr = "Period=" & cboPeriod.selectedIndex
   end if
   if cboGroup.selectedIndex > 0 then
      if Not IsEmpty(cFilterExpr) then
         cFilterExpr = cFilterExpr & " & "
      end if
      cFilterExpr = cFilterExpr & "Group=" & cboGroup.selectedIndex
      elem_list.object.Filter = cFilterExpr
   end if
   elem_list.object.Filter = cFilterExpr
   elem_list.Reset
end function

The code builds a single expression representing a filter on both the Period and the Group columns in the data set. Notice that if the first value (ALL) is selected in either drop-down, the respective code will not contribute to the filter expression. Also note that if the user has selected an explicit period as well as a group, the subexpressions are separated by an "&" indicating to the TDC that the records to be displayed must meet both criteria. If the user selects "ALL" in both drop-downs, none of the code within the boundaries of the conditional statements is executed, the filter expression remains empty, and all the data is displayed in the bound table.

The final line in this function invokes the Reset method, which evaluates the filter expression, applies it to the data set, and forces MSHTML to re-render the table in which the data is displayed.

Summary

This article has described the features of the Tabular Data Control, a simple read-only data source object provided with Internet Explorer 4.0. For more detailed information on the methods and properties supported by this object, see the Microsoft Tabular Data Control Reference.


Microsoft Tabular Data Control Reference

The Microsoft® Tabular Data Control allows an HTML page to display data from delimited text files, either as part of tables or a row at a time. The data can optionally be filtered or sorted by the browser under script control (with no server involvement). If the first line of the text file is a header line that describes the column names and data types, intelligent sorting and filtering will occur. For example, dates and numbers will sort as expected rather than in strict text order (that is, 2 will sort before 10). Extensions in Microsoft® Internet Explorer 4.0 allow you to bind data fields to controls on an HTML form as well as a single table row that will be expanded to show the data in all rows.

This reference describes the object, properties, and method of the Tabular Data Control.

Objects

Properties

Methods


Tabular Data Control (TDC)

The Tabular Data Control lets you display data that is stored in a delimited text file. The data can optionally be filtered or sorted by the browser using the properties and method exposed by the control.

Microsoft Tabular Data Control

Microsoft Tabular Data Control Reference


AppendData

Specifies whether new data is appended or replaces existing data.

Syntax

dataobj.AppendData = fValue

fValue Boolean expression that controls how data from DataURL is treated. If FALSE, when new data is read it replaces the existing data set. If TRUE, it is added to the existing data. The default value is FALSE.

When this property is set to its default value of FALSE, whenever DataURL is changed and Reset is called, the Tabular Data Control will clear any data it has stored, fetch a new copy of the data, and display it according to the Filter and Sort properties. When AppendData is TRUE, a data fetch will add the data to the existing data. For example, this could be used with search results so that initial results aren't discarded.

It is assumed that the new data exactly matches the format of the first data fetched. The header line is ignored and the data is added to the existing columns. If values are the incorrect type, they will be stored as string values and will thus sort to the end of the column.


CaseSensitive

Indicates whether or not comparisons with the data should ignore case.

Syntax

dataobj.CaseSensitive = fValue

fValue Boolean value. TRUE (default) indicates the data file should be treated case-sensitively. FALSE indicates that upper- and lower-case characters should be treated equally.


CharSet

Syntax

dataobj.CharSet = sValue

Identifies the character set of the data file.

sValue String expression that describes the character set used for the data file. If no value is supplied, the input file is interpreted using codepage 1252 (Western Alphabet).

In normal use, the CharSet property is set in the Web page (or is left at its default value) and never referenced again. Although you can set the property when the data has been loaded, this will not change the interpretation of the data. The only exception to this is if the DataURL property is set to a new value that forces all properties to be reevaluated.

The following are the possible values for the CharSet property.
CharSet Value | CodePage | Description
DIN_66003 | 20106 | IA5 (German)
NS_4551-1 | 20108 | IA5 (Norwegian)
SEN_850200_B | 20107 | IA5 (Swedish)
_autodetect | 50932 | Japanese (Auto Select)
_autodetect_kr | 50949 | Korean (Auto Select)
big5 | 950 | Chinese Traditional (Big5)
csISO2022JP | 50221 | Japanese (JIS-Allow 1 byte Kana)
euc-kr | 51949 | Korean (EUC)
gb2312 | 936 | Chinese Simplified (GB2312)
hz-gb-2312 | 52936 | Chinese Simplified (HZ)
ibm852 | 852 | Central European (DOS)
ibm866 | 866 | Cyrillic Alphabet (DOS)
irv | 20105 | IA5 (IRV)
iso-2022-jp | 50220 | Japanese (JIS)
iso-2022-jp | 50222 | Japanese (JIS-Allow 1 byte Kana)
iso-2022-kr | 50225 | Korean (ISO)
iso-8859-1 | 1252 | Western Alphabet
iso-8859-1 | 28591 | Western Alphabet (ISO)
iso-8859-2 | 28592 | Central European Alphabet (ISO)
iso-8859-3 | 28593 | Latin 3 Alphabet (ISO)
iso-8859-4 | 28594 | Baltic Alphabet (ISO)
iso-8859-5 | 28595 | Cyrillic Alphabet (ISO)
iso-8859-6 | 28596 | Arabic Alphabet (ISO)
iso-8859-7 | 28597 | Greek Alphabet (ISO)
iso-8859-8 | 28598 | Hebrew Alphabet (ISO)
koi8-r | 20866 | Cyrillic Alphabet (KOI8-R)
ks_c_5601 | 949 | Korean
shift-jis | 932 | Japanese (Shift-JIS)
unicode | 1200 | Universal Alphabet
unicodeFEFF | 1201 | Universal Alphabet (Big-Endian)
utf-7 | 65000 | Universal Alphabet (UTF-7)
utf-8 | 65001 | Universal Alphabet (UTF-8)
windows-1250 | 1250 | Central European Alphabet (Windows)
windows-1251 | 1251 | Cyrillic Alphabet (Windows)
windows-1253 | 1253 | Greek Alphabet (Windows)
windows-1254 | 1254 | Turkish Alphabet
windows-1255 | 1255 | Hebrew Alphabet (Windows)
windows-1256 | 1256 | Arabic Alphabet (Windows)
windows-1257 | 1257 | Baltic Alphabet (Windows)
windows-1258 | 1258 | Vietnamese Alphabet (Windows)
windows-874 | 874 | Thai (Windows)
x-euc | 51932 | Japanese (EUC)
x-user-defined | 50000 | User Defined


DataURL

Specifies the location of the data file.

Syntax

dataobj.DataURL = sValue

sValue String expression that points to the data file using a standard URL format such as http:, ftp:, or file: (for example, http://www.microsoft.com/dummy/testdata.txt).

Normally the DataURL property is specified in the Web page along with the <OBJECT> tag for the Tabular Data Control. However, if you change this property after the page has been loaded, this will cause the data file to be loaded on the next Reset. The most common use for DataURL is to set AppendData to TRUE and combine multiple different data files. It could also be used to force the data to be read a second time. You could use this to force a refresh during debugging, for example.

See also AppendData, Reset


EscapeChar

Specifies the character used to escape special characters.

Syntax

dataobj.EscapeChar = cValue

cValue Single character string that is used to avoid the meaning of the other special characters specified by the FieldDelim, RowDelim, and TextQualifier properties. If set to a zero-length string "" (the default), there is no escape character.

Having an escape character is useful if you have data that contains the same type of characters that you are using to delimit fields or rows. For example, if the TextQualifier property is set to the quotation mark character to surround input fields, but some of the fields themselves contain quotation marks, you could edit the data file to prefix the embedded quotation marks with the escape character. In this scenario, if TextQualifier is set to " (double-quote) and you set the EscapeChar property to \ (backslash), the following data file will be interpreted correctly.

"This is cool"
"This is \"really\" cool"

See also FieldDelim, RowDelim, TextQualifier


FieldDelim

Specifies the character used to mark the end of data fields.

Syntax

dataobj.FieldDelim = sValue

sValue String expression that separates one data field from the next. A comma (,) is the default character, but you can set it to any other character. Only a single character can be used to delimit the fields.

Setting nonprintable characters is dependent on the browser language used. In the initial object tag declaration, you can set the FieldDelim property to a tab character as follows:

<PARAM NAME=FieldDelim VALUE="&#09;">

See also EscapeChar, RowDelim, TextQualifier


Filter

Specifies how the data will be filtered.

Syntax

dataobj.object.Filter = sValue

sValue String expression containing one or more columns and associated criteria. By default, this is set to the empty string (that is, no filtering occurs and all rows are displayed). An invalid expression will cause all rows to be returned. If there is no header line that names the columns, they are given default names of Column1, Column2, Column3, and so on. The special wildcard character, *, can be used to match any character.

Filter restricts the data displayed to the user. It can be set in the <OBJECT> tag description to cause initial filtering, or the browser script language can set it and it will take effect when the Reset method is called. The data is fetched only once, so this is an efficient way of displaying the same data many different ways.

The following <OBJECT> tag description will cause address book data to be filtered so that only entries with phone numbers will be displayed.

<PARAM NAME=Filter VALUE="PhoneNum <> ''">

You could use the wildcard character to match all phone numbers starting with 9 with:

<PARAM NAME=Filter VALUE="PhoneNum <> '9*'">

A more complex filter could be:

<PARAM NAME=Filter VALUE="(Quantity > 10 & color = 'lime') |
    Quantity < 5"

This code would find rows with a quantity greater than 10 that are lime colored combined with all rows that have a quantity less than five.

The exact syntax support by filter is defined below. In essence, any arbitrary expression using the usual relational operators is allowed, including comparisons between fields. AND (&) and OR (|) operators have equal precedence and thus must be surrounded by parenthesis if combined.

Complex ::== Simple
 ::== Simple '&' Simple [ '&' Simple ... ]
 ::== Simple '|' Simple [ '|' Simple ... ]
Simple ::== '(' Complex ')'
 ::== Atom Relop Atom
Relop ::== '=' | '>' | '>=' | '<' | '<=' | '<>'
Atom ::== Characters up to a (, ), >, <, =, & or |

If an atom is recognizable as a field name, it is treated as a field name. Otherwise, it's treated as a value. Quotes (") are processed and force the atom to be treated as a value. Escape characters (\) are processed and allow the use of special characters within a field name. It is illegal to attempt a comparison of two columns with different types.

The definition of 'Complex' expressly forbids mixing logical ANDs and ORs (& and |) unless parentheses are used to clarify the query. The following is illegal:

field1 > 10 & field3 = "lime" | field4 < 5

But the following is allowed:

(field1 > 10 & field3 = "lime") | field4 < 5

See also Reset, Sort, UseHeader


Language

Specifies the language of the data file, including numerical and data formats.

Note The object property is specified to avoid a conflict with the language extender property which is exposed on all elements.

Syntax

dataobj.object.Language = sValue

sValue String expression that describes the language of the data file using the HTML standard codes (as defined by ISO 369). The default value is eng-us. Set this appropriately to ensure the correct handling of decimal separator characters in floating-point data and default data interpretation.

See also CharSet


Methods Methods *
  * Previous Topic: UseHeader
  * Next Topic: Reset

Methods

This section describes the Reset method.


Objects

Object

Syntax

<OBJECT ID=object
CLASSID = "clsid:333C7BC4-460F-11D0-BC04-0080C7055A83">
[<PARAM NAME=property VALUE=setting>]
</OBJECT>

Object | String identifying the object.
Property | One of the elements in the table below.
Setting | Value for the property.

Property | Description
AppendData | Specifies whether new data is appended or replaces existing data.
CaseSensitive | Indicates whether the TDC distinguishes characters in the data set based upon their case.
CharSet | Identifies the character set of the data file.
DataURL | Specifies the location of the data file.
EscapeChar | Specifies the character used to escape special characters.
FieldDelim | Specifies the character used to mark the end of data fields.
Filter | Specifies the criteria to use for filtering the data.
Language | Specifies the language of the data file, including numerical and date formats.
RowDelim | Specifies the character used to mark the end of each row.
Sort | Identifies the columns to be sorted, and ascending ordescending sort order.
TextQualifier | Specifies the optional character that surrounds a field.
UseHeader | Specifies whether the first line of the data file contains header information.

Method | Description
Reset | Causes the control to filter or sort its data based on new settings.


Properties

This section describes the TDC properties.

  • AppendData
  • CaseSensitive
  • CharSet
  • DataURL
  • EscapeChar
  • FieldDelim
  • Filter
  • Language
  • RowDelim
  • Sort
  • TextQualifier
  • UseHeader


Reset

Causes the control to filter or sort its data based on new settings.

Syntax

dataobj.Reset

When Reset is called, all the data is filtered and sorted according to the settings of the filter and sort properties. A typical use of the Reset method would be to specify a new Sort or Filter in script in response to a user action.

Data will only be fetched again if either DataURL has been changed or if the data has changed since the last Reset. Note that setting DataURL to itself is viewed as a change, so you can force a refetch of the data from script with the following:

dataobj.DataURL = Dataobj.DataURL
dataobj.Reset

After the Reset method is invoked, the browser will redisplay the data if necessary.

See also Filter, Sort


RowDelim

Specifies the character used to mark the end of each row.

Syntax

dataobj.RowDelim = sValue

sValue String expression that separates one data field from the next. The default value is "newline", but it can be set to any other character. Only a single character may be used to delimit a row.

Special interpretation is done for end-of-line or newline characters, which should provide correct parsing in most circumstances.

See also EscapeChar, FieldDelim, TextQualifier


Sort

Identifies the columns to be sorted, and ascending or descending sort order.

Syntax

dataobj.Sort = sValue

sValue String expression that is the name of one or more comma-separated names of columns in the text file. Each name can be optionally prefixed with a minus sign (-) to indicate a descending sort. By default this property is set to the empty string. If there is no header line that names the columns, they are given default names of Column1, Column2, Column3, and so on. If Sort is set to an empty string (""), no data will be sorted.

Data types are sorted as follows:
Data type | Ascending | Descending
Text | "a", "b", "c" ... "z" | "z", "y", "x" ... "a"
Numeric | ... -1, 0, 1, ... | ...1, 0, -1...
Date | 1/1/1950, 1/1/1990, 1/1/2000 | 1/1/2000, 1/1/1990, 1/1/1950
Logical | False, False, ... , True, True | True, True, ..., False, False

Sort sorts the data displayed to the users. It can be set in the initial <OBJECT> tag description to cause initial sorting, or the browser script language can set it and sorting will take effect when the Reset method is called.

Text data is sorted case-insensitively.

The following example shows how you could sort a food list into ascending order by name and decreasing price.

dataobj.Sort = "FoodItem; -Price"

All invalid data always sorts higher than valid data. For example, a string in an ascending numeric column will display at the end. Multiple invalid data rows are grouped together but not sorted into a defined order within the group.

See Also

Filter, Reset


TextQualifier

Specifies the optional character that surrounds a field.

Syntax

dataobj.TextQualifier = cValue

cValue Single character string used to surround fields that can include special characters such as newlines, tabs, or commas. These characters can also be active as field or row delimiters. The default value is the double quote character (").

Comma-delimited text files and similar text data files usually surround text fields in those files with quotes. For example, a simple phone book text file could be arranged like the following:

Fred Nurks, "42 Worldwide Way, Woy Woy", 555-1212
Brianne Hardy, "Apt 3, 14 Hopalong Crescent, Wogga", 555-2121

Normally the commas in the address text would cause the fields to be read incorrectly, but the surrounding double-quote characters avoid that.

Another common use for TextQualifier is when one of the data fields contains HTML text with lots of separate paragraphs (also known as newline characters).

See also EscapeChar, FieldDelim, RowDelim


UseHeader

Specifies whether the first line of the data file contains header information.

Syntax

dataobj.UseHeader = fValue

fValue Boolean expression that indicates that the data file contains an initial line that names each column and optionally specifies its data type.

If fValue is TRUE, the first line of the data file should match the following layout:

fieldname:type, fieldname:type, ...

Note that the above assumes the default field and row delimiters (comma and newline, respectively).

Fieldname can be an arbitrary text string, although it is best to avoid spaces and other punctuation characters.

Type can be one of the following types of values:
String | Textual data (default)
Date | Calendar dates (see below for formatting)
Boolean | Logical data (Yes/No, True/False, 0/not 0)
Int | Integral numbers (-3, 1, 5)
Float | Floating point numbers (3.141, 2.77, 0)

Date can be optionally followed by a space and then the letters D, M, and Y in any order. These correspond to Day, Month, and Year and control the interpretation of the dates in the data file. The date data is treated as three numbers separated by characters, so the actual separation character is not important.

Boolean will interpret the following data:
True values: Yes, True, 1, -1, any nonzero number
False values: No, False, 0 (zero)

The decimal separator used by float data is determined by the Language property.

The following sample data file shows how the various data types can be declared when UseHeader is set to TRUE and the default settings for FieldDelim, RowDelim, and Language are used.

FoodItem,Price:Float,Purchased:Date YMD,OnOrder:Boolean,Quantity:Int
Bread,1.57,97/5/12,Yes,30
Cheese,3.52,96/2/2,No,5
Old Wine,183.99,1905-1-1,No,1

See also DataURL, Language, Reset


Active Script Debugging API

Active Script Debugging API Active Script Debugging API *
  * Next Topic:

 Debug Property Interfaces

Active Script Debugging Interfaces

Active Script Debugging is a set of interfaces that allow language-neutral, host-neutral debugging, with support for a wide variety of development environments.

[ Architecture GIF]

By language neutral, we mean that a debugging environment can support essentially any programming language, without having to have specific knowledge of that language built into the environment. (Today, the interfaces focus primarily on support scripting languages such as VBScript and JScript, as well as Java, but in the future we intended evolve them to support native code in languages such as C++.) Furthermore, the debugger automatically has the ability to debug applications written in a mixture of multiple languages, with cross-language stepping and breakpoints.

By host neutral, we mean that the debugger can be automatically be used with any Active Scripting host, such as Internet Explorer, Spruuids, or any any other host written in the future. We also mean that the host has control over the structure of the document tree presented to the user and the contents and syntax coloring of the documents being debugged. This allows the host to present the source code being debugged in the context of the host document (for example, scripts can be show on an HTML page.) In the subsections below, we consider each of the key components in Active Debugging and their associated interfaces.

Before proceeding further, we should define several key Active Debugging concepts:

host application: The application that hosts the script engines and provides a scriptable set of objects (or "object model").

language engine: A component that provides parsing, execution, and debugging abstractions for a particular languages.

debugger IDE: The application that provides debugging UI by communicating with the host application and language engines.

machine debug manager: A component that maintains a registry of debuggable application processes.

process debug manager: A component that maintains the tree of debuggable documents a particular application, tracks the running threads, etc.

document context:: A document context is an abstraction representing a specific range in the source code of a host document.

code context: A code context represents a particular location in the running code of a language engine (a "virtual instruction pointer".)

expression context: A particular context (for example, a stack frame) in which expressions may be evaluated by a language engine.

object browsing: A structured, language-independent representation of an objects name, type, value, and subobjects, suitable for implementating a "watch window" UI.

Below, we provide an overview of each of the key Active Debugging components and their associated interfaces, followed by the details of those interfaces.

Language Engine

The language engine provides:

- Language parsing and execution

- Debugging support (breakpoints,etc..).

- Expression evaluation.

- Syntax coloring.

- Object browsing.

- Stack enumeration and parsing.

Below is a list of the key interfaces implemented by a language engine. These interfaces are used by the host application to map between its document context and the engine's code contexts, and also by the debugger UI to do expression evaluation, stack enumeration, and object browsing.

IActiveScriptDebug; // provides syntax coloring and code context enumeration

IActiveScriptErrorDebug; // returns document contexts and stack frames for errors

IActiveScriptSiteDebug; // host provided link from script engine to debugger

IActiveScriptTextInfo; // Language engine debugging abstractions

IDebugCodeContext; // a virtual "instruction pointer" in a thread

IEnumDebugCodeContexts;

IDebugStackFrame; // logical stack frame on the stack of a thread

IDebugExpressionContext; // a context in which expressions can be evaluated

IDebugStackFrameSniffer; // enumerator for stack frames known by an engine

IDebugExpressionContext; // context for expression evaluation

IDebugExpression; // an asynchronously evaluated expression

IDebugSyncOperation;

IDebugAsyncOperation;

IDebugAsyncOperationCallBack;

IDebugExpressionCallBack; // status events for IDebugExpression evaluation progress

IEnumDebugExpressionContexts;

IProvideExpressionContexts; // Object browsing

IDebugFormatter;

Hosts

The host:

- Hosts the language engines.

- Provides an object model (set of objects that can be scripted)

- defines a tree of documents that can be debugged and their contents

- Organizes scripts into virtual applications.

There are two kinds of hosts:

1. A dumb host supports just the basic ActiveScripting interfaces. It has no control over document structure or organizations; this is determined entirely by the scripts provided to the language engines.

2. A smart host supports a larger set of interface that allow it to define the document tree, document contents, and syntax coloring. There are a set of helper interfaces, described in the next subsection, which make it much easier for a host to be a smart host.

Smart-host Helper Interfaces

The IDebugDocumentHelper are a greatly simplified set of interfaces that a host can use to gain the benefits of smart-hosting without having to handle the full complexity (and power) of the full host interfaces.

A host is not required to use these interfaces, of course, but by using these can avoid having to implement or use a number of more complicated interfaces.

IDebugDocumentHelper; // implemented by PDM

IDebugDocumentHost; // implemented (optionally) by the host

Full Smart-host Interfaces

Below is the full set of interfaces that a smart-host needs to implement or use if it's not using the helper interfaces.

// implemented by host

IDebugDocumentInfo; // provides info on (possibily uninstantiated) doc

IDebugDocumentProvider; // allows doc to be instantiated on demand

IDebugDocument; // base document interface

IDebugDocumentText; // provides access to source text of document

IDebugDocumentTextEvents; // events fired when source text changes

IDebugDocumentTextAuthor;

IDebugDocumentContext; // represents a range within the document

// implemented by PDM on behalf of the host

IDebugApplicationNode; // represents the position of a doc in the hierarchy

IDebugApplicationNodeEvents; // events fired by PDM when document hierarchy changes

Debugger IDE

The IDE is a fully language independent debugging UI. It provides:

- Document viewers/editors.

- Breakpoint management.

- Expression evaluation and watch windows.

- Stack frame browsing.

- Object/Class browsing.

- Browsing the virtual application structure.

// Debugger implementation

IDebugSessionProvider; // establishes a debug session for a running application.

IApplicationDebugger; // primary interface exposed by a debugger IDE session

Machine Debug Manager

The machine debug manager provides the hookup point between virtual applications and debuggers by maintaining and enumerating a list of active virtual applications.

IMachineDebugManager;

IMachineDebugManagerCookie;

IMachineDebugManagerEvents;

IEnumRemoteDebugApplications;

Process Debug Manager

The PDM does the following:

- Synchronizes the debugging of multiple language engines.

- Maintains a tree of debuggable documents

- Merges stack frames.

- Coordinates breakpoints and stepping across language engines.

- Tracks threads.

- Maintains a debugger thread for asynchronous processing.

- Communicates with the machine debug manager and the debugger IDE.

The following are the interfaces provided by the process debug manager.

IProcessDebugManager; // creates, adds and removes virtual applications, etc.

IRemoteDebugApplication; // virtual application abstraction

IDebugApplication;

IRemoteDebugApplicationThread; // virtual thread abstraction

IDebugApplicationThread;

IEnumRemoteDebugApplicationThreads;

IDebugThreadCall; // dispatches marshalled calls

IDebugApplicationNode; // maintains a position for a document in the hierarchy

IEnumDebugApplicationNodes;

IEnumDebugStackFrames; // merged enumeration of stack frames from engines

Structures and Enumerations

These structures and enumerations are used in a number of the interfaces below.

BREAKPOINT_STATE

Indicates the state of a breakpoint.

typedef enum tagBREAKPOINT_STATE {

BREAKPOINT_DELETED = 0,// The breakpoint no longer exists but there are still references

BREAKPOINT_DISABLED = 1,// The breakpoint exists but is disabled

BREAKPOINT_ENABLED = 2// The breakpoint exists and is enabled

} BREAKPOINT_STATE;

APPBREAKFLAGS

Application break flags. Indicates the current debug state for the application and the current thread.

When certain of these bits are set (some are per-thread and some are for all threads), language engines should break at the next opportunity.

typedef DWORD APPBREAKFLAGS;

// DEBUGGER_BLOCK

// languages should break immediately with BREAKREASON_DEBUGGER_BLOCK

const APPBREAKFLAGSAPPBREAKFLAG_DEBUGGER_BLOCK= 0x00000001;

// DEBUGGER_HALT

// languages should break immediately with BREAKREASON_DEBUGGER_HALT

const APPBREAKFLAGSAPPBREAKFLAG_DEBUGGER_HALT= 0x00000002;

// STEP

// languages should break immediately in the stepping thread with BREAKREASON_STEP

const APPBREAKFLAGSAPPBREAKFLAG_STEP= 0x00010000;

// NESTED - the application is in nested execution on a breakpoint

const APPBREAKFLAGSAPPBREAKFLAG_NESTED= 0x00020000;

// STEP TYPES - defines whether we are stepping at source, bytecode, or machine level.

const APPBREAKFLAGSAPPBREAKFLAG_STEPTYPE_SOURCE= 0x00000000;

const APPBREAKFLAGSAPPBREAKFLAG_STEPTYPE_BYTECODE= 0x00100000;

const APPBREAKFLAGSAPPBREAKFLAG_STEPTYPE_MACHINE= 0x00200000;

const APPBREAKFLAGSAPPBREAKFLAG_STEPTYPE_MASK= 0x00F00000;

// BREAKPOINT IN_PROGRESS

const APPBREAKFLAGSAPPBREAKFLAG_IN_BREAKPOINT= 0x80000000;

BREAKREASON

Indicates the cause of hitting a breakpoint.

typedef enum tagBREAKREASON{

BREAKREASON_STEP,// Caused by the stepping mode

BREAKREASON_BREAKPOINT,// Caused by an explicit breakpoint

BREAKREASON_DEBUGGER_BLOCK,// Caused by another thread breaking

BREAKREASON_HOST_INITIATED,// Caused by host requested break

BREAKREASON_LANGUAGE_INITIATED,// Caused by a scripted break

BREAKREASON_DEBUGGER_HALT,// Caused by debugger IDE requested break

BREAKREASON_ERROR// Caused by an execution error

} BREAKREASON;

BREAKRESUME_ACTION

Describes how to continue from a breakpoint

typedef enum tagBREAKRESUME_ACTION{

BREAKRESUMEACTION_ABORT,// Abort the application

BREAKRESUMEACTION_CONTINUE,// Continue running

BREAKRESUMEACTION_STEP_INTO,// Step into a procedure

BREAKRESUMEACTION_STEP_OVER,// Step over a procedure

BREAKRESUMEACTION_STEP_OUT// Step out of the current procedure

} BREAKRESUMEACTION;

ERRORRESUME_ACTION

Describes how to continue from a runtime error.

typedef enum tagERRORRESUMEACTION {

ERRORRESUMEACTION_ReexecuteErrorStatement,// try executing the erroneous line again

ERRORRESUMEACTION_AbortCallAndReturnErrorToCaller,// let the language engine handle the error

ERRORRESUMEACTION_SkipErrorStatement,// resume execution from beyond the error

} ERRORRESUMEACTION;

DOCUMENTNAMETYPE

Describes what type of name you'd like to get for a document:

typedef enum tagDOCUMENTNAMETYPE {

DOCUMENTNAMETYPE_APPNODE,// Gets the name ass it appears in the app tree

DOCUMENTNAMETYPE_TITLE,// Gets the name as it appears on the doc viewer title bar

DOCUMENTNAMETYPE_FILE_TAIL,// Gets the filename without a path (for save as...)

DOCUMENTNAMETYPE_URL,// Gets the URL of the document, if any

} DOCUMENTNAMETYPE;

SOURCE_TEXT_ATTR

Describes the attributes of a single character of source text.

typedef WORD SOURCE_TEXT_ATTR;

// The character is a part of a language keyword. Example: while

const SOURCE_TEXT_ATTR SOURCETEXT_ATTR_KEYWORD= 0x0001;

// The character is a part of a comment block.

const SOURCE_TEXT_ATTR SOURCETEXT_ATTR_COMMENT= 0x0002;

// The character is not part of compiled language source text. Example:

// the HTML surrounding script blocks.

const SOURCE_TEXT_ATTR SOURCETEXT_ATTR_NONSOURCE= 0x0004;

// The character is a part of a language operator. Example: *

const SOURCE_TEXT_ATTR SOURCETEXT_ATTR_OPERATOR= 0x0008;

// The character is a part of a language numeric constant. Example: 1234

const SOURCE_TEXT_ATTR SOURCETEXT_ATTR_NUMBER= 0x0010;

// The character is a part of a language string constant. Example: "Hello World"

const SOURCE_TEXT_ATTR SOURCETEXT_ATTR_STRING= 0x0020;

// The character indicates the start of a function block

const SOURCE_TEXT_ATTR SOURCETEXT_ATTR_FUNCTION_START = 0x0040;

TEXT_DOC_ATTR

Describes the attributes of the document

typedef DWORD TEXT_DOC_ATTR;

// Indicates that the document is read-only.

const TEXT_DOC_ATTR TEXT_DOC_ATTR_READONLY = 0x00000001;

Parse Flags

Option flags used during IDebugExpressionContext::ParseLanguageText

// Indicates that the text is an expression as opposed to a statement. This

// flag may affect the way in which the text is parsed by some languages.

const DWORD DEBUG_TEXT_ISEXPRESSION= 0x00000001;

// If a return value is available, it will be used by the caller.

const DWORD DEBUG_TEXT_RETURNVALUE= 0x00000002;

// Don't allow side effects. If this flag is set, the evaluation of the

// expression should change no runtime state.

const DWORD DEBUG_TEXT_NOSIDEEFFECTS= 0x00000004;

// Allow breakpoints during the evaluation of the text. If this flag is not

// set then breakpoints will be ignored during the evaluation of the text.

const DWORD DEBUG_TEXT_ALLOWBREAKPOINTS= 0x00000008;

// Allow error reports during the evaluation of the text. If this flag is not

// set then errors will not be reported to the host during the evaluation.

const DWORD DEBUG_TEXT_ALLOWERRORREPORT= 0x00000010;

Script Engine Debugging Interfaces

Below are the interfaces that a script engine needs to support to provide debugging, expression evaluation, and object browsing.

IActiveScriptDebug

This interface is implemented by script engines that support debugging, and is QI-able from IActiveScript. It provides the means for:

1.Smart hosts to take over document management.

2.Process debug manager to synchronize debugging of multiple script engines.

[

object,

uuid(51973C10-CB0C-11d0-B5C9-00A0244A0E7A),

pointer_default(unique)

]

interface IActiveScriptDebug : IUnknown

{

// Returns the text attributes for an arbitrary block of script text. Smart hosts

// use this call to delegate GetText calls made on their IDebugDocumentText.

HRESULT GetScriptTextAttributes(

// The script block text. This string need not be null terminated.

[in, size_is(uNumCodeChars)]LPCOLESTRpstrCode,

// The number of characters in the script block text.

[in]ULONGuNumCodeChars,

// See IActiveScriptParse::ParseScriptText for a description of this argument.

[in]LPCOLESTRpstrDelimiter,

// See IActiveScriptParse::ParseScriptText for a description of this argument.

[in]DWORDdwFlags,

// Buffer to contain the returned attributes.

[in, out, size_is(uNumCodeChars)]SOURCE_TEXT_ATTR *pattr);

// Returns the text attributes for an arbitrary scriptlet. Smart hosts

// use this call to delegate GetText calls made on their IDebugDocumentText.

// Note: this call is provided because scriptlets tend to be expressions and

// may have a different syntax than a script block. For many languages the implementation

// will be identical to GetScriptTextAttributes.

HRESULT GetScriptletTextAttributes(

// The script block text. This string need not be null terminated.

[in, size_is(uNumCodeChars)]LPCOLESTRpstrCode,

// The number of characters in the script block text.

[in]ULONGuNumCodeChars,

// See IActiveScriptParse::AddScriptlet for a description of this argument.

[in]LPCOLESTRpstrDelimiter,

// See IActiveScriptParse::AddScriptlet for a description of this argument.

[in]DWORDdwFlags,

// Buffer to contain the returned attributes.

[in, out, size_is(uNumCodeChars)]SOURCE_TEXT_ATTR *pattr);

// Used by the smart host to delegate IDebugDocumentContext::EnumDebugCodeContexts.

HRESULT EnumCodeContextsOfPosition(

[in]DWORD dwSourceContext,// As provided to IActiveScriptParse::ParseScriptText

// or IActiveScriptParse::AddScriptlet

[in]ULONG uCharacterOffset,// character offset relative

// to start of script text

[in]ULONG uNumChars,// Number of characters in context

// Returns an enumerator of code contexts.

[out] IEnumDebugCodeContexts IEnumDebugCodeContexts **ppescc);

}

IActiveScriptSiteDebug

Implemented by smart hosts and is QI-able from IActiveScriptSite. It provides the means by which a smart host takes over document management and participates in debugging.

[

object,

uuid(51973C11-CB0C-11d0-B5C9-00A0244A0E7A),

pointer_default(unique),

local

]

interface IActiveScriptSiteDebug : IUnknown

{

// Used by the language engine to delegate IDebugCodeContext::GetSourceContext.

HRESULT GetDocumentContextFromPosition(

[in]DWORD dwSourceContext,// As provided to ParseScriptText

// or AddScriptlet

[in]ULONG uCharacterOffset,// character offset relative

// to start of script block or scriptlet

[in]ULONG uNumChars,// Number of characters in context

// Returns the document context corresponding to this character-position range.

[out] IDebugDocumentContext IDebugDocumentContext **ppsc);

// Returns the debug application object associated with this script site. Provides

// a means for a smart host to define what application object each script belongs to.

// Script engines should attempt to call this method to get their containing application

// and resort to IProcessDebugManager::GetDefaultApplication if this fails.

HRESULT GetApplication(

[out] IDebugApplication IDebugApplication **ppda);

// Gets the application node under which script documents should be added

// can return NULL if script documents should be top-level.

HRESULT GetRootApplicationNode(

[out] IDebugApplicationNode IDebugApplicationNode **ppdanRoot);

// Allows a smart host to control the handling of runtime errors

HRESULT OnScriptErrorDebug(

// the runtime error that occurred

[in] IActiveScriptErrorDebug IActiveScriptErrorDebug *pErrorDebug,

// whether to pass the error to the debugger to do JIT debugging

[out]BOOL*pfEnterDebugger,

// whether to call IActiveScriptSite::OnScriptError() when the user

// decides to continue without debugging

[out]BOOL *pfCallOnScriptErrorWhenContinuing);

}

IActiveScriptErrorDebug

Provides document context information for compile and runtime errors. QI-able from IActiveScriptError.

[

object,

uuid(51973C12-CB0C-11d0-B5C9-00A0244A0E7A),

pointer_default(unique)

]

interface IActiveScriptErrorDebug : IActiveScriptError

{

// Provides the document context for the associated error. The character-position range

// should include the entire offending text.

HRESULT GetDocumentContext(

[out] IDebugDocumentContext IDebugDocumentContext **ppssc);

// For runtime errors, provides the stack frame that is in effect.

HRESULT GetStackFrame(

[out] IDebugStackFrame IDebugStackFrame **ppdsf);

}

IDebugCodeContext

Abstraction reresenting a position in executable code. It can be thought of as a "virtual program counter".

[

object,

uuid(51973C13-CB0C-11d0-B5C9-00A0244A0E7A),

pointer_default(unique)

]

interface IDebugCodeContext : IUnknown

{

// Returns the document context associated with this code context.

//

// Note: For text documents, the character-position

// range should include the text for the entire statement. This allows the debugger IDE

// to hilight the current source statement.

HRESULT GetDocumentContext(

[out] IDebugDocumentContext IDebugDocumentContext **ppsc);

// Sets or clears a breakpoint at this code context.

HRESULT SetBreakPoint(

[in] BREAKPOINT_STATE bps);

}

IDebugExpression

Abstract representation of an asynchronously evaluated expression. Normally used by the debugger IDE to implement an immediate execution window or watch window. Normally provided by language engines.

Note: Currently, IDebugExpression is only available from a stack frame.

[

object,

uuid(51973C14-CB0C-11d0-B5C9-00A0244A0E7A),

pointer_default(unique)

]

interface IDebugExpression : IUnknown

{

// Begins the evaluation of the expression.

HRESULT Start(

// Provides an event driven means for indicating that the expression evaluation

// is complete. If NULL, no events will be fired and the client will need to

// poll the expression state using QueryIsComplete.

[in] IDebugExpressionCallBack *pdecb);

// Aborts the expression. Evaluation of an expression in progress will be stopped

// at the earliest opportunity. If the expression is actually aborted, GetResultAsString

// will return E_ABORT as phrResult.

HRESULT Abort(void);

// Returns S_FALSE if the operation is still pending.

// Returns S_OK if the operation is complete.

HRESULT QueryIsComplete(void);

// Returns the result of the expression evaluation as a string and an HRESULT. Returns

// E_PENDING if the operation is still pending. Returns S_OK and E_ABORT in phrResult

// when the operation was aborted with Abort.

HRESULT GetResultAsString(

[out] HRESULT *phrResult,

[out] BSTR *pbstrResult);

// Returns the result of the expression evaluation as an

// IDebugProperty and an HRESULT. Returns

// E_PENDING if the operation is still pending. Returns S_OK and E_ABORT in phrResult

// when the operation was aborted with Abort.

HRESULT GetResultAsDebugProperty(

[out] HRESULT *phrResult,

[out] IDebugProperty **ppdp);

}

IDebugExpressionContext

Abstract representation of a context in which expressions can be evaluated. Currently, this interface is only implemented by the stack frame object. In the future, other objects, such as the document context, may provide this interface.

[

object,

uuid(51973C15-CB0C-11d0-B5C9-00A0244A0E7A),

helpstring("IDebugExpressionContext Interface"),

pointer_default(unique)

]

interface IDebugExpressionContext : IUnknown

{

// Creates an IDebugExpression for the specified text.

HRESULT ParseLanguageText(

// Provides the text of the expression or statement(s).

[in]LPCOLESTRpstrCode,

// Radix to use

[in]UINTnRadix,

// See IActiveScriptParse::ParseScriptText

[in]LPCOLESTRpstrDelimiter,

// See above flags.

[in]DWORDdwFlags,

// Returns the IDebugExpression for the given text.

[out] IDebugExpression IDebugExpression **ppe

);

// Returns a name and GUID for the langauge owning this context

HRESULT GetLanguageInfo (

[out]BSTR*pbstrLanguageName,// the name of the language

[out]GUID*pLanguageID// an unique id for this language

);

}

IDebugExpressionCallback

Provides status events related to progress of an IDebugExpression evaluation.

[

object,

uuid(51973C16-CB0C-11d0-B5C9-00A0244A0E7A),

pointer_default(unique)

]

interface IDebugExpressionCallBack : IUnknown

{

// Indicates that the expression evaluation is complete. Note that

// IDebugExpression::GetResultAsString can be called from within this event

// handler.

HRESULT onComplete(void);

}

IDebugStackFrame

Abstraction representing a logical stack frame on the stack of a thread. Note that it derives from IDebugExpressionContext. This allows the debugger to evaluate expressions in the context of a particular stack frame.

Note: In general, you can QI a stack frame for IDebugExpressionContext to allow expression evaluation and watch windows

[

object,

uuid(51973C17-CB0C-11d0-B5C9-00A0244A0E7A),

pointer_default(unique)

]

interface IDebugStackFrame : IUnknown

{

// Returns the current code context associated with the stack frame.

HRESULT GetCodeContext(

[out] IDebugCodeContext IDebugCodeContext **ppcc);

// Returns a short or long textual description of the stack frame.

// Normally, when fLong if false, this will provide only the name of the

// function associated with the stack frame. When fLong is true it may

// also provide the parameter(s) to the function or whatever else is

// relevant.

HRESULT GetDescriptionString(

[in] BOOL fLong,

[out] BSTR *pbstrDescription);

// Returns a short or long textual description of the language. When fLong

// is false, just the language name should be provided, eg, "Pascal". When

// fLong is true a full product description may be provided, eg,

// "Gnat Software's Flaming Pascal v3.72".

HRESULT GetLanguageString(

[in] BOOL fLong,

[out] BSTR *pbstrLanguage);

// Returns the thread associated with this stack frame.

HRESULT GetThread(

[out] IDebugApplicationThread IDebugApplicationThread **ppat);

// Returns a property browser for the current frame (locals, etc.)

HRESULT GetDebugProperty(

[out] IDebugProperty **ppDebugProp);

}

IDebugStackFrameSniffer

Provides a means for enumerating logical stack frames known by a certain component. Generally implemented by each script engine. Used by the process debug manager to find all stack frames associated with a given thread. Note: This interface is called from within the thread of interest. It is up to the implementor to identify the current thread and return an appropriate enumerator.

[

object,

uuid(51973C18-CB0C-11d0-B5C9-00A0244A0E7A),

pointer_default(unique)

]

interface IDebugStackFrameSniffer : IUnknown

{

// Returns an enumerator of stack frames for the current thread. Top of stack should

// be returned first (the most recently pushed frame).

HRESULT EnumStackFrames(

[out] IEnumDebugStackFrames IEnumDebugStackFrames **ppedsf);

}

IDebugStackFrameSnifferEx

Provides a means for enumerating logical stack frames known by a certain component. Generally implemented by each script engine. Used by the process debug manager to find all stack frames associated with a given thread.

Note: This interface is called from within the thread of interest. It is up to the implementor to identify the current thread and return an appropriate enumerator.

[

object,

uuid(51973C19-CB0C-11d0-B5C9-00A0244A0E7A),

pointer_default(unique)

]

interface IDebugStackFrameSnifferEx : IDebugStackFrameSniffer IDebugStackFrameSniffer

{

// Returns an enumerator of stack frames for the current thread.

// dwSpMin is the minimum address to begin enumerating stack frames

// Stack frames before this address will be omitted from the enumeration.

// Top of stack should be returned first (the most recently pushed frame).

HRESULT EnumStackFramesEx( [in] DWORD dwSpMin, [out] IEnumDebugStackFrames IEnumDebugStackFrames **ppedsf);

};

IDebugSyncOperation

IDebugSyncOperation is generally implemented by a language engine to expose expression evaluation, etc. It allows the implementor to abstract an operation that needs to be performed nested in a particular blocked thread, and it provides a mechanism for cancelling hung operations.

[

object,

uuid(51973C1a-CB0C-11d0-B5C9-00A0244A0E7A),

pointer_default(unique),

local

]

interface IDebugSyncOperation : IUnknown

{

// Get TargetThread is called by PDM to determine what thread

// to call Evaluate() in

HRESULT GetTargetThread(

[out] IDebugApplicationThread IDebugApplicationThread **ppatTarget);

// Execute is called synchronously by the PDM in the target thread. It

// synchronously peforms the operation and returns. It returns E_ABORT if

// the operation was aborted with InProgressAbort();

HRESULT Execute(

[out]IUnknown **ppunkResult);

// InProgressAbort() is called by the PDM, from within the debugger thread,

// to cancel an operation which is in progress in another thread. The

// operation should be completed or error out with E_ABORT as soon as

// possible. E_NOTIMPL can be returned if the operation cannot be cancelled.

HRESULT InProgressAbort(void);

}

IDebugAsyncOperation

IDebugAsyncOperation is generally implemented by the PDM, and is obtained by a language engine through IDebugApplication::CreateAsyncDebugOperation(). The language engine can use it to provide asynchronous access to a SyncDebugOperation.

[

object,

uuid(51973C1b-CB0C-11d0-B5C9-00A0244A0E7A),

pointer_default(unique),

local

]

interface IDebugAsyncOperation : IUnknown

{

HRESULT GetSyncDebugOperation(

[out] IDebugSyncOperation IDebugSyncOperation **ppsdo);

// Start() causes the asynchronous operation to begin. It asynchronously

// causes IDebugSyncOperation::Execute() to be called in the thread obtained

// from IDebugSyncOperation::GetTargetThread(). It should only

// be called from within the debugger thread, or it will not return until

// the operation is complete (it degenerates to synchronous).

// Returns E_UNEXPECTED if an operation is already pending.

HRESULT Start( IDebugAsyncOperationCallBack IDebugAsyncOperationCallBack *padocb);

// Abort() causes InProgressAbort() to be called on the IDebugSyncOperation

// object. It is normally called from within the debugger thread to cancel

// a hung operation. If the abort happens before the request completes,

// GetResult() will return E_ABORT. E_NOTIMPL may be returned from this

// function if the operation is not cancellable.

HRESULT Abort(void);

// QueryIsComplete() returns S_OK if the operation is complete; otherwise it

// returns S_FALSE;

HRESULT QueryIsComplete(void);

// If the request is complete, returns the HRESULT and object parameter

// returned from IDebugSyncOperation::Execute(). Otherwise, returns

// E_PENDING.

HRESULT GetResult(

[out] HRESULT *phrResult,

[out] IUnknown **ppunkResult);

}

IDebugAsyncOperationCallBack

This interface is used to signal events from an IDebugAsyncOperation.

[

object,

uuid(51973C1c-CB0C-11d0-B5C9-00A0244A0E7A),

pointer_default(unique),

local

]

interface IDebugAsyncOperationCallBack : IUnknown

{

// onComplete() is fired by the AsyncDebugOperation when a result is available.

// The event is fired in the debugger thread.

HRESULT onComplete(void);

}

IEnumDebugCodeContexts

Enumerates code contexts. Generally used to enumerate the code contexts corresponding to a document context.

[

object,

uuid(51973C1d-CB0C-11d0-B5C9-00A0244A0E7A),

helpstring("IEnumDebugCodeContexts Interface"),

pointer_default(unique)

]

interface IEnumDebugCodeContexts : IUnknown {

[local]

HRESULT __stdcall Next(

[in] ULONG celt,

[out] IDebugCodeContext IDebugCodeContext **pscc,

[out] ULONG *pceltFetched);

HRESULT Skip(

[in] ULONG celt);

HRESULT Reset(void);

HRESULT Clone(

[out] IEnumDebugCodeContexts IEnumDebugCodeContexts **ppescc);

}

DebugStackFrameDescriptor

Used to enumerate stack frames and merge output from several enumerators (on the same thread). dwMin and dwLim provide a machine dependent representation of the range of physical addresses associated with this stack frame. This is used by the process debug manager to sort the stack frames from multiple script engines.

By convention, stacks grow down and, as such, on architectures where stacks grow up the addresses should be twos-complemented.

The punkFinal is used during enumerator merging. If punkFinal is non-null, It indicates that the that the current enumerator merging should stop and a new one should be started. The object indicates how the new enumeration is to be started.

typedef struct tagDebugStackFrameDescriptor

{

IDebugStackFrame IDebugStackFrame *pdsf;

DWORD dwMin;

DWORD dwLim;

BOOL fFinal;

IUnknown *punkFinal;

} DebugStackFrameDescriptor DebugStackFrameDescriptor ;

IEnumDebugStackFrames

Enumerates stack frames. Generally used to enumerate the stack frames corresponding to a thread.

[

object,

uuid(51973C1e-CB0C-11d0-B5C9-00A0244A0E7A),

helpstring("IEnumDebugStackFrames Interface"),

pointer_default(unique)

]

interface IEnumDebugStackFrames : IUnknown

{

[local]

HRESULT __stdcall Next(

[in] ULONG celt,

[out] DebugStackFrameDescriptor DebugStackFrameDescriptor *prgdsfd,

[out] ULONG *pceltFetched);

HRESULT Skip(

[in] ULONG celt);

HRESULT Reset(void);

HRESULT Clone(

[out] IEnumDebugStackFrames IEnumDebugStackFrames **ppedsf);

}

Smart Host Interfaces

Below are the details of the interfaces implemented by a smart host. As mentioned earlier, it is possible to avoid implementing these interfaces by using the smart host helper interfaces.

IDebugDocumentInfo

Provides information on a document, which may or may not be instantiated.

[

object,

uuid(51973C1f-CB0C-11d0-B5C9-00A0244A0E7A),

helpstring("IDebugDocumentInfo Interface"),

pointer_default(unique)

]

interface IDebugDocumentInfo : IUnknown {

// Returns the specified name for the document. If the indicated name is

// not known, E_FAIL is returned.

HRESULT GetName(

[in] DOCUMENTNAMETYPE dnt,

[out] BSTR *pbstrName);

// Returns a CLSID describing the document type. This allows the debugger IDE

// to host custom viewers for this document. returns CLSID_NULL if this document

// does not have viewable data.

HRESULT GetDocumentClassId(

[out] CLSID *pclsidDocument);

}

IDebugDocumentProvider

Provides the means for instantiating a document on demand. This indirect means for instanciating a document:

1.Allows lazy loading of the document.

2.Allows the document object to live at the debugger IDE.

3.Allows more then one way of getting to the identical document object.

This effectively segregates the document from its provider; this allows the provider to carry additional runtime context information.

[

object,

uuid(51973C20-CB0C-11d0-B5C9-00A0244A0E7A),

helpstring("IDebugDocumentProvider Interface"),

pointer_default(unique)

]

interface IDebugDocumentProvider : IDebugDocumentInfo {

// Causes the document to be instantiated if it does not already exist.

HRESULT GetDocument(

[out] IDebugDocument IDebugDocument **ppssd);

}

IDebugDocument

The base interface to all debug documents.

[

object,

uuid(51973C21-CB0C-11d0-B5C9-00A0244A0E7A),

pointer_default(unique)

]

interface IDebugDocument : IDebugDocumentInfo {

}

IDebugDocumentText

The interface to a text only debug document.

Conventions:

1.Both character positions and line numbers are zero based.

2.Character-positions represent character offsets; they do not represent byte or word offsets. For Win32, a character-position is an Unicode offset.

Note: the use of line-number based text management is not recommended; instead it is recommended that character-position based management be used. The line to character-position mapping functions described in this interface may be removed.

[

object,

uuid(51973C22-CB0C-11d0-B5C9-00A0244A0E7A),

pointer_default(unique)

]

interface IDebugDocumentText : IDebugDocument IDebugDocument {

// Returns the attributes of the document.

HRESULT GetDocumentAttributes(

[out]TEXT_DOC_ATTR *ptextdocattr);

// Returns the size of the document.

HRESULT GetSize(

[out] ULONG *pcNumLines,// NULL means do not return the number of lines.

[out] ULONG *pcNumChars);// NULL means do not return the number of characters.

// Returns character-position corresponding to the first character of a line.

HRESULT GetPositionOfLine(

[in] ULONG cLineNumber,

[out] ULONG *pcCharacterPosition);

// Returns the line-number and, optionally, the character offset within the line

// that corresponds to the given character-position.

HRESULT GetLineOfPosition(

[in] ULONG cCharacterPosition,

[out] ULONG *pcLineNumber,

[out] ULONG *pcCharacterOffsetInLine); // NULL means do not return a value.

// Retrieves the characters and/or the character attributes associated with

// a character-position range; where a character position range is specified by

// a character-position and a number of characters.

HRESULT GetText(

[in] ULONG cCharacterPosition,

// Specifies a character text buffer. NULL means do not return characters.

[in, out, length_is(*pcNumChars), size_is(cMaxChars)] WCHAR *pcharText,

// Specifies a character attribute buffer. NULL means do not return attributes.

[in, out, length_is(*pcNumChars), size_is(cMaxChars), ptr] SOURCE_TEXT_ATTR *pstaTextAttr,

// Indicates the actual number of characters/attributes returned. Must be set to zero

// before the call.

[in, out] ULONG *pcNumChars,

// Specifies the number maximum number of character desired.

[in] ULONG cMaxChars);

// Returns the character-position range corresponding to a document context. The document

// context provided must be associated with this document.

HRESULT GetPositionOfContext(

[in] IDebugDocumentContext IDebugDocumentContext *psc,

[out] ULONG *pcCharacterPosition,

[out]ULONG *cNumChars);

// Creates a document context object corresponding to the provided character position range.

HRESULT GetContextOfPosition(

[in] ULONG cCharacterPosition,

[in] ULONG cNumChars,

[out] IDebugDocumentContext IDebugDocumentContext **ppsc);

}

IDebugDocumentTextEvents

Provides events indicating changes to the associated text document. Note: The text alterations are reflected in the document at the time the events on this interface are fired. Event handlers may retrieve the new text using IDebugDocumentText.

[

object,

uuid(51973C23-CB0C-11d0-B5C9-00A0244A0E7A),

pointer_default(unique)

]

interface IDebugDocumentTextEvents : IUnknown

{

// Indicates that the underlying document has been destroyed and is no longer valid.

HRESULT onDestroy(void);

// Indicates that new text has been added to the document. Example: progressive loading

// of HTML.

//

HRESULT onInsertText(

// The position where the new text is inserted.

[in] ULONG cCharacterPosition,

// The number of characters that have been inserted.

[in] ULONG cNumToInsert);

// Indicates that text has been removed from the document.

HRESULT onRemoveText(

// The character-position of the first character removed.

[in] ULONG cCharacterPosition,

// The number of characters removed.

[in] ULONG cNumToRemove);

// Indicates that text has been replaced.

HRESULT onReplaceText(

// The starting character-position of the character-position range

// that is being replaced.

[in] ULONG cCharacterPosition,

// The number of characters replaced.

[in] ULONG cNumToReplace);

// Indicates that the text attributes associated with the underlying character-position

// range has changed.

HRESULT onUpdateTextAttributes(

// The character-position of the first character whose attributes have changed.

[in] ULONG cCharacterPosition,

// The number of characters in the range.

[in] ULONG cNumToUpdate);

// Indicates that the document attributes have changed.

HRESULT onUpdateDocumentAttributes(

// The new document attributes.

[in] TEXT_DOC_ATTR textdocattr);

}

IDebugDocumentHelper

IDebugDocumentHelper greatly simplifies the task of creating a smart host for ActiveDebugging.

IDebugDocumentHelper automatically provides implementations for IDebugDocumentProvider, IDdebugDocument, IDebugDocumentText, IDebugDocumentContext, IDebugDocumentTextEvents, and many of the other interfaces necessary for smart hosting.

To be a smart host using IDebugDocumentHelper, a host application only to do only three two things:

(1) CoCreate an IProcessDebugManager and use it to add your application to the list of debuggable applications.

(2) create an IDebugDocumentHelper for each host document and make the appropriate calls to define the document name, parent document, text, and script blocks.

(3) Implement IActiveScriptSiteDebug on your IActiveScriptSite object (implemented already for Active Scripting. The only non-trivial method on IActiveScriptSiteDebug simply delegates to the helper.

Additionally, the host can optionally implement IDebugDocumentHost if it needs additional control over syntax color, document context creation, and other extended functionality.

The main limitation on the smart host helper is that can only handle documents whose contents change or shrink after they have been added (though documents can expand, of course.) For many smart hosts, however, the functionality it provides is exactly what is needed.

Below we go into each of the steps in more detail.

Create an Application Object

Before the smart host helper can be used, it is necessary to create an IDebugApplication object to represent your application in the debugger. The steps for creating an application object are as follows:

(1) Create an instance of the process debug manager using CoCreateInstance.

(2) Call IProcessDebugManager::CreateApplication().

(3) Set the name on the application using SetName().

(4) Add the application object to the list of debuggable applications using AddApplication().

Below is code to do this, minus error-check and other niceties.

CoCreateInstance(CLSID_ProcessDebugManager, NULL,

CLSCTX_INPROC_SERVER | CLSCTX_INPROC_HANDLER

| CLSCTX_LOCAL_SERVER,

IID_IProcessDebugManager, (void **)&g_ppdm);

g_ppdm->CreateApplication(&g_pda);

g_pda->SetName(L"My cool application");

g_ppdm->AddApplication(g_pda, &g_dwAppCookie);

Using IDebugDocumentHelper

The minimal sequence of steps for using the helper is as follows:

(1) For each host document, create a helper using IProcessDebugManager::CreateDebugDocumentHelper.

(2) Call Init on the helper, giving the name, document attributes, etc.

(3) Call Attach with parent helper for the document (or NULL if the document is the root) to define the position of the document in the tree and make it visible to the debugger

(4) Call AddDBCSText() or AddUnicodeText() to define the text of the document. (These can be called multiple times if document is downloaded incrementally, as in the case of a browser.)

(5) Call DefineScriptBlock to define the ranges for each script block and the associated script engines.

Implementing IActiveScriptSiteDebug

To implement GetDocumentContextFromPosition, get the helper corresponding to the given site, then get the starting document offset for the given source context, as follows:

pddh->GetScriptBlockInfo(dwSourceContext, NULL, &ulStartPos, NULL);

Next, use the helper to create a new document context for the given character offset:

pddh->CreateDebugDocumentContext(ulStartPos + uCharacterOffset, cChars, &pddcNew);

To implement GetRootApplicationNode , simply call IDebugApplication::GetRootNode. To implement GetDebugApplication , simply return the IDebugApplication you initially created using the process debug manager.

The optional IDebugDocumentHost interface

The host can provide an implementation of IDebugDocumentHost using IDebugDocumentHelper::SetHost that gives it additional control over the helper. Here are some of the key things the host interface allows you to do:

(1) Add text using AddDeferredText so that the host doesn't have to provide the actual characters immediately. When the characters are really needed, the helper will call IDebugDocumentHost::GetDeferredCharacters on the host.

(2) Override the default syntax coloring provided by the helper. The helper will call IDebugDocumentHost::GetScriptTextAttributes when it needs to know the coloring for a range of characters, falling back on its default implementation if the host return E_NOTIMPL.

(3) Providing a controlling unknown for document contexts created by the helper my implementing IDebugDocumentHost::OnCreateDocumentContext. This allows the host to override the functionality of the default document context implementation.

(4) Provide a path name in the file system for the document. Some debugging UIs will use this to permit the user to edit and save changes to the document. IDebugDocumentHost::NotifyChanged will be called to notify the host after the document has been saved.

[

object,

uuid(51973C26-CB0C-11d0-B5C9-00A0244A0E7A),

helpstring("IDebugDocumentHelper Interface"),

pointer_default(unique)

]

interface IDebugDocumentHelper : IUnknown

{

// Initialize a debug doc helper with the given name and

// initial attributes.

//

// Note: The document will not actually appear in the tree

// until Attach is called.

HRESULT Init(

[in] IDebugApplication IDebugApplication *pda,

[in, string]LPCOLESTR pszShortName,

[in, string]LPCOLESTR pszLongName,

[in]TEXT_DOC_ATTR docAttr

);

// Add the document to the doc tree, using pddhParent as the parent.

// If the ppdhParent is NULL, the document will be top-level.

HRESULT Attach([in] IDebugDocumentHelper IDebugDocumentHelper *pddhParent);

// Remove the document from the doc tree.

HRESULT Detach();

// Add the given set of unicode characters to end of the document.

// (This will generate IDebugDocumentTextEvent notifications.)

//

// If this method is called after AddDeferredText has been called,

// E_FAIL will be returned.

HRESULT AddUnicodeText(

[in, string] LPCOLESTR pszText

);

// Add the given set of DBCS characters to end of the document.

// (This will generate IDebugDocumentTextEvent notifications.)

//

// If this method is called after AddDeferredText has been called,

// E_FAIL will be returned.

HRESULT AddDBCSText(

[in, string] LPCSTR pszText

);

// Set the DebugDocumentHost interface.

// If provided, this interface will be used for

// smart-host syntax coloring, fetching deferred text, and returning

// controlling unknowns for newly created document contexts.

HRESULT SetDebugDocumentHost(

[in] IDebugDocumentHost IDebugDocumentHost * pddh

);

// Notify the helper that the given text is available, but don't actually

// provide the characters.

// This allows the host to defer providing the characters unless they

// are actually needed, while still allowing the helper to generate

// accurate notifications and size information.

//

// dwTextStartCookie is a cookie, defined by the host, that represents

// the starting position of the text. (For example, in a host that

// represents text in DBCS, the cookie could be a byte offset.)

// This cookie will be provided in subsequent calls to GetText.

//

// NB: It is assumed that a single call to

// GetText can get characters from multiple calls to AddDeferredText.

// The helper classes may also ask for the same range of deferred

// characters more than once.

//

// It is an error to mix calls to AddDeferredText with calls to

// AddUnicodeText or AddDBCSText-- Doing so will cause E_FAIL to be

// returned.

HRESULT AddDeferredText(

[in] ULONG cChars,// number of (Unicode) characters to add

[in] DWORD dwTextStartCookie

// host-defined cookie representing the starting position of the text.

);

// Notify the helper that a particular range of

// characters is a script block handled by the given script engine.

// All syntax coloring and code context lookups for that range will be

// delegated to that script engine.

//

// This method would be used by a smart host whose documents contained

// embedded script blocks, or by a language engine containing embedded

// scripts for other languages.

//

// DefineScriptBlock should be called after the text has been

// added (via AddDBCSText, etc) but before the script script block

// has been parsed (via IActiveScriptParse).

HRESULT DefineScriptBlock(

[in] ULONG ulCharOffset,

[in] ULONG cChars,

[in] IActiveScript* pas,

[in] BOOL fScriptlet,

[out] DWORD* pdwSourceContext

);

// Set the default attribute to use for text that is not in a

// script block. (If not explicitly set, the default attributes for

// text outside of a script block is SOURCETEXT_ATTR_NONSOURCE.)

//

// This would allow, for example, for text outside of script blocks

// to be colored grey and marked read-only.

HRESULT SetDefaultTextAttr(SOURCE_TEXT_ATTR staTextAttr);

// Explicilty set the attributes on a range of text, overriding any

// other attributes on that text.

//

// It is an error to set the attributes on a text range that has not

// yet been added using AddText.

HRESULT SetTextAttributes(

[in] ULONG ulCharOffset,

[in] ULONG cChars,

[in, length_is(cChars), size_is(cChars)]

SOURCE_TEXT_ATTR* pstaTextAttr);

// Set a new long name for the document

HRESULT SetLongName(

[in, string] LPCOLESTR pszLongName);

// Set a new short name for the document

HRESULT SetShortName(

[in, string] LPCOLESTR pszShortName);

// Define a new set of document attributes

HRESULT SetDocumentAttr(

[in] TEXT_DOC_ATTR pszAttributes

);

// Return the debug application node corresponding to this document

HRESULT GetDebugApplicationNode(

[out] IDebugApplicationNode IDebugApplicationNode **ppdan);

// Once a script block has been defined, this method allows the

// associate range and script engine to be retrieved.

HRESULT GetScriptBlockInfo(

[in] DWORD dwSourceContext,

[out]IActiveScript** ppasd,

[out] ULONG *piCharPos,

[out]ULONG *pcChars);

// Allows the host to create a new debug document context

HRESULT CreateDebugDocumentContext(

[in]ULONG iCharPos,

[in]ULONG cChars,

[out] IDebugDocumentContext IDebugDocumentContext ** ppddc);

// Bring this document to the top in the debugger UI.

// If the debugger isn't started already, start it now.

HRESULT BringDocumentToTop();

// Bring the given context in this document to the top

// in the debugger UI.

HRESULT BringDocumentContextToTop( IDebugDocumentContext IDebugDocumentContext *pddc);

};

IDebugDocumentHost

The interface from the IDebugDocumentHelper back to the smart host or language engine. This interface exposes host specific functionality such as syntax coloring,

[

object,

uuid(51973C27-CB0C-11d0-B5C9-00A0244A0E7A),

helpstring("IDebugDocumentHost Interface"),

pointer_default(unique)

]

interface IDebugDocumentHost : IUnknown

{

// Return a particular range of characters in the original host document,

// added using AddDeferredText.

//

// It is acceptable for a host to return E_NOTIMPL for this method,

// as long as the host doesn't call AddDeferredText.

//

// (Note that this is text from the _original_ document. The host

// does not need to be responsible for keeping track of edits, etc.)

HRESULT GetDeferredText(

[in] DWORD dwTextStartCookie,

// Specifies a character text buffer. NULL means do not return characters.

[in, out, length_is(*pcNumChars), size_is(cMaxChars)] WCHAR *pcharText,

// Specifies a character attribute buffer. NULL means do not return attributes.

[in, out, length_is(*pcNumChars), size_is(cMaxChars)] SOURCE_TEXT_ATTR *pstaTextAttr,

// Indicates the actual number of characters/attributes returned. Must be set to zero

// before the call.

[in, out] ULONG *pcNumChars,

// Specifies the number maximum number of character desired.

[in] ULONG cMaxChars);

// Return the text attributes for an arbitrary block of document text.

// It is acceptable for hosts to return E_NOTIMPL, in which case the

// default attributes are used.

HRESULT GetScriptTextAttributes(

// The script block text. This string need not be null terminated.

[in, size_is(uNumCodeChars)]LPCOLESTRpstrCode,

// The number of characters in the script block text.

[in]ULONGuNumCodeChars,

// See IActiveScriptParse::ParseScriptText for a description of this argument.

[in]LPCOLESTRpstrDelimiter,

// See IActiveScriptParse::ParseScriptText for a description of this argument.

[in]DWORDdwFlags,

// Buffer to contain the returned attributes.

[in, out, size_is(uNumCodeChars)]SOURCE_TEXT_ATTR *pattr);

// Notify the host that a new document context is being created

// and allow the host to optionally return a controlling unknown

// for the new context.

//

// This allows the host to add new functionality to the helper-provided

// document contexts. It is acceptable for the host to return E_NOTIMPL

// or a null outer unknown for this method, in which case the context is

// used "as is".

HRESULT OnCreateDocumentContext(

[out] IUnknown** ppunkOuter);

// Return the full path (including file name) to the document's source file.

//*pfIsOriginalPath is TRUE if the path refers to the original file for the document.

//*pfIsOriginalPath is FALSE if the path refers to a newly created temporary file

//Returns E_FAIL if no source file can be created/determined.

HRESULT GetPathName(

[out] BSTR *pbstrLongName,

[out] BOOL *pfIsOriginalFile);

// Return just the name of the document, with no path information.

// (Used for "Save As...")

HRESULT GetFileName(

[out] BSTR *pbstrShortName);

// Notify the host that the document's source file has been saved and

// that its contents should be refreshed.

HRESULT NotifyChanged();

};

IDebugDocumentContext

Abstract representation of a portion of the debug document. For text documents this consists of a character-position range.

[

object,

uuid(51973C28-CB0C-11d0-B5C9-00A0244A0E7A),

pointer_default(unique)

]

interface IDebugDocumentContext : IUnknown

{

// Returns the document that contains this context.

HRESULT GetDocument(

[out] IDebugDocument IDebugDocument **ppsd);

// Enumerates the code contexts associated with this document context. Generally there will

// only be one code context but there are important exceptions, such as include file

// or templates (in C++).

HRESULT EnumCodeContexts(

[out] IEnumDebugCodeContexts IEnumDebugCodeContexts **ppescc);

}

Debugger UI interfaces

Below are the interfaces that allow other components to launch and interface with the debugger UI.

IDebugSessionProvider

The primary interface provided by a debugger IDE to enable host and language initiated debugging. Its sole purpose is to establish a debug session for a running application.

cpp_quote( "EXTERN_C const CLSID CLSID_DefaultDebugSessionProvider;")

[

object,

uuid(51973C29-CB0C-11d0-B5C9-00A0244A0E7A),

helpstring("IDebugSessionProvider Interface"),

pointer_default(unique)

]

interface IDebugSessionProvider : IUnknown

{

// Initiates a debug session with the specified application. The debugger should

// call IRemoteDebugApplication::ConnectDebugger before returning from this call.

HRESULT StartDebugSession(

[in] IRemoteDebugApplication IRemoteDebugApplication *pda);

};

IApplicationDebugger

This is the primary interface exposed by a debugger IDE.

[

object,

uuid(51973C2a-CB0C-11d0-B5C9-00A0244A0E7A),

helpstring("IApplicationDebugger Interface"),

pointer_default(unique)

]

interface IApplicationDebugger : IUnknown

{

// Indicates if the debugger is alive. Should always return S_OK. If the debugger

// has rudely shut down COM will return an error from the marshalling proxy.

HRESULT QueryAlive(void);

// Provides a mechanism for hosts and language engines running out-of-process to the

// debugger to create objects in the debugger process. This can be used for any purpose,

// including extending the debugger UI. This method simply delegates to CoCreateInstance.

HRESULT CreateInstanceAtDebugger(

[in]REFCLSID rclsid,// Class identifier (CLSID) of the object

[in]IUnknown *pUnkOuter,// Object is or isn't part of an aggregate

[in]DWORD dwClsContext,// Context for running executable code

[in]REFIID riid,// Interface identifier

[out, iid_is(riid)]IUnknown **ppvObject);

// Points to requested interface pointer

// This method is called when IDebugApplication::DebugOutput is called. The debugger

// can use this to display the string in an output window.

HRESULT onDebugOutput(

[in] LPCOLESTR pstr);

// This method is called when a breakpoint is hit. The application will remain

// suspended until the debugger IDE calls IDebugApplication::ResumeFromBreakPoint.

HRESULT onHandleBreakPoint(

// Indicates the thread in which the breakpoint occured.

[in] IRemoteDebugApplicationThread IRemoteDebugApplicationThread *prpt,

// Indicates the reason for the breakpoint.

[in]BREAKREASON br,

// optional runtime error info (for when br == BREAKREASON_ERROR)

[in] IActiveScriptErrorDebug IActiveScriptErrorDebug *pError);

// This method is called when IDebugApplication::Close is called.

HRESULT onClose(void);

// Handle a custom event.

// The semantics of the GUID and IUnknown are entirely application/debugger defined

// This method may return E_NOTIMPL.

HRESULT onDebuggerEvent(

[in]REFIID riid,

[in]IUnknown *punk);

};

IApplicationDebuggerUI

This is a secondary interface exposed by some debugger IDE that allows an external component to have additional control over the debuggers UI.

[

object,

uuid(51973C2b-CB0C-11d0-B5C9-00A0244A0E7A),

helpstring("IApplicationDebuggerUI Interface"),

pointer_default(unique)

]

interface IApplicationDebuggerUI : IUnknown

{

// Bring the window corresponding to the given debug document to the front.

// Returns E_INVALIDARG if the document is not known.

HRESULT BringDocumentToTop([in] IDebugDocumentText IDebugDocumentText * pddt);

// Bring the window containing the given doc context to the front,

// and scroll it to the correct location.

// Returns E_INVALIDARG if the context is not known.

HRESULT BringDocumentContextToTop([in] IDebugDocumentContext IDebugDocumentContext * pddc);

};

IMachineDebugManager

The primary interface to the Machine Debug Manager.

cpp_quote( "EXTERN_C const CLSID CLSID_MachineDebugManager;")

[

object,

uuid(51973C2c-CB0C-11d0-B5C9-00A0244A0E7A),

helpstring("IMachineDebugManager Interface"),

pointer_default(unique)

]

interface IMachineDebugManager : IUnknown

{

// Adds an application to the running application list. This method is called by the

// process debug manager whenever IProcessDebugManager::AddApplication is called.

HRESULT AddApplication(

[in] IRemoteDebugApplication IRemoteDebugApplication *pda,

[out] DWORD *pdwAppCookie);

// Removes an application from the running application list. This method is called by the

// process debug manager whenever IProcessDebugManager::RemoveApplication is called.

HRESULT RemoveApplication(

[in] DWORD dwAppCookie);

// Returns an enumerator of the current list of running applications. Used by the debugger

// IDE to display and attach applications for debugging purposes.

HRESULT EnumApplications(

[out] IEnumRemoteDebugApplications IEnumRemoteDebugApplications **ppeda);

};

IMachineDebugManagerCookie - As IMachineDebugManager with Debug Cookie support

[

object,

uuid(51973C2d-CB0C-11d0-B5C9-00A0244A0E7A),

helpstring("IMachineDebugManagerCookie Interface"),

pointer_default(unique)

]

interface IMachineDebugManagerCookie : IUnknown

{

// Adds an application to the running application list. This method is called by the

// process debug manager whenever IProcessDebugManager::AddApplication is called.

HRESULT AddApplication(

[in] IRemoteDebugApplication IRemoteDebugApplication *pda,

[in] DWORD dwDebugAppCookie,

[out] DWORD *pdwAppCookie);

// Removes an application from the running application list. This method is called by the

// process debug manager whenever IProcessDebugManager::RemoveApplication is called.

HRESULT RemoveApplication(

[in] DWORD dwDebugAppCookie,

[in] DWORD dwAppCookie);

// Returns an enumerator of the current list of running applications. Used by the debugger

// IDE to display and attach applications for debugging purposes.

HRESULT EnumApplications(

[out] IEnumRemoteDebugApplications IEnumRemoteDebugApplications **ppeda);

};

IMachineDebugManagerEvents

This event interface is used to signal changes in the running application list maintained by the machine debug manager. It can be used by the debugger IDE to display a dynamic list of applications.

[

object,

uuid(51973C2e-CB0C-11d0-B5C9-00A0244A0E7A),

helpstring("IMachineDebugManagerEvents Interface"),

pointer_default(unique)

]

interface IMachineDebugManagerEvents : IUnknown

{

// Indicates that a new application has appeared on the running application list.

HRESULT onAddApplication(

[in] IRemoteDebugApplication IRemoteDebugApplication *pda,

[in] DWORD dwAppCookie);

// Indicates that an application has been removed from the running application list.

HRESULT onRemoveApplication(

[in] IRemoteDebugApplication IRemoteDebugApplication *pda,

[in] DWORD dwAppCookie);

};

Process Debug Manager Interfaces

Below are the details of the interfaces for the process debug manager.

IProcessDebugManager

The primary interface to the process debug manager.

cpp_quote( "EXTERN_C const CLSID CLSID_ProcessDebugManager;")

[

object,

uuid(51973C2f-CB0C-11d0-B5C9-00A0244A0E7A),

helpstring("IProcessDebugManager Interface"),

pointer_default(unique),

local

]

interface IProcessDebugManager : IUnknown

{

// Creates a new debug application object. The new object is not added to the

// running application list and has no name.

HRESULT CreateApplication(

[out] IDebugApplication IDebugApplication **ppda);

// Returns a default application object for the current process, creating one and adding

// it to the running application list if necessary. Language engines should use this

// application if they are running on a host that does not provide an application.

HRESULT GetDefaultApplication(

[out] IDebugApplication IDebugApplication **ppda);

// Adds an application to the running application list in the machine debug manager.

HRESULT AddApplication(

[in] IDebugApplication IDebugApplication *pda,

// Returns a cookie used to remove the application from the machine debug manager.

[out] DWORD *pdwAppCookie);

// Removes an application from the running application list.

HRESULT RemoveApplication(

// The cookie provided by AddApplication.

[in] DWORD dwAppCookie);

HRESULT CreateDebugDocumentHelper(

[in] IUnknown *punkOuter,

[out] IDebugDocumentHelper IDebugDocumentHelper ** pddh);

};

IRemoteDebugApplication

An abstraction representing a running application. It need not correspond to an OS process. Applications are the smallest debuggable unit; that is, the debugger IDE normally targets an application for debugging.

The application object is normally implemented by the Process Debug Manager.

[

object,

uuid(51973C30-CB0C-11d0-B5C9-00A0244A0E7A),

helpstring("IRemoteDebugApplication Interface"),

pointer_default(unique)

]

interface IRemoteDebugApplication : IUnknown

{

// Continue an application which is currently in a breakpoint.

HRESULT ResumeFromBreakPoint(

// For stepping modes, the thread which is to be affected by the stepping mode.

[in] IRemoteDebugApplicationThread IRemoteDebugApplicationThread *prptFocus,

// The action to take (step mode, etc.) upon resuming the application

[in] BREAKRESUMEACTION bra,

// the action to take in the case that we stopped because of an error

[in] ERRORRESUMEACTION era);

// Causes the application to break into the debugger at the earliest opportunity. Note

// that a long time may elapse before the application actually breaks, particularly if

// the application is not currently executing script code.

HRESULT CauseBreak(void);

// Connects a debugger to the application. Only one debugger may be connected at a

// time; this method fails if there is already a debugger connected

HRESULT ConnectDebugger(

[in] IApplicationDebugger IApplicationDebugger *pad);

// Disconnects the current debugger from the application.

HRESULT DisconnectDebugger(void);

// Returns the current debugger connected to the application.

HRESULT GetDebugger(

[out] IApplicationDebugger IApplicationDebugger **pad);

// Provides a mechanism for the debugger IDE, running out-of-process to the

// application, to create objects in the application process.

// This method simply delegates to CoCreateInstance.

HRESULT CreateInstanceAtApplication(

[in]REFCLSID rclsid,// Class identifier (CLSID) of the object

// Note: This parameter may have to be removed.

[in]IUnknown *pUnkOuter,// Object is or isn't part of an aggregate

[in]DWORD dwClsContext,// Context for running executable code

[in]REFIID riid,// Interface identifier

[out, iid_is(riid)]IUnknown **ppvObject);

// Points to requested interface pointer

// Indicates if the application is alive. Should always return S_OK. If the application

// process has rudely shut down COM will return an error from the marshalling proxy.

HRESULT QueryAlive(

void);

// Enumerates all threads known to be associated with the application.

// New threads may be added at any time.

HRESULT EnumThreads(

[out] IEnumRemoteDebugApplicationThreads IEnumRemoteDebugApplicationThreads **pperdat);

// Returns the application node under which all nodes associated with the

// application are added.

HRESULT GetName(

[out]BSTR *pbstrName);

// Returns a node for the application

HRESULT GetRootNode(

[out] IDebugApplicationNode IDebugApplicationNode **ppdanRoot);

// Returns an enumerator that lists the global expression

// contexts for all languages running in this application

HRESULT EnumGlobalExpressionContexts (

[out] IEnumDebugExpressionContexts IEnumDebugExpressionContexts **ppedec);

};

IDebugApplication

This interface is an extension of IRemoteDebugApplication, exposing non-remotable methods for use by language engines and hosts.

[

object,

uuid(51973C32-CB0C-11d0-B5C9-00A0244A0E7A),

helpstring("IDebugApplication Interface"),

pointer_default(unique),

local

]

interface IDebugApplication : IRemoteDebugApplication IRemoteDebugApplication

{

// Sets the name of the application. The provided name will be returned in subsequent calls

// to IRemoteDebugApplication::GetName.

HRESULT SetName(

[in]LPCOLESTR pstrName);

// This method is called by language engines, in single step mode, just before they

// return to their caller. The process debug manager uses this opportunity to notify all

// other script engines that they should break at the first opportunity. This is how

// cross language step modes are implemented.

HRESULT StepOutComplete(void);

// Causes the given string to be displayed by the debugger IDE, normally in an output

// window. This mechanism provides the means for a language engine to implement language

// specific debugging output support. Example: Debug.writeln("Help") in JavaScript.

HRESULT DebugOutput(

[in]LPCOLESTR pstr);

// Causes a default debugger IDE to be started and a debug session to be attached to

// this application if one does not already exist. This is used to implement just-in-time

// debugging.

HRESULT StartDebugSession(void);

// Called by the language engine in the context of a thread that has hit a breakpoint.

// This method causes the current thread to block and a notification of the breakpoint

// to be sent to the debugger IDE. When the debugger IDE resumes the application this

// method returns with the action to be taken.

//

// Note: While in the breakpoint the language engine may be called in this thread to do

// various things such as enumerating stack frames or evaluating expressions.

HRESULT HandleBreakPoint(

[in]BREAKREASON br,

[out]BREAKRESUMEACTION *pbra);

// Causes this application to release all references and enter a zombie state. Called

// by the owner of the application generally on shut down.

HRESULT Close(void);

// Returns the current break flags for the application.

HRESULT GetBreakFlags(

[out]APPBREAKFLAGS *pabf,

[out] IRemoteDebugApplicationThread IRemoteDebugApplicationThread **pprdatSteppingThread);

// Returns the application thread object associated with the currently running thread.

HRESULT GetCurrentThread(

[out] IDebugApplicationThread IDebugApplicationThread **pat);

// Creates an IDebugAsyncOperation object to wrap a provided IDebugSyncOperation object.

// This provides a mechanism for language engines to implement asynchronous expression and

// evaluation, etc. without having to know the details of synchronization with the

// debugger thread. See the descriptions for IDebugSyncOperation and IDebugAsyncOperation

// for more details.

HRESULT CreateAsyncDebugOperation(

[in] IDebugSyncOperation IDebugSyncOperation *psdo,

[out] IDebugAsyncOperation IDebugAsyncOperation **ppado);

// Adds a stack frame sniffer to this application. Generally called by a language engine

// to expose its stack frames to the debugger. It is possible for other entities to

// expose stack frames.

HRESULT AddStackFrameSniffer(

[in] IDebugStackFrameSniffer IDebugStackFrameSniffer *pdsfs,

// Returns a cookie that is used to remove this stack frame sniffer

// from the application.

[out]DWORD *pdwCookie);

// Removes a stack frame sniffer from this application.

HRESULT RemoveStackFrameSniffer(

// The cookie returned by AddStackFrameSniffer.

[in]DWORD dwCookie);

// Returns S_OK if the current running thread is the debugger thread.

// Otherwise, returns S_FALSE.

HRESULT QueryCurrentThreadIsDebuggerThread(

void);

// Provides a mechanism for the caller to run code in the debugger thread. This is generally

// used so that language engines and hosts can implement free threaded objects on top

// of their single threaded implementations.

HRESULT SynchronousCallInDebuggerThread(

[in] IDebugThreadCall IDebugThreadCall *pptc,

[in]DWORD dwParam1,

[in]DWORD dwParam2,

[in]DWORD dwParam3);

// Creates a new application node which is associated with a specific

// document provider. Before it is visible, the new node must be

// attached to a parent node.

HRESULT CreateApplicationNode(

[out] IDebugApplicationNode IDebugApplicationNode **ppdanNew);

// Fire a generic event to the IApplicationDebugger (if any)

// The semantics of the GUID and IUnknown are entirely application/debugger defined

//

// This method is currently unimplemented but is here to allow for future extensions.

HRESULT FireDebuggerEvent(

[in]REFGUID riid,

[in]IUnknown *punk);

// Called by the language engine in the context of a thread that has caused a runtime error.

// This method causes the current thread to block and a notification of the error

// to be sent to the debugger IDE. When the debugger IDE resumes the application this

// method returns with the action to be taken.

//

// Note: While in the runtime error the language engine may be called in this thread to do

// various things such as enumerating stack frames or evaluating expressions.

HRESULT HandleRuntimeError(

[in] IActiveScriptErrorDebug IActiveScriptErrorDebug *pErrorDebug,// the error that occurred

[in]IActiveScriptSite *pScriptSite,// the script site of the thread

[out]BREAKRESUMEACTION *pbra,// how to continue execution (stepping etc...)

[out]ERRORRESUMEACTION *perra,// how to handle the error case

[out]BOOL *pfCallOnScriptError);// if TRUE then engine should call IActiveScriptSite::OnScriptError()

// return TRUE if there is a JIT debugger registered

BOOL FCanJitDebug ();

// returns TRUE if a JIT debugger is registered and it is registered to auto-JIT debug dumb hosts

BOOL FIsAutoJitDebugEnabled ();

// Adds a global expression context provider to this application

HRESULT AddGlobalExpressionContextProvider(

[in] IProvideExpressionContexts IProvideExpressionContexts *pdsfs,

// Returns a cookie that is used to remove this global expression context provider

// from the application.

[out]DWORD *pdwCookie);

// Removes a global expression context provider from this application.

HRESULT RemoveGlobalExpressionContextProvider(

// The cookie returned by AddGlobalExpressionContextProvider.

[in]DWORD dwCookie);

};

IRemoteDebugApplicationEvents:

This is the event interface supplied by a debug application: It is always called from within the debugger thread.

[

object,

uuid(51973C33-CB0C-11d0-B5C9-00A0244A0E7A),

helpstring("IRemoteDebugApplicationEvents Interface"),

pointer_default(unique)

]

interface IRemoteDebugApplicationEvents : IUnknown

{

HRESULT OnConnectDebugger(

[in] IApplicationDebugger IApplicationDebugger *pad);

HRESULT OnDisconnectDebugger(void);

HRESULT OnSetName(

[in]LPCOLESTR pstrName);

HRESULT OnDebugOutput(

[in]LPCOLESTR pstr);

HRESULT OnClose(void);

HRESULT OnEnterBreakPoint(

[in] IRemoteDebugApplicationThread IRemoteDebugApplicationThread *prdat);

HRESULT OnLeaveBreakPoint(

[in] IRemoteDebugApplicationThread IRemoteDebugApplicationThread *prdat);

HRESULT OnCreateThread(

[in] IRemoteDebugApplicationThread IRemoteDebugApplicationThread *prdat);

HRESULT OnDestroyThread(

[in] IRemoteDebugApplicationThread IRemoteDebugApplicationThread *prdat);

HRESULT OnBreakFlagChange(

[in]APPBREAKFLAGS abf,

[in] IRemoteDebugApplicationThread IRemoteDebugApplicationThread *prdatSteppingThread);

};

IDebugApplicationNode

Provides the functionality of IDebugDocumentProvider, plus a context within a project tree.

[

object,

uuid(51973C34-CB0C-11d0-B5C9-00A0244A0E7A),

pointer_default(unique)

]

interface IDebugApplicationNode : IDebugDocumentProvider IDebugDocumentProvider {

HRESULT EnumChildren(

[out] IEnumDebugApplicationNodes IEnumDebugApplicationNodes **pperddp);

HRESULT GetParent(

[out] IDebugApplicationNode IDebugApplicationNode **pprddp);

HRESULT SetDocumentProvider(

[in] IDebugDocumentProvider IDebugDocumentProvider *pddp);

HRESULT Close(void);

HRESULT Attach(

[in] IDebugApplicationNode IDebugApplicationNode *pdanParent);

HRESULT Detach(void);

}

IDebugApplicationNodeEvents

Event interface for DebugApplicationNode object.

[

object,

uuid(51973C35-CB0C-11d0-B5C9-00A0244A0E7A),

pointer_default(unique)

]

interface IDebugApplicationNodeEvents : IUnknown {

HRESULT onAddChild(

[in] IDebugApplicationNode IDebugApplicationNode *prddpChild);

HRESULT onRemoveChild(

[in] IDebugApplicationNode IDebugApplicationNode *prddpChild);

HRESULT onDetach(void);

HRESULTonAttach(

[in] IDebugApplicationNode IDebugApplicationNode *prddpParent);

}

IDebugThreadCall

IDebugThreadCall is implemented by a component making a cross-thread call using the IDebugThread marshalling implementation in the PDM. It is called by the PDM in the desired thread and should dispatches the call to the desired implementation, casting the parameter information passed in the dwParam's to the appropriate top. It is, of course, a free-threaded object.

[

object,

uuid(51973C36-CB0C-11d0-B5C9-00A0244A0E7A),

pointer_default(unique),

local

]

interface IDebugThreadCall : IUnknown

{

HRESULT ThreadCallHandler(

[in] DWORD dwParam1,

[in] DWORD dwParam2,

[in] DWORD dwParam3);

}

IRemoteDebugApplicationThread

An abstraction representing a thread of execution within a particular application.

[

object,

uuid(51973C37-CB0C-11d0-B5C9-00A0244A0E7A),

pointer_default(unique)

]

interface IRemoteDebugApplicationThread : IUnknown

{

// Returns an operating system dependent identifier associated with the thread.

//

// Note: The returned value does not need to be unique across machines.

HRESULT GetSystemThreadId(

[out]DWORD *dwThreadId);

// Returns the application object associated with the thread.

HRESULT GetApplication(

[out] IRemoteDebugApplication IRemoteDebugApplication **pprda);

// Returns an enumerator for the stack frames associated with the thread. Can only

// be called when in a breakpoint. The stack frame enumerator enumerates stack frames

// in the most recently called order.

HRESULT EnumStackFrames(

[out] IEnumDebugStackFrames IEnumDebugStackFrames **ppedsf);

HRESULT GetDescription(

[out]BSTR *pbstrDescription,

[out]BSTR *pbstrState);

// Forces execution to continue as close as possible to the

// given code context, in the context of the given frame.

// Either of these arguments may be NULL, representing the

// current frame or context.

HRESULT SetNextStatement (

[in] IDebugStackFrame IDebugStackFrame *pStackFrame,

[in] IDebugCodeContext IDebugCodeContext *pCodeContext);

// Thread State flags

typedef DWORD THREAD_STATE;

const THREAD_STATE THREAD_STATE_RUNNING=0x00000001;

const THREAD_STATE THREAD_STATE_SUSPENDED=0x00000002;

const THREAD_STATE THREAD_BLOCKED=0x00000004;

const THREAD_STATE THREAD_OUT_OF_CONTEXT=0x00000008;

// returns the current state of the thread

HRESULT GetState (

[out] DWORD *pState);

// suspends the thread (increments the suspend count)

HRESULT Suspend (

[out] DWORD *pdwCount);

// resumes the thread (decrements the suspend count)

HRESULT Resume (

[out] DWORD *pdwCount);

// returns the current suspend count of the thread

HRESULT GetSuspendCount (

[out] DWORD *pdwCount);

}

IDebugApplicationThread

An extension of IRemoteDebugApplicationThread that provides non-remotable access to the thread. This interface is used by language engines and hosts to provide thread synchronization and to maintain thread specific debug state information.

[

object,

uuid(51973C38-CB0C-11d0-B5C9-00A0244A0E7A),

pointer_default(unique),

local

]

interface IDebugApplicationThread : IRemoteDebugApplicationThread IRemoteDebugApplicationThread

{

// Provides a mechanism for the caller to run code in another thread. This is generally

// used so that language engines and hosts can implement free threaded objects on top

// of their single threaded implementations.

HRESULT SynchronousCallIntoThread(

// The interface to be called back in the target thread.

[in] IDebugThreadCall IDebugThreadCall *pstcb,

// Three arguments passed to the IDebugThreadCall.

[in]DWORD dwParam1,

[in]DWORD dwParam2,

[in]DWORD dwParam3);

// Returns S_OK when this is the currently running thread. Otherwise S_FALSE is returned.

HRESULT QueryIsCurrentThread(

void);

// Returns S_OK when this is the debugger thread. Otherwise, returns S_FALSE.

HRESULT QueryIsDebuggerThread(

void);

HRESULT SetDescription(

[in]LPCOLESTR pstrDescription);

HRESULT SetStateString(

[in]LPCOLESTR pstrState);

}

[

object, local,

uuid(51973C39-CB0C-11d0-B5C9-00A0244A0E7A),

helpstring("IDebugCookie Interface"),

pointer_default(unique)

]

interface IDebugCookie : IUnknown

{

HRESULT SetDebugCookie([in]DWORD dwDebugAppCookie);

};

IEnumDebugApplicationNodes

Enumerates Application nodes. Generally used to enumerate child nodes of a node associated with an application. Example: a project window.

[

object,

uuid(51973C3a-CB0C-11d0-B5C9-00A0244A0E7A),

helpstring("IEnumDebugApplicationNodes Interface"),

pointer_default(unique)

]

interface IEnumDebugApplicationNodes : IUnknown {

[local]

HRESULT __stdcall Next(

[in] ULONG celt,

[out] IDebugApplicationNode IDebugApplicationNode **pprddp,

[out] ULONG *pceltFetched);

HRESULT Skip(

[in] ULONG celt);

HRESULT Reset(void);

HRESULT Clone(

[out] IEnumDebugApplicationNodes IEnumDebugApplicationNodes **pperddp);

};

IEnumRemoteDebugApplications

Enumerates application objects. Generally used to enumerate the running applications on a machine. Example: the "attach to application" dialog.

[

object,

uuid(51973C3b-CB0C-11d0-B5C9-00A0244A0E7A),

helpstring("IEnumRemoteDebugApplications Interface"),

pointer_default(unique)

]

interface IEnumRemoteDebugApplications : IUnknown {

[local]

HRESULT __stdcall Next(

[in] ULONG celt,

[out] IRemoteDebugApplication IRemoteDebugApplication **ppda,

[out] ULONG *pceltFetched);

HRESULT Skip(

[in] ULONG celt);

HRESULT Reset(void);

HRESULT Clone(

[out] IEnumRemoteDebugApplications IEnumRemoteDebugApplications **ppessd);

}

IEnumRemoteDebugApplicationThreads

Enumerates thread objects. Generally used to enumerate the running threads in an application.

[

object,

uuid(51973C3c-CB0C-11d0-B5C9-00A0244A0E7A),

helpstring("IEnumRemoteDebugApplicationThreads Interface"),

pointer_default(unique)

]

interface IEnumRemoteDebugApplicationThreads : IUnknown {

[local]

HRESULT __stdcall Next(

[in] ULONG celt,

[out] IRemoteDebugApplicationThread IRemoteDebugApplicationThread **pprdat,

[out] ULONG *pceltFetched);

HRESULT Skip(

[in] ULONG celt);

HRESULT Reset(void);

HRESULT Clone(

[out] IEnumRemoteDebugApplicationThreads IEnumRemoteDebugApplicationThreads **pperdat);

}

IDebugFormatter

IDebugFormatter allows a language or IDE to customize the conversion between variants or VARTYPES and strings. This interface is used by the ITypeInfo->IDebugProperty mapping implementation.

[

object,

uuid(51973C3d-CB0C-11d0-B5C9-00A0244A0E7A),

helpstring("IDebugFormatter Interface"),

pointer_default(unique),

local

]

interface IDebugFormatter : IUnknown

{

HRESULT GetStringForVariant([in] VARIANT *pvar, [out] BSTR *pbstrValue);

HRESULT GetVariantForString([in] LPCOLESTR pwstrValue, [out] VARIANT *pvar);

HRESULT GetStringForVarType([in] VARTYPE vt, [in] TYPEDESC *ptdescArrayType, [out] BSTR *pbstr);

}

ISimpleConnectionPoint

This interface is the "IDispatchEx" of event interfaces. It provides a simple way for describing and enumerating the events fired on a particular connection pointan also for hooking up an IDispatch to those events. This interface will be available as extended info via the IDebugProperty interface on objects which support events. For simplicity, this interface only works with dispinterfaces.

[

object,

uuid(51973C3e-CB0C-11d0-B5C9-00A0244A0E7A),

helpstring("ISimpleConnectionPoint Interface"),

pointer_default(unique),

local

]

interface ISimpleConnectionPoint : IUnknown

{

// Return the number of events exposed on this interface

HRESULT GetEventCount([out] ULONG *pulCount);

// Return the DISPID and NAME for "cEvents" events, starting at "iEvent".

// The number of

//- Returns S_OK if all of the requested elements were returned.

//- Returns S_FALSE if the enumeration finished and the

//requested number of elements was not available.

//(Unavailable elements will be returned as DISPID_NULL and a null bstr.)

//- Returns E_INVALIDARG (or other error status) if no elements could be fetched

HRESULT DescribeEvents(

[in] ULONG iEvent,// starting event index

[in] ULONG cEvents,// number of events to fetch info for

[out, size_is(cEvents), length_is(*pcEventsFetched)]

DISPID *prgid,// DISPIDs of the events

[out, size_is(cEvents), length_is(*pcEventsFetched)]

BSTR *prgbstr,

[out] ULONG *pcEventsFetched

);// names of the events

HRESULT Advise([in] IDispatch *pdisp, [out] DWORD* pdwCookie);

HRESULT Unadvise([in] DWORD dwCookie);

};

IDebugHelper

IDebugHelper serves as a factory for object browsers and simple connection points.

cpp_quote( "EXTERN_C const CLSID CLSID_DebugHelper;")

[

object,

uuid(51973C3f-CB0C-11d0-B5C9-00A0244A0E7A),

helpstring("IDebugHelper Interface"),

pointer_default(unique),

local

]

interface IDebugHelper : IUnknown

{

// Returns a property browser that wraps a VARIANT

HRESULT CreatePropertyBrowser(

[in] VARIANT *pvar,// root variant to browse

[in] LPCOLESTR bstrName,// name to give the root

[in] IDebugApplicationThread IDebugApplicationThread *pdat, // thread to request properties on

// (or NULL for no marshalling)

[out] IDebugProperty**ppdob);

// Returns a property browser that wraps a VARIANT, and allows for custom conversion

// of variants or VARTYPEs to strings

HRESULT CreatePropertyBrowserEx(

[in] VARIANT *pvar,// root variant to browse

[in] LPCOLESTR bstrName,// name to give the root

[in] IDebugApplicationThread IDebugApplicationThread *pdat, // thread to request properties on

// (or NULL for no marshalling)

[in] IDebugFormatter IDebugFormatter *pdf,// provides custom formatting of variants

[out] IDebugProperty**ppdob);

// Returns an event interface that wraps the given IDispatch (see ISimpleConnectionPoint)

HRESULT CreateSimpleConnectionPoint(

[in] IDispatch *pdisp,

[out] ISimpleConnectionPoint ISimpleConnectionPoint **ppscp);

};

IEnumDebugExpressionContexts

[

object,

uuid(51973C40-CB0C-11d0-B5C9-00A0244A0E7A),

helpstring("IEnumDebugExpressionContexts Interface"),

pointer_default(unique)

]

interface IEnumDebugExpressionContexts : IUnknown

{

[local]

HRESULT __stdcall Next(

[in] ULONG celt,

[out] IDebugExpressionContext IDebugExpressionContext **ppdec,

[out] ULONG *pceltFetched);

HRESULT Skip(

[in] ULONG celt);

HRESULT Reset(void);

HRESULT Clone(

[out] IEnumDebugExpressionContexts IEnumDebugExpressionContexts **ppedec);

}

IProvideExpressionContexts

Provides a means for enumerating expression contexts known by a certain component. Generally implemented by each script engine. Used by the process debug manager to find all global expression contexts associated with a given thread. Note: This interface is called from within the thread of interest. It is up to the implementor to identify the current thread and return an appropriate enumerator.

[

object,

uuid(51973C41-CB0C-11d0-B5C9-00A0244A0E7A),

pointer_default(unique)

]

interface IProvideExpressionContexts : IUnknown

{

// Returns an enumerator of expression contexts.

HRESULT EnumExpressionContexts(

[out] IEnumDebugExpressionContexts IEnumDebugExpressionContexts **ppedec);

}

[

uuid(78a51821-51f4-11d0-8f20-00805f2cd064),

version(1.0),

helpstring("ProcessDebugManagerLib 1.0 Type Library")

]

library ProcessDebugManagerLib

{

importlib("stdole2.tlb");

interface IActiveScriptDebug;

interface IActiveScriptErrorDebug ;

interface IActiveScriptSiteDebug ;

interface IApplicationDebugger ;

interface IApplicationDebuggerUI ;

interface IDebugApplication ;

interface IDebugApplicationNode ;

interface IDebugApplicationNodeEvents ;

interface IDebugApplicationThread ;

interface IDebugAsyncOperation ;

interface IDebugAsyncOperationCallBack ;

interface IDebugCodeContext ;

interface IDebugCookie;

interface IDebugDocument ;

interface IDebugDocumentContext ;

interface IDebugDocumentHelper ;

interface IDebugDocumentHost ;

interface IDebugDocumentInfo;

interface IDebugDocumentProvider ;

interface IDebugDocumentText ;

interface IDebugDocumentTextAuthor ;

interface IDebugDocumentTextEvents ;

interface IDebugDocumentTextExternalAuthor ;

interface IDebugExpression ;

interface IDebugExpressionCallBack;

interface IDebugExpressionContext ;

interface IDebugFormatter ;

interface IDebugHelper ;

interface IDebugSessionProvider;

interface IDebugStackFrame ;

interface IDebugStackFrameSniffer ;

interface IDebugStackFrameSnifferEx ;

interface IDebugSyncOperation ;

interface IDebugThreadCall ;

interface IEnumDebugApplicationNodes ;

interface IEnumDebugCodeContexts ;

interface IEnumDebugExpressionContexts ;

interface IEnumDebugStackFrames ;

interface IEnumRemoteDebugApplications ;

interface IEnumRemoteDebugApplicationThreads ;

interface IMachineDebugManager ;

interface IMachineDebugManagerCookie ;

interface IMachineDebugManagerEvents ;

interface IProcessDebugManager;

interface IProvideExpressionContexts ;

interface IRemoteDebugApplication ;

interface IRemoteDebugApplicationEvents;

interface IRemoteDebugApplicationThread ;

interface ISimpleConnectionPoint ;

[

uuid(78a51822-51f4-11d0-8f20-00805f2cd064),

helpstring("ProcessDebugManager Class")

]

coclass ProcessDebugManager

{

[default] interface IProcessDebugManager;

};

[

uuid(0BFCC060-8C1D-11d0-ACCD-00AA0060275C),

helpstring("DebugHelper Class")

]

coclass DebugHelper

{

[default] interface IDebugHelper ;

};

// CDebugDocumentHelper

//

// The CDebugDocumentHelper makes it much easier for an ActiveScripting

// host or scripting engine to implement the IDebugDocument interfaces.

//

// Given the source text and (optionally) script blocks for a host's

// document, CDebugDocumentHelper provides implementations for

// the debug document interfaces, including:

//

//- IDebugDocumentText

//- IDebugDocumentTextAuthor (for authoring)

//- IDebugDocumentContext

//

// This class supports aggregation, so the host may provide a controlling

// unknown to CoCreateInstance for extensibility.

//

// This class fires events on IDebugDocumentTextEvents, so the host

// can monitor all changes to the document via that interface.

cpp_quote( "EXTERN_C const CLSID CLSID_CDebugDocumentHelper;")

[

uuid(83B8BCA6-687C-11D0-A405-00AA0060275C),

helpstring("DebugDocumentHelper Class")

]

coclass CDebugDocumentHelper

{

[default] interface IDebugDocumentHelper ;

interface IDebugDocumentProvider ;

interface IDebugDocument ;

interface IDebugDocumentText ;

interface IDebugDocumentTextAuthor ;

interface IConnectionPointContainer;

[default, source] interface IDebugDocumentTextEvents ;

};

};


Debug Property Interfaces

This document describes the following interfaces used to examine debugging properties:

IDebugProperty;

IDebugExtendedProperty;

IEnumDebugPropertyInfo;

IEnumDebugExtendedPropertyInfo;

IPerPropertyBrowsing2;

IDebugProperty Intro

The IDebugProperty interface provides a language-neutral way to browse entities such as:

  • object properties, methods, and events
  • interfaces
  • local variables

IDebugProperty is not intended to be a general replacement for ITypeInfo. For example, it does not include enough low-level information to construct vtable calls or implement IDispatch.

Instead, IDebugProperty is intended to provide human-readable information to allow IDE users to browse and modify objects at design or run-time. Because of this more limited scope, IDebugProperty is much easier to use and to implement than ITypeInfo.

One example of how IDebugProperty can be used is to get a root IDebugProperty from a given stack frame (this IDebugProperty actually represents that stack frame). The members of this root IDebugProperty are the local variables and method parameters, and can be retrieved by calling IDebugProperty::EnumMembers followed by IEnumDebugPropertyInfo::Next. Next returns an array of DebugPropertyInfo structures that contains all the info generally displayed by IDEs in a variables window: name, type, value, etc, as well as attributes that specify if a property is expandable, among other things.

The IDebugProperty interface could also be used to represent registers, memory, or whatever.

The majority of consumers of this interface will be interested only in the IDebugProperty and IEnumDebugPropertyInfo interfaces and will probably want to ignore IDebugExtendedProperty and IEnumDebugExtendedProperty.

INTERFACE NOTES:

===============

Run-time type vs. declared type

The type of a DebugProperty can be determined via two methods. When the type is obtained via GetPropertyInfo, the type is the run-time type. However, when the type obtained via a GetMemberEnum on the parent, the type is the declared type. In other words, object ‘A’ will give you its run-time type, but A’s parent will give you A’s declared type.

enum

{

// -----------------------------------------------------------------------

// OBJECT ATTRIBUTES

DBGPROP_ATTRIB_NO_ATTRIB = 0x00000000,

// ---------------------

// Characteristics

DBGPROP_ATTRIB_VALUE_IS_INVALID = 0x00000008, // the value in this slot is invalid

DBGPROP_ATTRIB_VALUE_IS_EXPANDABLE =0x00000010, // the object has children

DBGPROP_ATTRIB_VALUE_READONLY = 0x00000800, // the value is read-only

// ---------------------

// Attributes about a slot's type

// ---------------------

// Common attributes

// field access control

DBGPROP_ATTRIB_ACCESS_PUBLIC = 0x00001000,

DBGPROP_ATTRIB_ACCESS_PRIVATE = 0x00002000,

DBGPROP_ATTRIB_ACCESS_PROTECTED = 0x00004000,

DBGPROP_ATTRIB_ACCESS_FINAL = 0x00008000,

// storage types

DBGPROP_ATTRIB_STORAGE_GLOBAL = 0x00010000,

DBGPROP_ATTRIB_STORAGE_STATIC = 0x00020000,

DBGPROP_ATTRIB_STORAGE_FIELD = 0x00040000,

// type modifiers

DBGPROP_ATTRIB_STORAGE_VIRTUAL = 0x00080000, // this slot is virtual

DBGPROP_ATTRIB_TYPE_IS_CONSTANT = 0x00100000, // this slot is a constant value

DBGPROP_ATTRIB_TYPE_IS_SYNCHRONIZED =0x00200000, // this slot is thread synchronized

DBGPROP_ATTRIB_TYPE_IS_VOLATILE = 0x00400000, // this slot is volatile storage

DBGPROP_ATTRIB_HAS_EXTENDED_ATTRIBS =0x00800000 // has more attributes

};

typedef DWORD DBGPROP_ATTRIB_FLAGS;

// -----------------------------------------------------------------------

// DebugPropertyInfo

// Basic info that all IDebugProperty implementations must support

enum

{

// Flags used to specify DebugPropertyInfo (and ExtendedDebugPropertyInfo) fields

DBGPROP_INFO_NAME = 0x001, // init the bstrName field

DBGPROP_INFO_TYPE = 0x002, // init the bstrType field

DBGPROP_INFO_VALUE = 0x004, // init the bstrValue field

DBGPROP_INFO_FULLNAME = 0x020, // init the full name field

DBGPROP_INFO_ATTRIBUTES = 0x008, // init the dwAttrib field

DBGPROP_INFO_DEBUGPROP = 0x010, // init the pDebugProp field

DBGPROP_INFO_AUTOEXPAND = 0x8000000 // make the Value result auto-expand

};

typedef DWORD DBGPROP_INFO_FLAGS;

const DBGPROP_INFO_FLAGS DBGPROP_INFO_STANDARD =

DBGPROP_INFO_NAME |

DBGPROP_INFO_TYPE |

DBGPROP_INFO_VALUE |

DBGPROP_INFO_ATTRIBUTES;

const DBGPROP_INFO_FLAGS DBGPROP_INFO_ALL =

DBGPROP_INFO_NAME |

DBGPROP_INFO_TYPE |

DBGPROP_INFO_VALUE |

DBGPROP_INFO_FULLNAME |

DBGPROP_INFO_ATTRIBUTES |

DBGPROP_INFO_DEBUGPROP;

typedef struct tagDebugPropertyInfo

{

DBGPROP_INFO_FLAGS m_dwValidFields; // which DebugPropertyInfo fields were successfully initialized

BSTR m_bstrName; // property name

BSTR m_bstrType; // property type, as formatted string

BSTR m_bstrValue; // property value, as formatted string

BSTR m_bstrFullName; // property's full name, like pObject->m_fFlag

DBGPROP_ATTRIB_FLAGS m_dwAttrib; // property attributes (ORed DBGPROP_ATTRIB_* above)

IDebugProperty* m_pDebugProp; // IDebugProperty object corresponding to this DebugPropertyInfo

} DebugPropertyInfo;

// -----------------------------------------------------------------------

// Extended info that some IDebugProperty implementations support

enum

{

// Flags used to specify ExtendedDebugPropertyInfo fields

EX_DBGPROP_INFO_ID = 0x0100, // init the nDISPID field

EX_DBGPROP_INFO_NTYPE = 0x0200, // init the nType field

EX_DBGPROP_INFO_NVALUE = 0x0400, // init the varValue field

EX_DBGPROP_INFO_LOCKBYTES = 0x0800, // init the plb field

EX_DBGPROP_INFO_DEBUGEXTPROP = 0x1000, // init the pDebugExtProp field

};

typedef DWORD EX_DBGPROP_INFO_FLAGS;

typedef struct tagExtendedDebugPropertyInfo

{

// members from DebugPropertyInfo

DBGPROP_INFO_FLAGS m_dwValidFields; // which ExtendedDebugPropertyInfo fields were successfully initialized

LPOLESTR m_bstrName; // property name

LPOLESTR m_bstrType; // property type, as formatted string

LPOLESTR m_bstrValue; // property value, as formatted string

LPOLESTR m_bstrFullName; // property's full name, like pObject->m_fFlag

DBGPROP_ATTRIB_FLAGS m_dwAttrib; // property attributes (ORed DBGPROP_ATTRIB_* above)

IDebugProperty* m_pDebugProp; // IDebugProperty object corresponding to this DebugPropertyInfo

// extra members

DWORD m_nDISPID; // DISPID of this child (DISPID_NIL, if n/a or none)

DWORD m_nType; // property type

VARIANT m_varValue; // property value (if value can physically fit in VARIANT)

ILockBytes* m_plbValue; // property value (actual data bytes)

IDebugExtendedProperty* m_pDebugExtProp; // IDebugExtendedProperty object corresponding to this DebugPropertyInfo

} ExtendedDebugPropertyInfo;

// -----------------------------------------------------------------------

// IDebugProperty

[

object,

uuid(51973C50-CB0C-11d0-B5C9-00A0244A0E7A),,

pointer_default(unique)

]

interface IDebugProperty : IUnknown

{

// Get Information for this object

// By setting various PROPERTY_INFO_FLAGS, any subset of the basic info

// contained in DebugPropertyInfo can be fetched

HRESULT GetPropertyInfo(

[in] DBGPROP_INFO_FLAGS dwFieldSpec,

[in] UINT nRadix,

[out] DebugPropertyInfo* pPropertyInfo);

// Get ExtendedInfo for this object. This API only exists for the purpose

// of retrieving info that does not lend itself to being retrieved via the

// standard means (i.e. using DebugPropertyInfo)

//

// An array of GUIDs and result VARIANTs is passed so that multiple items

// of extended info can be fetched at the same time. If a variant cannot

// be initialized for some reason, the vt field should be set to VT_ERROR.

// The currently defined extended info guids are described below.

// A QI is typically required to obtain interfaces on the right from

// IUnknowns in the variant.

// GUID VALUE

//

// guidDefinitionContext IDebugDocumentContext2

// ISSUE: Add additional GUIDS, such as:

// <guidSomeRandomBSTR> BSTR

// <guidSomeRandomI4> I4

HRESULT GetExtendedInfo(

[in] ULONG cInfos,

[in, size_is(cInfos)] GUID* rgguidExtendedInfo,

[out, size_is(cInfos)] VARIANT* rgvar);

// Set the value of this object as a string

HRESULT SetValueAsString(

[in] LPCOLESTR pszValue,

[in] UINT nRadix);

// Get enumerator for props of members

HRESULT EnumMembers(

[in] DBGPROP_INFO_FLAGS dwFieldSpec,

[in] UINT nRadix,

[in] REFIID refiid,

[out] IEnumDebugPropertyInfo **ppepi);

// Get the parent property

HRESULT GetParent(

[out] IDebugProperty **ppDebugProp);

};

[

object,

uuid(51973C51-CB0C-11d0-B5C9-00A0244A0E7A),

pointer_default(unique)

]

interface IEnumDebugPropertyInfo : IUnknown

{

// Enumerate information for sub-objects

// get the next celt elements, if possible

[local]

HRESULT Next(

[in] ULONG celt,

[out] DebugPropertyInfo *pi,

[out] ULONG *pcEltsfetched

);

// Skip the next celt slots

HRESULT Skip(

[in] ULONG celt);

// Restart from the beginning

HRESULT Reset(void);

// Clone this property browser at the current enumeration state

HRESULT Clone(

[out] IEnumDebugPropertyInfo **ppepi);

// Get the number of elements in the enumerator

HRESULT GetCount(

[out] ULONG* pcelt);

};

Note: The IDebugExtendedProperty is QI’able from an IDebugProperty, and contains more information than the simpler IDebugProperty.

[

object,

uuid(51973C52-CB0C-11d0-B5C9-00A0244A0E7A),

pointer_default(unique)

]

interface IDebugExtendedProperty : IDebugProperty

{

// Get Information for this object

// By setting various EXPROPERTY_INFO_FLAGS and PROPERTY_INFO_FLAGS,

// any subset of the basic info contained in ExtendedDebugPropertyInfo

// can be fetched

HRESULT GetExtendedPropertyInfo(

[in] EX_DBGPROP_INFO_FLAGS dwFieldSpec,

[in] UINT nRadix,

[out] ExtendedDebugPropertyInfo *pExtendedPropertyInfo);

// Get enumerator for props of members

HRESULT EnumExtendedMembers(

[in] EX_DBGPROP_INFO_FLAGS dwFieldSpec,

[in] UINT nRadix,

[out] IEnumDebugExtendedPropertyInfo **ppeepi);

};

[

object,

uuid(51973C53-CB0C-11d0-B5C9-00A0244A0E7A),

pointer_default(unique)

]

interface IEnumDebugExtendedPropertyInfo : IUnknown

{

// Enumerate information for sub-objects

// Get the next celt elements, if possible

HRESULT Next(

[in] ULONG celt,

[out, size_is(celt), length_is(*pceltFetched)] ExtendedDebugPropertyInfo *rgExtendedPropertyInfo,

[out] ULONG *pceltFetched);

// Skip the next celt slots

HRESULT Skip(

[in] ULONG celt);

// Restart from the beginning

HRESULT Reset(void);

// Clone this property browser at the current enumeration state

HRESULT Clone(

[out] IEnumDebugExtendedPropertyInfo **pedpe);

// Get the number of elements in the enumerator

HRESULT GetCount(

[out] ULONG* pcelt);

};

[

object,

uuid(51973C54-CB0C-11d0-B5C9-00A0244A0E7A),

pointer_default(unique)

]

interface IPerPropertyBrowsing2 : IUnknown

{

// Get a string to display for those types which are inheritly non-viewable

// Note: The returned string is *not* a legal value for the property,

// just an indication to the user of what the property is.

HRESULT GetDisplayString(

[in] DISPID dispid,

[out] BSTR *pBstr);

// Return the CLSID of the property page which can be used to edit this

// property.

HRESULT MapPropertyToPage(

[in] DISPID dispid,

[out] CLSID *pClsidPropPage);

// These methods allow the caller to fill a listbox with a set of strings

// which _represent_ potential values for this property. When an item

// is chosen, the cookie is passed back to the object, so that the object

// can set itself to the corresponding value.

HRESULT GetPredefinedStrings(

[in] DISPID dispid,

[out] CALPOLESTR *pCaStrings,

[out] CADWORD *pCaCookies);

HRESULT SetPredefinedValue(

[in] DISPID dispid,

[in] DWORD dwCookie);

};

// the IDebugPropertyEnumType interfaces are really defined for their IIDs,

// we have no need currently to *implement* any of them, but we might one day

// These IIDs are passed to EnumMembers for filtering the enumerator.

[

object,

uuid(51973C55-CB0C-11d0-B5C9-00A0244A0E7A),

pointer_default(unique)

]

interface IDebugPropertyEnumType_All : IUnknown

{

HRESULT GetName([out] BSTR *);

};

[

object,

uuid(51973C56-CB0C-11d0-B5C9-00A0244A0E7A),

pointer_default(unique)

]

interface IDebugPropertyEnumType_Locals : IDebugPropertyEnumType_All

{

};

[

object,

uuid(51973C57-CB0C-11d0-B5C9-00A0244A0E7A),

pointer_default(unique)

]

interface IDebugPropertyEnumType_Arguments : IDebugPropertyEnumType_All

{

};

[

object,

uuid(51973C58-CB0C-11d0-B5C9-00A0244A0E7A),

pointer_default(unique)

]

interface IDebugPropertyEnumType_LocalsPlusArgs : IDebugPropertyEnumType_All

{

};

[

object,

uuid(51973C59-CB0C-11d0-B5C9-00A0244A0E7A),

pointer_default(unique)

]

interface IDebugPropertyEnumType_Registers : IDebugPropertyEnumType_All

{

};


Delivering Content to the Web

This section contains information on new ways Web publishers can deliver their content with Internet Explorer 4.0. Several new features using "push" technologies are explained, including Active Channels, Active Desktop items, and Software Update Channels.

Content Delivery Mechanisms

The User Experience

Authoring for New Delivery Mechanisms

CDF Reference

Tools


Creating Active Channels

This article explains Active Channels™ for Microsoft® Internet Explorer 4.0. Feature descriptions, screen shots, examples, guidelines, and a reference guide are provided to help Web publishers understand how to create their own Active Channels with a Channel Definition Format (CDF) file.

Webcasting

What Is an Active Channel?

Active Channel Types

Active Channel Features

Developing an Active Channel

Optimizing Active Channels over HTTP

Guidelines for Active Channel Logo Images

Using Dynamic HTML with Active Channels

Netcaster CDF Compatibility Notes


Authoring for New Delivery Mechanisms

These documents describe how Web publishers can create their own channels or desktop items and provide them to users.

Creating Active Channels

Creating Active Desktop Items

Creating Software Update Channels


Creating Active Desktop Items

The Microsoft® Internet Explorer 4.0 Active Desktop™ is capable of hosting any HTML item, such as Web pages, Java applets, ActiveX™ Controls, floating frames, and images. With this technology, users can create a highly customized environment that automatically brings their favorite Web content to the desktop. Web publishers can leverage their existing tools and production processes to enhance their Web content with Dynamic HTML support. The resulting integration of the desktop and the Web benefits users through an enhanced and easier Web experience. Web publishers also benefit from the increased presence in the users' working environment.

For the latest information about Active Desktop items, refer to the list of Frequently Asked Questions (FAQ) in the Internet Client SDK.

Overview: Active Desktop and Active Channels

Publishing Information on the Active Desktop

How the Active Desktop Works

Active Desktop Item Development Guidelines

How to Develop an Active Desktop Item

Overview: Active Desktop and Active Channels

Until now, the primary target for Web-based content has been the browser window. Most Web publishers today are forced to optimize their content to fit into a medium-sized browser window, based on the default window size of the browser. Internet Explorer 4.0 opens new opportunities for content by enabling your content to grow beyond the browser window, in two directions at once. The first direction lets you offer your customers a more focused browsing experience by taking over the entire screen, minimizing most of the "chrome" (toolbars) surrounding your content, and taking full advantage of Dynamic HTML extensions. This helps Web publishers provide a multimedia experience that is more engaging than anything currently possible inside a browser window. This is the idea behind Active Channels.

At the same time, Internet Explorer 4.0 enables your content to grow in a second direction. Now you can augment your content offering by providing your customers a more immediate, condensed experience. This is accomplished with lightweight entry points to top-level summaries and headlines in a small HTML page displayed directly on the user's Active Desktop. This HTML page presents top-level links and lets your customers point and click to open a larger window and absorb the details waiting underneath. This is the idea behind items on the Active Desktop.

For the user, Active Desktop items and Active Channels complement each other to provide different types of information in a useful manner. In a typical situation, users would log onto their computer and immediately see your Active Desktop item (along with several others) on their desktop. The user scans your Active Desktop item to see highlights and news as of the last scheduled update. The user can then click on any link inside the item to see the full story. At this point, the Active Desktop item can launch the user directly into your Active Channel instead of loading the associated URL into a regular browser window. This example illustrates how the Active Desktop item presents the content summary and the Active Channel presents the details.

For the content provider, Active Desktop items and Active Channels are also a great match. This is because the same knowledge and experience you build when authoring an Active Channel also applies to authoring Active Desktop items. Both Active Channels and Active Desktop items use Dynamic HTML to make the most engaging use of their screen area, while at the same time conserving bandwidth. It is important to note that both Active Channels and Active Desktop items require a separate Channel Definition Format (CDF) file to configure their update schedules and presentation requirements.

Active Desktop Features

Because Active Desktop items and Active Channels leverage the same technology, many of the features that apply to Active Channels also apply to Active Desktop items. These features include:

Subscriptions | Icons are placed in the Subscriptions folder to let users manage update schedules and notification attributes.
CDF Support | Subscription icons are based on the information in a CDF file that you author. The CDF file contains special tags to alert Internet Explorer 4.0 that the content is intended for use as an Active Desktop item. Additional CDF elements are available to control how the item is displayed and when it is updated.
Personalized Active Channels and Passwords | Personalized password-based access to a Web publisher's content is available. Since an Active Desktop item is just a tiny Web page, navigating to the content is the same as navigating to a page in a browser window, so you can use a CDF file to support automatic login and password verification.

Publishing Information on the Active Desktop

The following sections describe how Web publishers can create and display content in an Active Desktop item. Examples of Active Desktop item installations are provided at http://www.microsoft.com/ie/ie40/gallery.

Active Desktop items are placed beside existing desktop shortcuts to give users a highly customizable space for creating dynamic links to their favorite Web content. Active Desktop items are typically designed to provide summary information in a small amount of screen space. Most items offer hot spots so the user can click on that area of the item to open a new browser window; the user can then read the full story or browse through the rest of the Web site. The following screen snapshot shows an example of an Active Desktop hosting two Active Desktop items on the right side of the screen, with the standard desktop shortcuts placed on the left edge of the screen.

Active Desktop items

Possible Active Desktop items include:

  • Tickers for sports scores, stock quotes, or weather.
  • Headline lists for news stories or announcements.
  • Pop-up broadcast messages for internal corporate announcements.
  • Notifications for new mail, chat, or public discussion forums.
  • Pictures of sports highlights or breaking news stories. A picture can be configured for daily update; clicking the picture could launch a browser window to preview the related story.

Active Desktop items are completely customizable:

  • By the end user.

    An item can be positioned and resized anywhere on the desktop. The user can also customize schedules for updating each item separately.

  • By the corporation.

    MIS managers can pick and choose a mix of default Active Desktop items for their clients by workgroup or division. Managers can also lock the Active Desktop items to prevent incorrect configuration by end users and filter out undesirable content by implementing a full range of security restrictions. Desktops can be configured for roaming access across workstations, and all settings can be administered remotely.

  • By the publisher.

    Items can consist of any HTML-based content, including Dynamic HTML, ActiveX Controls, Java applets, scripting, frame sets, and so on. Items can be initially configured with a default update schedule so content providers can manage their server traffic. This is accomplished with the use of a Channel Definition Format (CDF) file.

Active Desktop items are an evolution of Internet Explorer 3.0 desktop shortcuts. They can be any size or shape and can display any HTML-based content. Items are dynamic and can be configured to update at regularly scheduled times, so their content is always up to date. As part of the information delivery system in Internet Explorer 4.0, the URL associated with any Active Desktop item is automatically added to the user's Subscriptions folder. This has the following effects:

  • All content is automatically cached offline in the user's cache. This makes content available for browsing when no Internet connection is currently available.
  • Users will be automatically notified whenever the item is changed on the server. Internet Explorer 4.0 provides this service automatically for all subscriptions.
  • Each Active Desktop item can be scheduled individually for updates on the client. For example, users could display a sports ticker that is updated once an hour, a news headline service that is updated once a day, and a comic strip that is updated once a week, all sharing space on the same desktop. Internet Explorer 4.0 automatically refreshes the associated HTML content on the desktop whenever the update occurs.

Site subscription data flow

How the Active Desktop Works

The Active Desktop in Internet Explorer 4.0 is built from two separate layers. The transparent icon layer exposes all the user's existing desktop shortcuts, and the background HTML layer hosts all Active Desktop items. The HTML layer is described by a single, local HTML file called Desktop.htm that is created and edited automatically by Internet Explorer 4.0. This file contains the following:

  • HTML tags that represent each Active Desktop item. Each Active Desktop item consists of a single HTML tag with arbitrary x- and y-positions. Refer to the documentation on Positioning for a description of 2-D positioning and layering with Dynamic HTML. The HTML tag used for an Active Desktop item can be either an image (IMG tag) or a floating frame (IFRAME tag). The tag is generated automatically by Internet Explorer 4.0. The floating frame is the most commonly used approach, because it neatly encapsulates an entire arbitrary HTML document that can contain anything the publisher desires. In either case, there is a single URL that points to the actual content.
  • An ActiveX control that enables moving and resizing of the Active Desktop items and also helps manage the list of items.
  • Any other static HTML that the user wants to have in the background. By default, this is just a reference to the user's chosen wallpaper, which is exposed as the background watermark for the HTML page.

Active Desktop layers

Active Desktop Item Development Guidelines

An item is nothing more than a small, borderless frame that displays a Web page and is embedded on the Active Desktop. The Web page can contain anything that a standard Web page can contain, including ActiveX Controls, Java applets, Dynamic HTML, and so on. The Active Desktop lets the user add and remove the frames at will, as well as adjust their size and position with the mouse.

Users can choose to create an Active Desktop item out of any existing Web page, but the best ones are Web pages that have been specifically designed to be used as Active Desktop items.

When designing an Active Desktop item, there are several guidelines to keep in mind.

  • The item must work offline.

    Since most dial-up users do not have a constant connection to the Internet, an Active Desktop item should display some reasonable content in the absence of a connection. This is of key importance, because the desktop is immediately visible when the user launches the operating system, even before the user has a chance to initiate a dial-up session. An Active Desktop item that displays a blank, gray square or an error message while the user is offline is neither useful nor attractive. For this reason, any necessary data files the item requires should be configured to be cached on the user's computer. This can be particularly tricky for Java applets, because image objects typically sit in separate GIF or JPEG files on the Web server. Fortunately, the Internet Explorer 4.0 subscription feature can be configured to cache any object referenced by an Active Desktop item by including it in the CDF file with the ITEM element.

    In the typical case where an item is built from an HTML document inside a floating frame, Internet Explorer 4.0 subscriptions can be set to automatically download any inline images, sounds, objects, or applets, and also any number of HTML links n levels deep. It is important to note that Java applets cannot be pre-cached if the Java classes are not wrapped together in a CAB, ZIP, or JAR file. If the classes are in separate files, Internet Explorer cannot determine the Java class dependencies and cache appropriately because Java binds classes dynamically.

    Java- and ActiveX-based desktop items should also be authored to give an error or informational message when not connected to the network to prevent an empty gray box from being displayed. Also, to read from the cache when not connected to the network, Java applets should call setUseCaches(TRUE) in their java.net objects. For more information about authoring Java or ActiveX desktop items, review the list of frequently asked questions.

    Active Desktop items can also specify individual subscriptions for any data files or objects it might reference. Please note that Java applets and ActiveX Controls must be signed so they can access content from the offline cache. For more information about signing Java applets or ActiveX Controls, see http://www.microsoft.com/java/ or http://www.microsoft.com/windowsdna/.

  • Avoid using in-place navigation controls.
    Active Desktop items are meant to be lightweight and therefore have no navigation controls available for the user to move backward and forward. By default, clicking a link inside an Active Desktop item creates a new browser window. The intended purpose of an Active Desktop item is to provide quick summary information and an easy browser-launching mechanism if the user wants more information. Therefore, authors shouldn't create in-place navigation controls, and they shouldn't depend on the Back and Forward commands being available to the item. Active Desktop item authors should not make any assumptions about the context in which the item is running. More information about properly handling the context in which an Active Desktop item runs is available in the list of frequently asked questions.

  • Smaller is better.

    An Active Desktop item needs to share the desktop space with any other icons or Active Desktop items the user has selected. Because this space is completely customizable by the user, Active Desktop items should be authored to be as small as possible to display their desired content. This gives Active Desktop users the maximum flexibility to arrange their desktop as they wish. A good benchmark is to make sure that the Active Desktop item takes up no more than one-sixth the area of the screen. By default, Internet Explorer lays out new Active Desktop items on a 3´2 grid. As more items are added to the desktop, they will start to overlap each other. For a desktop at a resolution of 640´480, allowing for reasonable spacing between items, this would translate into a maximum size of no more than 200´200 pixels. This size specification is merely a guideline. Internet Explorer 4.0 does not itself enforce any restrictions on the size of an Active Desktop item.

    Active Desktop item layout

  • Avoid pop-up messages.

    Today it is common for ActiveX Controls, Java applets, and scripting content to notify the user of error messages or warnings by using modal dialog boxes that overlap the browser window. This is fine when the browser window is in the foreground. However, launching a modal dialog box from an Active Desktop item might confuse the user. If an Active Desktop item delivers a pop-up message to the user while the desktop is not in the foreground, the user might not be sure where the message came from or what to do about it. The typical situation to avoid is showing error messages when an Active Desktop item can't connect to the server. In these cases, the item should display some type of status message in the Active Desktop item itself, preferably with a hot spot or link that lets the user get more information and figure out how to proceed.

  • Use the default color palettes.

    A large portion of Internet Explorer 4.0 users have displays that are limited to 256 colors. For these users, Internet Explorer chooses a default palette that is intended to give a broad range of hues across the entire color spectrum. Therefore, when authoring an Active Desktop item, it is important to keep in mind exactly what the image colors will look like on a 256-color display.

  • Include a rating tag in your item.

    Content Advisor is a feature in Internet Explorer that allows parents and supervisors to filter out Web content based on rating labels. This feature is based on the World Wide Web Consortium (W3C) standard for content ratings, known as PICS (http://www.w3.org/PICS External link), or Platform for Internet Content Selection. PICS allows for any rating system to be used and lets the parents or supervisors decide what types of content are acceptable. Web publishers should include a rating tag in their HTML files because someone browsing with the Content Advisor turned on will not be able to see content that is not rated. For more information, see Internet Ratings in the Internet Client SDK.

  • Handle expiration dates.

    Web publishers can define an expiration date for time-sensitive desktop items. This information is specified by the STOPDATE attribute of the SCHEDULE element. For example, a typical desktop item schedule might look like this:

    <Schedule STOPDATE="1998.11.05T08:15-0500">
    <IntervalTime DAY="1" />
    <EarliestTime HOUR="12" />
    <LatestTime HOUR="18" />
</Schedule>

    This schedule shows that on November 5, 1998, Internet Explorer will stop refreshing this desktop item's data from the source URL. The desktop item will remain on the user's desktop, but its content will become stale. A few days before the desktop item expires, Web publishers should replace the content that is pointed to by the desktop item with a notification page. This page should explain to users that the desktop item is no longer valid and that they should either close it or get a new one. The actual desktop item should not be deleted from the HTTP server until after the expiration date to avoid having broken desktop items on users' desktops.

How to Develop an Active Desktop Item

The process for creating an Active Desktop item is very similar to the process for developing a simple channel. In fact, the same steps apply:

  1. Design the Active Desktop item.
  2. Create the CDF file.
  3. Post the CDF file.
  4. Offer the Active Desktop item to users.

Design the Active Desktop Item

An Active Desktop item is just a small Web page. This page gets embedded in the user's Active Desktop as a floating frame inside a single Desktop.htm file that describes the user's HTML wallpaper and all other Active Desktop items.

Note Try implementing Dynamic HTML in your Active Desktop item. It is common for an Active Desktop item to cycle through a set of headlines or summary information. Dynamic HTML makes it possible to achieve this effect without using Java or ActiveX code.

Create the CDF file

Creating a CDF file is very similar to creating a CDF file for an Active Channel. The primary rule is that you are required to create a separate CDF file for each Active Desktop item or Active Channel you author. For more information about CDF elements and their syntax, see the documentation on CDF Extensions for Active Desktop Items and the CDF Reference for Active Channels.

Basic syntax: The ITEM and USAGE elements

The CDF for an Active Desktop item must include at least one ITEM element under the top-level CHANNEL element with a USAGE child element marked as "DesktopComponent" (see the example below). It is this USAGE element that tells Internet Explorer the CDF file refers to an Active Desktop item, as opposed to an Active Channel. The CDF file should also include a SCHEDULE element to indicate when the item will be updated.

Additional ITEM elements

Since an Active Desktop item is comprised of a single HTML page, the only ITEM you need to include in the CDF file is the small Web page you want to embed in the user's desktop. This should be marked with the USAGE element as indicated in the example below. If you like, you can include additional ITEM elements for each page that the Active Desktop item links to. Including these as ITEMs in the CDF file has the additional benefit of keeping those pages "subscribed to" and available for offline viewing. The ITEMs other than the actual Active Desktop item URL are not exposed to the user. Note that this differs from Active Channels, which present a hierarchical list of their ITEM tags to the user in the form of the Internet Explorer Channel Pane.

CDF restrictions on Active Desktop items

The following restrictions are placed on CDF files for Active Desktop items:

  • If your CDF file has more than one ITEM element marked with USAGE equal to "DesktopComponent", Internet Explorer uses the first one it encounters.
  • Only the top-level CHANNEL element is valid. Nested CHANNEL elements have no effect because these additional items don't correspond to any list or hierarchy that the user can access.
  • USAGE elements set to anything other than "DesktopComponent" are ignored.

Active Desktop item CDF example

The following example shows a CDF file for an Active Desktop item.

<?XML version="1.0"?>
<Channel>

        <Schedule STOPDATE="1998.11.05T08:15-0500">
                <IntervalTime DAY="1"  />
                <EarliestTime HOUR="12"/>
                <LatestTime   HOUR="18"/>
        </Schedule>

        <Item HREF="http://www.microsoft.com" LastMod="1996.11.05T08:15-0500">

                <Title>My News Ticker</Title>    <!-- Friendly name               -->

                <Usage VALUE="DesktopComponent"> <!-- Required                    -->
                        <OpenAs VALUE="HTML"/>   <!-- "HTML" (default) or "Image" -->
                        <Width  VALUE="200" />   <!-- Width in pixels             -->
                        <Height VALUE="80"  />   <!-- Height in pixels            -->
            <CanResize VALUE="Yes"/> <!-- Yes (default) or No	    -->
                </Usage>
        </Item>

        <!-- Other Item tags may go here.  IE4 won't display them anywhere, but   -->
        <!-- will use them for site crawling and place them in the user's cache. -->

        <Item HREF="http://www.foosports.com/topstories.html" LastMod="1996.11.05T08:15-0500" >
        </Item>

</Channel>

Post the CDF File

Post the CDF file by making it publicly available on your Web servers.

Offer the Active Desktop Item to Users

As with Active Channels, a link or button should be placed on any Web page that references the CDF file to allow users to subscribe to the new Active Desktop item. When the user clicks the link, Internet Explorer 4.0 automatically detects the USAGE element, which tells it that the CDF refers to an Active Desktop item. Internet Explorer 4.0 then activates the Active Desktop item Subscription Wizard on the user's computer and allows the user to receive updated information about this Active Desktop item. As the content contained in the Active Desktop item is added, removed, or modified, Web publishers should update the CDF file to reflect the changes. Information about button images and scripts used for enabling subscriptions is available in the Active Channels documentation.


Creating Software Update Channels

Software Update Channels are specialized channels that provide the ability to notify users of software updates and also to deliver and install program files onto users' computers.

Software developers can use Software Update Channels as a method of delivering updated versions of their software to their users. All users who subscribe to the developer's Software Update Channel will receive notification that a new version is available.

Corporations can use Software Update Channels to distribute applications and software updates to all of the desktops connected to their corporate network instead of updating each system individually.

Distributing Software

To distribute software using a Software Update Channel, the developer or corporation needs to:

  1. Create a Software Update Channel.
  2. Create an Open Software Description (OSD) file.
  3. Create a distribution unit.

Creating a Software Update Channel

A Software Update Channel is defined with a Channel Definition Format (CDF) file, which is written in the Extensible Markup Language (XML). For more information on CDF files, see CDF Reference for Active Channels. For Software Update Channel extensions to the CDF, see VERSION= (SOFTPKG)
. For information on XML, see XML Object Model documentation.

The VALUE= attribute of the USAGE tag is set to the value "SoftwareUpdate" in the CDF file to notify Microsoft® Internet Explorer 4.0 that this is a Software Update Channel. The shortcut for the channel will be created in the Software Updates folder in the Favorites menu.

For a Software Update Channel, the CDF file would contain details on the software distribution unit available. These details include:

  • The unique string name of the distribution unit. One way to ensure the name is unique is to use a globally unique identifier (GUID).
  • The title of the distribution unit, which should be something meaningful to the user.
  • The operating system for which the distribution unit is available.
  • The location of the distribution unit.

The following is an example of a CDF file for a Software Update Channel for a fictitious company, Awesome Computers.

<CHANNEL HREF="http://www.server.com/setup-page.htm">
<SELF HREF="http://www.awesome_computers.com/awesome_comp.cdf" />
<USAGE VALUE="SoftwareUpdate" />
<TITLE>Awesome Computer's Software Update Channel</TITLE>
<ABSTRACT>Awesome Computers' site for updated drivers and programs for all our awesome systems.
</ABSTRACT>

<LOGO HREF="http://www.awesome_computers.com/ac-channel.gif" STYLE="IMAGE" />
<LOGO HREF="http://www.awesome_computers.com/ac-channel.ico" STYLE="ICON" />

    <SOFTPKG NAME="{D27CDB6E-AE6D-11CF-96B8-444553540000}"
        HREF="http://www.awesome_computers.com/Update.htm"
        VERSION="2,0,0,0"
        AUTOINSTALL="Yes"
        STYLE="MSICD">
        <TITLE>Update for the system diagnostic control for Windows 95</TITLE>

        <ABSTRACT>System diagnostic control that tracks download efficency information.
        </ABSTRACT>

        <USAGE VALUE="email" />
        <IMPLEMENTATION>
                <OS VALUE="win95" />
                <CODEBASE HREF="http://www.awesome_computers.com/diagnostic.cab" />
        </IMPLEMENTATION>
    </SOFTPKG>
</CHANNEL>

The NAME= attribute of the VERSION= (SOFTPKG)
tag contains the unique string name for the distribution unit, which is a GUID in the example.

The TITLE tag contains the friendly title that is used to notify the user of the software distribution unit's availability.

The IMPLEMENTATION tag contains the information on the operating system and the location of the code. The VALUE= attribute of the OS tag indicates the operating system for which the distribution unit is available (Microsoft® Windows 95® in the example), and the HREF= attribute of the CODEBASE tag indicates the location of the distribution unit. If no CODEBASE tag is provided, the Active Channel acts as an advertisement for the software package. The content in the ABSTRACT tag should contain information about where to download the advertised software package.

The CDF file should contain scheduling information so that the user's computer knows how often to check the server for updates. The schedule should also provide information to let the user's computer randomize its checks. For details about adding schedule information to the CDF file, see the SCHEDULE tag in the CDF Reference for Active Channels.

For Software Update Channels that are provided for a one-time download, the DELETEONINSTALL tag can be added inside the VERSION= (SOFTPKG)
tag in the CDF file. The channel will be deleted after the installation of the software package has been completed.

Creating the Open Software Description file

The Open Software Description (OSD) file is also written in XML and is similar to the CDF file. This file contains the information about what the user's computer needs to do after it downloads the distribution unit from the server. For more information on OSD files, see http://www.microsoft.com/sitebuilder/standards/osd/ External link. For more information on XML, see http://www.microsoft.com/sitebuilder/standards/xml/ External link.

The following example is a sample OSD file for Awesome Computer's updated diagnostic control that indicates a download location for the updated control.

<?XML version="1.0" ?>
<!DOCTYPE SOFTPKG SYSTEM "http://www.microsoft.com/standards/osd/osd.dtd" >
<?XML::namespace href="http://www.microsoft.com/standards/osd/msicd.dtd" as="msicd"?>

<SOFTPKG NAME="{D27CDB6E-AE6D-11CF-96B8-444553540000}" VERSION="2,0,0,0" STYLE="MSICD">
    <TITLE>System diagnostic control for Windows 95</TITLE>
    <ABSTRACT>This distribution contains updated diagnostic control.
    </ABSTRACT>

    <msicd::NATIVECODE>
        <CODE   NAME="diagnose.ocx"
                        CLASSID="{D27CDB6E-AE6D-11CF-96B8-444553540000}"
                        VERSION="2,0,0,0">
                <IMPLEMENTATION>
                    <OS VALUE="win95" />
                    <CODEBASE HREF="http://www.awesome_computers.com/diagnose.cab" />
                </IMPLEMENTATION>
        </CODE>
    </msicd::NATIVECODE>
</SOFTPKG>

The <!DOCTYPE SOFTPKG SYSTEM "http://www.microsoft.com/standards/osd/osd.dtd" > line sets the Document Type Definition (DTD) file, which defines the formal grammar for a type document. In this case, it is defining the grammar for an OSD file. This file allows an XML parser or other verifier to check if the OSD file is well-formed.

The <?XML::namespace href="http://www.microsoft.com/standards/osd/msicd.dtd" as="msicd"?> line specifies additional legal elements that will use the name space identifier defined by the as= attribute. For this example, the name space is "msicd".

The NATIVECODE tag defined in the Msicd.dtd file notifies the user's computer that the distribution unit is written in the native code of the operating system noted in the VALUE= attribute of the OS tag. The JAVA tag is used if the distribution unit contains a Java class, a Java application, or JavaBeans.

The DEPENDENCY tag can be added inside the VERSION= (SOFTPKG)
tag section to indicate a software dependency. The DEPENDENCY tag allows developers or corporations to have the distribution unit downloaded only if certain conditions exist. For example, you could set a dependency that a particular distribution unit has to be installed. If it is installed, it will download a distribution unit that contains a patch for the installed software.

Describing Java packages

Describing Java packages is similar to describing native code distribution units, except they use the JAVA tag instead of NATIVECODE and the PACKAGE tag instead of CODEBASE.

The following example shows the VERSION= (SOFTPKG)
tag section that describes a Java package.

<SOFTPKG NAME="StorePackage" VERSION="1,0,0,0">
<TITLE>The StoreData class</TITLE>

<ABSTRACT>StorePackage contains a single class called StoreData.
</ABSTRACT>

<msicd::JAVA>

    <PACKAGE NAME="com.ms.StorePackage" VERSION="1,0,0,2">
    <IMPLEMENTATION>
    </IMPLEMENTATION>
    </PACKAGE>

</msicd::JAVA>

</SOFTPKG>

Describing Java applications

The following example shows the VERSION= (SOFTPKG)
tag section that describes a Java application.

<SOFTPKG NAME="Some Application for Java" VERSION="1,0,0,0">

    <TITLE>MS Office for Java</TITLE>

    <ABSTRACT>Some Application for Java is a standalone Java application.
    </ABSTRACT>

        <msicd::JAVA>
            <NAMESPACE>Some Application for Java</NAMESPACE>
            <PACKAGE VERSION="1,0,0,2">

                <IMPLEMENTATION>
                </IMPLEMENTATION>

            </PACKAGE>

        </msicd::JAVA>

</SOFTPKG>

Describing JavaBeans

The OSD file can describe both JavaBeans and Microsoft® ActiveX™ Controls wrapped as JavaBeans. ActiveX Controls wrapped as JavaBeans require the CLASSID= attribute in the CLASS element and the ICON or TYPELIB element, while a regular JavaBean does not require these elements.

The following is a sample description of an ActiveX control wrapped as a JavaBean.

<msicd::JAVA>

    <NAMESPACE>some-namespace-string</NAMESPACE>

    <PACKAGE NAME="com.ms.JPMBrowser" VERSION="1,0,0,0">
        <CLASS NAME="Browserbean" CLASSID="{383807B5-2C60-11D0-A31D-00AA00B92C04}">
            <ISBEAN />
            <ICON FILENAME="Browser.ico" />
            <TYPELIB CLASSID="{...}" />
        </CLASS>
    </PACKAGE>
    <IMPLEMENTATION />
</msicd::JAVA>

Creating a distribution unit

The distribution unit contains the OSD file and the files that belong to an application. These files are compressed using the cabinet (CAB) compression format. The CAB file then must be digitally signed by a certificate authority. For more information on CABs, see the CAB SDK, which is provided as a self-extracting executable file (Cab-SDK.exe) in the \bin directory of the Internet Client SDK.

There are three ways to package a distribution unit:

  • Only the OSD file in the CAB file.
  • The OSD file and application files in the CAB file.
  • The OSD file and another CAB file in the CAB file.

Having only the OSD file in the CAB file is the minimal distribution unit possible. The OSD file would indicate the URL of the resource containing the software update in the CODEBASE tag of the OSD file.

The simplest case is to package the OSD file with the program files into the CAB file. In this case, the OSD file does not need a CODEBASE tag in it. When no CODEBASE is given, Internet Explorer automatically looks for the program file in the same CAB file where the OSD file was found.

When multiple program files are involved, and especially when the program files are separated into multiple subdirectories, it is easier to organize the distribution unit by creating a CAB file that contains the OSD file and another CAB file that contains the program files.

Related Topics

For more information on software update channels and OSD, see the following:

Open Software Description (OSD)
Contains more information about OSD and references for all the elements supported by OSD.
Internet Component Download
Contains information on the mechanism that handles the download and installation of software through the Internet.


What Is an Active Channel?

An Active Channel is a Web site that has been enabled for Webcasting to information-receiving programs such as Microsoft® Internet Explorer 4.0. The mechanism that makes this possible in Internet Explorer 4.0 is the Channel Definition Format (CDF) file. The CDF file provides an index of resources available in the channel and a recommended schedule for when the channel should be updated on the user's computer.

A typical CDF file contains a top-level CHANNEL element to define the channel itself, along with ITEM elements to specify the actual contents of the channel. Subsequent occurrences of the CHANNEL element define subchannels and allow publishers to create a hierarchy for the channel. The TITLE and ABSTRACT elements can be used to describe the contents of each item or channel element. Publishers may also want to use the LOGO element to associate an image with each item in the channel, as well as with the channel itself.

Web Publisher's Perspective

Web publishers can give users a better browsing experience by offering their content in a channel. A channel can be created that Webcasts the following items to a browser:

  • Branded icons and logos representing the Active Channel in the desktop Channel Bar.
  • A sitemap describing the content available in the Active Channel.
  • Web pages containing text, images, and ActiveX™ Controls. These pages can have a special use associated with them, such as appearing in a screen saver or Active Desktop item.

A traditional Web site can be viewed as an Active Channel with a minimal amount of work by the Web publisher. These are the required tasks:

  • Create logo images to be displayed in the desktop Channel Bar and Channels Explorer Bar.
  • Create a CDF file listing the resources (logo images, descriptions, and HTML pages) of the channel.
  • Post the CDF file on an HTTP server and place a button linked to the CDF file on the existing Web site. Users who click this button will add the channel to their desktop Channel Bar and select a subscription option for the channel.


Developing an Active Channel

To create an Active Channel on an existing Web site, simply create a CDF file by following these steps:

  1. Design the channel.
  2. Create the logo images.
  3. Create the CDF file.
  4. Post the CDF file.
  5. Offer the new channel to users.

Design the Active Channel

When creating a CDF file, the first step is to determine the structure of the channel. The channel can be designed to represent the structure of an existing Web site, or it can be a subset of a Web site's content with a completely different hierarchy. The structure of the channel is created in the CDF file with the use of the CHANNEL and ITEM elements to represent the subchannel hierarchy and HTML items (content). To prevent users from being overwhelmed with information and images, as well as to provide a uniform "look and feel" among channels, keep the following guidelines in mind:

  • A channel should have no more than eight total subitems in the first level.
  • Web publishers should provide all the images to be used with their channel. Images are needed for the desktop Channel Bar, Channels Explorer Bar, and items in the channel.
  • Design the channel to be one of the recommended Active Channel Types.

Create the Logo Images

There are several places in the user interface where images associated with an Active Channel are displayed:

  • Desktop Channel Bar (32H x 80W)
  • Channel Pane Explorer Bar in the browser (32H x 194W)
  • Icons for items within categories (16H x 16W)

When creating a channel, Web publishers should provide appropriate images for each of these categories, although Microsoft will provide default images wherever necessary. The top-level CHANNEL element should include three LOGO child elements, one for each type of STYLE attribute, as follows:

<CHANNEL HREF="http://www.mysample.com/mainchannel.htm">
    <LOGO HREF="http://www.mysample.com/widelogo.gif" STYLE="IMAGE-WIDE"/>
        <!-- For Channels Explorer Bar -->
    <LOGO HREF="http://www.mysample.com/logo.gif" STYLE="IMAGE"/>
        <!-- For desktop Channel Bar -->
    <LOGO HREF="http://www.mysample.com/icon.gif" STYLE="ICON"/>
        <!-- For category folder -->
    <subitems omitted>
    .
    .
    .
</CHANNEL>

The STYLE="ICON" attribute is included in case the user places an Active Channel in a category folder. When this occurs, the channel will appear in the list of available channels in the Channels Explorer Bar when that channel folder group is selected. All other CHANNEL and ITEM elements in the CDF file should include only one LOGO child element with the STYLE="ICON" attribute. When creating your image files, be sure to make the background color transparent, if applicable. It's also recommended that your image be fairly simple so that it's easy to recognize at the 16H x 16W size. Additional information about image specifications is available in the Guidelines for Active Channel Images.

Create the CDF file

When the channel structure has been designed and the logos have been created, the CDF file can be written. The CDF file must include at least one CHANNEL element and should include the SCHEDULE and LOGO elements. The ITEM element must be used to include any Web pages as part of the channel's content. As the content contained in the channel is added, removed, or modified over time, Web publishers should update the CDF file to reflect the changes. For information about using a channel creation tool, see Microsoft CDF Generator.

The CHANNEL element is used to define the top-level channel itself, along with any subitems nested within that channel. Thus, the occurrence of the <CHANNEL> and </CHANNEL> tags defines the hierarchy of the channel. The LOGO element is used to specify an image file that is displayed in the desktop Channel Bar.

Post the CDF file

After creating the CDF file, it should be posted on the Web site it describes. Typically, the file would be placed in a public folder on the Web site's HTTP server.

Offer the New Channel to Users

Finally, Web publishers need to provide a method for users to install their Active Channel (or Active Desktop item). Users will be able to add channels from three primary sources:

  • A button image placed on a Web page.
  • The Channel Guide.
  • The pre-installed set of channels in the Channel Bar.

Although a simple HREF in an anchor (<A>) element pointing to a CDF file will initiate the channel subscription process, your page should include the Add Active Channel or Add to Active Desktop logo button for consistency and maximum usability. These buttons should have scripts associated with them that, when clicked, perform the proper behavior in any browser. When using the scripts in the following example, clicking the button with Microsoft® Internet Explorer 4.0 displays the Add Channel dialog box by linking to the CDF file. If users without Internet Explorer 4.0 click the button, they will be directed to download the new version.

Note To use the Microsoft Add Active Channel button logo image or the Add to Active Desktop button logo image, you must sign up and accept the terms of the Active Channel Logo Agreement at http://www.microsoft.com/sbnmember/ielogo/default.asp.

Follow these steps to add the logos and scripts to your HTML page.

Step 1. Place these logo image buttons on your Web server.

Add Active Channel

Use this image to allow users to install your Active Channel.

Add to Active Desktop

Use this image to allow users to add your item to their Active Desktop.

Web publishers are encouraged to use these official Internet Explorer button logo images to provide users with a more visible, consistent, and easily recognizable method for adding Active Channels and Active Desktop items.

Step 2. Using Notepad or your favorite HTML editor, open the HTML page that will contain these logos.

Step 3. Copy and paste the following script between the <HEAD> and </HEAD> tags in the HTML page you are editing:

<!-- Begin Put this script into the head of the page -->
<script language="JavaScript">
    function isMsie4orGreater() {
    var ua = window.navigator.userAgent;   var msie = ua.indexOf ( "MSIE " );
    if  (msie > 0)
        {return (parseInt ( ua.substring ( msie+5, ua.indexOf ( ".", msie ) ) ) >=4) &&
        (ua.indexOf("MSIE 4.0b") <0) ;}
    else {return false;}}
</script>
<!-- End   Put this script into the head of the page -->

Step 4. For each individual Add logo included on the HTML page, copy and paste the following lines of HTML:

<a name="uniqueName"
href="http://www.microsoft.com/ie/ie40/download/?/ie/ie40/download/redirect.htm">
<img src="urlOfLogoImage" border=0 width=136 height=20></a>
<script language="JavaScript">
    if ( isMsie4orGreater()) { uniqueName.href ="urlToCDF"; }
</script>

Edit the above script by making the following changes:

  • Replace each occurrence of uniqueName with a unique name for each logo placed on the page. The unique name for each logo must not contain any spaces.
  • Include the actual URL of the button image on your server in place of urlOfLogoImage. This should be one of the GIF files shown in Step 1.
  • Include the actual URL of the CDF file on your server in place of urlToCDF. This can be any URL that returns a CDF file, such as ASP or CGI pages.

Tip Web publishers might also want to use Dynamic HTML to conditionally display or hide content based on whether the user has a subscription to their Active Channel.

The channel guide

Web publishers can include their Active Channels in the Internet Explorer 4.0 channel guide. This acts as a primary resource for users to find channels that match their interests. The channel guide provides users with several channel listings that are separated into the following categories:

  • Business
  • Entertainment
  • Lifestyle and Travel
  • News and Technology
  • Sports

Microsoft Active Channel partners will be listed in the guide with a 32H x 80W GIF logo image. All other channels will be listed in the guide with the channel's title only. When a user places the mouse pointer over the publisher's logo or title, a ToolTip appears with the channel's description. When the user clicks the channel title or logo in the channel guide, a "Preview Page" is displayed. This page is a 365H x 460W-pixel HTML page located on the publisher's server that acts as an advertisement for all of the publisher's Webcasting offerings. The use of Dynamic HTML is strongly encouraged on this page to make the experience more interactive and engaging for the user. Similar to the "Webcasting Offerings Page" described above, the Preview Page should contain the official button and script for each Active Channel or Active Desktop item offered by the Web publisher. The logo image (where applicable), channel description, and Preview Page URL must be provided to Microsoft by the publisher to be placed in the Internet Explorer channel guide. For more information about placing your channel in the Internet Explorer 4.0 channel guide, see the Microsoft SiteBuilder Network Web site at http://www.microsoft.com/sitebuilder, or look in the channel guide itself.

CDF Sample and Explanation

The following sample CDF file shows the syntax used in the CDF, with detailed explanations in the next section. This sample is included in the \samples\channel directory, which is installed in the c:\inetsdk directory by default. To subscribe to the sample channel, follow the instructions provided in the Readme.txt file located in that directory. To subscribe to a channel on a Web page, simply click one of the channel logos in the desktop Channel Bar, or click on the Channel Guide to find a list of additional channels. To subscribe to the Internet Client SDK channel, use Internet Explorer 4.0 to navigate to http://www.microsoft.com/msdn/sdk/inetsdk/help/default.htm, and click the Add Active Channel button. Following is the sample CDF file included in the SDK.

<?XML version="1.0"?>
<CHANNEL HREF="http://www.mysite.com/Channel/homepage.htm"
     BASE="http://www.mysite.com/Channel/">
    <TITLE>Sample "Color" Channel</TITLE>
    <ABSTRACT>The sample color channel contains a red, green, and blue page for viewing.</ABSTRACT>
    <LOGO HREF="logo_big.gif" STYLE="IMAGE-WIDE"/>
    <LOGO HREF="logo_med.gif" STYLE="IMAGE"/>
    <SCHEDULE STARTDATE="1997-09-23">
        <INTERVALTIME DAY="1" />
        <EARLIESTTIME HOUR="2" />
        <LATESTTIME HOUR="6" />
    </SCHEDULE>
       <ITEM HREF="page1.htm">
        <LOGO HREF="red.gif" STYLE="ICON"/>
        <TITLE>The Red Page</TITLE>
        <ABSTRACT>This is the abstract description for the red page.</ABSTRACT>
    </ITEM>
    <ITEM HREF="page2.htm">
        <LOGO HREF="green.gif" STYLE="ICON"/>
         <TITLE>The Green Page</TITLE>
        <ABSTRACT>This is the abstract description for the green page.</ABSTRACT>
       </ITEM>
    <ITEM HREF="page3.htm">
        <LOGO HREF="blue.gif" STYLE="ICON"/>
        <TITLE>The Blue Page</TITLE>
        <ABSTRACT>This is the abstract description for the blue page.</ABSTRACT>
    </ITEM>
    <ITEM HREF="scrnsave.htm">
        <USAGE VALUE="ScreenSaver"></USAGE>
    </ITEM>
</CHANNEL>

The following section lists portions of the CDF example file and then describes the function of the elements and their associated attributes. Where possible, the effect on the user is also indicated.

<CHANNEL HREF="http://www.mysite.com/Channel/homepage.htm"
     BASE="http://www.mysite.com/Channel/">

In this case, the CHANNEL element defines the top-level channel of the hierarchy. Every element that follows until the matching </CHANNEL> element is subordinate to this channel. The HREF attribute defines the Web page to be displayed in the browser when the channel is selected either in the desktop Channel Bar or in the Channels Explorer Bar. The BASE attribute defines the URL of the location where the channel's resources exist. This allows Web publishers to specify other URLs in the CDF file using relative paths.

<TITLE>Sample "Color" Channel</TITLE>
<ABSTRACT>The sample color channel contains a red, green, and blue page for viewing.</ABSTRACT>

The TITLE element defines the text that is associated with this channel in the browser's channel pane. The ABSTRACT element defines a text string that is displayed in a ToolTip when the cursor is placed over the channel.

<LOGO HREF="logo_big.gif" STYLE="IMAGE-WIDE"/>
<LOGO HREF="logo_med.gif" STYLE="IMAGE"/>

The LOGO element marked with the "IMAGE-WIDE" style attribute is displayed in the Channels Explorer Bar, while the "IMAGE" style is shown in the desktop Channel Bar. Clicking this image results in opening the URL specified in the top-level CHANNEL element, or the channel hierarchy is shown, if applicable.

<SCHEDULE STARTDATE="1997-09-23" STOPDATE="1997-11-23">
    <INTERVALTIME DAY="1" />
    <EARLIESTTIME HOUR="2" />
    <LATESTTIME HOUR="6" />
</SCHEDULE>

The SCHEDULE element indicates how often, and during what time range, the channel should be updated. This is designed to help Web sites manage their server traffic. The preceding example is set to update the channel every day between 2 A.M. and 6 A.M. This schedule information is set to expire on November 23, 1997.

<ITEM HREF="page1.htm">
    <LOGO HREF="red.gif" STYLE="ICON"/>
    <TITLE>The Red Page</TITLE>
    <ABSTRACT>This is the abstract description for the red page.</ABSTRACT>
</ITEM>

The ITEM element defines a Web page as a subitem in the sample CDF channel. This item will be displayed in the channel's hierarchy exposed in the Channels Explorer Bar, along with the "ICON" image specified in the LOGO element.

<ITEM HREF="scrnsave.htm">
    <USAGE VALUE="ScreenSaver"></USAGE>
</ITEM>

This occurrence of the ITEM element (along with USAGE) defines the URL of an HTML page to be displayed in the Channel Screen Saver page. The ITEM and USAGE elements can also be used to define an HTML page as an Active Desktop item. These items can contain any valid HTML elements, such as images, ActiveX™ Controls, Java applets, and so on, and can be placed directly on the desktop with Internet Explorer 4.0. For more information on Active Desktop items, review the documentation for Creating Items for the Active Desktop.

</Channel>

This end tag indicates that the definition of the sample CDF channel is complete.


Using Dynamic HTML with Active Channels

A variety of Dynamic HTML features can be used to modify the appearance of a Web page, including changing the text or images that are displayed. As an example, the following steps show how a publisher might use the window.external.isSubscribed method to hide an Add Active Channel logo button if its associated channel is already subscribed.

Assuming the Add Active Channel button was placed on a Web page as previously described, the page would include the following Add Active Channel button:

<a name="channelA"
href="http://www.microsoft.com/ie/ie40/download/?/ie/ie40/download/redirect.htm">
<img src="IEAddChannel.gif" border=0 width=136 height=20></a>
<script language="JavaScript">
    if ( isMsie4orGreater()) { channelA.href ="urlToCDF"; }
</script>

Step 1. Add the ID attribute to the anchor element. The value must be unique.

<a name="channelA" id="idA"
href="http://www.microsoft.com/ie/ie40/download/?/ie/ie40/download/redirect.htm">
<img src="IEAddChannel.gif" border=0 width=136 height=20></a>
<script language="JavaScript">
    if ( isMsie4orGreater()) { channelA.href ="urlToCDF"; }
</script>

Step 2. Include the following script between the page's <HEAD> and </HEAD> tags. Note that the isMsie4orGreater function should already exist in the HEAD section of this page.

<SCRIPT LANGUAGE="JavaScript">
function HideIfSubscribed(elementID, urlToCDF){
if (window.external.isSubscribed(urlToCDF)) {ss.addRule("#"+ elementID,"visibility: hidden");}}

var ss = null;
ss = document.createStyleSheet()
if(isMsie4orGreater()){ //Test if the browser is IE
// For each element you want to conditionally hide, include the following line
// (uniqueID is the unique value for the ID attribute of the element and
// urlToCDF is the URL to the channel's CDF).
HideIfSubscribed("uniqueID","urlToCDF");
}
</SCRIPT>

When using these scripts, remember that the URLs of the channels must include the same protocol and secondary domain name as the page that contains the scripts. Also, any element in Dynamic HTML that has the visibility property can be hidden using the same code.

The following HTML page shows a full example of the scripting shown above.

<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
    function isMsie4orGreater() {
        var ua = window.navigator.userAgent;   var msie = ua.indexOf ( "MSIE " );
        if  (msie > 0)
            {return (parseInt ( ua.substring ( msie+5, ua.indexOf ( ".", msie ) ) ) >=4)
            && (ua.indexOf("MSIE 4.0b") <0) ;}
        else    {return false;}}

    function HideIfSubscribed(elementID, urlToCDF){
        if (window.external.isSubscribed(urlToCDF))
        {ss.addRule("#"+ elementID,"visibility: hidden");}}

    var ss = null;
    if(isMsie4orGreater()){ //Test if the browser is IE
        ss = document.createStyleSheet()
        HideIfSubscribed("idA","http://www.mycorp.com/channelA.cdf");
    }
</SCRIPT>
</HEAD>

<BODY>
<a name="channelA" id="idA"
href="http://www.microsoft.com/ie/ie40/download/?/ie/ie40/download/redirect.htm">
<img src="IEAddChannel.gif" border=0 width=136 height=20></a>
<script language="JavaScript">
    if ( isMsie4orGreater()) { channelA.href ="urlToCDF"; }
</script>

</BODY>
</HTML>

If the Web page contains more than one Add Active Channel or Add to Active Desktop logo button, the name and ID attributes must be unique.


Active Channel Features

The following sections explain the details of various Active Channel features, as well as what Web publishers need to know to take advantage of them.

  • Scheduled updates and server loads
  • Personalized channels and passwords
  • Password-protected Active Channels
  • Page-hit logging
  • Active Channel screen savers
  • Category folders

Scheduled Updates and Server Loads

Web publishers can create a default schedule in the CDF file that Microsoft® Internet Explorer uses to determine when the channel information on the user's computer should be updated. Specifying a schedule with a range of valid update times can help to effectively manage server loads when Webcasting to Internet Explorer. The actual time Internet Explorer updates the channel is randomly selected from the valid time range for each update. The CDF file specifies the valid time range for updates by including the EARLIESTTIME and LATESTTIME elements as child elements of the SCHEDULE element. The INTERVALTIME element specifies how often, on average, the updates will occur. The following examples illustrate different update schedules for an Active Channel.

Note The shaded areas in the diagrams below represent the range of time during which the actual channel update will occur.

Daily Schedule

The schedule shown below would cause the channel to be updated every day at a random time between 2 A.M. and 6 A.M. Since the publisher didn't specify a start or end date, the schedule takes effect immediately and doesn't expire.

<SCHEDULE>
    <IntervalTime Day="1" />
    <EarliestTime Hour="2" />
    <LatestTime Hour="6" />
</SCHEDULE>

Hourly Schedule

For channels that Webcast extremely time-critical information, a channel may need to be updated many times during the day. The example below shows a channel that is updated four times per day. The actual updates occur sometime after the second hour of each six-hour interval. This schedule is set to expire on December 31, 1999, at which point no further updated information will be downloaded for this channel.

<SCHEDULE STOPDATE="1999-12-31">
    <IntervalTime Hour="6" />
    <EarliestTime Hour="2" />
    <LatestTime Hour="6" />
</SCHEDULE>

Weekly Schedule

A schedule that updates a channel once a week is shown below. Because this weekly schedule started on a Monday, this channel will be updated every Monday sometime between 2 A.M. and 6 A.M. until it reaches the expiration date. This schedule takes effect on Monday, September 29, 1997, and expires on December 31, 1999.

<SCHEDULE StartDate="1997-09-29" STOPDATE="1999-12-31">
    <IntervalTime Day="7" />
    <EarliestTime Hour="2" />
    <LatestTime Hour="6" />
</SCHEDULE>

By default, users accessing the Internet with a dial-up connection need to manually update their channels by either right-clicking on a logo image representing a channel subscription and selecting the Update Now option from the context menu, or by selecting the Update All option from the Favorites menu. Modem users can also configure their subscriptions to automatically dial up their Internet connection on a regular basis without any user intervention. To set up automatic updates over a modem, the user must select the "Dial as needed..." check box in the Schedule tab of the Channel Properties. Once automatic updates are enabled by modem users, the publisher's recommended schedule or a standard schedule (daily, weekly, monthly) can be used. If the "Dial as needed..." feature is not enabled, the channel updating schedule is effectively manual for modem users. Users connected to a network should use the publisher's recommended schedule specified in the CDF file for updating channels.

Personalized Channels

The HTTP cookie standard provides a powerful mechanism for personalizing Web content. The CDF file integrates this standard with Internet Explorer. A Web publisher who wants to create a personalized channel can use regular HTTP cookies to deliver personalized information to users by dynamically generating a custom CDF file based on user preferences. The CDF file thus leverages the existing cookie standard for personalized HTML on the Web and takes it one step further by allowing personalized channels for individual users. Web publishers can create personalized channels for users or groups of users by performing the following tasks:

  1. The first time users visit a channel, present them with a form asking for their preferences, as they relate to the channel.
  2. Store those user preferences on the Web server or within a cookie on the user's computer.
  3. Whenever Internet Explorer 4.0 subsequently requests an updated CDF for that user, the server could either download an existing CDF file or dynamically generate one that matches the user's profile information stored locally in the cookie.

Web publishers using active server pages with Microsoft Internet Information Server (IIS) to dynamically generate personalized CDF files (named with an .asp extension) must insert the following line at the top of the CDF file:

<% Response.ContentType = "application/x-cdf" %>

Note As an alternative for IIS 4.0 site authors, the CDF file can be created with a .cdx extension instead of .asp, and the MIME content type line above can be omitted.

This ensures that the server will return the correct MIME/content type to the browser. Without this line, the browser will not perform the expected actions for CDF files. For example, the CDF file might display as text in the browser window rather than launch the Add Channel dialog box.

Password-Protected Active Channels

Web publishers implementing HTTP authentication in their channels need to make sure Internet Explorer has the user name and password so it can update the channel content without user intervention. To accomplish this, publishers can force Internet Explorer to ask users for this information during the channel subscription setup process by using the LOGIN element in the CDF file. When the channel subscription wizard encounters this element in a CDF file, it will prompt users to enter their user name and password. When the channel setup is complete, the user name and password are stored with the channel's subscription properties. Therefore, subsequent CDF files sent to that user for updating the channel don't require the LOGIN element. Internet Explorer will automatically authenticate HTML pages when using Basic, NTLM, RPA, and HTML forms.

If the authentication process is based on an HTML form, Internet Explorer needs to be able to fill out the form correctly. For the login process to be successful, follow the guidelines just mentioned for the HTTP authentication, and make sure the HTML form complies with these requirements:

  • The form must use the "post" method.
    <FORM METHOD="POST" ACTION="http://www.foo.com/login">
  • The name of the input text box for the user's name must be "username" or "user".
    <INPUT TYPE=TEXT NAME="username" SIZE=20>

    or

    <INPUT TYPE=TEXT NAME="user" SIZE=20>
  • The name of the password field must be "password".
    <INPUT TYPE=PASSWORD NAME="password" SIZE=20>

Note All other elements on the form will be posted with their default values.

Page-Hit Logging

Important Note The page-hit logging feature enables Active Channels to collect the same page-hit information from offline users as they can already collect from online users. This feature can easily be disabled by a home user or a corporate administrator, if desired.

Page-hit logging collects information for Web publishers about activity on their channel pages by logging page hits in the browser, screen saver, and Active Desktop in both offline and online modes. The page-hit engine allows the collection of data for the time and date that the channel pages were loaded into the browser.

Client-side logging

Using the CDF file, publishers can tightly control exactly what page hits are logged. They can also define the maximum time to archive the data. To enable page-hit logging of a channel, the CDF file should contain the LOG element, indicating what items are to be logged, and the LOGTARGET element, indicating where the log file should be sent. Web publishers should use discretion when using the LOG element in the CDF file and select specific items for logging. Be aware that a large number of items marked for logging could potentially create large log files, which could raise bandwidth issues for the user when the log file is uploaded to the LOGTARGET URL. The uploading of the log file back to the server occurs when the CDF file is updated. For more information about the LOG and LOGTARGET elements, including examples, see the CDF Reference for Internet Explorer.

Note Items marked for logging must have an HREF attribute that falls under the URL of the CDF file or the path specified in the LOGTARGET element.

Web publishers receive the page-hit logging files in the directory (URL) specified in the LOGTARGET element, in "Extended Log File Format," as defined by the World Wide Web Consortium (W3C). Every page hit that is logged has two types of records associated with it. The first record is a "header" that contains the URL of the channel item being logged. The records subsequent to the header are details of the page hits. Here is a sample record:

#Fields: s-URI
http://www.foosports.com/news/default.htm
#Fields: c-context c-cache c-date c-time c-duration
N 1 06-02-1997 19:12:37 00:00:04
T 1 06-03-1997 11:38:04 00:00:23

These records indicate that the URL "http://www.foosports.com/news/default.htm" was viewed in normal mode on June 2, 1997, from the cache at 7:12 P.M. for four seconds, and again in full-screen view on June 3 at 11:38 A.M. for 23 seconds. The context value can be "N", "T", "D", or "S" to indicate whether the URL was viewed in a normal browser window, full screen view (Theater View), as an Active Desktop item, or in the Internet Explorer screen saver, respectively. The value for the cache field can be "1" to indicate the URL was retrieved from the local cache or "0" to indicate the URL was retrieved from the site itself. The Web publisher can filter out online or offline records by using the SCOPE= attribute of the LOGTARGET element. The date field shows the date on which the URL was viewed. The time value indicates what time (on the local computer) the URL was viewed, and the duration indicates how long the user viewed the page. The time and duration fields are in HH:MM:SS format, while the date is in MM-DD-YYYY format.

Server-side log file processing

Web publishers that receive page-hit log files can extract and process the data listed above in any way they choose. However, Microsoft provides the following two methods for parsing the information in the log file:

  • A Perl script
  • The ISAPI DLL (IIS users only)

The following Perl script can be used to parse the log file.

require("cgi-lib.pl");
$logfile='log/cdfpost.dat';
$method=$ENV{REQUEST_METHOD};
$clen=$ENV{CONTENT_LENGTH};
print "Content-type: text/html\n\n";
print "<HTML>\n";
&open_logfile;
    &print_env;
&ProcessRawdata;
print "Just to show we got here too <BR>\n";
print "</HTML>\n";
sub ProcessRawdata
{
    &add_logdata;
    close(OUT);
}

sub print_env
{
    print OUT "<!--Request method : ", $method, "\n";
    print OUT "Server : ", $ENV{SERVER_NAME}, "\n";
    print OUT "Script : ", $ENV{SCRIPT_NAME}, "\n";
    print OUT "Client : ", $ENV{REMOTE_ADDR}, "\n";
    print OUT "Content-length : ", $clen, "-->\n";
}

sub open_logfile
{
    if (-e $logfile) {
        open (OUT, ">>$logfile");
    } else {
        open (OUT, ">$logfile");
    }
}

sub add_logdata
{
    open(IN, "-");
    binmode IN;

    while ($clen) {
        print OUT getc(IN);
        $clen=$clen-1;
    };
    print OUT "\n";
}

When running Microsoft Internet Information Server (IIS), you can use the ISAPI DLL to parse the log file. For more information about how to accomplish this, see the Readme file located in the inetsdk\samples\iislog directory. Note that this sample also demonstrates how to decompress encoded posted strings, and the associated CDF file must contain the HTTP-EQUIV element as follows:

<LOGTARGET HREF="http://www.mysite.com/logging/" METHOD="POST">
    <HTTP-EQUIV NAME="encoding-type" VALUE="gzip">
</LOGTARGET>

Additional information is available on how to programmatically access the log file in the page-hit logging API reference.

Active Channel Screen Savers

As part of the CDF file, the publisher may designate a specific URL to be downloaded as content for the Channel Screen Saver. This screen saver supports standard HTML pages, including scripting, images, Java applets, and ActiveX™ Controls. Screen saver content pages can include scripting and Dynamic HTML support to provide a page that dynamically changes the content, style, and position of the HTML elements on the screen. These pages are displayed on the full screen during computer idle times. The Channel Screen Saver cycles through enabled channel screen savers, allocating the same amount of display time to each one (by default, 30 seconds per channel). A channel's screen saver page is automatically included in the rotation when the channel is subscribed to, or subsequently through the Screen Saver Properties dialog box. If a user subscribes to a channel containing a screen saver page and the Channel Screen Saver isn't currently selected, the following dialog box will be displayed.

Screen Saver Confirmation

Publishers can enable a specific URL as a screen saver page by including the USAGE element in a channel's CDF file. In the following example, the HTML page at URL "http://www.foosports.com/screensaver.htm" is defined as the screen saver for the channel in which it occurs.

<ITEM HREF="http://www.foosports.com/screensaver.htm">
    <USAGE VALUE="ScreenSaver"></USAGE>
</ITEM>

Note The screen saver item's USAGE element must be a child of the top-level CHANNEL element. If the USAGE element occurs within a nested CHANNEL element representing a subchannel, the screen saver will be ignored.

Unlike many common screen savers, the user can move the mouse and click objects without immediately dismissing the Internet Explorer screen saver. Clicking a link opens a new browser window and dismisses the screen saver. Pressing a key or clicking on a location that is not an image, link, or object also closes the screen saver. Moving the mouse causes the screen saver toolbar to appear in the upper-right corner of the screen. From this toolbar, the user can close the screen saver or access the screen saver properties.

Active Channel screen saver

Category Folders

The desktop Channel Bar contains some category folders, such as News and Technology, Sports, Business, Entertainment, and Lifestyle and Travel, for grouping channels that have similar types of content. When the user clicks one of these categories, the browser opens a page of all the channels in that category and their associated branded logo images. Selecting one of these channels causes the browser to navigate to the associated channel's main page. The Add Channel dialog box is automatically displayed if the user does not already subscribe to the channel.


Guidelines for Active Channel Logo Images

The guidelines listed in this section are provided to help Web publishers create useful and compelling logos that represent their channel content. When creating images, be aware that the logos are displayed with a fixed 256-color palette, regardless of the monitor's color depth. Therefore, using the Microsoft® Windows® halftone palette is recommended, if possible. The height (H) and width (W) of the images described in these guidelines are assumed to be in pixels.

Active Channel Logos

Microsoft Internet Explorer 4.0 uses different logo sizes for channels displayed on the desktop and channels displayed inside the browser window, as previously discussed. The desktop Channel Bar logo is 32H x 80W, and the Channels Explorer Bar logo is 32H x 194W. When a user resizes the width of the Channels Explorer Bar beyond 194 pixels, the remaining area on the right side of the 32H x 194W logo is filled in with the rightmost top pixel. If only the 32H x 80W image is provided, it is displayed in both places—on the desktop and inside the browser window. When displayed in the browser window Channels Explorer Bar, the remaining area on the right side of the logo is filled in with the same color as the leftmost top pixel. The 32H x 80W logo for the desktop must have a black background, while the logo for the browser should use a colored background. To specify the logos in the CDF file, the following format is used.

For the 32H x 80W logo:

<LOGO HREF="example.gif" STYLE="Image">

For the 32H x 194W logo:

<LOGO HREF="example-wide.gif" STYLE="Image-Wide">

For the 16H x 16W icon images:

<LOGO HREF="example-icon.gif" STYLE="Icon">

Logo Image Descriptions

Desktop Channel Bar Logos

The desktop Channel Bar displays the smaller logo (32H x 80W) for each available channel. To match the visual elements used on the desktop, a black background is required for each logo. All logos in the desktop Channel Bar are shown at the same time. The following illustration shows the hot tracking behavior for when a user moves the mouse over a logo. As the cursor is placed on an image in the desktop Channel Bar, the border around the logo surfaces into a 3-D button, much like other toolbars within Internet Explorer 4.0. This behavior helps make the desktop Channel Bar look like a well-integrated part of the product.

Desktop Channel Bar

Channels Explorer Bar Logos

Inside the Browser window, Internet Explorer 4.0 uses the full-width logo (32H x 194W) in the Channels Explorer Bar. By default, only the channel name is displayed in white text on a black background for each channel. However, when the user moves the mouse over an item, it will hot-track to show the logo for that item. Using a color background for the large logo is recommended. If a user clicks a channel to activate it, that logo remains visible. This allows users to easily determine the current channel because they aren't distracted with logos from other channels.

Channels Explorer Bar

Icons with Visual Clues

When designing your icons, use different images, colors, or shapes to indicate whether an item is a container for other subitems or is actual content. This will help the user discover your channel's content.

Update Gleams

The channel bar provides the user with a 14H x 14W "gleam" to indicate when content has been updated. This gleam is a triangular overlay applied to the upper-left corner of a channel logo. When authoring images for any size, it's important not to place critical text or visual elements in this area, because it will be covered when the gleam is visible. Gleams are also overlaid on any 16H x 16W icon in the channel's hierarchy when that page has been updated. The gleam placed on icons is 7H x 7W.

Guideline Summary for Active Channel Images

Use the following guidelines when authoring Active Channel images:

  • Logos for the desktop must use a predominately black background. The appearance of the channel bar needs to blend into the Active Desktop, which uses a black background. This reduces visual clutter for the user and helps the logos visually tie in to the desktop Channel Bar user interface.
  • When creating the large logo, do not bleed an image on the right. If the user resizes the Channels Explorer Bar, the image will be cropped and the space to the right of the logo will be filled with the upper-right corner pixel color. Design your large logo with this in mind.
  • Provide consistent elements in both large logo sizes. When creating these logos, try to include a visual tie-in so users can recognize the channel in the transition from desktop to browser. When users click your desktop logo, they should be able to easily recognize its larger counterpart inside the browser.
  • Provide consistent elements in icons for pages and folders. Icons for pages and folders should tie in visually with their logo. Try to avoid creating too many icons, because it may be difficult for users to recognize all of them.
  • Be aware of the location of the update gleam. Avoid putting critical text or visual elements in the upper-left corner, because this area will be covered by the gleam for channel updates.


Netcaster CDF Compatibility Notes

Due to the similarities between HTML and the Channel Definition Format, other browsers might be able to perform site crawling on a CDF file. This section describes the CDF file compatibility issues related to the release of Netscape Netcaster. For more information about CDF files and the implementation of this standard, see Microsoft's Webcasting White Paper.

Site Crawling a CDF File

Site crawling is the process of a browser proceeding through the following steps:

  1. Retrieve an HTML page.
  2. Store that page locally on a user's computer.
  3. Find the links (anchors) in the HTML page.
  4. Repeat this process from step 1 for each link (anchor) to an HTML page.
  5. Stop the above process when the browser has run out of links to follow or when the process has repeated enough times based on some criteria.
  6. Retrieve the actual content for each link to a non-HTML document, such as an image file or a text file.

Netcaster can use CDF files only toward site crawling and not for full CDF processing. For this to happen, Netcaster must use a CDF file as though it is an HTML page. The key to a browser site crawling CDF files lies in the anchor (A) element, which defines links in HTML.

<A HREF="http://www.microsoft.com/">Visit Microsoft!</A>

This element identifies links for browsers to follow when site crawling. The anchor element can be found inside ITEM and CHANNEL elements of a CDF file. The HREF attributes of these anchor (A) elements identify which HTML pages are displayed when items and channels are selected.

<CHANNEL>
    <A HREF="http://www.microsoft.com/cover.htm"></A>
    <ITEM>
        <A HREF="http://www.microsoft.com/page1.htm"></A>
        <TITLE>Page 1</TITLE>
    </ITEM>
</CHANNEL>

When a browser uses the above CDF section as an HTML page for site crawling, it identifies the links "http://www.microsoft.com/cover.htm" and "http://www.microsoft.com/page1.htm". How the remaining content of the CDF file is used by the browser is less important. Some of it will be rendered, while most of it is ignored. In the majority of circumstances, a CDF file will never be displayed as HTML; it will simply be used for site crawling.

It is important to note that because Netcaster does not take advantage of the BASE attribute in a CDF file, relative URLs will be resolved by Netcaster against the base URL of the CDF file itself rather than the BASE attribute. For this reason, it is suggested that when authoring a CDF file for both Netcaster and Internet Explorer, either omit BASE attributes or make sure their value is the base URL of the CDF file itself. For example, if the CDF http://msn.com/channels/channel2.cdf has any BASE attributes, they should have the value "http://msn.com/channels/".

MIME Types and Extensions

For Netcaster to use a CDF file toward site crawling, it must process the file as an HTML file. To process the CDF file as HTML, one of the following three criteria must be met:

  • A copy of the original CDF file must have the extension "htm" or "html".
  • The HTTP server providing the CDF files must return the MIME (content) type "text/html" to browsers without full CDF support, and "application/x-cdf" to clients with full CDF support.
  • The browser site crawling the CDF files must have the extension or MIME type of CDF files, "cdf" and "application/x-cdf", configured to be opened as HTML by the browser itself.

After one of these criteria has been met, a Netcaster user can subscribe to a channel defined by a CDF file. The user simply proceeds in the usual manner when subscribing to any Web page, except entering the URL of the CDF file.

Netcaster CDF Site Subscriptions

In Netcaster, when a user subscribes to a channel by specifying the URL of a CDF file created through the mentioned methods, the initial page for the channel will not be a normal HTML page. Instead, it will be a CDF file rendered as an HTML page and will probably not appear as desired. To remedy this situation, a channel author can create an intermediate HTML page to represent the channel content along with a reference to the CDF file. This can be achieved using Netscape's LAYER tag. A hidden LAYER tag referencing the new CDF file is inserted into the desired initial HTML as follows:

<LAYER SRC="cdf_file.htm" VISIBILITY=HIDDEN></LAYER>

With this additional work, a user can use the URL of the intermediate HTML page rather than the URL to the CDF file when subscribing to a channel in Netcaster. To enable Netcaster to automatically subscribe to a CDF channel, script can be inserted into the intermediate HTML page as specified in Netscape documentation. This would allow a CDF channel to be subscribed to when a user clicks a button on the intermediate HTML page. The following examples show a CDF file and an intermediate HTML page that could be used with Netcaster.

A CDF file named "cdf_file.cdf":

<?XML VERSION="1.0"?>
<CHANNEL HREF="http://msn.com/default.htm">
    <ABSTRACT>This channel was created using the proposed CDF standard.</ABSTRACT>
    <LOGO HREF="http://msn.com/logo.gif" STYLE="IMAGE" >
    <SCHEDULE> <INTERVALTIME DAY="1" /> </SCHEDULE>
    <!-- the following items are needed for offline use -->
    <ITEM> <A HREF="http://msn.com/page1.html"></A> </ITEM>
    <ITEM> <A HREF="http://msn.com/page2.html"></A> </ITEM>
    <ITEM> <A HREF="http://msn.com/page3.html"></A> </ITEM>
</CHANNEL>

An intermediate Netcaster-compatible HTML page named "channel.htm" is provided below. This page references a copy, named "cdf_file.htm", of the above CDF file.

<HTML>
<BODY>

<LAYER SRC="cdf_file.htm" VISIBILITY=HIDDEN></LAYER>

<SCRIPT language="JavaScript1.2" >

var nc = components["netcaster"];
nc.activate();
var chan = nc.GetChannelObject();
chan.url = "http://msn.com/channel.htm";
chan.name = "My Channel";
chan.desc = "This Channel was created using JavaScript API extensions";
chan.cardURL = "http://msn.com/logo.gif";
function openDialog() { nc.AddChannelObject(chan); }

</SCRIPT>

</BODY>
</HTML>


Optimizing Active Channels over HTTP

Web publishers are strongly encouraged to follow the size guidelines discussed in the Design Guidelines for Active Channels section. In addition to considering bandwidth issues, Web publishers should support the following HTTP headers to ensure efficient use of their site by eliminating unnecessary data transfer:

  • Send a "Last-Modified" response header upon HEAD and GET requests. This allows the CDF client to monitor changes to the channel without downloading any resources.
  • Use the LASTMOD= attribute on ITEM elements. This optimization technique prevents Internet Explorer from hitting the server to retrieve the last modified date for each item referenced in the CDF file.
  • Use the "Expires" response header to indicate the lifetime of the resource.
  • Don't send the "Pragma: no-cache" response header unless absolutely necessary.
  • Support the "If-Modified-Since" request header.


Active Channel Types

This section describes basic types of channels that properly use the strengths of the Microsoft® Internet Explorer information delivery architecture within the constraints of bandwidth available in the home or the corporation. Web publishers can create channels to take advantage of the following three key Internet Explorer 4.0 capabilities.

Notification | Internet Explorer 4.0 uses a red "gleam" (resembling an asterisk) to visually flag the logos and icons of channels that have changed since their previous update. Users can choose to have an e-mail message sent to them when a channel is updated.
Sitemap | The Channels Explorer Bar can display a navigable outline of URLs as specified in a channel's CDF file. The exposed hierarchy of the channel helps users efficiently navigate through a channel to find the content they are most interested in.
Offline Content Caching | Internet Explorer 4.0 downloads the set of resources specified in the CDF file to be locally cached. This allows users to browse through the entire content of an active channel even when they are offline. It is important to note that offline content is available only to users accepting the default "download content" option when subscribing to the channel.

Channel Sitemaps and Notifications

Channel Sitemaps and Notifications

These capabilities can, of course, be combined to create different types of end-user channel experiences. It's important to realize, however, that this flexibility also permits authors to define impractical channels (for example, a channel that tries to replicate an extensive Web site to the user's local disk). As a general rule, an Active Channel should fit into one of these categories: news, immersion, or notification. A hybrid channel is also possible.

News Channels

A news channel is used to keep the user up to date on breaking news. This channel periodically Webcasts a hierarchically structured set of news items to the desktop, through the CDF file. The actual content referenced in the CDF file is downloaded into the user's cache and is available for offline use. A news channel uses all three Internet Explorer key capabilities: notification, sitemap, and offline content caching. When developing the content for a news channel, keep the following guidelines in mind:

  • Each news item is a discrete, simple, self-contained page.
    • Each page is dedicated to a single "story."
    • News items don't use frames.
    • The TITLE of the page is the news item's headline.
    • The ABSTRACT of the page summarizes the news item.
  • Each news item page is designed to be small.
    • The page should consist mainly of text and utilize Dynamic HTML layout features.
    • Pages should reuse and/or minimize the use of images, especially large ones.

The CDF file allows Web publishers to hierarchically organize items in a channel into subchannels. The TITLE of each subchannel serves to classify the items contained within the subchannel. By default, subchannels and items in the channel's CDF are displayed in an outline format in the Channels Explorer Bar. In addition to any navigation mechanism authored into the pages themselves, the user can expand and collapse subchannels in the outline and jump to individual news items.

Example: A news publisher, Action News, generates business stories as individual HTML pages.

Today's business stories are:

  • A daily summary of the stock market
    • URL: http://www.action.com/channel/bus/bus001.htm
    • Title: "The Market"
    • Abstract: "Summary of today's market news."
  • An article on the general economy
    • URL: http://www.action.com/channel/bus/bus002.htm
    • Title: "Business nirvana: low inflation, high growth"
    • Abstract: "Best environment for business in 25 years due to convergence of factors."
  • An article on rise in technology issues
    • URL: http://www.action.com/channel/bus/bus003.htm
    • Title: "Tech stocks soar on XYZ Corp. news"
    • Abstract: "XYZ Corp. showed unexpected growth this quarter, dragging up prices through the technology segment."

The pages are primarily textual, sharing a common masthead graphic, as shown here.

Action News Channel Pages

For the purpose of this example, the publisher's channel consists of only these stories organized into a single subchannel called The Market. The publisher could deliver these articles to the desktop by providing the following CDF file:

<?XML VERSION="1.0" ENCODING="UTF-8"?>

<CHANNEL
    HREF="home.htm"
    BASE="http://www.action.com/channel/" >

    <TITLE>Action News</TITLE>
    <ABSTRACT>Description of the Action News Channel</ABSTRACT>
    <LOGO HREF="ActionLogo16x16.gif" STYLE="ICON"/>
    <LOGO HREF="ActionLogo32x80.gif" STYLE="IMAGE"/>

    <SCHEDULE STARTDATE="1997-10-17" STOPDATE="1997-10-17">
        <INTERVALTIME DAY="1"/>
    </SCHEDULE>

    <CHANNEL
        HREF="bus001.htm">
        <TITLE>The Market</TITLE>
        <ABSTRACT>"Summary of today's market news"<ABSTRACT>
        <LOGO HREF="marketLogo.gif" STYLE="ICON"/>

        <ITEM HREF="bus002.htm" LASTMOD="1997-10-17T11:12">
            <TITLE>Business nirvana: low inflation, high growth</TITLE>
            <ABSTRACT>Best environment for business in 25 years due to
                convergence of factors.</ABSTRACT>
            <LOGO HREF="TopStoryLogo.gif" STYLE="ICON"/>
        </ITEM>

        <ITEM HREF="bus003.htm" LASTMOD="1997-10-17T11:12">
            <TITLE>Tech stocks soar on XYZ Corp. news </TITLE>
            <ABSTRACT>XYZ Corp. showed unexpected growth this quarter,
                dragging up prices through the technology segment.</ABSTRACT>
            <LOGO HREF="TopStoryLogo.gif" STYLE="ICON"/>
        </ITEM>
    </CHANNEL>
</CHANNEL>

Once subscribed to by the user, Action News would appear within the browser's Channels Explorer Bar as:

Action News Channel

Since none of the stories in the CDF include the PRECACHE="NO" attribute on the ITEM elements, all of the pages will be precached during updating. Therefore, each news page will be available for offline viewing if the user subscribes to the channel and chooses to receive channel content.

Immersion Channels

An immersion channel presents the user with an authored "environment" that provides all navigation (for example, the Channels Explorer Bar is assumed to be hidden). All content is precached so the channel can be used offline. It is important to note that this channel's items and subchannels do not appear in the Channels Explorer Bar. In this case, the CDF file is used exclusively to specify content that needs to be downloaded and to notify the user when the channel has been updated. Downloading channel content helps increase online performance and allows offline use. Similar to the CDF of a news channel, the author specifies a list of items to be updated and a schedule for updating them. However, unlike a news channel, each item in the CDF must include the following child element:

<USAGE VALUE="None"></USAGE>

This element instructs Internet Explorer 4.0 not to display the subchannel or item in the Channels Explorer Bar, but it will download and precache each item. Resources other than HTML pages, such as images and ActiveX™ controls, can also be specified in the CDF to be precached when the channel is updated. Since the channel is designed for offline use, the amount of content specified by the CDF file must be compatible with bandwidth constraints of the target audience.

Example: A maze game immersion channel containing a set of interlinked rooms implemented as HTML pages. On each subsequent update of the CDF file, the publisher dynamically generates a new CDF file that adds new rooms or modifies the existing maze.

Maze Game Immersion Channel

The CDF file to deliver a simple maze game might look something like this:

<?XML VERSION="1.0" ENCODING="UTF-8"?>

<CHANNEL
    HREF="home.htm"
    BASE="http://www.gamer.com/channel/" >

    <TITLE>The Castle</TITLE>
    <ABSTRACT>An always changing maze of rooms for you to explore</ABSTRACT>
    <LOGO HREF="Castle16x16.gif" STYLE="ICON"/>
    <LOGO HREF="Castle32x80.gif" STYLE="IMAGE"/>

    <SCHEDULE STARTDATE="1997-10-17" STOPDATE="1997-10-17">
        <INTERVALTIME DAY="1"/>
    </SCHEDULE>

    <ITEM HREF="room01.htm" LASTMOD="1997-10-17T11:12">
        <USAGE VALUE="None"></USAGE>
    </ITEM>

    <ITEM HREF="room02.htm" LASTMOD="1997-10-17T11:12">
        <USAGE VALUE="None"></USAGE>
    </ITEM>

    <-- a list of additional items -->

    <ITEM HREF="roomNN.htm" LASTMOD="1997-10-17T11:12">
        <USAGE VALUE="None"></USAGE>
    </ITEM>

</CHANNEL>

Maze Game Immersion Channel

Notification Channels

A notification channel informs the user when new information is available within a channel and provides a sitemap (through the CDF file) to the new information without downloading the content itself. The CDF file of a notification channel is similar to a news channel, except that the PRECACHE= attribute of each subchannel and item is explicitly set to "NO". The hierarchy of items and subchannels in the CDF file is displayed in the Channels Explorer Bar, but the content referenced by the outline is available only online. It's important that the publisher sets the user's expectations appropriately, specifically indicating that this type of channel is designed to notify the user of changes to content available online. Like all channels, a "gleam" appears on the channel's logo to inform the user that the channel has been updated.

Example: A corporation wants to create a channel to notify employees about the latest information on their employee services, benefits, company policies, and so on.

Corporate Notification Channel

The following illustrates the notification channel's CDF file. The example includes only the Employee Services subchannel.

<CHANNEL
    HREF="home.htm"
    BASE="http://www.corp.com/channel/"
    PRECACHE="No">

    <TITLE>Corporate Channel</TITLE>
    <ABSTRACT>CorpCo's Corporate Channel</ABSTRACT>
    <LOGO HREF="CorpLogo16x16.gif" STYLE="ICON"/>
    <LOGO HREF="CorpLogo32x80.gif" STYLE="IMAGE"/>

    <SCHEDULE STARTDATE="1997-10-17" STOPDATE="1997-10-17">
        <INTERVALTIME DAY="1"/>
    </SCHEDULE>

    <-- omitted subchannels -->

    <CHANNEL
        HREF="services.htm"
        PRECACHE="NO">

        <TITLE>Employee Services</TITLE>
        <ABSTRACT>Employee services  from CorpCo</ABSTRACT>
        <LOGO HREF="CategoryLogo.gif" STYLE="ICON"/>

        <ITEM HREF="companyStore.htm" PRECACHE= "NO" LASTMOD="1997-10-17T11:12">
            <TITLE>Company Store</TITLE>
            <ABSTRACT> Offerings from the company store </ABSTRACT>
            <LOGO HREF="BulletLogo.gif" STYLE="ICON"/>
        </ITEM>

        <ITEM HREF="StockServices.htm" PRECACHE= "NO" LASTMOD="1997-10-17T11:12">
            <TITLE>Stock Services</TITLE>
            <ABSTRACT>Buying and selling CorpCo stock</ABSTRACT>
            <LOGO HREF="BulletLogo.gif" STYLE="ICON"/>
        </ITEM>

        <ITEM HREF="Career.htm" PRECACHE= "NO" LASTMOD="1997-10-17T11:12">
            <TITLE>Career Center</TITLE>
            <ABSTRACT>Job opportunities at CorpCo</ABSTRACT>
            <LOGO HREF="BulletLogo.gif" STYLE="ICON"/>
        </ITEM>

        <ITEM HREF="Handbook.htm" PRECACHE= "NO" LASTMOD="1997-10-17T11:12">
            <TITLE>Employee Handbook</TITLE>
            <ABSTRACT>Rules and regulations for CorpCo employees</ABSTRACT>
            <LOGO HREF="BulletLogo.gif" STYLE="ICON"/>
        </ITEM>

        <ITEM HREF="Cafeteria.htm" PRECACHE= "NO" LASTMOD="1997-10-17T11:12">
            <TITLE>Cafeteria Menus</TITLE>
            <ABSTRACT>Today's eats </ABSTRACT>
            <LOGO HREF="BulletLogo.gif" STYLE="ICON"/>
        </ITEM>

        <ITEM HREF="Vacation.htm" PRECACHE= "NO" LASTMOD="1997-10-17T11:12">
            <TITLE>Vacation and Sick Reporting </TITLE>
            <ABSTRACT>Vacation and sick day reporting form </ABSTRACT>
            <LOGO HREF="BulletLogo.gif" STYLE="ICON"/>
        </ITEM>
    </CHANNEL>

    <-- omitted subchannels -->

</CHANNEL>

Hybrid Channels

Hybrid channels combine two or more of the news, immersion, and navigation channel types. When creating a hybrid channel, follow these guidelines:

  • Remember that the total daily download from any channel, including hybrid channels, must take into account bandwidth limitations.
  • Segregate items that can be used offline from those that must be used online into discrete subchannels. Therefore, the subchannels of a hybrid channel should fall into one of the three basic channel types previously discussed. For example, a single hybrid channel that delivers news-style items for offline reading and provides a sitemap to an online site might look like this:

Design Guidelines for Active Channels

To take true advantage of the "push" mechanism available in Internet Explorer 4.0, channels must be as small as possible to minimize download time and provide compelling content and interaction when used offline. When designing your Active Channel, follow these guidelines:

  • Design your channel to conform to one of the Active Channel types previously described in this document. Some channels, of course, might naturally cross the boundaries.
  • Channels intended for offline use (news and immersion channels, for example) should consider the impact of bandwidth limitations. If the target user is a home user dialing over a modem, the average amount of content delivered per update, per channel should be no more than 500K to 1 MB—preferably smaller. Under ideal conditions, a megabyte of content can be downloaded by a 28.8K modem in about six minutes. In practice, however, depending on line and server conditions, downloading 1 MB takes about 10 minutes. The following table shows download connect times for a 28.8K modem for different numbers of channels under different line conditions.

    Number of | 500K | 500K | 1 MB | 1 MB
    channels | (ideal) | (typical) | (ideal) | (typical)
    2 | 6 min. | 10 min. | 12 min. | 20 min.
    4 | 12 min. | 20 min. | 24 min. | 40 min.
    8 | 24 min. | 39 min. | 49 min. | 80 min.
    12 | 36 min. | 59 min. | 73 min. | 120 min.

    Note Sizes represent the average amount of data downloaded per channel.

  • Active Channels should be self-contained. The channel must deliver real value to the user while offline. It is likely that users will become annoyed with an offline channel that constantly forces online connections. This means that links to noncached resources should be minimized or hidden when the user is offline. Scripting can be used on an HTML page to determine when the user is offline and reflow the page accordingly using Dynamic HTML.
  • Channels should be personalized whenever possible. A publisher can provide a personalized channel experience for each user by generating a custom CDF for each user (for example, based on user preferences stored in a cookie). Channels based on personalized CDF files can be more rapidly delivered because content that is not important to the user will not be downloaded. Generating a customized CDF is as easy as offering a personalized home page using server-side scripting.


Webcasting

Web publishers can now broadcast content to their users on a regular schedule with new "push" and "pull" technologies that are collectively referred to as Webcasting. Users benefit by having the information that is most important to them automatically delivered directly to their desktop without having to go look for it, and also by being notified when the information has been updated. Web publishers benefit through improved feedback from increased exposure, more interactive relationships with their users, and a better understanding of their user base.

Microsoft® Internet Explorer 4.0 supports these new open, standards-based technologies as an "information receiver" client. Web sites can broadcast their content to an information receiver such as Internet Explorer by turning their Web site into an Active Channel. This article describes Active Channels and provides a sample that illustrates how to create one. Consult the CDF Reference for Active Channels for detailed descriptions of the CDF file elements and attributes. Further information on Webcasting is available on Microsoft's Web site, located at http://www.microsoft.com/ie/ie40/press/push.htm.


Content Delivery Mechanisms

The new technology delivered in Microsoft® Internet Explorer version 4.0 integrates HTML items such as Web pages, Java applets, ActiveX™ Controls, images, and floating frames into the user interface. When combined with support for Channel Definition Format (CDF) files, users can customize their desktop environment and have information on the Web automatically delivered directly to their desktop.

Web Site Content Arrives on the Active Desktop

New Ways to Display or Access Web Content

Web Site Content Arrives on the Active Desktop

Today, users don't see a Web site's content unless they intentionally visit that site. However, with the release of Internet Explorer 4.0, Web publishers can now broadcast their content directly to users' desktops on a continuing and increasingly personal basis. Web publishers can transform their Web site into a server that automatically broadcasts content to Active Channels on the desktop, just as a radio station broadcasts to a radio receiver. Active Channels are represented on the user's desktop with a logo button located in the desktop Channel Bar. When adding a channel to their desktop Channel Bar, users can configure channels to notify them of any updates to the channel and optionally have the Web pages automatically downloaded into their local cache for offline reading. Modifying a Web site to support Active Channels involves relatively minor additions to current production processes on existing Web sites, and no additional server software is required. Web content can also be broadcast to Active Desktop items, which allows users to display any HTML content directly on their desktop.

The content authoring options available in Internet Explorer 4.0 are designed to increase the visibility of content and to improve the user experience while viewing that content. Active Channels promote an enhanced user experience through depth, by providing a more personalized content experience than a browser currently offers. Active Desktop items promote the enhanced user experience through breadth, by giving users a way to pull together their favorite summarized Web content into a single desktop space. Therefore, Web publishers will want to author content for both mechanisms to provide maximum exposure of their Web sites. The additional exposure also helps Web publishers maintain an ongoing relationship with their users.

New Ways to Display or Access Web Content

Internet Explorer 4.0 introduces several new mechanisms Web publishers can use to present the content of their Web pages to users:

  • Active Channels
  • Active Desktop Items
  • Software Update Channels
  • HTML-based Web view of folders
  • Site subscriptions

Active Channels

Active Channels are Web sites that are described by a Channel Definition Format (CDF) file. Web sites offering their content as an Active Channel will be required to make a CDF file available on their Web server. The CDF file provides information about the contents of the channel, including titles, abstract descriptions, and images associated with each resource in the channel. In addition to defining the set of resources appearing in the channel, the CDF file also specifies how each item will be used or displayed and when the channel should be updated. Further information on channels and CDF files is available in Creating Active Channels and the CDF Reference for Active Channels.

Active Channel features include:

  • Desktop Channel Bar
  • Category folders
  • Update "gleams" and e-mail notifications
  • Full-screen view
  • Channels Explorer Bar
  • Channel screen savers
  • Page-hit logging

Desktop Channel Bar and category folders

A channel is represented by a branded logo button in the desktop Channel Bar. The desktop Channel Bar contains a list of logo images for all channels currently available on the user's desktop. This allows users to quickly launch the browser into a special full-screen view and load the channel's main HTML page by clicking the desired channel logo.

Desktop Channel Bar

Users can add a channel to their desktop Channel Bar by clicking an "Add Active Channel" button image placed on a publisher's Web page or in the channel guide. Microsoft maintains a list of channels that users can subscribe to or add to their Channel Bar in the channel guide.

In addition to the channel guide, category folders are provided to group together channels with similar topics. When users click an Add button, a dialog box is presented to allow them to add the channel to their Channel Bar and optionally subscribe to the channel.

Channel updates and notification

When adding a channel to the desktop Channel Bar, users select whether they want to just add the Active Channel to the Channel Bar, download the channel hierarchy (the CDF file), or download the hierarchy and all the channel content. If the user selects either the second or third option, Internet Explorer 4.0 monitors the channel for new information and automatically notifies the user that the channel has been updated. A red, asterisk-like "gleam" is placed on a channel logo to indicate an update has occurred. The user can also receive an optional e-mail notification when a channel is updated. To receive e-mail update notifications, users must enable this feature by clicking the Customize button on the Add Channel dialog box when adding the channel, or by changing the channel's properties after it is added.

Full-screen view and Channels Explorer Bar

When the user clicks a logo button in the Desktop Channel Bar, the content from that Web site is immediately displayed in full-screen view. If the user is viewing a subscribed channel (with downloaded content) while offline, the browser opens the most recent update of the channel's resources from the local cache. While full-screen view is active, a status bar and a toolbar with a small set of navigational controls are provided. Internet Explorer full-screen view can be enabled on any browser window by selecting the Full Screen option on the View menu or by clicking the Full Screen icon located in the standard toolbar. By default, a channel launched into full-screen view will also display the Channels Explorer Bar on the left side of the screen. This is an autohiding pane that displays the currently selected channel. Note that the currently selected channel logo is the only one displayed, and all other channel logos are replaced with the channel titles in black-and-white text. Placing the cursor over a nonselected channel causes the channel's logo to be displayed.

Channels Explorer Bar

The Channels Explorer Bar also helps users navigate through a channel's content by acting as a sitemap for the channel. The CDF file hierarchy is exposed through this view, if one exists for the channel. The currently selected channel hierarchy contracts when a user clicks a different channel in the Channels Explorer Bar, and the newly selected channel's hierarchy is expanded. Some channels might not have a hierarchy to display in this pane, in which case the logo is the only item shown.

Screen savers

Web publishers can specify an HTML page in a CDF file to be used as screen saver content. This page is displayed in the Channel Screen Saver included with Internet Explorer 4.0. Each installed channel's screen saver page displays in rotation until the user presses a key or clicks the autohidden Close button in the upper-right corner of the screen. However, the Channel Screen Saver must be enabled by the user before any screen saver content specified in the CDF file will be displayed. If the Channel Screen Saver is not enabled, users are prompted with a dialog box to enable it when subscribing to a channel that contains a screen saver item.

The following is an example of an HTML-based Channel Screen Saver.

HTML-based Channel Screen Saver

By default, moving the mouse doesn't close the screen saver because there may be content or links on the screen saver page that users might want to access. Users can change this behavior by accessing the Screen Saver tab in the Display Properties dialog box and selecting the appropriate option.

Page-hit logging

Internet Explorer 4.0 helps Web publishers better understand the users who visit their sites by providing reliable feedback. When connecting to a Web server to update an Active Channel or Active Desktop item, the page-hit logging feature can be enabled to report the viewing of the channel's pages, including offline browsing. However, Microsoft protects users' privacy with the Profile Assistant. This standards-based feature allows the user to specify exactly what type of demographic information, if any, can be sent back to a Web server.

Note The Profile Assistant can also be used with regular (nonchannel) HTML pages. Page-hit logging only applies to Web content using a CDF file, such as an Active Channel or an Active Desktop Item.

Active Desktop Items

Internet Explorer 4.0 introduces the Active Desktop, which provides you with the ability to include HTML documents and items, such as Java applets or ActiveX Controls, directly on the desktop. This allows users to create a highly customized desktop that contains their favorite updated Web content. Users can add items to the Active Desktop in one of three ways:

  • Clicking an "Add to Active Desktop" button provided on a Web page.
  • Accessing the Web tab in the Display Properties Control Panel, and selecting the "New..." button.
  • Using the right mouse button to drag an HTML icon from the Internet Explorer address or title bar and drop it on the desktop. Once the icon is positioned, select "Create Active Desktop item here" from the context menu.

Because the Active Desktop uses HTML, items can be created using any technique or technology supported by the Internet Explorer browser, including images, Dynamic HTML, ActiveX Controls, Java applets, scripting, and multimedia filters and transitions. This means that Web publishers can leverage what they already know to begin publishing information to the Active Desktop. For more information about desktop items, see Creating Items for the Active Desktop.

Software Update Channels

Software developers can use this new mechanism to automatically deliver their software updates on the Web. Software Update Channels require three major components: a CDF file, an Open Software Description (OSD) file, and a distribution unit. Users subscribing to these channels will receive notifications when the software update is available and can choose to have the software automatically downloaded and installed.

HTML-Based Web View of Folders

The release of Internet Explorer 4.0 extends the original folder views in Windows 95 (Large Icons, Small Icons, List, and Details) with a new HTML-based viewing mode. This mode allows any folder to be represented as a Web page. Therefore, users can create custom HTML files to view file systems containing more graphical and interactive content, such as images and animations, through Java applets, ActiveX Controls, and Dynamic HTML. Web publishers or software developers might want to supply the necessary HTML files in directories created for their products to display important information that is usually presented in a readme file. Viewing a folder as a Web page works on any folder containing an HTML file named Folder.htt and an associated Desktop.ini file. Internet Explorer 4.0 includes Folder.htt templates for some special folders, such as My Computer, Favorites, Control Panel, Printers, and History. Note that the My Computer and Control Panel folders cannot be customized.

To create a Folder.htt file for any directory, bring up the context menu in a directory by clicking the right mouse button and selecting the "Customize this folder..." option. Now select the first option, "Create or edit an HTML document," and follow the steps provided in the wizard. A default Folder.htt file is provided for you to edit. Once this process is completed, the directory is viewed as an HTML page. To disable and re-enable this view at any time, users can toggle the "as Web Page" option in the View menu.

The following illustrates a Web view for Control Panel.

Web view for Control Panel

Site Subscriptions

A site subscription allows users to automatically download the content of any Web site (through site crawling), up to three levels deep, from the specified URL. If the local computer connects to the Internet by modem, the site subscriptions can be configured to automatically dial up and download Web pages without user intervention. Site subscriptions allow users to view the cached information from any Web site when they are offline. Note that Channel Bar logo buttons, Channels Explorer Bar sitemaps, page-hit logging, screen savers, and publisher-recommended update schedules are not available with site subscriptions because they don't have an associated CDF file.

When adding any Web page to the Internet Explorer favorites list, users will be prompted with the following dialog box asking if they want to subscribe to that site.

Add to Favorites Dialog

Web publishers can disable site crawling by Internet Explorer on any Web page by inserting the following line into the HEAD section of the page.

<META NAME="ROBOTS" CONTENT="NOFOLLOW">

To prevent Internet Explorer from crawling any pages on a Web site, a file named Robots.txt should be placed in the root directory of an HTTP server. This file should contain the lines:

User-Agent:MSIECrawler
Disallow:/path/

In this example, path is the name of the path that Internet Explorer should not site crawl. A path of "/" can be used to exclude all pages on the server. Note that "MSIECrawler" can be replaced with "*" to indicate that all automated crawling robots (including Internet Explorer) should be excluded.


CDF Reference

These documents contain reference information for Channel Definition Format (CDF) elements used with Active Channels, Active Desktop items, and Software Update Channels.

CDF Reference for Active Channels

CDF Extensions for Active Desktop Items

CDF Extensions for Software Update Channels


A

<A
 HREF="url"
>

Defines a hypertext link for an element. The URL specified in the HREF= attribute will be displayed in the browser channel pane if the TITLE element is not present.

HREF="url"
Required. Specifies the URL associated with the parent element. The browser navigates to this location when the parent element is clicked.

Number of allowed occurrences: None or one (per parent element)
Parent elements | Child elements
CHANNEL | None
ITEM

The HREF= attribute of the parent element must be omitted when using the A element. To a CDF client, including the A element is functionally equivalent to using the HREF= attribute with the parent element and omitting the A element.

The end tag </A> is required.

Example

<ITEM>
    <A HREF="http://www.foosports.com/page1.htm">This is a link to page 1.</A>
</ITEM>


ABSTRACT

<ABSTRACT
 XML-SPACE="DEFAULT" | "PRESERVE" >

Represents a description of the associated CHANNEL or ITEM parent element. Microsoft® Internet Explorer displays this text in a ToolTip to the right of the icon in the browser channel pane when the cursor is paused over the channel or item title.

When applied to the top-level CHANNEL element, the abstract should appear near the top of the CDF file before any ITEM or nested CHANNEL elements.

XML-SPACE="DEFAULT" | "PRESERVE"
Specifies how white space, such as tabs, spaces, and blank lines, should be handled. The default behavior (XML-SPACE="DEFAULT") indicates that white space characters are not considered significant, and therefore some of these characters may be filtered out during file processing. Set the value of this attribute to "PRESERVE" to ensure that all white space characters are retained. This attribute can be used with any CDF element that uses significant white space. When used as an attribute of a parent element, the XML-SPACE value applies to all child elements unless specifically overridden with another XML-SPACE attribute.

Number of allowed occurrences: None or one
Parent elements | Child elements
CHANNEL | None
ITEM
SOFTPKG

The ABSTRACT element can optionally be used as an attribute with the CHANNEL and ITEM elements to support previous implementations of CDF. Any new CDF files should use ABSTRACT as a child element.

The end tag </ABSTRACT> is required.

Example

<ABSTRACT>This article describes how to create a CDF file.</ABSTRACT>


CHANNEL

<CHANNEL
BASE="url"
HREF="url"
LASTMOD="date"
LEVEL="n"
PRECACHE="YES" | "NO"
>

Defines a channel or subchannel. The channel is defined by the first occurrence of the CHANNEL element and the corresponding </CHANNEL> end tag. All CHANNEL elements contained within the top-level channel represent subchannel folders that are used to create a hierarchy of channel items.

BASE="url"
Base URL for the channel. This is used to resolve relative URLs specified in ITEM and CHANNEL elements contained within this channel. The BASE value applies to all child elements of the current channel or subchannel. This attribute supersedes the BASE value previously defined by a parent CHANNEL element, if any exist. The URL specified must end with a trailing "/", or the last word will be removed.
HREF="url"
Uniform Resource Locator associated with the channel. The browser navigates to this location when the user activates the channel. The HREF attribute should be omitted if the CHANNEL element contains an anchor (A) as a child element.
LASTMOD="date"
Last date/time in GMT that the page indexed by the HREF attribute was modified. GMT is Greenwich Mean Time, also known as Universal Time Coordinated (UTC). Note that the LASTMOD date/time is not necessarily your local time. This attribute allows the channel client to determine whether the content has changed since the last time it was downloaded. The item is downloaded only if the date associated with the cached item is older than the LASTMOD value in the CDF file. Additional information on optimizing channels is available in the Creating Active Channels documentation. The date format used in the LASTMOD attribute is specified in the form yyyy-mm-ddThh:mm, where:
yyyy | Specifies the year.
mm | Specifies the month (01-12).
dd | Specifies the day of the month (01-31).
hh | Specifies the hour of the day (00-23).
mm | Specifies the minutes (00-59).
LEVEL="n"
Number of levels (or links) deep the client should "site crawl" and precache the HTML content from the URL specified in the HREF attribute. The default is zero, which specifies to only precache the URL of the CHANNEL, along with any images it uses. If the URL contains frames, the client will also retrieve all content inside the frames. By default, the maximum number of levels that can be specified for site crawling is three.
PRECACHE="YES" | "NO"
Specifies whether content should be downloaded and cached on the client computer. If PRECACHE is omitted or set to "YES", content is downloaded only if the user of Internet Explorer has specified that channel content should be downloaded. If PRECACHE is set to "NO", content is not downloaded and the LEVEL attribute is ignored.

Number of allowed occurrences: Any number
Parent elements | Child elements
None | ABSTRACT
CHANNEL
ITEM
LOG
LOGIN
LOGO
LOGTARGET
SCHEDULE
SOFTPKG
TITLE

An optional SELF= attribute can be added in the top-level CHANNEL to indicate the location of the CDF file to use for creating a channel subscription. Note that this attribute is unnecessary and is only supported for backward compatibility.

If more than one mechanism is used to specify a URL for a channel, Internet Explorer will look for URLs in this order of precedence:

  1. The HREF= attribute of the CHANNEL element.
    <CHANNEL HREF="http://...">
  2. The HREF of the anchor (A) element that is the immediate child of the CHANNEL element.
    <CHANNEL>
    <A HREF="http://...">My Channel</A>
  3. The optional INFOURI=url attribute of the CHANNEL element. This attribute is available for compatibility with other CDF parsers.
    <CHANNEL INFOURI="http://...">

The end tag </CHANNEL> is required.


CDF Reference for Active Channels

The following section describes the suggested revision to Channel Definition Format (CDF) that Microsoft and other partners are presenting to the W3C (World Wide Web Consortium). For reference purposes, this revision is CDF version 0.4. CDF is an application of the Extensible Markup Language (XML). The original submission of CDF to the W3C can be found at http://www.w3.org.

CDF Syntax

CDF Elements

CDF Syntax

Note that the syntax might vary for different elements. The following table describes the possible formats in which the tags might appear.

Description Example
Empty element with attributes
<ELEMENT ATTR1="value" ATTR2="value"/>
Element with content and end tag
<ELEMENT>Element Content Here</ELEMENT>
Parent element with attributes and child elements
<PARENT ATTR1="value">
    <CHILD1>
        Content
    </CHILD1>
    <CHILD2 ATTR1="value"/>
</PARENT>

CDF Parsing Rules and Hints

To avoid some common mistakes, keep the following rules in mind when creating a CDF file.

Special Characters When placing text content between an element start and end tag, you must encode the following characters to prevent CDF parsing errors.
Character Encoded value
< &lt;
> &gt;
' &apos;
" &quot;
& &amp;

For a complete list of other named character set entities, see the documentation on HTML Character Sets (Charsets) and Named Entities.

Character Encoding | The CDF file supports encoding for any ASCII character with the format &#nnn. For example, the ampersand character could also be encoded with its ASCII decimal value of 38 by using the string &#038.
Attribute Syntax | All attribute values must be enclosed in quotation marks, even if the value is a number.
Comments | Any text you want to be ignored by the CDF parser should be placed between the comment start tag (<!--) and the comment end tag (-->).

CDF Elements

This section describes the elements and associated attributes used to create Channel Definition Format (CDF) files for Active Channels. Some CDF files may be used for other types of Webcasting, such as Active Desktop items and Software Update Channels, depending on the value of the USAGE element.

?XML A ABSTRACT CHANNEL
EARLIESTTIME HTTP-EQUIV INTERVALTIME ITEM
LATESTTIME LOG LOGIN LOGO
LOGTARGET PURGETIME SCHEDULE TITLE
USAGE


EARLIESTTIME

<EARLIESTTIME
 DAY="n"
HOUR="n"
MIN="n"
/>

Specifies the beginning of the valid range of time that the update to the CDF can occur. By default, if this value is not specified, the earliest time is set to the beginning of the INTERVALTIME value. The days, hours, and minutes are totaled to determine the offset value from the start of the INTERVALTIME. Additional information on scheduled updates is available in the Creating Active Channels documentation.

DAY="n"
First day within the INTERVALTIME that the schedule can be updated.
HOUR="n"
First hour within the INTERVALTIME that the schedule can be updated.
MIN="n"
First minute within the INTERVALTIME that the schedule can be updated.

Number of allowed occurrences: None or one
Parent elements | Child elements
SCHEDULE | None

Client applications can round the specified value to the nearest value that they consider significant.


HTTP-EQUIV

<HTTP-EQUIV
 NAME="headerparam"
VALUE="text"
/>

Supplies information that can also be provided through HTTP response headers. In the context of sending files over the HTTP protocol through the LOGTARGET element, it indicates that an HTTP header parameter based on the information in this tag should be added.

NAME="headerparam"
Required. Specifies the name of the HTTP header parameter sent with the log file, such as "Encoding-Type."
VALUE="text"
Required. Specifies the value of the corresponding parameter.

Number of allowed occurrences: Any number
Parent elements | Child elements
LOGTARGET | None

Example

The following example shows how to send a compressed log file back to the server.

<LOGTARGET HREF="http://www.mysite.com/logging/" METHOD="POST">
    <HTTP-EQUIV NAME="encoding-type" VALUE="gzip" />
</LOGTARGET>


INTERVALTIME

<INTERVALTIME
 DAY="n"
HOUR="n"
MIN="n"
/>

Indicates the interval of time over which the schedule should repeat. The days, hours, and minutes are totaled to determine the length of the repeating range. Additional information on scheduled updates is available in the Creating Active Channels documentation.

DAY="n"
Number of days over which the schedule will repeat.
HOUR="n"
Number of hours over which the schedule will repeat.
MIN="n"
Number of minutes over which the schedule will repeat.

Number of allowed occurrences: None or one
Parent elements | Child elements
SCHEDULE | None

The time quantity specified by this element will be rounded up to a fraction of a day (fourth, third, half, and so on) or rounded to the nearest multiple of a day. For example, 1-, 2-, 3-, and 4-hour increments will be used by Internet Explorer without rounding, but 5 hours will be rounded to 6 hours (a fourth of a day). An INTERVALTIME with a value greater than a half day but less than a day will be rounded up to a day. This element is a required child element of SCHEDULE, and it must contain a nonzero value to be considered valid.

Example

The following example shows a schedule that will update the channel every day during the month of December (1997) sometime between 10 A.M. and 2 P.M.

<SCHEDULE STARTDATE="1997-12-01" STOPDATE="1997-12-31">
<INTERVALTIME DAY="1" />
<EARLIESTTIME HOUR="10" />
<LATESTTIME HOUR="14" />
</SCHEDULE>


ITEM

<ITEM
HREF="url"
LASTMOD="date"
LEVEL="n"
PRECACHE="YES" | "NO"
>

Defines an item in a channel. An item is a unit of information that usually corresponds to a Web page. In an Active Channel, items will appear in the hierarchy exposed in the Channels Explorer Bar. To prevent an item from showing up in the Channels Explorer Bar, the USAGE element should be included as a child element of the ITEM with the VALUE attribute set to "None."

HREF="url"
Required. URL that represents the channel. The browser navigates to this location when the user activates the channel. There must be exactly one HREF attribute with the ITEM element. The HREF attribute should be omitted if the ITEM element contains an anchor (A) as a child element.
LASTMOD="date"
Last date/time in GMT that the page indexed by the HREF attribute was modified. GMT is Greenwich Mean Time, also known as Universal Time Coordinated (UTC). Note that the LASTMOD date/time is not necessarily your local time. This allows the channel client to determine whether the content has changed since the last time it was downloaded. The item is downloaded only if the date associated with the cached item is older than the LASTMOD value in the CDF file. Additional information on optimizing channels is available in the Creating Active Channels documentation. The date format used in the LASTMOD attribute is specified in the form yyyy-mm-ddThh:mm, where:
yyyy | Specifies the year.
mm | Specifies the month (01-12).
dd | Specifies the day of the month (01-31).
hh | Specifies the hour of the day (00-23).
mm | Specifies the minutes (00-59).
LEVEL="n"
Number of levels (or links) deep the client should site crawl and precache the HTML content from the URL specified in the HREF attribute. The default is zero, which specifies to precache only the URL of the item and the images it references. If the URL contains frames, the client also retrieves all content inside the frames.
PRECACHE="YES" | "NO"
Specifies whether content should be downloaded and cached on the client computer. If PRECACHE is omitted or set to "YES", content is downloaded only if the user of Internet Explorer has specified that channel content should be downloaded. If PRECACHE is set to "NO", content is not downloaded and the LEVEL attribute is ignored.

Number of allowed occurrences: Any number
Parent elements Child elements
CHANNEL ABSTRACT
LOG
LOGO
TITLE
USAGE

The end tag </ITEM> is required.

Example

<ITEM HREF="http://www.foosports.com/intro.htm" LASTMOD="1997-09-11T10:30">
    <TITLE>Welcome to FooSports!</TITLE>
    <ABSTRACT>FooSports articles, news, and promotional offers</ABSTRACT>
</ITEM>


LATESTTIME

<LATESTTIME
 DAY="n"
HOUR="n"
MIN="n"
/>

Specifies the latest time during the INTERVALTIME that the schedule will be applied and updated. The days, hours, and minutes are totaled to determine the offset value from the INTERVALTIME that represents the latest valid time for updating a channel. If omitted, the latest time is set to the beginning of INTERVALTIME. Additional information on scheduled updates is available in the Creating Active Channels documentation.

DAY="n"
Latest number of days to which the schedule will be applied.
HOUR="n"
Latest number of hours to which the schedule will be applied.
MIN="n"
Latest number of minutes to which the schedule will be applied.

Number of allowed occurrences: None or one
Parent elements | Child elements
SCHEDULE | None

Client applications can round the specified value to the nearest value that they consider significant.


LOG

<LOG
 VALUE="document:view"
/>

Specifies that the URL of the parent ITEM element should be recorded in a page-hit log file. Additional information on page-hit logging is available in the Creating Active Channels documentation.

VALUE="document:view"
Required. Specifies the event to be logged. Currently, "document:view" is the only value supported by Internet Explorer.

Number of allowed occurrences: Any number
Parent elements | Child elements
ITEM | None

An ITEM can be logged only if the path of the ITEM's HREF attribute falls under the path of the CDF file's URL or the path of the LOGTARGET's HREF. Note that this element is also valid for a CDF file being used as an Active Desktop item (<USAGE VALUE="DesktopComponent"></USAGE>).

There is no end tag associated with this element.

Example

<ITEM  HREF="http://www.foosports.com/promotion.htm">
    <LOG VALUE="document:view"/>
</ITEM>


LOGIN

<LOGIN/>

Specifies that the channel requires authentication for updates. A CDF file containing this element will prompt the user for a name and password during the channel subscription process.

Number of allowed occurrences: None or one (top-level channel only)
Parent elements | Child elements
CHANNEL | None

There is no end tag associated with this element.

Example

<LOGIN />


LOGO

<LOGO
 HREF="url"
STYLE="ICON" | "IMAGE" | "IMAGE-WIDE" />

Specifies an image that can be used to represent a channel or channel item.

HREF="url"
Required. Specifies the URL associated with the channel logo or icon image.
STYLE="ICON" | "IMAGE" | "IMAGE-WIDE"
Text string indicating the context in which a logo will be used, as follows:
Value | Image size | Display description
"ICON" | 16H x 16W | This image appears in the Channels Explorer Bar hierarchy and other areas of the Microsoft® Windows® name space, such as when viewing the contents of a folder containing the CDF.
"IMAGE" | 32H x 80W | This logo image is placed in the desktop Channel Bar to provide a quick launching mechanism for the main channel page.
"IMAGE-WIDE" | 32H x 194W | Wide logos are displayed in the Channels Explorer Bar to provide a link to the main channel page. When clicked, this image will also expand or contract the channel's hierarchy (if one exists) in the Channels Explorer Bar.

Number of allowed occurrences: None or one (per STYLE attribute)

Note GIF, JPEG, and other standard image formats supported by Internet Explorer can be used for logo images. However, animated GIF files are not supported with this element. Image formats and styles are subject to change.
Parent elements | Child elements
CHANNEL | None
ITEM
SOFTPKG

There is no end tag associated with this element.

Example

<LOGO HREF="http://www.foosports.com/images/logo.gif" STYLE="IMAGE"/>


LOGTARGET

<LOGTARGET
 HREF="url"
METHOD="POST"
SCOPE="ALL" | "OFFLINE" | "ONLINE"
>

Specifies where to send a CDF client page-hit log file. This element must occur before any ITEM elements in the CDF file. For details about the type of information gathered, see the Page-Hit Logging section.

HREF="url"
Required. Specifies the URL of where the log should be sent.
METHOD="POST"
Required. Specifies the HTTP method to be used for sending the data.
SCOPE="ALL" | "OFFLINE" | "ONLINE"
Specifies which type of page hits should be logged. Page hits can be logged for offline (read from local cache) or online (read from URL) browsing. The default for this attribute is "ALL", which logs both types of hits.

Number of allowed occurrences: None or one (top-level channel only)
Parent elements Child elements
CHANNEL HTTP-EQUIV
PURGETIME

The end tag </LOGTARGET> is required.

Example

<LOGTARGET HREF="http://www.foosports.com/logging" Method="POST" SCOPE="OFFLINE">
    <PURGETIME HOUR="12"/>
    <HTTP-EQUIV NAME="ENCODING-TYPE" VALUE="gzip"/>
</LOGTARGET>


PURGETIME

<PURGETIME
 HOUR="n"
/>

When the log file is being uploaded, any page hits older than PURGETIME will not be reported.

HOUR="n"
Number of hours for which the logging information is considered valid.

Number of allowed occurrences: None or one
Parent elements | Child elements
LOGTARGET | None

There is no end tag associated with this element.

The log file (filename.log) is stored in the user's local cache in the %userprofile%\history\log folder. This file is cleared after it is successfully posted to the HTTP server during the CDF update.


SCHEDULE

<SCHEDULE
 STARTDATE="date"
STOPDATE="date"
TIMEZONE="offset"
>

Defines the schedule used for channel updating. Starting at midnight on STARTDATE, channel updating occurs once within each consecutive time interval specified by the INTERVALTIME child element. The EARLIESTTIME and LATESTTIME child elements specify offsets that define the valid range of time within each interval that channel updates can occur.

The schedule must be placed directly under the top-level channel element, and it must contain a nonzero INTERVALTIME value to be considered valid. This schedule is relative to the time zone in TIMEZONE, if present; otherwise, the schedule is relative to the local time of the user. This schedule applies to the channel only if the user accepts the default "publisher's recommended schedule" when subscribing to the channel. Additional information on scheduled updates is available in the Creating Active Channels documentation.

This element should appear near the top of the CDF file, after the top-level CHANNEL element and before any ITEM or nested CHANNEL elements.

ENDDATE="date"
Obsolete. Do not use. This attribute has been replaced by STOPDATE.
STARTDATE="date"
Day on which the schedule will start to apply. If this attribute is omitted, the schedule will start to apply on the current day. The date for this attribute is specified in the form yyyy-mm-dd, where:
yyyy | Specifies the year.
mm | Specifies the month (01-12).
dd | Specifies the day of the month (01-31).
STOPDATE="date"
Day on which the schedule stops updating (expires). If this attribute is omitted, the schedule will not expire. The date for this attribute is specified in the form yyyy-mm-dd, where:
yyyy | Specifies the year.
mm | Specifies the month (01-12).
dd | Specifies the day of the month (01-31).
TIMEZONE="offset"
Difference between local time and Universal Time Coordinated (UTC). This allows channel publishers to specify an absolute time for an update schedule. The offset specified for this attribute adjusts the EARLIESTTIME and LATESTTIME child elements accordingly. The date for this attribute is specified in the form szzzz, where:
s | Specifies the relationship of the local time to UTC. A minus (-) or plus (+) sign is used to indicate whether the local time is earlier or later than UTC.
zzzz | Specifies the offset from UTC in hours and minutes.

Number of allowed occurrences: None or one (top-level channel only)
Parent elements Child elements
CHANNEL EARLIESTTIME
ITEM INTERVALTIME
LATESTTIME

The end tag </SCHEDULE> is required.

For example, to specify the U.S. Eastern Standard Time (EST), which is 5 hours earlier than UTC, use: TIMEZONE="-0500".

Example

The following example shows a schedule that takes effect immediately and updates the channel once per day, sometime between noon and 6 P.M. The channel will stop receiving updates on December 1, 1997.

<SCHEDULE ENDDATE="1997-12-01">
    <INTERVALTIME DAY="1"/>
    <EARLIESTTIME HOUR="12"/>
    <LATESTTIME HOUR="18"/>
</SCHEDULE>


TITLE

<TITLE
 XML-SPACE="DEFAULT" | "PRESERVE" >

Specifies a text string representing the title of the CHANNEL or ITEM element. Internet Explorer displays this title to the right of the item's icon in the Channels Explorer Bar. A TITLE element that is the direct child of the top-level channel element appears in place of the channel logo in the Channels Explorer Bar when another channel is selected by the user.

When applied to the top-level CHANNEL element, the title should appear near the top of the CDF file before any ITEM or nested CHANNEL elements.

XML-SPACE="DEFAULT" | "PRESERVE"
Specifies how white space, such as tabs, spaces, and blank lines, should be handled. The default behavior (XML-SPACE="DEFAULT") indicates that white space characters are not considered significant, and therefore some of these characters may be filtered out during file processing. Set the value of this attribute to "PRESERVE" to ensure that all white space characters are retained. This attribute can be used with any CDF element that uses significant white space. When used as an attribute of a parent element, the XML-SPACE value applies to all child elements unless specifically overridden with another XML-SPACE attribute.

Number of allowed occurrences: None or one
Parent elements | Child elements
CHANNEL | None
ITEM
SOFTPKG

The TITLE element can optionally be used as an attribute with the CHANNEL and ITEM elements to support previous implementations of CDF. Any new CDF files should use TITLE as a child element.

The end tag </TITLE> is required.

Example

<TITLE>CDF Reference</TITLE>


USAGE

<USAGE
 VALUE="Channel" | "Email" | "DesktopComponent" | "NONE" | "ScreenSaver" | "SoftwareUpdate" >

Indicates how an ITEM element should be used.

VALUE="Channel" | "Email" | "DesktopComponent" | "NONE" | "ScreenSaver" | "SoftwareUpdate"
Required. Specifies a special usage of the parent element.
"Channel" | These items appear in the browser channel pane. This is the default behavior when no USAGE element appears under an ITEM.
"Email" | This one item is e-mailed when the channel content is updated (one per CDF).
"NONE" | If a "NONE" value is used as the only USAGE element in an ITEM, the item will not appear in the Channels Explorer Bar.
"DesktopComponent" | These items are displayed in a frame located on the Active Desktop. A CDF with this usage value can only be used in the context of an Active Desktop item. An Active Channel would require a separate CDF file.
"ScreenSaver" | This one item is displayed in the special Internet Explorer screen saver (one per CDF).
"SoftwareUpdate" | This indicates the CDF file is being used for a Software Update channel, which allows software to be automatically updated over the Web. This value is only valid for the top-level channel. For more information on Software Update channels, see Creating Software Update Channels and the Open Software Description (OSD) documentation.

Number of allowed occurrences: Any number
Parent elements | Child elements
ITEM | None
SOFTPKG

For information on additional CDF elements supported for "DesktopComponent" usage, see CDF Extensions for Active Desktop Items.

For information on additional CDF elements supported for "SoftwareUpdate" usage, see CDF Extensions for Software Update Channels.

Some older implementations of CDF clients look for a SHOW attribute instead of the USAGE child element inside the ITEM element. An attribute of SHOW="string" in an ITEM element is functionally equivalent to adding a child element of <USAGE VALUE="string"></USAGE> to an ITEM element.

The end tag </USAGE> is required. The content of the element is optional and varies according to the VALUE attribute.

Example

<ITEM HREF="http://www.foosports.com/screensaver.htm">
    <USAGE VALUE="ScreenSaver"></USAGE>
</ITEM>

Note "SmartScreen," a trademark of PointCast Inc., can be used in place of "ScreenSaver".


?XML

<?XML
 ENCODING="char-set"
 VERSION="n.n"
?>

Indicates an Extensible Markup Language (XML) document and specifies the version and character set for the current document. This tag should occur only once at the beginning of the CDF file.

ENCODING="char-set"
Character set used in the document. The default is "UTF-8". Additional information on character encoding and character sets is available in the CDF Parsing Rules and Hints section.
VERSION="n.n"
Major and minor version of XML the CDF file supports. If not specified, the default value is "1.0".

Number of allowed occurrences: One
Parent elements | Child elements
None | None

Example

<?XML ENCODING="UTF-8" VERSION="1.0"?>


CANRESIZE

<CANRESIZE
 VALUE="No" | "Yes"
/>

Indicates whether the Active Desktop item can be resized along both the x and y axes by the user. The value of this element overrides the CANRESIZEX and CANRESIZEY elements.

VALUE="No" | "Yes"
Specifies whether the Active Desktop item can be resized. The default is "Yes".

Number of allowed occurrences: Exactly one.
Parent elements | Child elements
USAGE | None


CANRESIZEX

<CANRESIZEX
 VALUE="No" | "Yes"
/>

Indicates whether the Active Desktop item can be resized along the x-axis by the user.

VALUE="No" | "Yes"
Specifies whether the width of the Active Desktop item can be resized. The default is "Yes".

Number of allowed occurrences: Exactly one.
Parent elements | Child elements
USAGE | None


CANRESIZEY

<CANRESIZEY
 VALUE="No" | "Yes"
/>

Indicates whether the Active Desktop item can be resized along the y-axis by the user.

VALUE="No" | "Yes"
Specifies whether the height of the Active Desktop item can be resized. The default is "Yes".

Number of allowed occurrences: Exactly one.
Parent elements | Child elements
USAGE | None


CDF Extensions for Active Desktop Items

The following reference information applies to Channel Definition Format (CDF) files created for Active Desktop items. For the complete CDF element reference, see the CDF Reference for Active Channels. The elements listed here are valid only when used as a child element within the USAGE element for an Active Desktop item.


HEIGHT

<HEIGHT
 VALUE="pixels"
>

Indicates the height, in pixels, of the Active Desktop item specified in the ITEM element.

VALUE="pixels"
Required. Specifies the height of the Active Desktop item.

Number of allowed occurrences: Exactly one.
Parent elements | Child elements
USAGE | None


OPENAS

<OPENAS
 VALUE="HTML" | "Image"
>

Indicates the content type of the Active Desktop item specified in the ITEM element.

VALUE="HTML" | "Image"
Content type of the Active Desktop item. This determines how the content will be hosted in the user's Active Desktop Desktop.htm file. HTML items are hosted with IFRAME elements, and images are hosted with IMG elements. The default is "HTML".

Number of allowed occurrences: None or one.
Parent elements | Child elements
USAGE | None


WIDTH

<WIDTH
 VALUE="pixels"
>

Indicates the width, in pixels, of the Active Desktop item specified in the ITEM element.

VALUE="pixels"
Required. Specifies the width of the Active Desktop item.

Number of allowed occurrences: Exactly one.
Parent elements | Child elements
USAGE | None


DELETEONINSTALL

<DELETEONINSTALL />

Indicates that the software subscription should unregister itself when the software it describes has been successfully downloaded and installed, either through AUTOINSTALL or manually by the user. Therefore, DELETEONINSTALL subscriptions are not permanent.

Number of allowed occurrences: None or one
Parent elements | Child elements
SOFTPKG | None

Applies To

CDF


CDF Extensions for Software Update Channels

This section describes the elements and associated attributes used to create Channel Definition Format (CDF) and Open Software Description (OSD) files for Software Update Channels. This new technology allows users to automatically have new versions of software downloaded and installed from the Web. More information on CDF files is available in CDF Reference for Active Channels. For more information on OSD, see Open Software Description (OSD). Also, for more information on Microsoft Internet Code Download, which includes elements that enhance OSD files, see Microsoft Internet Code Download.

The reference for each element defined below includes an "Applies To" section indicating which type of file (OSD or CDF) uses the element.

CDF Elements
DELETEONINSTALL
OSD Elements
ABSTRACT CODEBASE DISKSIZE
IMPLEMENTATION IMPLTYPE LANGUAGE
LICENSE MEMSIZE OS
OSVERSION PROCESSOR SOFTPKG
TITLE VM
MSICD Elements
CLASS CODE CODEBASE
ICON IMPLEMENTATION ISBEAN
JAVA LANGUAGE NAMESPACE
NATIVECODE NEEDSTRUSTEDSOURCE OS
OSVERSION PACKAGE PROCESSOR
SOFTPKG SYSTEM TYPELIB

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


Profile Assistant

This document describes how Web publishers can use the new Microsoft® Internet Explorer 4.0 Profile Assistant to collect profile information from the user. All information submitted to the Web server requires the user's approval.

Introduction

Using the Profile Assistant

Authoring an HTML Form

Introduction

The Platform for Privacy Preferences (P3) is a World Wide Web Consortium (W3C) project determining the overall architecture for enabling privacy on the Web. The Profile Assistant in Internet Explorer 4.0 is the first implementation of the types of privacy capabilities enabled by P3.

This new architecture defines a means by which user profiles can be exchanged between Web clients and servers while respecting the user's right to privacy. This profile information is valuable, but it cannot be used by companies or service organizations unless a standard mechanism is defined by which the information can be programmatically accessed on either the client or the server. Such a mechanism must respect a user's privacy constraints. Therefore, a Web site cannot be allowed to retrieve user information to which it is not entitled. Sites should not be hindered, however, from accessing profile information with the informed consent of the user, as defined by the P3 architecture.

This article includes a description of the scripting object model exposed on the client user-agent (Internet Explorer 4.0). The new userProfile object allows Web publishers to create scripts in Web pages that request read access to private information within the constraints of the privacy guidelines defined by the P3 architecture. Note that Internet Explorer 4.0 does not yet allow for write access to the user profile as specified in the P3 architecture. Instead, Internet Explorer 4.0 implements a subset of the P3 schema, which is undergoing the standardization process at the W3C. To install the Profile Assistant, you must use either the "standard" or "full" installation option for Internet Explorer 4.0. The Profile Assistant is available only on the Microsoft® Windows® 95 and Windows NT® versions of Internet Explorer 4.0.

Using the Profile Assistant

The purpose of the Profile Assistant is to make it easy for users to share registration and demographic information with sites that require this information. The goal is to eliminate the need for users to repeatedly enter information such as their address or e-mail name for each site's registration page. This is accomplished, while at the same time maintaining user privacy, by giving users complete control over access to their data. User information is stored securely in protected storage on the client computer. Web servers can request to read this information, but it is shared only if users give their consent in the Profile Assistant confirmation dialog box. This dialog box is required, and it is not possible to access this data without the user's permission.

Populating the client data store

In Internet Explorer 4.0, the user can enter data into the secure client profile storage by using an edit dialog box accessed through the Content tab in the View/Internet Options dialog box. This form allows the user to enter or change all data elements in the store. Note that the Profile Assistant is automatically populated with registration information collected from the user by Internet Explorer 4.0. If there is no data, or if you wish to edit the data previously collected, follow this simple process:

  1. Open the Internet Explorer 4.0 browser.
  2. From the View menu, select Internet Options.
  3. From the Internet Options dialog box, click the Content tab.
  4. On the Content tab, click the Edit Profile button.
  5. Enter or edit your information, and click OK.

The following illustration shows a typical Profile Assistant data entry.

Profile Assistant Data Entry

Authoring an HTML Form

Authoring an HTML form for use with the Profile Assistant is accomplished by adding some scripting code to an HTML page. This makes retrofitting existing forms easy. Note that if your registration page is viewed frequently in the same session, you may want to write some scripting code to ensure that the user is prompted only once. Please view the source for the sample page (Proftest.htm) shown in the next section.

Object model for the Profile Assistant

To be able to write scripts for the Profile Assistant, you need to first understand the Profile Assistant object and its associated methods. The object model consists of a single object, the userProfile object. This object is available to scripts running on Internet Explorer 4.0 through the HTML document object model as window.navigator.userProfile.

The following diagram shows the relation of objects in the object model.

    window
      |
      +---navigator
             |
             +---userProfile

Methods of the userProfile object

The userProfile object provides methods that allow a script to request read access to a user's profile information and also to perform read actions. Note that the requests are queued up before the action of reading or writing is performed. This simplifies the user's experience by prompting for profile release permissions once for a batch of requests. Web pages utilizing the Profile Assistant should follow this logic sequence:

  1. Use clearRequest to clear out the request queue.
    clearRequest();
  2. Perform a series of addReadRequests to fill the request queue with the items that will be requested from the client storage. This method uses a predefined attribute name as the parameter.
    addReadRequest("Vcard.FirstName");
  3. Issue a doReadRequest to prompt the user with the confirmation dialog box. When confirmed, return the requested data from the client store. Parameters are an integer (0-12) representing a standard usage code and optional strings for the header.
    doReadRequest(10, "XYZ Corp.");
  4. Access the data elements that have been pulled from the client with the getAttribute method. This method takes a predefined attribute name as a parameter and returns the user's stored value as a string.
    getAttribute("Vcard.FirstName");

Profile Assistant scripting examples

The following excerpt is an example of a script written in JScript that can be run on Internet Explorer 4.0 to read various values from the user's profile information store.

Note User profile attributes are specified with the format Vcard.attribute. The Vcard_attribute format is no longer supported by Internet Explorer 4.0.

// This ensures that the request queue is in a clean, known state.
navigator.userProfile.clearRequest();

// Queue up a request for read access to multiple profile attributes.
navigator.userProfile.addReadRequest("Vcard.FirstName");
navigator.userProfile.addReadRequest("Vcard.Gender");

// Request access to specific information via a confirmation dialog box.
navigator.userProfile.doReadRequest(usage-code, "Foobar Inc.");

// Perform read operations to access the information.
name = navigator.userProfile.getAttribute("Vcard.FirstName");
gender  = navigator.userProfile.getAttribute("Vcard.Gender");

// The script can now use the 'name' and 'gender' variables
// to personalize content or to send information back to the server.

An HTML page called Proftest.htm containing the HTML code shown in the next section is available in the Samples directory of the Internet Client SDK. This is a simple registration form that asks the user to enter a name, an e-mail address, and a telephone number. When navigating to this form, users will be prompted with a dialog box informing them that profile information is being requested. As you will see, there are several elements to this user interface:

  • The URL of the site requesting the user's information.
  • A list of all the data elements requested. The Profile Assistant allows the user to view exactly what information is being requested and to deliberately exclude information if desired.
  • The usage code that specifies how the data will be used by the site. An example would be "disclosed to others, who may contact you for marketing of services and/or products". A list of usage codes is provided with the doReadRequest documentation.
  • Information about the connection security. Since the user's information is transferred over the Internet, the data is only as secure as its connection. This identifies if data is transferred over an SSL connection and, if so, allows the user to verify the site identity by viewing the certificate.

The information provided on the dialog box helps the user verify who is requesting the data, choose which particular data elements (if any) to share with the Web publisher, and understand the intended usage as specified by the site. Clicking the OK button will add the information to the form. Users consenting to the information request will not be asked for confirmation when visiting this page later unless the "Always allow site to see checked items" box is cleared.

The following illustration shows the Profile Assistant confirmation dialog box.

Profile Assistant Confirmation Dialog Box

The following HTML file (Proftest.htm) shows how a simple page can be set up to populate a form with data requested from the user's profile. If the user chooses not to disclose information from one or more of the requested fields, those text fields will remain blank. An explanation of the script is provided after the listing of the entire HTML page.

Note This sample must be placed on an HTTP server to work properly. If the file is opened locally with the "file://" protocol, it will automatically access the profile data without requiring user consent.

<html>

<head>
<title>Sample Profile Assistant HTML</title>
</head>
<body>

<form method=POST action="http://www.foobar.com/cgi/bin/collectInfo">
<table>
  <tr>
    <td align="right">Last Name:       </td>
    <td align="left"><input type=text name=user  size=32 maxlength=80></td>
  </tr>
  <tr>
    <td align="right">Email:       </td>
    <td align="left"><input type=text name=email  size=32 maxlength=80></td>
  </tr>
  <tr>
    <td align="right">Phone #:       </td>
    <td align="left"><input type=text name=phone  size=16 maxlength=80></td>
  </tr>
  <tr>
    <td></td>
    <td><input type=submit></td>
  </tr>
</table>
</form>

<script language="JavaScript">

    var profile = navigator.userProfile;

    profile.clearRequest();

    profile.addReadRequest("Vcard.LastName");
    profile.addReadRequest("Vcard.Email");
    profile.addReadRequest("Vcard.Business.Phone");

    profile.doReadRequest(1,"foobar Inc.");

    var myForm = document.forms[0];

    myForm.elements["user"].value = profile.getAttribute("Vcard.LastName");
    myForm.elements["email"].value = profile.getAttribute("Vcard.Email");
    myForm.elements["phone"].value = profile.getAttribute("Vcard.Business.Phone");

    profile.clearRequest();

</script>

</body>
</html>

Following is a step-by-step explanation of the required elements for the Profile Assistant and how they are used in the preceding example.

var profile = navigator.userProfile;

Set the variable profile to be client.userProfile so less typing is required. This is an optional step.

profile.clearRequest();

Clear the queue of requests for profile information.

profile.addReadRequest("Vcard.LastName");
profile.addReadRequest("Vcard.Email");
profile.addReadRequest("Vcard.Business.Phone");

Queue up requests for user information. All fields the Web publisher wants to view should be added to the request queue at this time.

profile.doReadRequest(1,"Foobar Inc.");

Begin processing the current batch of read requests and display the user confirm/deny dialog box. This example shows that the Web publisher has specified a usage code of 1, indicating the data will be used for research and product development purposes. The name of the organization requesting this information is "Foobar Inc."

myForm.elements["user"].value = profile.getAttribute("Vcard.LastName");
myForm.elements["email"].value = profile.getAttribute("Vcard.Email");
myForm.elements["phone"].value = profile.getAttribute("Vcard.Business.Phone");

Populate the form input fields using the data obtained from the user with the getAttribute method.

profile.clearRequest();

Clear the queue of requests for profile information. This is an optional step.

When opened in the browser, the HTML file is displayed as:

Example HTML File


Tools

The tools in this section help Web publishers who are developing content for use with Microsoft® Internet Explorer 4.0.

Microsoft CDF Generator

Profile Assistant


Adding an Active Channel to the Desktop

Microsoft® Internet Explorer 4.0 includes a special Active Desktop item called the desktop Channel Bar. This item contains the 32W x 80H logos for all channels currently available on the user's computer. The desktop Channel Bar appears on the right side of the desktop by default and is visible only when the Active Desktop is enabled. The user can enable the Active Desktop by right-clicking the desktop and selecting the View as Web Page option from the Active Desktop menu. The desktop Channel Bar is pre-populated with channels and category folders containing groups of channels on related topics. The channel guide appearing in the desktop Channel Bar (shown below) contains a list of Active Channels and is maintained by Microsoft.

Desktop Channel Bar

As the user moves the cursor onto a LOGO image in the desktop Channel Bar, the image is presented as a 3-D button and displays the channel's ABSTRACT description in a ToolTip, if one is specified in the CDF file.

Users can add channels from three sources—a publisher's Web page, the Channel Guide, and preinstalled channels in the desktop Channel Bar. While browsing a Web site or a category in the Channel Guide, the user will encounter a link or image button that can be clicked to add the Active Channel to the desktop Channel Bar and optionally subscribe to the channel. Information on how to place an Add Active Channel logo button is available in the Creating Active Channels documentation.

The Add Active Channel button is shown here.

Add Active Channel button

Invoking the Add Channel Dialog Box

Immediately after users click the Add Active Channel button, the Add Channel dialog box is displayed. This gives users three options for how the channel will be set up on their computer, as follows:

  • Add the channel to the Channel Bar.

    This option simply adds the channel to the desktop Channel Bar. When the user clicks the channel logo, the browser launches into full-screen view and loads the URL specified by the CHANNEL element in the CDF file. Adding a channel with this option is similar to creating a favorite. The user can view the channel while he or she is online, but no content is available for offline viewing, and the content is not updated on the user's computer. Therefore, users are not notified when changes occur on this site.

  • Subscribe to the channel, but only notify the user when updates occur.

    This option updates the channel's CDF file according to a schedule set by the publisher with the SCHEDULE element in the CDF file, unless overridden by the user with a custom schedule. The user is notified that content has been updated by a "gleam" placed over the logo in the desktop Channel Bar and on the icons representing the individual content items. A user can optionally be notified of changes through e-mail. With this option, the channel's navigable hierarchy, or sitemap, is available for offline viewing, if one exists. However, clicking any of the channel's content requires a connection to the Internet because the content wasn't previously downloaded into the cache.

  • Subscribe to the channel, download the content for offline viewing, and notify the user when updates occur.

    A channel with this option set will place the channel's sitemap (if one exists) and the actual content of the channel in the user's cache. Similar to the second option, this type of subscription is updated according to the publisher's schedule unless the user overrides it. Therefore, the user can browse through the entire channel at any time, even when not connected to the Internet, and view the latest information since the last channel update. However, some content may not be available for offline viewing if the publisher has specified the PRECACHE="No" attribute on one or more items.

The Add Active Channel dialog box is shown below.

Add Channel Dialog

Running the Channel Subscription Wizard

If a channel subscription is selected, the user can click the Customize button to run the channel Subscription Wizard. This allows the user to modify the settings for the channel subscription. The first dialog box allows the user to specify whether the entire contents referenced in the CDF file should be downloaded, or just the main channel page. If the user chooses the latter, clicking any item exposed in the sitemap other than the main channel page would require a connection to the Internet, as the resources will not be available in the local cache.

The channel Subscription Wizard content selection is shown below.

Channel Subscription Wizard Content

Next, the user can select how content update notifications will be handled. By default, Internet Explorer uses the visual "gleams" to indicate new content. However, e-mail notification can also be sent to the user when the content is updated.

Channel Subscription Wizard Notifications

The final property set in the channel customization wizard is the update schedule for the CDF file and/or content, depending on the type of subscription selected. The user can select either daily, weekly, monthly, or the publisher's recommended update schedule option. If no recommended schedule exists in the CDF file, the default schedule is "Daily".

Channel Subscription Wizard Schedule

If the user connects to the Internet through a modem, the user must check the "Dial as needed..." box to enable the automatically scheduled updates when the user is offline. Modem users who don't enable the "Dial as needed..." option will receive channel updates only if the update occurs while they are online. Channels can be manually updated at any time by performing one of the following actions:

  • Right-click the channel logo in the desktop Channel Bar and select Update Now.
  • Select the Manage Subscriptions option from the Favorites menu and either right-click the item and select Update Now, or click the Update or Update All button in the toolbar.

Viewing the Active Channel Content

At this point, the user will return to the original Add Channel dialog box presented after the initial Add Active Channel button was clicked. When the user clicks the OK button, the channel subscription is updated, if one exists, and the browser opens the channel in full-screen view, as shown below.

Full-Screen View with Channels Pane

The full-screen view of the browser includes a toolbar at the top of the screen with a smaller set of navigational controls and a status bar. The autohiding Channels Explorer Bar is displayed on the left side of the screen when the channel is initially loaded and whenever the user places the cursor at the left edge of the screen. On screens 1024 x 768 and larger, the Channels Explorer Bar is continuously displayed by default. This behavior can be achieved on smaller screens by clicking the "pin" icon in the right side of the bar. This disables the autohide feature until the pin is clicked again. Note that when viewing a channel in a normal browser window without full-screen view enabled, the Channels Explorer Bar does not autohide.

The ToolTip shown in the following picture is specified in the channel's CDF file using the ABSTRACT element, and it is displayed when the user pauses the mouse over that item.

Notice that the hierarchy of the channel just added is now expanded to show the first level of subchannels and items. Clicking a subchannel further expands the current channel hierarchy displayed in the sitemap to show its contents. The user can select any of these exposed items to navigate to the associated Web page, similar to using the Favorites menu. When the user selects a different channel, the previously selected channel hierarchy contracts in the channel pane, and the newly selected one expands to show any items and subchannels it contains. The Channels Explorer Bar also replaces the previous channel's logo with the title of the channel in plain text, and it now displays the logo of the newly selected channel. The first example below shows the user switching to the News and Technology category folder, and in the second example switching back to the Internet Client SDK channel.

Switching back to the first channel

Although the full-screen view shown above is the default viewing mode for Active Channels, users can navigate through a channel in a normal browser window. To toggle the full-screen view on or off, users can either click the Full Screen button located on the standard button toolbar or select Full Screen on the View menu.

The following illustrates the channel in normal view.

Channel in normal view

Active Channel Screen Savers

Channel publishers can designate Web pages as screen saver pages in CDF files by setting the VALUE="ScreenSaver" attribute on the USAGE element. These pages rotate through the Internet Explorer screen saver with equal display times while the computer is idle. By default, the screen saver page from each channel is shown for 30 seconds before moving on to the next channel.

Active Channel Screen Saver

The user can move the mouse without closing the Channel Screen Saver page. This allows users to navigate to a URL by clicking HTML links displayed on the screen saver page. Web publishers can use the Channel Screen Saver page to provide users with all the latest information because the screen saver is a URL that is downloaded to users' computers on a regular basis. To close the Channel Screen Saver, the user can press any key or click the "x" appearing in the autohide toolbar in the upper-right corner of the screen. This toolbar also allows users to change the screen saver properties as shown below.

Note If the Channel Screen Saver is not enabled when subscribing to a channel containing a screen saver page, users will be asked if they would like to enable it.

Accessing Installed Channels

Now that the channel has been added to the user's computer, a logo image representing a shortcut to the Internet Client SDK channel has been placed just below the channel guide in the desktop Channel Bar, as shown below.

Desktop Channel Bar

When the user clicks the Internet Client SDK logo button, the browser launches the channel's associated URL into the Internet Explorer full-screen view. Channels can also be accessed by clicking the "View Channels" icon in the quick-link launch bar located in the task bar next to the Start button. Clicking this icon opens the browser in full-screen view and loads the most recently viewed channel.

Removing an Active Channel

To remove a channel, the user simply right-clicks an icon or logo image representing the channel and selects Delete from the context menu. Items representing a channel can be found in the following places:

  • The desktop Channel Bar
  • The Channels Explorer Bar
  • The \WINDOWS\Profiles\username\Favorites\Channels folder

This will remove the logo images from the desktop Channel Bar and the Channels Explorer bar, as well as remove the channel's subscription (if any) from the \WINDOWS\Subscriptions folder.

Managing an Active Channel Subscription

Channel subscriptions provide a way for users to automatically receive updated information about a channel. Users can choose to subscribe to just the hierarchy of the channel or to have the content delivered as well. The Subscription tab provides a summary of the channel subscription information and offers the option of unsubscribing from the channel. If the user chooses to unsubscribe, the channel remains in the desktop Channel Bar as a link to the main channel page, but no content is updated in the local cache with a CDF file. This is equivalent to selecting the first option, "Just add to my channel bar," when adding a channel.

To view or modify a channel subscription, hold down the right mouse button on an icon or logo image representing a channel and select Properties from the context menu. Channel icons can be accessed by selecting the "Manage Subscriptions..." option from the Favorites menu, and logos can be accessed from the desktop Channel Bar or Channels Explorer Bar.

The following is an example of subscription properties.

The Receiving tab on the subscription properties allows users to modify the type of subscription (with or without content), e-mail notifications, and login information for the associated Active Channel.

The following is an example of receiving properties.

When channels with full subscriptions are actually updated, the default behavior is to download all content specified in a channel to the local cache, along with designated screen saver files specified in the CDF. The type of content downloaded by default includes the HTML page (or URL) indicated in the ITEM element of the CDF file and any image files it displays. However, users can manage the amount and type of data being sent to their computer by selecting the "Advanced..." button on the Receiving tab. The Advanced Download Options dialog box, shown below, allows users to enable and disable whether images, sounds, video, Java applets, and ActiveX™ Controls used in an HTML page automatically get downloaded to their local cache.

Advanced Download Options

Web publishers can require files to be downloaded as part of the channel by specifying each one in an ITEM element, regardless of the Advanced Download Options settings. If the required resource is not intended to be exposed in the hierarchy displayed in the Channels Explorer Bar, the USAGE element should be included as a child element of the item with its value set to "None".

The Schedule tab allows users to modify the schedule on which the channel's CDF file and content (for full subscriptions) is updated. Besides the publisher's recommended schedule, users can select a standard daily, weekly, or monthly schedule. The "New..." and "Edit..." buttons are provided for creating custom schedules.

The following is an example of schedule properties.

Note Modem users must check the "Dial as needed..." check box to use the publisher's recommended schedule.


Active Channels

This document describes how users interact with Active Channels for Microsoft® Internet Explorer 4.0. Details are provided on how users add and remove channels from their desktop, as well as how channel subscriptions are managed.

Introduction to Active Channels

Adding an Active Channel to the Desktop

Removing an Active Channel

Managing an Active Channel Subscription

Introduction to Active Channels

An Active Channel is a Web site described by a Channel Definition Format (CDF) file. The information contained in the CDF includes the hierarchy of the Web pages and resources available for that channel, as well as a schedule recommended by the Web publisher for updating the information in the channel. This document describes the user interface associated with Active Channels, including how users can manage their channels. CDF elements corresponding to a specific feature or user interface element are indicated where applicable. For demonstration purposes, the Internet Client SDK channel is used throughout this document. This channel is available by navigating to Channel Preview with Internet Explorer 4.0 and clicking the Add Active Channel button. Note that some of the images and text shown for this channel are subject to change.

Note Additional information on channels and CDF files is available in Content Delivery Mechanisms, Creating Active Channels, and the CDF Reference for Active Channels.


Active Desktop Items

Active Desktop™ items are small Web pages or HTML components, such as a Java applet or an ActiveX™ control, that are displayed directly on the desktop. This document describes how users interact with Active Desktop items, including adding an item to the desktop, removing an item, managing an item subscription, and moving or resizing an item. For further explanation of Active Desktop items, see Creating Active Desktop Items.

Adding an Item to the Active Desktop

Managing Active Desktop Item Subscriptions

Moving and Resizing

Enabling and Disabling Desktop Items

Adding an Item to the Active Desktop

Users can customize their desktop by installing Active Desktop items designed for Microsoft® Internet Explorer 4.0. Users add these items by clicking an Add to Active Desktop button on a Web page, or by using the right mouse button to drag an icon in Internet Explorer's address or title bar to the desktop. Users also have the option of manually specifying a URL for an image or floating frame by selecting the Web option tab in the Display Properties Control Panel and clicking the New button. Items added to the desktop manually by the user will have static content unless the user subscribes to that item. An Active Desktop item can be subscribed to by selecting the item in the Web tab of the Display Properties dialog box and then clicking the Properties button followed by the Subscribe button.

Typically, users will encounter a Web page that offers an Active Desktop item related to the Web publisher's content and a button that, when clicked, adds the item to the users' Active Desktop. The button itself is linked to the item's Channel Definition Format (CDF) file. After clicking the button, the user will be presented with a dialog box (shown below) confirming the creation of this item on the Active Desktop. Once confirmed, Internet Explorer downloads the necessary resources and displays the item on the Active Desktop.

Confirmation Dialog Box

Note If the item doesn't appear on the Active Desktop, position the cursor on the desktop and click the right mouse button to bring up the context menu. Under the Active Desktop menu, make sure the View as Web Page option is checked.

Before confirming the addition of the Active Desktop item, users can modify the item's update schedule by clicking the Customize Subscription button. The user should accept the default schedule set up by the desktop item's publisher whenever possible. The dialog box presented to the user is shown below.

Managing Active Desktop Item Subscriptions

When adding an Active Desktop item with a CDF file to the desktop, a subscription for that item is created in the \Windows\Subscriptions folder. The user can easily access the subscription by selecting the Manage Subscriptions option from the Internet Explorer Favorites menu. Right-clicking the mouse on a subscription brings up the context menu for that item, allowing the user to update the item immediately, delete the subscription, or view and modify its properties. Active Desktop item subscription properties can also be accessed by selecting Properties on the menu on the desktop item itself. This menu bar appears when the cursor is placed near the top of the item.

It is important to note that deleting an item's subscription won't remove it from the desktop. To permanently delete an item, users select the Display Properties Control Panel and click the Web tab. From the list of "Items on the Active Desktop," users select the item to be removed and click the Delete button.

Display Properties Control Panel

The "New..." button allows users to manually create a desktop item that points to any valid URL. Additionally, a desktop item can be enabled or disabled by clicking the check box to the left of each item in the list.

Moving and Resizing

The user can move or resize any Active Desktop item. To make this feature easily discoverable, move and resize features have been implemented so they become available as soon as the user moves the mouse over an item. To move an Active Desktop item, the user must position the cursor near the top edge of the item to expose a bar. When the bar appears, the user holds down the mouse button on the bar and moves the mouse to reposition the item on the desktop.

This illustration shows an Active Desktop item.

Active Desktop Item

This illustration shows an Active Desktop item with mouseover focus.

Active Desktop Item with Mouseover Focus

To resize an Active Desktop item, the user positions the mouse cursor over any edge of the rectangular, 2-D HTML layer that contains the item. The cursor then changes to one of the standard directional resize cursors, and the user can drag it to change the size. However, if the desktop item CDF includes one of the CANRESIZE, CANRESIZEX, or CANRESIZEY elements with a value of "No", resizing the item is restricted or disallowed completely. In this case, the resize cursor will only appear for the resize-enabled axis, if one exists.

Enabling and Disabling Desktop Items

Users can disable an Active Desktop item either by unchecking it in the list of desktop items under the Web tab in the Display Properties Control Panel or by clicking the "x" in the bar at the top of the item. This autohide bar appears only when you pause the cursor over the top edge of the item. To reenable an item, users must access the Display Properties Control Panel and click the check box next to the item to be displayed.


Software Update Channels

Software Update Channels provide users with a mechanism for receiving software updates over the Web. If the user chooses, the subscription can be set up to automatically download and install the software when it becomes available. This document describes the user interface associated with Software Update Channels. Further information is available on Creating Software Update Channels and VERSION= (SOFTPKG)
.

Software Channels in the Internet Explorer User Interface

Channels Under the Favorites Menu

Adding a Software Update Channel

Software Channel Update Notification

Software Channels in the Internet Explorer User Interface

The Microsoft® Internet Explorer 4.0 user interface offers two views of the Software Update Channels located in the folder \WINDOWS\Profiles\username\Favorites\Software Updates:

  • The "Software Updates" folder located in the Favorites menu.
  • The "Software Updates" folder in the Favorites Explorer Bar. This view is accessed either by selecting Explorer Bar/Favorites in the View menu, or by clicking the Favorites button in the standard Internet Explorer toolbar.

Channels Under the Favorites Menu

The Favorites menu contains two folders for channel subscriptions: the "Software Updates" folder contains software subscriptions, while the "Channels" folder contains Active Channel subscriptions. Internet Explorer separates software subscriptions from Active Channel subscriptions because the two usually have very different update frequencies.

Many Active Channel subscriptions are set up to receive the latest news stories, business reports, and entertainment information. An Active Channel can send out updates several times a day. Therefore, the user should expect frequent update activity in the "Channels" folder.

On the other hand, a user would not expect to see updated subscriptions in the "Software Updates" folder on a daily basis. Software subscriptions are updated only when a new version of the subscribed software becomes available. With that in mind, users should expect a software channel to update once every few weeks, or even months.

Adding a Software Update Channel

Adding a software channel to the "Software Updates" folder is similar to adding an Active Channel. Users will be presented with an image button or link that references the CDF file for the software channel. Upon clicking the button, users will be presented with the Add Software Update Channel dialog box.

Add Software Channel Dialog Box

At this point, users can choose whether they want to subscribe to the software channel or not. Software Update Channel subscriptions will notify the user whenever the new software is available and, if the user chooses, will also download the software.

Software Channel Update Notification

Internet Explorer uses a "gleam" placed on the channel icon as the basic method for notifying users that a channel subscription contains updated content or software. The icon representing a channel in the "Software Updates" folder will have a red gleam overlaid on it when that channel is updated. Because the Internet Explorer interface provides multiple ways to access software subscriptions, the icon gleam is seen in the "Software Updates" folder, the \WINDOWS\Subscriptions folder, and the Favorites Explorer Bar.

Although the icon gleam is the default notification method for channel updates, the user can choose to be notified by e-mail as well. When a subscription is updated, the user receives e-mail with a short summary describing the update. The user's e-mail address can be specified at subscription time, or it can be specified later by modifying the properties of the software channel's subscription. To access the software channel's properties, hold the right mouse button down on the CDF file and select Properties. The CDF can be accessed by either selecting "Manage Subscriptions..." or the "Software Updates" folder located on the Favorites menu. Note that the context menu used to access the properties of the software channel can also be used for other functions, such as immediately updating or deleting the channel.

In addition to gleams and e-mail notifications, Internet Explorer 4.0 provides the underlying mechanism, using Software Update Channels, for an application to check its own update availability status. When an update is detected, the application can notify the user by presenting a dialog box alert at the time the application is launched.


The User Experience

The documents in this section describe the Microsoft® Internet Explorer 4.0 user interface elements for these content delivery mechanisms.

Active Channels

Active Desktop Items

Software Update Channels


Dynamic HTML

Dynamic HTML is a set of innovative features in Microsoft® Internet Explorer 4.0. By enabling authors to dynamically change the rendering and content of a document, Dynamic HTML gives authors the ability to create visually outstanding HTML documents that interact with the user without the burden of relying on server-side programs or complicated sets of HTML pages to achieve special effects.

With Dynamic HTML, you can easily add effects to your documents that were previously difficult to achieve. For example, you can:

  • Hide text and images in your document and keep this content hidden until a given time elapses or the user interacts with the page.
  • Animate text and images in your document, independently moving each element from any starting point to any ending point, following a path that you choose or that you let the user choose.
  • Create a ticker that automatically refreshes its content with the latest news, stock quotes, or other data.
  • Create a form, then instantly read, process, and respond to the data the user enters in the form.

Dynamic HTML achieves these effects by modifying the current document and automatically reformatting and redisplaying the document to show changes. It does not need to reload the document or load a new document, or require a distant server to generate new content. Instead, it uses the power of the user's computer to calculate and carry out changes. This means a user does not have to wait for text and data to complete time-consuming round-trips to and from a server before seeing results. Furthermore, Dynamic HTML does not require additional support from applications or embedded controls to carry out changes. Typically, Dynamic HTML documents are self-contained, using styles and a little script to process user input and directly manipulate the HTML tags, attributes, styles, and text in the document.

The HTML elements, attributes, and styles in Dynamic HTML are based on existing HTML and cascading style sheet (CSS) specifications. Users can view your documents whether they use Internet Explorer version 4.0 or some other browser. Naturally, the dynamic and interactive features that you add to your documents may not be fully functional when viewed with a browser that does not support Dynamic HTML. But Dynamic HTML is designed to "degrade gracefully"—by following some basic guidelines, the content of your document can be viewable in other browsers.

Dynamic HTML works well with applications, ActiveX™ Controls, and other embedded objects. You can use existing applications and controls, or you can create new ones that specifically take advantage of the features of Dynamic HTML. Applications and controls work best when you rely on them to do computationally difficult tasks, and use Dynamic HTML to display output and process user input. For example, you can create a document that lets the user query, display, and modify the content of a large, server-based database by combining the data binding features of Dynamic HTML with a data source object. The data source object retrieves and sets data in a database, and Dynamic HTML does the rest: processing user queries, displaying the data, and carrying out the necessary interaction with the object.

In short, Dynamic HTML eliminates the shortcomings of previous browser technologies. Authors can create innovative Web sites, whether on the Internet or an intranet, without having to sacrifice performance for interactivity and special effects. Not only does Dynamic HTML enhance the user's perception of your documents, it also improves server performance by reducing requests to the server and subsequently server load.

The following topics explain Dynamic HTML in more detail and introduce you to the topics in this section that will help you begin using Dynamic HTML.

  • Dynamic Styles
  • Dynamic Content
  • Positioning and Animation
  • Filters and Transitions
  • Font Download
  • Data Binding
  • Dynamic HTML Object Model

Microsoft is working with Internet standards bodies such as the W3C (World Wide Web Consortium) to provide the best standards-based solutions that make the Web a better open environment for building efficient and interactive multimedia content. Dynamic HTML represents the next step in that effort—all the HTML and CSS extensions for Dynamic HTML conform to W3C specifications or have been submitted to the W3C for consideration. Microsoft will enhance future versions of Internet Explorer to conform to future specifications recommended by the W3C.

Dynamic Styles

Dynamic styles are a key feature of Dynamic HTML. By using styles and style sheets, you can quickly change the appearance and formatting of elements in a document without adding or removing elements. This helps keep your documents small and the scripts that manipulate the document fast.

The object model gives you programmatic access to styles. This means you can change inline styles on individual elements and change style rules in a document's cascading style sheets (CSS) using simple script-based programming. These scripts can be written in JavaScript, JScript, or VBScript.

Inline styles are CSS style assignments that have been applied to an element using the STYLE attribute. You can examine and set these styles by retrieving the style object for an individual element. For example, if you want to highlight the text in a heading when the user moves the mouse over it, you can use the heading's inline style to enlarge the font and change its color, as in the following simple document.

<HTML>
<HEAD><TITLE>Dynamic Styles</TITLE>
<SCRIPT LANGUAGE="JScript">
function doChanges() {
    window.event.srcElement.style.color = "green";
    window.event.srcElement.style.fontSize = "20px";
}
</SCRIPT>
<BODY>
<H3 ID=heading onmouseover="doChanges()" STYLE="color:black;font-size:18">Welcome to Dynamic HTML!</H3>
<P>You can do the most amazing things with the least bit of effort.
</BODY>
</HTML>

In the above example, the process (also known as an event handler) that responds when the onscreen cursor moves over an HTML tag that contains a onmouseover statement receives control when the user first moves the mouse into the heading (known as an event). The handler uses the srcElement property of the event object to determine which element is the source of the event (in this case, the H3 element). It then uses the color and fontSize properties of the style object for the element to change the color and font size. Setting these properties changes the CSS "color" and "font-size" attributes given in the STYLE attribute for the heading, and the browser immediately updates the onscreen text to show these new attribute values.

By using styles, you can create a simple document, such as the following, in which all items in a bullet list are hidden until the user clicks the mouse.

<HTML>
<HEAD><TITLE>Dynamic Styles</TITLE>
<SCRIPT LANGUAGE="JScript">
function showMe() {
    document.all.MyHeading.style.color = "red";
    document.all.MyList.style.display = "";
}
</SCRIPT>
<BODY onclick="showMe()">
<H3 ID=MyHeading>Welcome to Dynamic HTML!</H3>
<P>You can do the most amazing things with the least bit of effort. Just click and see!
<UL ID=MyList STYLE="display:none">
<LI>Change the color, size, and typeface of text
<LI>Show and hide text
<LI>And much, much more
</UL>
<P>And this is just the beginning!
</BODY>
</HTML>

In the above example, the CSS display attribute is set to "none", causing the UL list to be hidden from view. When the user clicks the document, the event handler clears the value of this attribute, making the browser display the list onscreen. Notice how any content that comes after the list shifts down to accommodate the new text rendering.

Dynamic styles are based on the W3C Recommendation for Cascading Style Sheets (CSS) specification for static style sheets. For a list of topics that describe and explain dynamic styles in full detail, see Dynamic Styles.

Dynamic Content

With Dynamic HTML, you can change the content of a document after it is loaded. Internet Explorer gives you a rich set of properties and methods to dynamically construct and alter documents, from inserting and deleting elements to modifying the text and attributes in individual elements.

The Dynamic HTML object model gives you access to all elements in the document. Consider the following simple document. You can replace and change elements as well as change colors and text by using a few lines of script.

<HTML>
<HEAD><TITLE>Welcome!</TITLE>
<SCRIPT LANGUAGE="JScript">
function changeMe() {
    document.all.MyHeading.outerHTML = "<H1 ID=MyHeading>Dynamic HTML!</H1>";
    document.all.MyHeading.style.color = "green";
    document.all.MyText.innerText = "You can do the most amazing things with the least bit of effort.";
    document.all.MyText.align = "center";
    document.body.insertAdjacentHTML("BeforeEnd", "<P ALIGN=\"center\">Just give it a try!</P>");
}
</SCRIPT>
<BODY onclick="changeMe()">
<H3 ID=MyHeading>Welcome to Dynamic HTML!</H3>
<P ID=MyText>Click anywhere on this page.</P>
</BODY>
</HTML>

When the user clicks on the page above, the script replaces the H3 element with an H1 element, centers the paragraph, and inserts a new paragraph at the end of the document. Using script in this way, you can add, delete, and replace any elements and text in the document.

For a list of topics that describe and explain dynamic content in full detail, see Dynamic Content.

Positioning and Animation

Positioning is the ability to place an HTML element at a specific point in a document by assigning an x- and y-coordinate and a z-plane to that element. This means you can place elements—images, controls, and text—exactly where you want them and achieve special, overlapping effects by defining in what order elements at the same point should be stacked atop one another.

Positioning is an extension of cascading style sheets. This means that you set the position of an element by setting the appropriate CSS attributes for that element. The following simple document shows how you can set the absolute position of an image.

<HTML>
<HEAD><TITLE>Positioning</TITLE>
<BODY>
<H3>Welcome to Dynamic HTML!</H3>
<P>With positioning, you can place images exactly where you want them, even behind text and other images.
<IMG STYLE="position:absolute;top:0; left:0; z-index:-1" SRC="banner.gif">
</BODY>
</HTML>

In the above example, the image is placed at the top left corner of the document. Setting the z-index attribute to -1 causes the image to be placed behind the text on the page.

Internet Explorer 4.0 supports positioning and animation of elements even after a document has been loaded. Because the object model gives you access to styles and style sheets, you can set and change the position of an element as simply as you set and change its color. This makes it especially easy to change the position of elements based on how the user is viewing the document, and to even animate the elements. For animation, all you need is to slightly modify the position of an element on some interval. For example, the following document presents an image that glides across the top of the document and comes to rest at the upper-left corner.

<HTML>
<HEAD><TITLE>Dynamic Positioning</TITLE>
<SCRIPT LANGUAGE="JScript">
var id;
function StartGlide()
{
    document.all.Banner.style.pixelLeft =
        document.body.offsetWidth;
    document.all.Banner.style.visibility = "visible";
    id = window.setInterval("Glide()",50);
}
function Glide()
{
    document.all.Banner.style.pixelLeft -= 10;
    if (document.all.Banner.style.pixelLeft<=0) {
        document.all.Banner.style.pixelLeft=0;
        window.clearInterval(id);
    }
}
</SCRIPT>
<BODY onload="StartGlide()">
<H3>Welcome to Dynamic HTML!</H3>
<P>With dynamic positioning, you can move images anywhere in the document even while the user views the document.
<IMG ID="Banner" STYLE="visibility:hidden;position:absolute;top:0; left:0; z-index:-1" SRC="banner.gif">
</BODY>
</HTML>

In this example, the "StartGlide" function is called when the document is loaded. The function sets the absolute position of the "Banner" image to the top and far right edge of the document body, shows the image, and starts an interval. The "Glide" function is called repeatedly in 50-millisecond intervals. The function moves the image to the left by 10 pixels, and when the image is finally at the left edge, it cancels the interval.

Dynamic positioning has many uses in consumer and business applications. By combining dynamic styles, positioning, transparent images, and transparent ActiveX Controls, you can present a rich set of animation effects in your documents.

Dynamic positioning and animation is based on the W3C Working Draft on Positioning HTML with Cascading Style Sheets and will be adapted as needed to conform to the final recommendation. Documents that use positioning will be compatible with browsers that support this standard.

For a list of topics that describe and explain CSS positioning in full detail, see Positioning.

Filters and Transitions

Internet Explorer 4.0 supports an extensible architecture that enables you to specify filters and transitions using CSS properties. Visual filters can be used to apply visual effects to an element without requiring any scripts. The syntax is:

filter: filter_name( param1, param2, ...)

Transitions are effects that can be applied when changing the display of an element—switching from one image to another, for example. Both interpage transitions and transitions on specific elements within a page are supported. Transitions are most commonly seen in "slide show" presentations. Filters are effects (such as text drop shadows) that can be applied to content on Web pages. In addition to the set of standard filters and transitions included in Internet Explorer 4.0, the standard filters and transitions can be supplemented by additional third-party filters and transitions. For more information on filters, see Creating Multimedia Effects with Visual Filters and Transitions.

Font Download

Internet Explorer 4.0 supports the use of dynamically downloaded fonts. Using the @font-face style attribute, a document can reference a font that is automatically downloaded, used for the page only, and discarded once the page is no longer displayed. The following example shows the use of downloaded fonts.

<HTML><HEAD>
<STYLE>@font-face {font-family:comic;0 src:url(http://abc.domain.com/fonts/comicbold.eot);}
</STYLE>
</HEAD>
<BODY>
<p style="font-family:comic;font-size:18pt">this line uses the @font-face style element to display this text using the Comic Sans MS font in 18-point size and bold.
<p>
</BODY></HTML>

Data Binding

Data binding is a great feature of Dynamic HTML that lets you easily bind individual elements in your document to data from another source, such as a database or comma-delimited text file. When the document is loaded, the data is automatically retrieved from the source and formatted and displayed within the element.

One very practical way to use data binding is to automatically and dynamically generate tables in your document. You can do this by binding a TABLE element to a data source. When the document is viewed, a new row is created in the table for each record retrieved from the source, and the cells of each row are filled with text and data from the fields of the record. Because this generation is dynamic, the user can view the document even while new rows in the table are being created. Additionally, once all the table data is present, you can manipulate the data, such as sorting or filtering, without requiring the server to send additional data. The table is simply regenerated, using the previously retrieved data to fill the new rows and cells of the table.

Another practical use is to bind one or more elements in the document to specific fields of a given record. When the document is viewed, the elements are filled with text and data from the fields in that record, sometimes called the "current" record. A simple example is a form letter in which the name, e-mail address, and other details about an individual are filled from a database. To adapt the letter for a given individual, you simply specify which record should be the current record. No other changes to the letter are needed.

Yet another practical use is to bind the fields in a form to fields in a record. Not only can the user view the content of the record, but the user can also change that content by changing the settings and values of the form. The user can then submit these changes so that the new data is uploaded to the source—for example, to the HTTP server or database.

To provide data binding in your documents, you must add a data source object to your document. This invisible object is simply an ActiveX control or Java applet that knows how to communicate with the data source. Microsoft provides two data source objects with Internet Explorer 4.0: one to access comma-delimited data in text files, and another to access SQL data in SQL Server and other ODBC sources. Additional data source objects, such as a JDBC data source, will also be available from Microsoft and third parties.

The following simple document shows how easy it is to bind to a data source. When viewed, this document displays the first three fields from all the comma-delimited records of the file "sampdata.csv" in a clear, easy-to-read table.

<HTML>
<BODY>
<OBJECT CLASSID="clsid:333C7BC4-460F-11D0-BC04-0080C7055A83" ID=sampdata>
   <PARAM NAME="DataURL" VALUE="sampdata.csv">
   <PARAM NAME="UseHeader" VALUE="True">
</OBJECT>
<TABLE BORDER=1 DATASRC="#sampdata">
<THEAD>
<TR><TH>First Field<TH>Second Field<TH>Third Field
<TBODY>
<TR><TD><SPAN DATAFLD=A></SPAN><TD><SPAN DATAFLD=B></SPAN><TD><SPAN DATAFLD=C></SPAN>
</TABLE>
</BODY>
</HTML>

For a list of topics that describe and explain data binding in full detail, see Data Binding.

Dynamic HTML Object Model

The object model is the foundation of Dynamic HTML, providing the interface that allows scripts and components to access Dynamic HTML features.

Using the object model, you can access and manipulate virtually anything within the document. The HTML elements in the document are available as individual objects, meaning you can examine and modify an element and its attributes by reading and setting properties and by calling methods. The text is available through properties and methods on the elements.

The object model also makes user actions, such as pressing a key and clicking the mouse, available as events. You can intercept and process these and other events by creating event handler functions and routines. The event handler receives control each time a given event occurs and can carry out any appropriate action, including using the object model to change the document.

The following simple HTML document shows how you can use the object model to modify a document. This document changes the color of the heading and adds a line of text when the user clicks the mouse in the document.

<HTML>
<HEAD><TITLE>Welcome!</TITLE>
<SCRIPT LANGUAGE="JScript">
function changeMe() {
    document.all.MyHeading.style.color = "green";
    document.all.MyText.innerText = "You can do the most amazing things with the least bit of effort.";
}
</SCRIPT>
<BODY onclick="changeMe()">
<H3 ID=MyHeading>Welcome to Dynamic HTML!</H3>
<P ID=MyText>Click anywhere in this document.</P>
</BODY>
</HTML>

The example above contains an event handler, named "changeMe", that processes mouse clicks for the document. The handler uses the all collection of the document object to pick out the H3 and P elements using their ID values. It changes the color of the heading by setting the color property of the style object for that element. It replaces the text in the paragraph by setting the innerText property.

The object model is a superset of the JavaScript object model found in Netscape Navigator. This means that portions of the model are compatible with other browsers, even if they do not support Dynamic HTML. By following basic guidelines, you can write scripts that take full advantage of the object model when run in Internet Explorer and that provide reasonable results when run in browsers that do not support Dynamic HTML.

For lists of topics describing important aspects of the object model, see Working with Windows, Frames, and Dialogs, Scripting with Elements and Collections, and Understanding the Event Model.

For a complete listing of the objects, properties, methods, collections, and methods of the object model, see DHTML References.

Recommended Reading

Dynamic HTML provides authors with total creative control over all aspects of an HTML document. It extends traditional HTML and cascading style sheets to let you access and manipulate all elements of a document—tags, attributes, styles, images, objects, and text—creating, moving, and modifying these elements when and as needed.

If you are not familiar with HTML, cascading style sheets, and scripting languages, you should review the following documents before creating your own Dynamic HTML pages.

  • HTML 3.2 Reference Specification
  • W3C Recommendation for Cascading Style Sheets (CSS)
  • W3C Working Draft on Positioning HTML with Cascading Style Sheets
  • VBScript Tutorial & VBScript Language Reference
  • JScript Tutorial & JScript Language Reference


DHTML Accessibility

Writing Accessible Dynamic HTML with Internet Explorer 4.0

Because traditional HTML describes the structure as well as the content of a Web page, it has been easy in the past to create tools that make Web pages largely accessible to people with disabilities. Dynamic HTML gives Web pages many more capabilities, including enhanced support for accessibility. Authors writing interactive Dynamic HTML pages can ensure that their Web pages remain accessible for all people by following a few simple tips.

What Is an Accessible Web Page?

Accessibility problems arise in the interaction between the user and the Web page. The problems involve difficulty either in viewing the content of the page—for example, blindness or low vision—or in providing input to interact with the page—the most common being the inability to maneuver a mouse. Web pages are accessible if they allow alternate methods for both viewing the page and providing input to the page.

The first requirement for accessibility is that the page can be represented nonvisually. Programs called screen readers are used in conjunction with Microsoft® Internet Explorer to represent the page to the user through a sense other than sight, such as sound (voice synthesizer) or touch (Braille). A second requirement for accessibility is that the Web page allows keyboard/alternative-input access to all parts of the page that can be clicked by the mouse.

Internet Explorer, by taking advantage of HTML's structural nature, makes most Web pages accessible automatically. For example, the A tag indicates which areas on the page can be clicked, so Internet Explorer automatically allows the user to tab to any A tag. The A tag also encloses text that Internet Explorer can provide to a screen reader, which can in turn use the text to describe the link to the user.

There are some potential difficulties, however, that can hinder the ability of Internet Explorer to expose a Web page in an accessible manner. Implementing the following tips helps avoid these problems.

Tip#1: Use A tags for all textual areas on the page that respond to a mouse click

Although you can associate a click event with nearly any text element using Dynamic HTML, for accessibility reasons this should be done only on A tags. This allows the keyboard user to navigate to these areas using the keyboard and also gives hints that allow screen readers to know which parts of the Web page are interactive. An additional benefit to using the A tag to denote areas that can be clicked is that the mouse cursor automatically changes to the "hand" cursor when hovering over these areas.

A tags normally navigate to another Web page or bookmark when clicked. To avoid this, set the returnValue property of the window.event object equal to FALSE in the script that runs when the anchor is clicked. This causes the default action (navigating) to be canceled.

To run a specific Visual Basic® Scripting Edition (VBScript) function when an A tag is clicked, use the following syntax:

<A HREF="" ID=anchor1>Click here</A>
<SCRIPT LANGUAGE=vbscript>
function anchor1_onclick

    msgbox "you clicked on anchor1"
    window.event.returnValue=FALSE

end function
</SCRIPT>

Tip #2: Use the LABEL tag to associate text with intrinsic controls

In the HTML 3.2 specification, there was no way for an author to associate text with an intrinsic control such as a radio button or text box. Unlike an A tag, which has an accompanying /A tag and encloses text, the INPUT tag does not have an /INPUT tag. Therefore, screen readers have a difficult time finding exactly what text to use to describe the control to the user. HTML 4.0 introduces the LABEL tag, which allows the author to associate text with another HTML element. This is particularly useful for associating text with intrinsic controls. Whenever an intrinsic control is used on a page, it should be accompanied by a LABEL tag containing its associated text. Doing so provides an additional benefit: clicking the label toggles the value of the associated intrinsic control.

To associate a LABEL tag with a radio button, use the following HTML syntax:

<FORM>
<INPUT TYPE=radio ID=FirstButton NAME=radio1>
  <LABEL FOR=FirstButton>I'm the text for the first radio button</LABEL><BR>
<INPUT TYPE=radio ID=SecondButton NAME=radio1>
  <LABEL FOR=SecondButton>I'm the text for the second radio button</LABEL>
</FORM>

Tip #3: Always assign values for the TITLE attribute of items such as AREA or BGSOUND

The HTML 4.0 TITLE attribute allows the author to specify additional descriptive information about an HTML tag. This capability is particularly important for elements that do not normally have textual information associated with them, such as the AREA tag, which is used to designate a region of an image map, and the BGSOUND tag, which specifies a sound file to play in the background for a Web page. The TITLE attribute should always be used when dealing with these tags. For example:

<BGSOUND SRC="soundfile.mid" TITLE="Sound of falling water">

Tip #4: When using CSS positioning, be sure to specify your coordinates in "em" units

An important part of IE 4.0's Dynamic HTML, CSS positioning allows you to specify exactly where you want an HTML element to appear on the screen. Problems can arise, however, if the user changes the default font size or overrides the font sizes on a Web page. In that case, absolutely positioned elements can increase in size and overlap unless they are created properly. Specifying the position of objects using "em" units helps to solve this problem. Ems are measurement units like inches or pixels, except that they change based upon the default font size. In other words, when the default font size goes up, the value of one em increases as well. Content positioned and sized in ems correctly adjusts for the increased font size.

For example, to specify a <DIV> tag that is absolutely positioned, you can use the following syntax:

<DIV STYLE="position: absolute; left: 10em;top: 12em;height: 5em; width: 5em">Here is some positioned text!</DIV>

Ems tend to be quite large units compared to something like pixels. A good rule of thumb is that 1 em is roughly equivalent to 10 pixels for the standard font size.

Tip #5: Test positioned HTML for accessibility

Here are some test cases for the accessibility of positioned objects. When creating pages that use HTML elements positioned in ems, try changing between the Windows display settings for font size to both "Small Fonts" and "Large Fonts." Also, go to the Accessibility options in the Internet Options dialog and choose "Ignore Font sizes specified on web pages." Then set IE's font size on the View menu to "Largest." A final test is to turn on "High Contrast" mode on the Display tab of the Windows Accessibility options in the Control Panel. Each of these settings should change the font size of elements on your page in ways that are commonly used by people with disabilities.

Tip #6: Use client-side image maps to make pages keyboard navigable

Client-side image maps are more accessible than server-side image maps because the user can tab to each of the defined areas. To further enhance keyboard navigation, add anchors to each of the defined areas in the image map. This way all the user has to do is tab to the desired link and hit ENTER.

Links to Additional Information on Accessibility

The following links provide additional information on accessibility.

  • Microsoft Accessibility Home Page
  • Trace Research and Development Center
  • Web Accessibility Initiative
  • Yuri Rubinsky Insight Foundation


Command Identifiers

Command identifiers specify an action to take on the given object. Use them with the following methods:

  • execCommand
  • queryCommandEnabled
  • queryCommandIndeterm
  • queryCommandState
  • queryCommandSupported
  • queryCommandValue
BackColor Command Bold Command Copy Command
CreateBookmark Command CreateLink Command Cut Command
Delete Command FontName Command FontSize Command
ForeColor Command FormatBlock Command Indent Command
InsertButton Command InsertFieldset Command InsertHorizontalRule Command
InsertIFrame Command InsertInputButton Command InsertInputCheckbox Command
InsertInputFileUpload Command InsertInputHidden Command InsertInputPassword Command
InsertInputRadio Command InsertInputReset Command InsertInputSubmit Command
InsertInputText Command InsertMarquee Command InsertOrderedList Command
InsertParagraph Command InsertSelectDropdown Command InsertSelectListbox Command
InsertTextArea Command InsertUnorderedList Command Italic Command
JustifyCenter Command JustifyLeft Command JustifyRight Command
Outdent Command OverWrite Command Paste Command
Refresh Command RemoveFormat Command SelectAll Command
UnBookmark Command Underline Command Unlink Command
Unselect Command

Command Identifiers Reference

BackColor Command

Sets the background color of the current selection.

value
A string specifying a color. Can be any one of the color names or values given in Color Table.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

Bold Command

Wraps a <B> tag around the object.

This command does not use the value parameter.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

Copy Command

Copies the object to the clipboard.

This command does not use the value parameter.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

CreateBookmark Command

Wraps an <A Name=> tag around the object, or edits an existing tag.

value
A string specifying any valid bookmark name. If value is blank, the bookmark is removed.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

CreateLink Command

Wraps an <A HREF...> tag around the current selection.

value
A string specifying any valid URL.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

Cut Command

Copies the object to the clipboard and then deletes it.

This command does not use the value parameter.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

Delete Command

Deletes the object.

This command does not use the value parameter.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

FontName Command

Sets the typeface for the current selection.

value
A string specifying a font name, as described by the face property.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

FontSize Command

Sets the font size of the current selection.

value
A string specifying a font size, as described by the size property.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

ForeColor Command

Sets the foreground (text) color of the current selection.

value
A string specifying a color. Can be any one of the color names or values given in Color Table.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

FormatBlock Command

Wraps a block tag as specified around the current object.

value
A string specifying the action to carry out.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

Indent Command

Indents the current selection.

This command does not use the value parameter.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

InsertButton Command

Inserts a <BUTTON> tag at the current insertion point.

value
A string specifying an SGML identifier, as described by the id property.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

InsertFieldset Command

Inserts a <FIELDSET> tag at the current insertion point.

value
A string specifying an SGML identifier, as described by the id property.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

InsertHorizontalRule Command

Inserts <HR> at the current insertion point.

value
A string specifying the size of the rule.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

InsertIFrame Command

Inserts an <IFRAME> tag at the current insertion point.

value
A string specifying a valid URL, as described by the src property.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

InsertInputButton Command

Inserts an <INPUT Type = Button...> tag at the current insertion point.

value
A string specifying an SGML identifier, as described by the id property.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

InsertInputCheckbox Command

Inserts an <INPUT Type = Checkbox...> tag at the current insertion point.

value
A string specifying an SGML identifier, as described by the id property.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

InsertInputFileUpload Command

Inserts an <INPUT Type = FileUpload...> tag at the current insertion point.

value
A string specifying an SGML identifier, as described by the id property.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

InsertInputHidden Command

Inserts an <INPUT Type = Hidden...> tag at the current insertion point.

value
A string specifying an SGML identifier, as described by the id property.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

InsertInputImage Command

Inserts an <INPUT Type = Image...> tag at the current insertion point.

value
A string specifying an SGML identifier, as described by the id property.

Applies To

execCommand, queryCommandEnabled, queryCommandIndeterm, queryCommandState, queryCommandSupported, queryCommandValue

InsertInputPassword Command

Inserts an <INPUT Type = Password...> tag at the current insertion point.

value
A string specifying an SGML identifier, as described by the id property.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

InsertInputRadio Command

Inserts an <INPUT Type = Radio...> tag at the current insertion point.

value
A string specifying an SGML identifier, as described by the id property.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

InsertInputReset Command

Inserts an <INPUT Type = Reset...> tag at the current insertion point.

value
A string specifying an SGML identifier, as described by the id property.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

InsertInputSubmit Command

Inserts an <INPUT Type = Submit...> tag at the current insertion point.

value
A string specifying an SGML identifier, as described by the id property.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

InsertInputText Command

Inserts an <INPUT Type = Text...> tag at the current insertion point.

value
A string specifying an SGML identifier, as described by the id property.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

InsertMarquee Command

Inserts a <MARQUEE> at the current insertion point.

value
A string specifying an SGML identifier, as described by the id property.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

InsertOrderedList Command

Inserts an <OL> tag at the current insertion point.

value
A string specifying an SGML identifier, as described by the id property.

The command creates an initial LI element if necessary.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

InsertParagraph Command

Inserts a <P> tag at the current insertion point.

value
A string specifying an SGML identifier, as described by the id property.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

InsertSelectDropdown Command

Inserts a <SELECT Type = Dropdown...> tag at the current insertion point.

value
A string specifying an SGML identifier, as described by the id property.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

InsertSelectListbox Command

Inserts a <SELECT Type = Listbox...> tag at the current insertion point.

value
A string specifying an SGML identifier, as described by the id property.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

InsertTextArea Command

Inserts a <TEXTAREA> tag at the current insertion point.

value
A string specifying an SGML identifier, as described by the id property.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

InsertUnorderedList Command

Inserts a <UL> tag at the current insertion point.

value
A string specifying an SGML identifier, as described by the id property.

The command creates an initial LI element if necessary.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

Italic Command

Wraps an <I> tag around the object.

This command does not use the value parameter.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

JustifyCenter Command

Centers the current selection.

This command does not use the value parameter.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

JustifyFull Command

Full justifies the current selection.

This command does not use the value parameter.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

JustifyLeft Command

Left justifies the current selection.

This command does not use the value parameter.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

JustifyRight Command

Right justifies the current selection.

This command does not use the value parameter.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

Outdent Command

Outdents the current selection.

This command does not use the value parameter.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

OverWrite Command

Sets the input-typing mode to overwrite or insert.

value
A Boolean value or a string representing a Boolean value. If true, input-typing mode is overwrite.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

Paste Command

Pastes the contents of the clipboard at the current insertion point or over the current selection.

This command does not use the value parameter.

To prevent a breach of security, this command can only paste data that has been placed on the clipboard by script.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

Refresh Command

Reloads the source of the current document.

This command does not use the value parameter.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

RemoveFormat Command

Removes formatting from the current selection.

This command does not use the value parameter.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

SelectAll Command

Selects the entire text of the document.

This command does not use the value parameter.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

UnBookmark Command

Removes tags from the given selection or text range.

If you have the following selection, the command removes the A tag, leaving the string "testing".

<a name=foo>testing</a>

document.execCommand("selectall");
document.execCommand("Unbookmark")

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

Underline Command

Wraps a <U> tag around the object.

This command does not use the value parameter.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

Unlink Command

Removes a link.

This command does not use the value parameter.

Applies To

execCommand queryCommandEnabled queryCommandIndeterm queryCommandState queryCommandSupported queryCommandValue

Unselect Command

Clears a selection from the document.

This command does not use the value parameter.

Applies To


Dynamic Content

Before Microsoft® Internet Explorer 4.0, once a Web page was loaded into a user's browser, changing the information displayed on the page required another round-trip to the server. The user interacted with the page (submitted a form, or clicked a link to another page), and the server delivered a new page to the client. Any customization of the information (such as building the page on the fly from a template) required that the server spend additional time processing a page request. Furthermore, the only way to maintain the context for the page's content was to use frame sets, where one frame's content stays constant and another frame changes its content based on the user's activity on the initial page.

Dynamic content is all about changing the content of the HTML document—inserting and deleting elements or the contents of an element before or after the document has been loaded. To see an example of how dynamic content works, enter text in the text box to change the following text:

Dynamic content is cool

Internet Explorer 4.0 gives you a rich set of properties and methods to dynamically construct and alter Web pages on the fly. For example, a script can insert a list of section titles at the beginning of the document, or replace that list with a list of links to the actual sections in the document.

The following topics show how to dynamically access and modify the content in your Web pages.

Changing HTML Content

Adding Document Content

Example: Building a Table of Contents

Advanced Topics

For more information about advanced text manipulation that can be done using a TextRange object, see Using the TextRange Object.

Changing HTML Content

Internet Explorer 4.0 provides a set of properties and methods on each element that are designed to make it quite simple to change the document. There are four properties that provide the ability to see what's inside an element on the page and replace that content with new information: innerText, outerText, innerHTML, and outerHTML.

Assigning new text (also called a "string") to one of these properties replaces the contents of the element, including any elements contained by that element, with the new string. Consider the following HTML for an H1 heading.

<H1 id=myH1>Dynamic Content is Very Cool!</H1>

The content of the H1 can be changed with the innerText property.

document.all.myH1.innerText = "DHTML is Very Cool"

The H1 element remains in the document, while the content of the H1 changes to contain the new string "DHTML is Very Cool". The string assigned to innerText renders any HTML tags as text, and does not process the HTML. To insert HTML code into the contents of another element, you must use the innerHTML property.

document.all.myH1.innerHTML = "DHTML is <I>Very</I> Cool!"

The new string replaces the original content of the H1, and the word "Very" appears in italic.

The outerText and outerHTML properties represent the element itself, as well as the contents of the element. Assuming that the preceding example is contained by a BODY element, using an outerText property on the H1 replaces the entire element with the string attached. The following script causes the H1 to go away entirely, and the text string appears where the element was in the flow of the BODY 's content.

document.all.myspan.outerText = "DHTML is VERY Cool!"

The outerHTML property replaces the element with rich HTML. Much like the example above where HTML was inserted in the H1, using the outerHTML property will do the same, except the H1 would also be removed.

document.all.myH1.outerHTML = "<SPAN STYLE='height:0;width:200;FILTER:Shadow(color=#00FF00)'>RICH HTML</SPAN>";

Adding Document Content

The properties described above replace the entire contents of an element with a new string. What if you only want to insert new text or HTML and don't want to change what is already in the document? There are two helper methods on most elements that help you do just this.

These methods, insertAdjacentHTML and insertAdjacentText, place the new content at the beginning or end of the element, leaving the existing content intact. These methods all take a parameter that indicates one of four possible places the new content can be inserted with regard to the element: BeforeBegin, AfterBegin, BeforeEnd, and AfterEnd.

The following example appends a new paragraph to the end of the document when it loads.

<HTML>
<HEAD>
<TITLE>Dynamic Content: Inserting Elements</TITLE>
<SCRIPT LANGUAGE="JScript">
function insertPara()
{
   document.body.insertAdjacentHTML("BeforeEnd", "<P>But adding a line makes it less so.");
}
</SCRIPT>
</HEAD>
<BODY onload="insertPara()">
<P>This is a <B>very</B> short document.
</P>
</BODY>
</HTML>

Example: Building a Table of Contents

Building a table of contents is a good example of dynamic content at its best. By using a relatively small amount of script, you can automatically generate a detailed list of the contents of any document.

This example consists of three functions: buildTOC, setAnchor, and setLink. The buildTOC function creates the table of contents, calling the other two functions to apply anchors and insert the links. The example depends on the document having an element, such as DIV or P, that has the identifier "MyTOC". The setLink function inserts the links there. To build the table successfully, buildTOC cannot be called until the document is fully loaded.

Once buildTOC is called, it uses the all collection to check each element to see whether it is a header element: H1, H2, H3, or H4. It starts the search at the first element after the BODY element since no links are possible before this. When it finds a header, it sets the "level" variable and calls the setAnchor and setLink functions.

function buildTOC() {
    var coll = document.all;
    var level;
    var id;
    for (i=document.body.sourceIndex+1; i<coll.length; i++) {
        switch (coll[i].tagName) {
        case "H1":
            level = 0;
            break;
        case "H2":
            level = 1;
            break;
        case "H3":
            level = 2;
            break;
        case "H4":
            level = 3;
            break;
        default:
            level = -1;
        }
        if (level!=-1) {
            id = i;
            setAnchor(coll[i], id);
            i++;
            setLink(coll[i], level, id);
            i+=2;
        }
    }
}

Notice how the variable "i" is updated after the call to setAnchor and setLink. These functions insert new elements into the document, causing the all collection to be immediately updated and requiring a new index value for the heading. The setAnchor function inserts one element before the heading, so the index is increased by one; the setLink function inserts two elements at the top of the document, so the index is increased by two.

The setAnchor function adds an A element to the document, inserting the start and ends tags for this element immediately before and after the header tag, and setting the NAME= attribute of the new element to be equal to the "id" parameter passed to the function.

function setAnchor(el, id) {
    el.insertAdjacentHTML("BeforeBegin", "<A NAME=\"" + id + "\">");
    el.insertAdjacentHTML("AfterEnd", "</A>");
}

The setLink function adds another A element to the document. This time the element is a link to the heading that setAnchor just created an anchor for. The HREF= attribute is set to the same "id" value as was set in the matching anchor. Notice that the setLink function places the link just before the end of the element having the identifier "MyTOC", separating it from the previous link with a BR element and inserting zero or more nonbreaking spaces for a very simple way to indicate the heading level.

function setLink(el, level, id) {
    document.all.MyTOC.insertAdjacentHTML("BeforeEnd", "
");
    var s = "&nbsp;";
    for (j=0; j<level; j++)
        s = s + s;
    document.all.MyTOC.insertAdjacentHTML("BeforeEnd",
        s + "<A HREF=\"#" + id + "\">" + el.innerText + "</A>");
}

There are a few things to keep in mind when you are dynamically changing content in your Web page.

Can't modify the content until after the document has been loaded: Keep in mind that you cannot assign a string to these properties until the document has been completely loaded, that is, until the onload event occurs. If you attempt to do so before loading, an error occurs.

Be careful! When you add an element to a document, the all and other element collections are automatically updated to reflect the change. This also affects the value of the sourceIndex for elements that follow the new elements. If you have saved the index value of an element, be careful to update that value or retrieve a new value whenever you add or delete elements in a document.

Can't put invalid HTML in the document: You cannot assign a string to innerHTML or outerHTML that contains invalid HTML. For example, trying to replace the content of the P element with another P will fail. A P element can only contain text and inline elements. However, replacing the entire P element with another P would work just fine.

Which Elements Will This Work For?

Here are a few guidelines for which elements you can expect these properties and methods to work.

Only elements that appear in the BODY of the document can be changed with these properties. You can replace the contents of the BODY, but you can't replace the BODY itself.

This should be obvious, but deserves mention anyway: you can't replace the contents of an element where the element type doesn't have any contents like the replaced elements, INPUT and IMG.

The contents of a TD can be changed (innerText and innerHTML) and the TABLE element itself can be replaced (outerText and outerHTML), but no other table elements and their contents can be changed with these properties.

Advanced Topics

The following sections provide information on more advanced text manipulation.

Using the TextRange Object

Finding Text in the Document


Data Binding

Microsoft® Internet Explorer 4.0 enables content providers to develop data-centric Web applications that support retrieval and update through native data binding facilities. The use of HTML extensions and pluggable data source objects makes data-driven pages easy to author with minimal scripting required. Because data is downloaded to the client asynchronously, pages render quickly and provide immediate interactivity. Once downloaded, the data can be sorted and filtered without requiring additional trips to the server. Compare that to traditional Web pages and those generated by server-side scripts. Once the data reaches the client, it's static, and any manipulation of that data requires another server request.

Consider a simple example, the list of samples in the Internet Client SDK. While the list could be hard-coded into this text, a better solution is to store the data external to the document in a delimited text file. If the samples change, only the data in the database needs to be modified. Once the modifications are made, this page and any others that display that data will reflect the changes.

While this maintenance issue justifies the use of data binding in place of a static page, consider a slightly more complex scenario, an online classical music catalog maintained on a server in a relational database management system. Using today's server-side technologies such as the Common Gateway Interface (CGI), the Internet Server API (ISAPI), or one of its derivatives such as Active Server Pages (ASP), a developer can write a script to extract a subset of data based on criteria specified by the client, such as all titles by a particular composer. The script might generate and return to the client a Web page including a tabular view of this data, including the title, the year composed, the type of composition, and a list of the movements in the composition. While the page may contain the information in date order, if the user wants to view the compositions in alphabetical order or to limit their view to orchestral works or fugues, the user is forced to submit additional requests to the server. This is an expensive way to view the same data in only a slightly different way. The problem is compounded if the Web author decides to present each composition in single record view, that is, one record per page. A full round-trip to the server is required to obtain each subsequent record.

If Web authors want to allow the user to add or update the data, they typically create HTML forms and submit GET and POST requests to an application running on the server. The server application parses out the data from an HTTP data stream and then logs the data to a database. For every update request, the page containing the Submit button and the form data is reloaded. This is not a seamless experience for the user.

The following sections show how the various components in the data binding architecture offer solutions to these problems and make the most efficient use of the Web.

Data Binding Architecture

Adding a Data Source Object to a Page

Binding HTML Elements to Data

DHTML Object Model Support for Data Binding

DHTML Event Model Support for Data Binding

Microsoft Tabular Data Control (TDC)

Microsoft Remote Data Service (formerly ADC)


Filters and Transitions

With the introduction of Microsoft® Internet Explorer 4.0, Web page authors now can apply multimedia-style effects to their content through the use of visual filters and transitions. These effects are implemented in Web pages using a Cascading Style Sheets (CSS) attribute. Visual filters and transitions can be applied to standard HTML controls, such as text containers, images, and any other windowless object. Transitions are time-varying filters that can create a transition from one visual state to another. By combining filters and transitions with basic scripting, authors have a powerful tool for creating visually engaging and interactive documents.

Creating Multimedia Effects with Visual Filters and Transitions

Defining Visual Filters

Scripting Filters

Migrating from OBJECT-based Filters

Filter Design Considerations

Visual Filter Scenarios

Transitions

Interpage Transitions

Transition Design Considerations

Transition Scenarios

Visual and Transition Filters Reference

Visual Filter Effects Reference

Properties, Methods, and Events Reference

Creating Multimedia Effects with Visual Filters and Transitions

Visual filters are extensions to Internet Explorer 4.0 behavior that create onscreen effects in a document's contents. In some cases, filter effects are little more than prepackaged behavior that could have been done otherwise as script. In other cases, they go far beyond script and modify the rendered appearance of a control. Using visual filters greatly simplifies the task of incorporating sophisticated effects in Web documents.

Filters are applied to HTML controls through the filter style sheet property. The filter property is a string of filter descriptions that uses a function-like notation but does not require any knowledge of scripting. The syntax for a filter property in a style attribute is:

filter:filtername(parameters)

Here's an example of how filters are written as style attributes.

<img id=sample src="sample.jpg" style="filter:blur(strength=50) flipv()">

The sample HTML above attaches two filters to the IMG control. The first causes the image to blur over a specified number of pixels. The second filter flips the image vertically.

Each filter can have a set of optional parameters to define the precise nature of the effect, such as color or duration of behavior. Some filters, such as FlipV and FlipH for vertical and horizontal mirror images, have no parameters (although all filters and transitions have an enabled property, and all transitions have a Duration property). Multiple filters can be applied so that in the above example the "flipv" and "blur" filters are applied in combination to the IMG.

Filters often create effects that can also be generated with script. This raises the question, "Why use filters if script can do the job?" There are several reasons for using filters. Probably the most important is because they don't require script. For better or for worse, many HTML authors shy away (or are kept away) from scripting. Filters are a convenient package for the same functionality that scripting can provide. Another benefit of filters over script is that because they use the declarative and inherited syntax of CSS, they are easier to author and can be applied to entire classes of elements.

Another reason for using filters is because they provide a good downlevel story. Browsers that don't support the filter property or even style sheets simply ignore them. Even browsers that do support the filter property can do so in totally different ways without affecting the author. For instance, while filters in Internet Explorer 4.0 are implemented as special COM objects and can be easily extended, it is likely that the Windows® 3.1 implementation will be built in and represent a subset of the Internet Explorer 4.0 functionality.

Although all the filters that ship with Internet Explorer 4.0 are "visual," it is not a requirement. An example of a nonvisual filter would be a filter that changed various style sheet attributes (such as color, font size, bold, and even position) on the filtered element. These filters can be applied to any element (not just controls).

What Are HTML Controls?

Visual filters can be applied only to HTML elements that are controls. A control element defines a rectangular space within a browser window when the browser renders the Web document. Controls cannot be windowed, such as an IFRAME. Valid HTML controls are:
BODY
BUTTON
DIV (with a defined height, width, or absolute positioning)
IMG
INPUT
MARQUEE
SPAN (with a defined height, width, or absolute positioning)
TABLE
TD
TEXTAREA
TFOOT
TH
THEAD
TR

Windowless controls, such as structured graphics and ActiveX™ Controls, can also apply filter attributes. Filters follow the standard CSS attribute inheritance scheme (if it exists for the object) except for the exceptions noted below.

Filters are ignored for any positioned elements nested inside nonpositioned elements, such as a positioned SPAN inside a nonpositioned DIV. The simple solution is to always position or define a width for your outermost element.

Elements and windowed objects that cannot have filters applied to them include Java™ applets, IFRAME, the SELECT and OPTION form elements, P paragraph elements, Hn headings, and EM and STRONG logical text style elements.

Defining Visual Filters

Visual filters modify the appearance of a control. In fact, they can totally take over the visual output of a control when applying their effect. A good example of a visual filter is the alpha filter. It blends its target into the background. The author controls the amount of blend (or opacity). Opacity is expressed as a percentage. For example, the following HTML causes the image to be 20 percent opaque:

<img id=sample src=sample.jpg style="filter:alpha(opacity=20)">

Internet Explorer 4.0 supports a range of visual filters, shown in the following table, from the aforementioned alpha blend to a light filter that simulates colored lights shining on the control.
Filter effect | Description
Alpha | Sets a transparency level.
Blur | Creates the impression of moving at high speed.
Chroma | Makes a specific color transparent.
Drop Shadow | Creates an offset solid silhouette.
FlipH | Creates a horizontal mirror image.
FlipV | Creates a vertical mirror image.
Glow | Adds radiance around the outside edges of the object.
Grayscale | Drops color information from the image.
Invert | Reverses the hue, saturation, and brightness values.
Light | Projects light sources onto an object.
Mask | Creates a transparent mask from an object.
Shadow | Creates a solid silhouette of the object.
Wave | Creates a sine wave distortion along the x-axis and y-axis.
XRay | Shows just the edges of the object.

To experiment with filters use the following samples provided with the Internet Client SDK. Filters Wizard
Wave Filter Wizard

Scripting Filters

A filters collection is available on every element to provide script with access to their individual filters. The collection can be accessed like any other object model collection. For example, the following line of script addresses the first filter in the collection of filters on the element with id=theDiv.

theDiv.filters.item(0).enabled = true;

Filters are considered sub-objects of the control to which they are attached. Like other objects, they expose properties and methods for changing their internal state. Like other object model collections, the filters collection supports several kinds of access.

<img id=sample src="sample.jpg" style="filter: alpha(opacity=50) fliph(enabled=0) blur(amount=10); position: relative">
<script language="JavaScript">
function foo()
{
sample.filters.alpha        // sub object
sample.filters["alpha"]    // named index
sample.filters[0]              // numeric index
}
</SCRIPT>

The numeric access is particularly useful when more than one filter of the same type is applied or when the type of filter isn't known in advance (if it is set through script or data binding, for instance). This is particularly important for filters and transitions that have common properties and methods such as Amount, Color, and Play.

In the following example, the opacity of a control is dynamically changed by changing the opacity property on the alpha filter.

<img id=sample src=sample.jpg style="filter: alpha(opacity=50)">
<script language="javascript">
function foo()
{
     sample.filters.alpha.opacity += 10;
}

This same syntax can be used to call the methods needed to make the transition revealTrans work in the following example.

<div id=mydiv style="height:50;width:50;filter:wave(strength=100) revealTrans(transition=3 duration=4)"> This is a div </div>

<script language="JavaScript">
mydiv.filters.revealTrans.apply()
mydiv.innerText = "This is different text"
mydiv.filters.revealTrans.play()
</script>

Alternately, revealTrans can be accessed by index.

<script language="JavaScript">
mydiv.filters[1].apply()
mydiv.innerText = "This is different text"
mydiv.filters[1].play()
</script>

The Filter String

The style object also has a filter property. This is a read/write string that can be used to manipulate the CSS filters of an element directly. For instance, using the DIV defined above, the following code:

<div id=mydiv style="height:50;width:50;filter:wave(strength=100) revealTrans(transition=3 duration=4)"> This is a div </div>

<script>
...
alert(mydiv.style.filter)
...
</script>

Would produce an alert with the following string:

wave(strength=100) revealTrans(transition=3 duration=4)

Writing to this property is especially useful to change an element's filters dynamically. Note that writing to this property overwrites the existing value and the browser renders the new string immediately. The following example adds a FlipH filter to a collection on the fly.

<div id=mydiv style="height:50;width:50;filter:wave(strength=100) revealTrans(transition=3 duration=4)"> This is a div </div>

<script>
...
mydiv.style.filter = mydiv.style.filter +  " fliph()"
...
</script>

After the change, the new filter string would now look like this:

wave(strength=100) revealTrans(transition=3 duration=4) fliph()

Any additional changes to that collection's filter string will modify the new string. For complex filter manipulation, authors need to keep track of the current states of their element filter collections.

Note It is strongly recommended that CSS filters be accessed through the object model whenever possible, and the filter string be accessed only under special circumstances where object model functionality is not adequate. Even in the case of dynamically adding filters, it is recommended in most cases to actually add the filter in the initial filter attributes of the element's style sheet with enabled=0. When the script wants the filter to be displayed, it can then simply set that filter to enabled=1 and the filter will be displayed.

This Web page demonstrates a simple example of changing filter properties from script. This page uses a more complex script that calls filter methods and manipulates properties.

Migrating from OBJECT-based Filters

As Internet Explorer 4.0 was developed, filters were initially supported as OBJECT elements. With the release of the final version of Internet Explorer 4.0, filters made the logical switch to the CSS model for implementation. While this switch won't have any effect on new Web pages, existing documents that employed filter effects as objects are now broken. Authors who are accustomed to using objects and enjoyed the ability to apply a single object to many different controls at once must now specify the filters on each control that will use them. However, since you can change the style.filter string in script, the old-style syntax can be approximated as follows:

<object id=aFilter clsid=...><param name=param-name value=param-value> ... </object>
site.filter = aFilter

This becomes:

site.style.filter = "someFilter(param-name=param-value, ...)"

However, this solution is hardly the best way to use filters. The new CSS syntax allows multiple filters to be attached and active at once. The Enabled property can be used to turn a given filter on and off.

Filter Design Considerations

Some filters require transparency to function properly. These include Shadow, DropShadow, Glow, and Mask. Text automatically has "transparency," or space around the characters that shows through to the object (or page) behind it. GIF images must be in gif89a format with a transparent color to display these filters properly.

Margins can affect how some filters are applied and rendered. "Clipping" can occur when a margin or DIV boundary is set too close to an object that has a filter applied to it. For instance, applying a glow to text without a margin may have some of the glow effect clipped by the DIV boundary if the text is directly next to it.

Performance is an important factor to consider when designing Web pages with filters. Internet Explorer 4.0 requires processing time to calculate the visual display of filter effects, and some require more time than others to apply. It is useless to try to apply and change a filter on an element before the browser can even render it (such as manipulating a light effect quickly in a looping script function).

While selecting text in the browser window, any applied filter effects are ignored. Once the mouse button is released, the browser reapplies the filter effects to the text. This operation is subject to any performance limitations that were previously experienced.

It is possible to apply one or more filter effects to a group of elements by wrapping them in a DIV. Take care that the DIV itself is positioned if the enclosed elements are positioned. As noted previously, filters require that all containers be either positioned or have defined widths, and parent elements be positioned to display filter effects properly on child elements.

Filters have different methods for creating their effects on elements. For example, the alpha filter affects each pixel as a function of itself (creating either a uniform or gradient effect), while with the glow filter, each pixel inherits from the pixels directly around it, creating a diminishing effect. Your choice of content might be affected by the application method a filter requires to achieve its effect.

Visual Filter Scenarios

There are unlimited uses for filters in both static and dynamic Web pages. The following scenarios explore some of the more common or interesting applications of filter styles and combinations of script and filters.

Creating Static Visual Effects

Static visual effects are the most common use of style filters. These include simply applying a filter to a DIV or object to create a nonchanging effect, such as a text drop shadow. Static effects are an easy way to enhance a Web page's design with minimum effort and bandwidth, and often without scripting.

No-script example

The following example shows how television-style effects can be created using dynamic HTML positioning and the alpha visual filter.

<HTML>
<HEAD><TITLE>Static Alpha Filter Demo</TITLE>
</HEAD>
<BODY>
<DIV style="position:absolute; top:20; left:15; width:50%; height:35; background-color: black; filter: alpha(opacity=50)"></DIV>
<DIV style="color:red; position:absolute; top:20; width:50%; height:100; margin-top:5; margin-left:5;"><P style="font-size:14pt; font-weight:bold; text-align:center">HERE IS CAPTION TEXT</P></DIV>
<IMG src="sam2.jpg">
</BODY>
</HTML>

Timer script example

Visual effects can be "animated" using a timer script. The following sample shows two filters, alpha and glow, and two different timer methods.

<HTML>
<HEAD><TITLE>Timer Demos</TITLE>
<SCRIPT>
function init()  {
    makeFlash(bob)
    setInterval("fred.filters.alpha.opacity = (fred.filters.alpha.opacity + 5) % 101", 100)
    setInterval("foo(dave)", 100)
}
var delta = 5
function foo(obj)  {
    if ((obj.filters.alpha.opacity + delta > 100)
    ||  (obj.filters.alpha.opacity + delta < 0))
        delta = - delta
    obj.filters.alpha.opacity += delta
}
function makeFlash(obj)  {
    obj.flashTimer = setInterval("bob.filters.glow.enabled = !bob.filters.glow.enabled", 1000)
}
function stopFlash(obj)  {
    clearInterval(obj.flashTimer)
}
</SCRIPT>
</HEAD>
<BODY onload="init()">
<DIV id=bob style="width:50%; filter:glow(Color=#FAF900,Strength=2,enabled=0);" onclick="stopFlash(this)"><H1>Here is some text</H1></DIV>
<DIV id=fred style="width:50%; filter:alpha(opacity=100);"><H1>Here is some text</H1></DIV>
<DIV id=dave style="width:50%; filter:alpha(opacity=50); color: blue"><H1>Here is some text</H1></DIV>
</BODY>
</HTML>

Creating Dynamic Visual Effects

Dynamic visual effects bring a basic level of interactivity to Web documents. Dynamic effects require an event to prompt a change in the document—this can be a mouse rollover or click event, a timer interval, or a sequence of script functions calling the new content states.

Event script example

Here an interactive step has been added to the previous "television caption" sample that displays the caption only when the mouse is over the inline image.

<HTML>
<HEAD><TITLE>Dynamic Alpha Filter Demo</TITLE>
<SCRIPT>
function caption()  {
    if (bob.style.visibility == "hidden")    {
        bob.style.visibility = ""
        fred.style.visibility = ""
    }
    else  {
        bob.style.visibility = "hidden"
        fred.style.visibility = "hidden"
    }
}
</SCRIPT>
</HEAD>
<BODY>
<DIV id="bob" style="visibility:hidden; position:absolute; top:20; left:15; width:50%; height:35; background-color: black; filter: alpha(opacity=50)"></DIV>
<DIV id="fred" style="visibility:hidden; color:red; position:absolute; top:20; width:50%; height:100; margin-top:5; margin-left:5;"><P style="font-size:14pt; font-weight:bold; text-align:center">HERE IS CAPTION TEXT</P></DIV>
<IMG src="sam2.jpg" onmouseover="caption()" onmouseout="caption()">
</BODY>
</HTML>

Timer script example

Timers create cyclical effects, as in the following interactive demonstration.

Creating a Disabled UI Element Effect

Web authors often resort to the trick of using multiple graphics to indicate a user state for a single graphic, such as a navigation bar button. With visual filters, these are no longer required—any graphic can be displayed in such a manner as to indicate whether it is available for user interaction or not. Best of all, it's all done in code, and doesn't require an additional download from a server.

No script example

This page shows how both the gray and alpha filters can visually represent unavailable link states.

Event script example

As interactive objects, links can change state in response to mouse events, as this page demonstrates.

Creating Complex Visual Effects

Combining visual filters, transitions, and sophisticated programming allows Web authors to create complex and compelling visual designs and interactivity. The following examples provide just a glimpse into the versatility of visual effects that are available in authoring for Internet Explorer 4.0.

Simple script example

The following Web page shows how the mask filter can be combined with a series of style changes to create an interesting effect.

Event script example

The light filter is the most unique and complex visual filter. The following sample shows how the filter can be combined with mouse events to create a unique DHTML experience.

Programming example

The same light filter can be controlled by sophisticated programming, as the following sample shows. Watch for additional examples of sophisticated Internet Explorer 4.0-enhanced Web site design on Microsoft Site Builder.

Transitions

Transitions are time-varying visual filters. Their role is to visually transition a control from one state to the next. A common example is changing the SRC of an image to change one image to another onscreen. A transition would provide some kind of animated effect to bring in the new image. Transitions can also be applied to make a control gradually fade in or fade out by changing the visibility property.

Transition filters have methods and events for manipulation. When the filter wants to fire an event, the onfilterchange event is fired. This event can be used to script the srcFilter property on the event object, and then supplies all the necessary information about the event. In this way a script can know when a transition has completed. The methods for the filters allow a transition to be applied and played.

The Apply method freezes the visual appearance of the control by first applying the transition, allowing changes to be made without an immediate repaint such as specifying a new image. The Play method then invokes the transition. At any time, the script can "cut to the chase" and finish the transition by calling Stop. The following example shows how to perform an automatic slide show between images.

<HTML>
<HEAD><TITLE>Transition Blend Demo</TITLE>
<SCRIPT language="JavaScript">
var fRunning = 0
function startTrans()
{
    if (fRunning == 0)
    {
        fRunning = 1
        SampleID.filters.blendTrans.Apply();
        SampleID.src = "sunset.jpg";
        SampleID.filters.blendTrans.Play()
    }
}
</SCRIPT>
<SCRIPT for="SampleID" event="onfilterchange">
fRunning = 0
</SCRIPT>
</HEAD>
<BODY>
<IMG id="SampleID" src="beach.jpg" style="filter:blendTrans(duration=3)" onclick="startTrans()"><BR>
Click image for Transition Filter: Blend
</BODY>
</HTML>

Two transition filters ship with Internet Explorer 4.0, blend and reveal. The blend transition allows a simple fade-in or fade-out with a specified duration, while the reveal transition specifies multiple effects such as boxin, boxout, horizontal blinds, and so on.

The following HTML is an example of a simple transition between two images. Clicking the button runs the doTrans script, which first calls Apply on the revealTrans filter to stop painting of the image. It then sets an alternative image and calls Play on the filter to proceed with the transition. In this case the transition type is set to 8, which corresponds to the vertical blinds transition effect. This is applied using an inline style on the IMG tag.

<HTML>
<HEAD><TITLE>Transition Sample</TITLE>
<SCRIPT LANGUAGE=JavaScript>
Function doTrans()
{
    theImg.filters.item[0].Apply();
    theImg.src="circles.bmp";
    theImg.filters.item[0].Play();
}
</SCRIPT>
</HEAD>
<BODY style="background-color:darkblue">
<IMG ID=theImg width=200 height=200
src="clouds.bmp" style="filter:revealTrans(Duration=3.3, Transition=8);">
<BR>
<INPUT type=button value="Start Transition" onClick="doTrans()">
<IMG src="clouds.bmp" style="position:relative; width:1; height:1;visibility:hidden">
<IMG src="circles.bmp" style="position:relative; width:1; height:1; visibility:hidden">
</BODY>
</HTML>

This example also demonstrates the differences between asynchronous and synchronous changes. Changing the innerText of an element is synchronous—the action is completed by the time the statement has executed. Changing the src is effectively asynchronous. Although the actual src property changes immediately, the visual state of the IMG element isn't fully updated until the actual download of the new image is complete. A careful script would wait for the onload event on the image. "Pre-loading" graphics with separate IMG tags is a good way to avoid the synchronicity issue but it will only work if the transition is applied after all image downloads are complete.

Interpage Transitions

Interpage transitions make it possible to provide visual effects to the entire window as a Web page is loaded or exited. Just as programs such as PowerPoint® allow for transitions between slides, you can provide wipes, fades, and even create custom transition types.

Transitions are implemented with META tags placed in the HEAD section of Web pages. The META tag specifies the type of transition, duration, and other variables, as well as whether the transition should occur as the following page is loaded or as it is exited.

Transition Syntax

The syntax for transitions consists of three parts: specifying when the event should be played, the duration of the transition, and what kind of transition effect to use. The following two examples show how to set transitions upon entry and exit of a page.

<META http-equiv="Page-Enter"
CONTENT="RevealTrans(Duration=4,Transition=1)>

<META http-equiv="Page-Exit"
CONTENT="RevealTrans(Duration=2.500,Transition=6)>

The first META tag causes transition 1 to play when the user enters the page, lasting 4 seconds; the second META tag causes transition 6 to play when the user leaves the page, lasting 2.5 seconds (written as 2 seconds and 500 milliseconds).

There are four events that can initiate interpage transitions: Page-Enter , Page-Exit, Site-Enter, and Site-Exit. Duration has a maximum value of 30 seconds.

Transitions Reference

The available reveal transitions that are supported in Internet Explorer 4.0 are described below.
Transition name | Value
Box in | 0
Box out | 1
Circle in | 2
Circle out | 3
Wipe up | 4
Wipe down | 5
Wipe right | 6
Wipe left | 7
Vertical blinds | 8
Horizontal blinds | 9
Checkerboard across | 10
Checkerboard down | 11
Random dissolve | 12
Split vertical in | 13
Split vertical out | 14
Split horizontal in | 15
Split horizontal out | 16
Strips left down | 17
Strips left up | 18
Strips right down | 19
Strips right up | 20
Random bars horizontal | 21
Random bars vertical | 22
Random | 23

To easily construct and experiment with these transitions use the following wizard distributed with the Internet Client SDK.

  • Transitions Wizard HTML-based wizard that generates basic code for the different Transitions, based on the parameters entered by the user.

    Transition Design Considerations

    The primary concern of designers when implementing transitions is that, since they run asynchronously, it is necessary to track each transition state through events (onfilterchange) to determine when a particular transition is finished. Remember that image downloading is asynchronous and that the visual state of IMG elements isn't fully updated until after images are completely downloaded.

    Transition Scenarios

    There are unlimited uses for transitions in both static and dynamic Web pages. The following scenarios explore some of the more common or interesting applications of filter styles combined with transitions and, as in the more complex demonstrations, script functions.

    Creating Non-Event Transitions

    Non-event transitions are analogous to static visual filters—they are used frequently to enhance the visual appearance of a page without changing the level of interactivity of the document.

    Simple script example

    The following demonstration uses transitions to display information in an interesting manner as the page loads.

    Creating Event-Driven Transitions

    Event script example

    This demonstration shows how a mouse event can trigger a sequence of transitions.

    Creating Complex Transitions

    Combining visual filters and transitions allows Web authors to create complex and compelling visual designs and interactivity. The following example provides just a glimpse into the versatility of visual effects that are available in authoring for Internet Explorer 4.0.

    Event Script Example

    Intermediate Web pages (sometimes called "logo pages") provide an opportunity to be creative with transitions.

    Timer script example

    Computer-based training applications can use timed transitions to demonstrate their subject matter, as the following example shows.

    Programming

    Transitions can be combined with visual filters and scripting to develop complex site designs. Watch for examples of sophisticated Internet Explorer 4.0-enhanced Web site design on Microsoft Site Builder.


Finding Text in the Document

You can search for a given string of text in a document by using the findText method on a TextRange object. This method starts the search at the beginning of the range and, if it finds the string, positions the range so that it entirely encloses the string. The following example uses findText to search for each instance of the word "sample" and displays a message identifying how many instances it found.

var rng = document.body.createTextRange();
for (i=0; rng.findText("sample")!=false; i++) {
    rng.collapse( );
}
alert("There are " + i + " instances of sample");

In the above example, the collapse method moves the start of the text range to the same position as the end point, ensuring that the same instance of "sample" is not counted twice.

You can carry out a global search and replace by using findText and the text property. The following example searches for each instance of "sample" and replaces it with the word "final".

var rng = document.body.createTextRange();
for (i=0; rng.findText("sample")!=false; i++) {
    rng.text = "final";
}

You can select the text that you find, making it easier for the user to see, by using the select method. Similarly, you can scroll the text into the user's view by using the scrollIntoView method. Together, these methods give you a way to make the result of a search clearly visible to the user. The following JScript example searches for the word "sample", selects the word, and then scrolls the word to the top of the window.

var rng = document.body.createTextRange();
if (rng.findText("sample")==true) {
    rng.select();
    rng.scrollIntoView();
}

Note that you can also create a text range from a selection made by the user. The createRange method on the selection object returns a text range. You can use the same methods and properties on this range as you do for ranges created using createTextRange.


Font Embedding

Web page designers are at a disadvantage compared to print desktop publishers when creating documents; desktop publishers control every aspect of the layout and choose which fonts their content will be printed in. On the other hand, Web authors are at the mercy of the browser and the user's font support when their content is displayed.

Font embedding has been a feature of Microsoft applications such as Microsoft Word and PowerPoint® for several years. It allows fonts used in the creation of a document to travel with that document, assuring that a user sees the pages exactly as the author intended them to be seen. Now, Microsoft® Internet Explorer 4.0 brings embedded font support to the Web. This technology gives site designers the confidence that Internet Explorer 4.0 users will see their pages exactly as intended.

Embedded Font Technology

Embedded Font Examples

Limitations in Internet Explorer 4.0

Internet Explorer 4.0 Security Alert

Using Microsoft WEFT

Embedded Font Technology

In the early years of the World Wide Web, browsers had full control over which font was used to display pages. Later, the FONT element and Cascading Style Sheets (CSS) font-family property were introduced to provide the Web author more control and access to fonts installed on the user's system. However, if the font was not previously installed on the user's computer, the author and user had no recourse but to display the document in a default or secondary font face. Today, Internet Explorer 4.0 supports font embedding, allowing authors to temporarily install fonts on user systems so that Web page content can be rendered exactly as intended.

At this time there is no defined industry standard for font embedding. The Microsoft TrueType font embedding technology is one proposed implementation. The World Wide Web Consortium (W3C) has a working draft available that provides the latest proposed specifications.

Microsoft font embedding uses CSS notation to indicate font styles in Web documents. Designers can limit the frequency that embedded fonts must be transferred to the users' computers if they anticipate fonts that might already be installed. The following example uses an embedded font as a secondary font face, if by chance the preferred font is not already installed on the client computer.

<STYLE>
<SPAN style="COLOR: red">@font-face myfont { src:url(garamond.eot); }</SPAN>
P { font-family: "Garamond, <SPAN class=blue>myfont</SPAN>" }
</STYLE>

For information about the current implementation of embedded fonts in Internet Explorer 4.0, see Limitations in Internet Explorer 4.0.

Different Levels of Font Embedding

TrueType fonts have embedding permissions encoded within them that determine how they can be used by tools that convert them into the embedded font format. There are four levels of embedding:

  • No-embedding permissions are used by a small proportion of available fonts. The creators of these fonts have decided not to allow embedding. Some foundries set their fonts to no-embedding but offer upgrades to embeddable versions. If you come across a no-embedding font that you would really like to use, contact the supplier and ask about a possible upgrade.
  • Print and preview fonts can be embedded, but only within pages that remain static on the client side. If a page allows client-side interaction that results in content displayed using the font changing, "editable" or "installable" fonts must be used. An example of such a page might be one that contains an inline Java™-based word processor, or an e-mail editor.
  • Editable fonts can be embedded using a tool such as WEFT (Web Embedding Fonts Tool) without the restrictions imposed on "print and preview" fonts.
  • Installable fonts are treated as editable fonts by Internet Explorer 4.0. Installable fonts will not be installed in your visitors fonts folder. The main reason for this is that during the course of users' Web travels, they could easily find their fonts folder stuffed with hundreds of full and subsetted fonts that they do not want or need.

Embedded Font Examples

The following demonstrations located on the Microsoft Typography Web site show how font embedding is a dramatic improvement over the traditional use of fonts on the Web.

Note You must be online and using Microsoft Internet Explorer 4.0 to view these examples.

Example 1: Healthy eating recipe

Design process. Some type designers don't allow their fonts to be embedded, so the fonts used in this example were first checked using Microsoft's font properties extension. Checking the embedding permissions of the fonts first is the best way to avoid disappointment later.

The page itself was designed around a simple HTML table. Cascading Style Sheet features were used to specify fonts and ensure the correct alignment of the text and symbols. At this stage the fonts used were all installed locally.

When the copy and layout were set, Microsoft WEFT (Web Embedding Fonts Tool) was used to create "font-objects" that were linked to the page. The WEFT tool analyzes the font usage of Web pages, gathers the required characters from each font used, and creates the compressed font objects. It also modifies the HTML page by writing in the Cascading Style Sheet code linking the font objects to that page. If you use View Source on the demonstration page, you'll see the format of the code added.

@font-face {
    font-family: Goudy Stout;
    font-style:  normal;
    font-weight: 700;
    src: url(GOUDYST0.eot);

This code tells Internet Explorer 4.0 to use the GOUDYST0.eot font object whenever there is text on the page specified in the Goudy Stout font. The following table shows the fonts used by the page, the number of unique characters used, and the size of the font object that contains them.
Font used | Unique characters | Object size
Pie | 9 | 4.27K
Goudy Stout Bold | 15 | 7.43K
Garamond Bold | 15 | 10.3K
Garamond | 19 | 10.3K
Script MT Bold | 49 | 3.97K

How the page looks in other browsers. Browsers that don't support embedding will ignore the code linking the font objects to the page. Users of browsers that support Cascading Style Sheets will see text displayed in the real font if it's installed. Since Goudy Stout and Garamond come with Microsoft Office, they may be in luck. If the first-choice font isn't available, the browser displays the text using the second- or third-choice font (if they are installed). Users of older browsers see all the text displayed using their default font.

One thing to bear in mind is that symbol fonts appear as ordinary characters in browsers other than Internet Explorer 4.0—even CSS browsers do not display the symbols properly. For this reason, using symbol fonts in this way is recommended only for content specific to Internet Explorer 4.0.

Example 2: A blot on the copybook

Design process. This demonstration consists of four pages and shows how one font object can be used across any number of pages. The French Script MT font object contains all the letters and punctuation used in the story and is referenced by all four pages.

Unlike the characters used in the text of the story, the pictures only appear once. For this reason, four font objects were created, each one containing only the pictures used by the page that references it.

The third font is a custom font created specifically for this demonstration. The phrase "A Blot on the Copybook" was drawn as a single character using Macromedia Fontographer, and mapped to the letter Q. The phrase "fin" was also drawn and mapped to the letter K.
Font used | Unique characters | Object size
French Script MT | 52 | 11.1K
Copyblot | 2 | 4.23K
Dingblots (p. 1) | 3 | 2.56K
Dingblots (p. 2) | 27 | 8.42K
Dingblots (p. 3) | 17 | 5.47K
Dingblots (p. 4) | 13 | 3.57K

How the page looks in other browsers. Like the previous demonstration, this uses an embedded symbol font. Two pages also use a custom font that maps the phrases "A Blot on the Copybook" and "fin" to the Q and K keys, respectively. Using custom and symbol fonts in this way means that the pages are Internet Explorer 4.0-specific.

Example 3: Typographic ornament

Design process. These pages use HTML tables to achieve checkerboard patterns, which are colored and filled with various symbols taken from the Border Web and Kingston inline fonts.
Font used | Unique characters | Object size
Kingston Inline | 36 | 17.1K
Runic MT Condensed | 33 | 9.85K
BorderWeb | 10 | 8.36K

How the page looks in other browsers. Like the previous demonstrations, these pages also use embedded symbol fonts, making them Internet Explorer 4.0- specific.

Example 4: Progressive rendering

Design process. Internet Explorer 4.0 will not render a page until the font objects referenced by that page have been downloaded, decompressed, and temporarily installed. In some cases you might want to have a page displayed using an installed font that is dynamically replaced by the font stored within the font object.

The code required to implement this progressive rendering is very compact, and takes the following form:

<SCRIPT LANGUAGE="VBSCRIPT">
Sub Window_onLoad
Msgbox("Click here to continue the demo")
document.stylesheets(<SPAN class=red>i</SPAN>).href="ftembed.css"
End Sub
</SCRIPT>

The stylesheets(<SPAN class=red>i</SPAN>) section is the element of the style sheet collection you want to replace. In this example, a null style sheet corresponding to stylesheets(0) is dimensioned so as to create a style sheet element. This requires the following code to be added in the HEAD element of your HTML code.

<LINK rel=stylesheet href=null>

The font object links are contained in the external style sheet and are therefore referenced only after the page itself has downloaded. The Msgbox code has been inserted so that those lucky enough to have fast connections can see how the progressive rendering effect works. This line can be removed if you implement this code on your own pages.
Font used | Unique characters | Object size
Braggadocio | 18 | 3.16K
Curlz MT | 36 | 10.4K
OCR A Extended | 19 | 4.75K
Gradl | 23 | 4.08K
Snap ITC | 29 | 7.09K

Limitations in Internet Explorer 4.0

At present Microsoft Internet Explorer 4.0 downloads, decompresses, and privately installs font objects even if the real font is installed on a user's system. Future versions will check if the real version of the font is available before downloading the linked font object. Currently this behavior has to be simulated using VBscript (Visual Basic® Scripting Edition) or JScript.

The W3C font embedding draft also describes the way in which browsers should be able to combine font objects containing different subsets of the same font. This way you could link to a font object that contains the uppercase letters from a particular font and another font object containing lowercase letters. At present Internet Explorer 4 uses only the first font object specified.

Internet Explorer 4.0 Security Alert

Depending on how Internet Explorer 4.0 security settings are set, you might get a warning every time a page accesses an embedded font. Although your security level settings can easily be modified, you should first access the Internet Explorer online help and read the sections discussing security before making the following changes:

  1. On the View menu, click Options and then click the Security tab.
  2. Select Custom and click Settings.
  3. Scroll down to the Downloads section.
  4. Change the Font Download setting from Prompt to Enable.

Using Microsoft WEFT

The Microsoft Web Embedding Fonts Tool is being released to coincide with the release of Internet Explorer 4.0. WEFT is a free utility that lets site designers create font objects that are linked to their Web pages.

Download the current version of WEFT for Windows® 95 and Windows NT® from the Microsoft Typography Web site.

The font objects created by WEFT differ from traditional font files in a number of ways. The font objects are compressed and are usually subsetted so that they contain only the characters used by a particular site or page. They are also privately installed by Internet Explorer 4.0 so that they can't be accessed by other applications, and they can't be linked to sites that don't have permission to use them. In the future, WEFT features will be built into popular Web authoring tools.

WEFT Style Code

WEFT adds a STYLE section to the HEAD part of each HTML page that uses one or more font objects.

<STYLE TYPE="text/css">
  @font-face {
    font-family: Garamond;
    font-style:  italic;
    font-weight: normal;
    src: url(Garamond1.eot); }
</STYLE>

This code tells Internet Explorer 4.0 to use the Garamond1.eot font object whenever the Garamond Italic font is specified within the page. The browser will use the font object regardless of whether the font is specified using the FONT FACE tag, a linked or inline Cascading Style Sheet, or some other method.

Cascading Style Sheet Files

WEFT uses Internet Explorer 4.0 to determine the fonts and characters used on each page. If a page references a linked style sheet, this style sheet usually determines the fonts Internet Explorer 4.0 uses to display the page. Note that WEFT does not modify linked style sheets. Instead, the tool modifies the HTML pages by adding code that links the font objects to pages that require them.

In some cases it will be more efficient to reference the font objects within one or more linked style sheets. If you'd like to try this, skip the option asking if you want to publish the modified pages back to your Web site. Instead, cut and paste the relevant code from the modified pages (by default these will be stored in the My Documents folder) into your linked style sheet.

A word of caution is needed. As style sheets cascade, a font specified in a linked style sheet may be overridden by one specified inline. Also, because a style sheet can be linked to any number of pages, care should be taken when choosing an appropriate subsetting level.

For more information about Cascading Style Sheets, see Microsoft Site Builder.

Frequently Asked Questions

Q. Which fonts can I use?

There are thousands of TrueType fonts available, and most of these can be embedded within Web pages using the Microsoft Web Embedding Fonts Tool. However, WEFT will not let you embed certain categories of fonts, such as "no embedding" fonts, and those that contain serious errors.

Q. How can I check the embedding permissions of my fonts?

You can check the embedding permissions of any font using the Microsoft Font Properties Extension. WEFT also has a font check feature that reports the permissions of fonts you have installed on your system.

You may come across very old TrueType fonts, or converted Macintosh® TrueType fonts that do not have any embedding permissions encoded within them. WEFT treats these as "no embedding" fonts. In the unlikely event that you encounter such a font, your best option is to contact the foundry that created the font, and ask about an upgrade.

Q. Should I embed common core fonts such as Arial or Times New Roman?

WEFT will identify common fonts that your readers are likely to have installed. These include Windows core fonts such as Arial, Times New Roman, and Courier New. You can still embed these fonts; however, Internet Explorer 4.0 will download, decompress, and temporarily install font objects even if the real font is present on the user's computer.

The current version of WEFT does not identify the fonts supplied with Internet Explorer 4.0 as common core fonts. Users who have installed Internet Explorer 4.0 will have added Verdana, Comic Sans MS, Arial Black, Impact, and Webdings to their system. Although it is possible that a few users might remove these fonts from their system, it is not recommended that you embed them.

Q. Can I use Type 1 fonts?

If you have specified Type 1 fonts as your first-choice fonts and have Adobe Type Manager installed, these fonts will be identified by WEFT. However, they will be flagged as "status unknown", and you will not be able to embed them using the public preview version of WEFT.


Positioning

Microsoft® Internet Explorer 4.0 supports the ability to position HTML elements in x- and y-coordinates, as well as overlap elements in planes along the z-axis, which extends toward and away from the viewer in a Web document. This capability allows authors to place elements—images, controls, or text—exactly where they want on the page. By using scripts to manipulate the position coordinates and other dynamic styles, authors can move elements around a page, creating animated effects. The combination of dynamic styles, positioning, transparent ActiveX™ Controls, and transparent images presents authors with a rich set of animation options.

What Is Positioning?

Absolute Positioning

Relative Positioning

Positioning Considerations

Controlling Content Visibility

Element Visibility

What Is Positioning?

CSS Positioning defines the placement of elements on a page, and is an extension of cascading style sheets as specified in the W3C Working Draft on Positioning HTML with Cascading Style Sheets. By default, elements "flow" one after another in the same order as they appear in the HTML source, with each element having a size and position that depends on the type of element, the contents of the element, and the display context for the element as it will render on the page. This default "flow" model for HTML layout doesn't provide the author a high level of control over the placement of elements on the page. By applying a small set of CSS attributes to the elements that are defined for the page, you can control the precise position of elements by giving exact coordinates, or specifying placement relative to the position of other objects on the page.

Just like any other HTML or CSS attribute, the CSS attributes used to control an element's position are available for scripting. The position of these elements on the page can thus be dynamically changed with script. This is very powerful! The position of these elements can be recalculated and redrawn after the document is loaded without needing to reload the page from the server.

Controlling the position of an element uses several other layout control techniques. These include controlling the display of the object—that is, whether or not the element is displayed on the page, and how much of the element can be viewed by the user.

There are two ways to position an element in x- and y-coordinates. The type of positioning to use depends on the layout of the content and the purpose of the document. Absolute positioning means that the element is precisely placed relative to the parent coordinate system, regardless of any other content. Relative positioning places the item with respect to other elements on the page. Relative positioning depends on the default flow of the document, and reflows content should the user resize the browser.

Absolute Positioning

An absolutely positioned element is always relative to either the next positioned parent or, if there isn't one, the BODY by default. Values for left and top are relative to the upper-left corner of the next positioned element in the hierarchy. For example, to place an image at the top left corner of the document, you set the attributes to 0 as follows:

<IMG SRC="sample.gif" STYLE="position:absolute; left:0; top:0">

This positions the image within the border of the BODY element. Remember, there is a default border on the BODY, so if no border is desired, set the border of the BODY to 0 to position the image at the 0,0 coordinates of the client area.

To see how a positioned parent affects the absolute position, consider the following example.

<DIV STYLE="position:relative;left:50;top:30;height:100;width:100">
        Some text inside the DIV that will be hidden by the image because the image will be positioned over this flowing text.
    <IMG SRC="sample.gif" STYLE="position:absolute; left:0; top:0">
</DIV>

This example places the IMG element at the upper-left corner of the DIV element, which is itself positioned on the page.

Setting an absolute position pulls the element out of the "flow" of the document and positions it regardless of the layout of surrounding elements. If other elements already occupy the given position, they do not affect the positioned element, nor does the positioned element affect them. Instead, all elements are drawn at the same place, causing the objects to overlap. You can control this overlap by using the z-index attribute to specify the order in which elements are stacked at the same location.

The contents of a positioned element flow within the given dimensions as default HTML would flow. For instance, text would wrap normally based on the width of the element, and various inline elements contained within the positioned elements will be placed next to each other in source order according to the constraints of size and shape of the "container" (that is, the positioned element).

Relative Positioning

Setting the CSS position attribute to "relative" places the element in the natural HTML flow of the document but offsets the position of the element based on the preceding content. For example, placing a piece of text within a paragraph with "relative" positioning renders the text relative to the text in the paragraph that precedes it.

<P>The superscript in this name<SPAN STYLE="position: relative; top:-3px">xyz</SPAN> is "xyz".

Should the user resize the window, the "xyz" still appears three pixels above the natural baseline of the text. You can set the left attribute in a similar way to change the horizontal spacing between "name" and "xyz". If the contents of the SPAN were absolutely positioned, the "xyz" would be placed relative to the BODY (or the next positioned element in the hierarchy), and the "xyz" would be barely visible at the upper corner of the client area—not the effect the author probably intended!

Text and elements that follow a relatively positioned element occupy their own space and do not overlap the natural space for the positioned element. Contrast this with an absolutely positioned element where subsequent text and elements occupy what would have been the natural space for the positioned element before the positioned element was pulled out of the flow.

It is quite possible that relatively positioned elements will overlap with other objects and elements on the page. As with absolute positioning, you can use the z-index attribute to set the z-index of the positioned element relative to other elements that might occupy the same area. By default, a positioned element always has a higher z-coordinate than its parent element so that it will always be on top of its parent element.

Positioning Considerations

The type of positioning to use depends on the layout of the content and the purpose of the document. Relative positioning depends on the default flow of the document and will reflow content should the user resize the browser. However, absolute positioning gives you the control to precisely place images and text no matter what the user does to the display.

Here is an example of nesting an absolutely positioned element within a relatively positioned element. The desired effect is to center text in a rectangle. In the past, you might build tables and use attributes to center the content inside a table cell. However, this layout restricts you to a static table. Using positioning, this content can be worked into a larger layout, and then you can add scripting that might, for instance, have each of these elements fall into place from somewhere outside the document as the user loads the page!

<HTML>
<HEAD><TITLE>Center the DIV</TITLE>
<SCRIPT LANGUAGE="JScript">
function doPosition() {
document.all.two.style.top = document.all.one.offsetHeight/2 -
document.all.two.offsetHeight/2;
document.all.two.style.left = document.all.one.offsetWidth/2 -
document.all.two.offsetWidth/2;
}
</SCRIPT>
</HEAD>
<BODY onload="doPosition()">
<P>Some text in the beginning.</P>
<DIV ID=one STYLE="position:relative; top:10;height:200;width:200;background-color:green">
Some text in the outer DIV
<DIV ID=two STYLE="position:absolute;left:50;width:100;color:red;border:red 2px solid">
text in the inner DIV - color should be red
</DIV>
</DIV>
</BODY>
</HTML>

In the example above, the outer DIV "flows" with the contents of the document that precedes it, meaning it is positioned 10 pixels immediately after the first paragraph. The inner DIV has an initial absolute position, but this position is modified by the script function "doPosition" when the document is loaded. The offsetWidth and offsetHeight properties are used to calculate the new absolute position for an element. In the example above, you can also use the posLeft or pixelLeft property to center the images. These properties give alternate access to the left property, letting you set the position using a floating point number or an integer. There are similar pos* and pixel* properties that provide alternate access to the top, width, and height properties.

Combining Dynamic Positioning Techniques

The previous example can be expanded to manipulate multiple items on the page. Or, to animate this script, you might rework the scripting function on the "onload" of the document to have the inner piece of text "fly in" from offscreen. This function could be based on a timer that would move the inner DIV from an initial top and left coordinate somewhere off the visible portion of the page, and, over a given amount of time, move it to a position that would be in the center of the outer DIV.

The following example makes the DIV element visible and animates the content to glide across the screen. By setting an interval using the setInterval method on the window object, you can move one or more elements each time the interval elapses.

<HTML>
<HEAD><TITLE>Glide the DIV</TITLE>
<SCRIPT LANGUAGE="JScript">
var action;
function StartGlide() {
    document.all.Banner.style.pixelLeft =
        document.body.offsetWidth;
    document.all.Banner.style.visibility = "visible";
    action = window.setInterval("Glide()",50);
}
function Glide() {
    document.all.Banner.style.pixelLeft -= 10;
    if (document.all.Banner.style.pixelLeft<=0) {
        document.all.Banner.style.pixelLeft=0;
        window.clearInterval(action);
    }
}
</SCRIPT>
</HEAD>
<BODY onload="StartGlide()">
<P>With dynamic positioning, you can move elements and their content
anywhere in the document even
after the document has loaded!
<DIV ID="Banner" STYLE="visibility:hidden;position:absolute;top:0; left:0">Welcome to Dynamic HTML!</DIV>
</BODY>
</HTML>

Note that you cannot dynamically change an element from nonpositioned to positioned. The position attribute should be set in the HTML source, as setting the position attribute in script will not work with Internet Explorer 4.0.

For more ideas on how to integrate positioning with other DHTML techniques, check out Filters and Transitions to learn how to incorporate visual filter affects.

Controlling Content Visibility

In addition to controlling where on the page the element is positioned, the content of positioned elements can be restricted from the user's view in several ways. The display and visibility attributes control whether the element appears on the screen at all, and the clip and overflow attributes control how much of the content the user can see. As mentioned previously, authors can also control the visibility of overlapping elements by manipulating the z-index ordering.

Clipping Regions and Overflow

You can set a clipping region for a positioned element by using the clip attribute. The clipping region defines a rectangle within which the element is visible. Any portion of the element that extends outside the clipping region is "clipped," that is, not displayed. The clipping region does not alter the HTML, but simply changes how the element is displayed.

For example, the following document uses clip to define a clipping region for the absolutely positioned DIV. The region, a 30-by-30 pixel square, displays only a portion of the text; the rest is clipped from view.

<HTML>
<HEAD><TITLE>Clip the DIV</TITLE>
</HEAD>
<BODY>
<DIV
STYLE="position:absolute;top:50;left:50;height:100;width:100;clip:rect(0 30 30 0);background-color:green">
some content some content some content some content some content
some content some content some content some content some content
some content some content some content some content some content
some content some content
</DIV>
</BODY>
</HTML>

Be careful when you define a clipping region—the parameter order (top, right, bottom, left) is important. For example, setting clip:rect to (0 0 30 30) causes the region not to display because the top and right have been defined as zero. The correct definition for a 30-by-30 clipping region based off the top left corner of the positioned object is to set clip:rect to (0 30 30 0).

You can change the clipping region dynamically by using the clip property, as in the following example.

document.all.MyDiv.style.clip = "rect(0 50 75 0)";

Overflow occurs when there is more content in a positioned element than can fit within the area defined for it. By default, any extra content is displayed but flows beyond the end of the area and therefore may overlap other elements in the document. You can prevent this overflow by using the "overflow" attribute to either hide the overflow or enable scroll bars to let the user view it by scrolling.

For example, the following document uses "overflow" to apply scroll bars. Only the portion of the text that fits within the 100-by-100 area is initially displayed, but the user can scroll the rest into view by using the scroll bars.

<HTML>
<HEAD><TITLE>Scroll the Overflow</TITLE>
</HEAD>
<BODY>
<DIV STYLE="position:absolute;top:50;left:50;height:100;width:100;overflow:scroll">
some content some content some content some content some content
some content some content some content some content some content
some content some content some content some content some content
some content some content
</DIV>
</BODY>
</HTML>

You can hide any overflow by setting "overflow" to "hidden". Similarly, you can let the overflow flow beyond the end of the area by setting it to "visible".

You can change the overflow dynamically by using the overflow property, as in the following example.

if (document.all.MyDiv.style.overflow != "scroll")
    document.all.MyDiv.style.overflow = "scroll";

Z-Index Ordering

The z-index specifies in what order elements should be drawn when two or more elements occupy the same area. Setting the z-index is useful whenever you have absolute or relative positioned elements that overlap other elements in the document.

You set the z-index by using the z-index attribute. Setting this to a positive value causes the element to be stacked on top of other elements; negative values cause it to be stacked below. The following document uses z-index to stack text on top of the image.

<HTML>
<HEAD><TITLE>Stack the Image</TITLE>
</HEAD>
<BODY>
<P STYLE="position:absolute; top:0; left:0">Text Over Image</P>
<IMG SRC="sample.jpg" STYLE="position:absolute; top:0; left:0; z-index:-1">
</BODY>
</HTML>

The element with the greatest z-index is always placed at the very top of the stack, and the element with the least z-index at the very bottom. If two elements have the same z-index, their source order determines the stacking—the last element is stacked highest.

You can change the z-index dynamically by setting the zIndex property, as in the following example.

document.all.MyImg.style.zIndex = 2;

In general, all elements are "windowless" and will participate in z-order overlapping. However, some objects are "windowed". ActiveX Controls that have not been specifically written to be windowless will not overlap with other objects. IFRAME elements represent a window object, and window objects do not participate in z-order. Another exception in Internet Explorer 4.0 is the SELECT element.

Element Visibility

The visibility of a positioned element determines whether the user can see the element. Visibility is useful for temporarily hiding an element, such as when time is needed to calculate its position or when carrying out simple transition effects. You can set the visibility by using the visibility attribute. The following example uses the attribute to make the DIV element invisible.

<p> A paragraph above the DIV element</p>
<DIV ID=MyDiv STYLE="position:absolute;top:50;left:50;height:100;width:100;visibility:hidden">
<p> A paragraph below the DIV element</p>

You can set the visibility of an element from script by using the visibility property. For example, assume that the DIV in the previous example is loaded. Initially, it is invisible, but you can change this to visible by using the following:

document.all.MyDiv.style.visibility = "visible";

An invisible element continues to affect the document layout; that is, the space that the element would occupy remains in the document even though it is empty. This is unlike the display attribute, which does not reserve space. The following sample demonstrates the difference between visibility and display.


Using the TextRange Object

Most users will only want to use the innerText/innerHTML and outerText/outerHTML properties and methods discussed previously. However, there is some more advanced text manipulation that can be done using a "text range" object. The TextRange object can be used to:

  • Locate the text for a given element or a given point.
  • Search for words and characters in the text of the document.
  • Move through the text in logical units.
  • Provide read/write access to the plain text and the HTMLText in the document.

This feature might not be available on non-Win32® platforms. See article Q172976 in the Microsoft Knowledge Base for the latest information on Internet Explorer cross-platform compatibility.

Overview of the TextRange Object

Text range objects are an advanced feature of Dynamic HTML that you can use to carry out useful tasks related to dynamic content, such as searching for and selecting text. Text ranges let you selectively pick out characters, words, and sentences from a document. The TextRange object is an abstract object that creates a start and end position over the stream of text that would appear in the HTML document. Consider the following simple HTML document:

<HTML>
<BODY>
<H1>Welcome</H1>
<CENTER><H2>Overview<H2></CENTER>
<P>Be sure to <B>Refresh</B> this page.</P>
</BODY>
</HTML>

In this document, creating a text range over the BODY would position the start at the beginning of the textual content of the BODY, and the end at the end of the textual content of the BODY. This text range would contain the plain text "Welcome Overview Be Sure to Refresh this page."

What Do I Do with a TextRange Object?

There are two parts to manipulating text with a TextRange object. The first is to create a text range so that the start and end positions encompass the desired text. The next step is to apply a method to the text range, or make a copy of the text to be used elsewhere in the document. Once the text range is positioned, you can search for text, select the text, and make a copy of the text and use it elsewhere in your document.

See the TextRange object in the Object Model Reference for the properties and methods supported.

Positioning the TextRange Object

Each text range has a start and an end position defining the scope of the text that is encompassed by the TextRange object. When you create a new text range, the start and end positions encompass the entire content by default. Use methods such as move, moveStart, and moveEnd to change the scope of the text range.

Other methods can position the TextRange object with respect to a particular element, or a point on the page. For example, moveToElementText positions the text range so that it encompasses the text contained by the given element. moveToPoint positions the text range at a given point where the user clicked a mouse button. The x and y positions of the user's click are known by the window.event object and can be used to position the range over a given point. From this collapsed point, the range can then be expanded to encompass a word, sentence, or a whole textEdit (the entire possible TextRange object).

<HTML><HEAD>
<TITLE>moveToPoint Example</TITLE>
<script>
function selectMe() {
var r=document.body.createTextRange();
r.moveToPoint(window.event.x, window.event.y);
r.expand("word");
r.select();
}
</script>
</HEAD>
<BODY>

<H1 id=myH1 onclick=selectMe()>Click on a word and it will highlight</H1>

</BODY></HTML>

You create a TextRange object by applying the createTextRange method to a BODY, TEXTAREA, or BUTTON element. You can also create a text range from a selection made by the user. The createRange method on the selection object returns a text range. You can use the same methods and properties on this range as you do for ranges created using createTextRange.

Creating a TextRange object on the body will not include the content inside a TEXTAREA or BUTTON. Conversely, you cannot change the start or end position of a text range over the TEXTAREA or BUTTON to move outside the scope of these particular elements. Use the properties provided on each element, isTextEdit and parentTextEdit, to walk the hierarchy. If the document above contained a TEXTAREA, a createTextRange on the body object would not find the position where the user actually clicked. The following reworks the above example to handle this case.

<HTML><HEAD>
<TITLE>moveToPoint Example</TITLE>
<script for=document event=onclick>
     var r
     if(window.event.srcElement.isTextEdit)
           {
            r=window.event.srcElement.createTextRange();
     }else{
            var el=window.event.srcElement.parentTextEdit;
            r=el.createTextRange();
           }
     r.moveToPoint(window.event.x, window.event.y);
     r.expand("word");
     r.select();
</script>
</HEAD>
<BODY>

<H1 id=myH1>Click on a word and it will highlight</H1>

<TEXTAREA>
There's text in this element too that you could click on
</TEXTAREA>

</BODY></HTML>

Getting the Content of a TextRange

The content of a TextRange object can be viewed with the text or HTMLtext property on the TextRange object. The text property is a read/write property that is similar to the innerText properties on the element objects, only this replaces the text encompassed by a TextRange object.

HTMLtext is a read-only property that lets you examine the HTML that is contained within the start and end points of the TextRange object. To add rich HTML content to the text range, use the pasteHTML method. Although you can paste any HTML text that you want into a text range, the pasteHTML method does not preserve the hierarchy of the document, as do the innerHTML and outerHTML properties. Although pasteHTML won't fail if you paste invalid or inappropriate tags into the range, the resulting document may not look or behave the way you expect. If you paste an HTML fragment, the fragment is automatically closed to prevent it from affecting subsequent text and elements. For example, this means if your scripts rely on ordinal positions in the document's all collection, after a pasteHTML, the sourceIndex into the document.all collection may point to a different element.

Comparing Ranges

You can create more than one text range at a time, using them for independent, simultaneous access to different portions of the text in an element. You can also copy a text range by using the duplicate method. This is useful if you want temporary access to a portion of the original range but don't want to bother recreating or restoring the original range. You can determine the relationship of one text range to another by using methods such as isEqual and inRange.

Because the object model never holds on to a text range, you'll need to recreate any range whenever control leaves and then reenters your code. For example, any text range objects created by an event handler are discarded when the event handler returns.

You can determine whether one range in entirely contained within another text range by using the inRange method. You can determine whether two text ranges are identical by using the isEqual method. Text ranges are identical if they start and end at exactly the same positions. Note that identical text ranges are always considered to be within one another, meaning the inRange method returns true for these.

You can set the start or end point of a range to match the start or end point of another range by using the setEndPoint method. The method takes two parameters: a string describing which end points to transfer, and a range from which the source end point is taken. The following example sets the end of the range "r1" to the start of "r2".

r1.setEndPoint( "StartToEnd", r2 )

You can also use "StartToStart", "EndToStart", and "EndToEnd" to set the end points.

You can compare the start or end points of two ranges by using the compareEndPoints method. This method compares the end points and returns -1, 0, or 1, indicating whether the end point of the first range is less than, equal to, or greater than that of the second.

A bookmark is an easy way to save the current start and end positions of a text range and quickly restore these positions when you need them. You create a bookmark for a given range by using the getBookmark method, which returns an opaque string that uniquely identifies the bookmark. (Opaque means the string cannot be examined or modified.) You use the string with the moveToBookmark method to move the text range back to the same start and end positions as when the bookmark was created.

Commands

You can use commands to apply formatting and to carry out special actions on the text of a text range. You execute a command by using the execCommand method. You supply a command identifier and provide any additional command parameters. For example, you can change text to bold by using the Bold command as in the following JScript example.

var rng = document.body.createTextRange();
rng.collapse();
rng.expand("sentence");
rng.execCommand("Bold");

The above example makes bold all text up to the first period in the document.

Not all commands are available at all times. You can determine whether a command is available for a given text range by using the queryCommandEnabled and queryCommandSupported methods. For a list of commands, see Command Identifiers.

To determine whether a given command has already been applied to a text range, use the queryCommandState method to retrieve the state of the command. The state is true if the command has been applied.


Data Binding Architecture

Data binding is based on a component architecture consisting of four major pieces—data source objects, data consumers, the binding agent, and the table repetition agent. Data source objects provide the data to a page, data-consuming HTML elements display the data, and the agents ensure that both provider and consumer are synchronized. The following diagram illustrates how the components fit together.

Data Source Objects

To bind data to the elements of an HTML page in Internet Explorer 4.0, a data source object (DSO) must be present on that page. DSOs implement an open specification that leaves it to the DSO developer to determine the following:

  • How the data is transmitted to the page. A DSO can use any transport protocol it chooses. This might be a standard Internet protocol such as HTTP or simple file I/O. A DSO also determines whether the transmission occurs synchronously or asynchronously. Asynchronous transmission is preferred, as it provides the most immediate interactivity to the user.
  • How the data set is specified. A DSO might require an ODBC connection string and an SQL statement, or it might accept a simple URL.
  • How the data is manipulated through scripts. Since the DSO maintains the data on the client, it also manages how the data is sorted and filtered.
  • Whether updates are allowed.

A DSO typically exposes this functionality through an object model accessible to scripts.

The only strict requirement imposed upon a DSO is that it must provide access to its data through the OLE DB or OLE DB Simple Provider APIs. Because all DSOs provide data access through a standard set of interfaces, MSHTML extends the object model of the DSO with a standard set of properties, methods, and events. It is through this object model that scripts can manipulate the data.

Specifics on adding a DSO to a page are provided below. Information on implementing custom data source objects is available in IE4/MSHTML Data Binding Interfaces.

Data Consumers

Data consumers are elements on the HTML page capable of rendering the data supplied by a DSO. Elements include many of those intrinsic to HTML, as well as custom objects implemented as Java applets or ActiveX™ Controls. Internet Explorer 4.0 supports HTML extensions to allow authors to bind an element to a specific column of data in a data set exposed by a DSO. Applets and ActiveX Controls support additional binding semantics described below.

Elements support the consumption of either single-valued or tabular data. Single-valued consumers such as INPUT elements consume a single value from the current record provided by a data source. Tabular data consumers such as the TABLE element repeat an entire set of records from a data provider. This is called set binding.

The section on HTML extensions explains the extended attributes that allow Web authors to bind elements to the data supplied by a DSO. For further information on the individual elements that support data binding, see Binding an HTML Element to Data.

Binding Agents

The binding and repetition agents are implemented by Mshtml.dll, the HTML viewer for Internet Explorer 4.0, and they work completely behind the scenes. When a page is first loaded, the binding agent finds the DSOs and the data consumers among those elements on the page. Once the binding agent recognizes all DSOs and data consumers, it maintains the synchronization of the data that flows between them. For example, when the DSO receives more data from its source, the binding agent transmits the new data to the consumers. Conversely, when a user updates a data bound element on the page, the binding agent notifies the DSO.

To signal the Web author of important changes in the state of the data caused by providers and consumers, the binding agent fires a variety of scriptable events.

Table Repetition Agent

The repetition agent works with tabular data consumers such as the HTML TABLE element to repeat the entire data set supplied by a DSO. Note that individual elements in the table are synchronized through interaction with the binding agent.

HTML Extensions for Data Binding

To enable Web authors to add data binding to their pages, Internet Explorer 4.0 provides support for several new HTML attributes. All data binding-related HTML attributes correspond to a similarly named property in the Document Object Model. The following section introduces these attributes and describes their use.

The key to data binding is connecting a data source object to a data consumer. To achieve a binding between a data source object (DSO) and a data consumer, Internet Explorer 4.0 extends HTML to support the following attributes:
DATASRC | Specifies the identification of the DSO to which a consumer is bound.
DATAFLD | Identifies the specific column exposed by the DSO to which the element is bound.
DATAFORMATAS | Indicates how the data in the specified column should be rendered.
DATAPAGESIZE | Indicates how many records are displayed in a table at once.

Bound elements fall into two specific categories:

  • Single-valued consumers
  • Tabular data consumers

The binding agent takes a single value from the current record of a data source and passes it to a single-valued consumer. The repetition agent works with the binding agent to pass the entire set of records to a tabular data consumer.

By specifying the DATASRC and DATAFLD attributes on a single-valued data consuming element of a Web page, the Web author fully specifies the binding of an element to data. By specifying DATAFORMATAS on a single-valued element, the Web author indicates how the data should be interpreted. DATAPAGESIZE allows the author to restrict the number of records that are displayed by a tabular consumer. All these properties can be set at run time through the document object model.

Here's a sample declaration for a single-valued data consuming element that might appear on an HTML page.

<SPAN DATASRC=#dsoComposer DATAFLD=compsr_first></SPAN>

The DATASRC attribute in this example is set to the ID (dsoComposer) of a data source object (DSO) embedded on the page. The DATAFLD is set to the name of a column in the data set provided by the DSO. For this binding to succeed, the data set retrieved by the DSO must contain a column named "compsr_first".

Click the Show Me button to see a working example.

The following example shows how a table, a tabular data consumer, can be bound to a data source object. The repetition agent uses the table row (TR) in the table body as a template. As the DSO identified in this example as "dsoComposer" supplies each record in the data set, the template including the DIV is repeated, until all composers' first names are displayed.

<TABLE DATASRC=#dsoComposer>
    <TR><TD><DIV DATAFLD=compsr_first></DIV></TD></TR>
</TABLE>

Click the Show Me button to see a working example that uses the TDC to display a table of composers, including their first and last name, date of birth and death, and country of origin.

Specifying Data Rendering with the DATAFORMATAS Attribute

The data supplied by a DSO can be in a variety of formats, and the page author can use the DATAFORMATAS attribute on single-valued consumer elements that support the attribute to indicate how the data should be rendered. In Internet Explorer 4.0, HTML and TEXT are the valid values for this attribute.

<MARQUEE DATASRC=#dsoAdvertisement DATAFLD=banner
    DATAFORMATAS=html>
</MARQUEE>

The previous example describes a MARQUEE that calls upon a data source object that supplies various banners for display in a page. Click the Show Me button to see how a timer can be used to randomly select and display an advertisement supplied by a data source.

Optimizing Table Viewing with the DATAPAGESIZE Attribute

When binding a TABLE to a data source, all the records in the data set will be displayed by default. If the data set is large, the page may grow beyond what is visible to the user. In addition, any content positioned below the table will get pushed off the screen. The DATAPAGESIZE attribute can be applied to a TABLE to specify the maximum number of records that should be displayed at any one time. To enable the user to move to the next and previous page of records viewed in the table, Web authors can use the nextPage and previousPage methods exposed by the TABLE object in the document object model. Authors can also change the page size of the table at run time by setting the dataPageSize property. Click the Show Me button to see how it works.

In addition to limiting table size, Web authors should investigate the specific functionality exposed by the DSO they have chosen for use on their HTML page. Both the TDC and RDS provide filtering capabilities.


Binding HTML Elements to Data

To display the data provided by a data source object (DSO), the page author binds elements on an HTML page to the DSO. Using the data binding extensions or the corresponding data binding properties makes it easy. This section shows how to bind an element to data, the elements that support data binding, and the capabilities of those elements. Capabilities include support for updating the data to which an element is bound and the format in which the data is displayed—HTML or plain text.

Bindable HTML elements fall into two categories—single-valued and tabular consumers. Single-valued consumers bind to a single field of the current record provided by a DSO. Tabular consumers bind to an entire data set and use their contained elements as a template to repeat the data. In Internet Explorer 4.0, the TABLE element is an example of a tabular data consumer, and the procedure for binding it to data is described below.

Binding a Single-Valued Element to Data

The procedure for binding a single-valued element to data is the same regardless of the element. Elements can be bound to data at design time using the DATASRC and DATAFLD attributes or at run time using the dataSrc and dataFld properties exposed by the corresponding objects in the document object model.

Binding a single-valued element to data at design time

To specify a complete binding to a field in a data set, data-consuming elements use the DATASRC and DATAFLD attributes. Given a text box, for example, a page author can bind that element to data as follows:

<INPUT TYPE=TEXTBOX DATASRC=#dsoComposers DATAFLD=compsr_last>

The DATASRC attribute in this example specifies the ID, prefixed by a hash mark (#), of a data source object (DSO) embedded on the page. The hash mark is required. The DATAFLD attribute identifies the field in the data provided by the DSO to which the text box should be bound.

Click the Show Me button to see how it works.

Binding a TABLE to Data

Because the TABLE element is a tabular data consumer, it relies upon the elements that it contains to bind to the individual fields in the data set provided by the DSO. The contained elements serve as a template, and they are repeated once for each record in the data set. The TABLE specifies the DATASRC attribute. The contained elements specify the DATAFLD attribute and inherit the DATASRC from the table. Here's a simple example:

<TABLE DATASRC=#dsoComposer>
    <TR><TD><SPAN DATAFLD=compsr_first></SPAN></TD></TR>
</TABLE>

Click the Show Me button to see how it works.

As with single-valued consumers, a tabular data consumer can be bound to data at run time using the document object model. The procedure for accomplishing this is described below.

Elements that Support Data Binding

The previous sections used a TEXTBOX, a SPAN, and a TABLE element to illustrate how to bind single-valued and tabular consumers to the data provided by a DSO. Many other HTML elements can be bound to data. Some of these elements support updating the data to which they are bound. Changes can be persisted to the back-end data set if the DSO supports update. Other elements support rendering of the data as HTML in addition to the plain text default using the DATAFORMATAS attribute.

The following table presents the single-valued HTML elements that support data binding. Additional columns indicate:

  • If the element supports update.
  • If the element can render its data as HTML.
  • The property to which the data is applied.

Use the drop-down list to filter the elements appropriately.

Element Updatable Renders HTML Bound Property

Read-only elements

Bindable HTML elements that supply read-only functionality include A (anchor), BUTTON, DIV, IMG (image), FRAME, IFRAME, LABEL, MARQUEE, and SPAN.

Additionally, the BUTTON, DIV, LABEL, MARQUEE, and SPAN elements support the usage of the DATAFORMATAS attribute and the corresponding dataFormatAs property to render the data to which they are bound as plain text (default) and as HTML. The data displayed by the element is automatically updated as the record pointer maintained by the DSO moves or the underlying data to which the element is bound changes. Individual descriptions for these elements follow.

A

An anchor element applies the data supplied by a DSO to the HREF attribute; thus, the supplied data should represent a URL. An example of a bound anchor is:

<A DATASRC=#dsoLinks DATAFLD=link_href><SPAN DATASRC=#dsoLinks DATAFLD=link_friendly></SPAN></A>

BUTTON

A BUTTON element renders the data supplied by a DSO on its face. An example of a bound BUTTON is:

<BUTTON DATASRC=#dsoLinks DATAFLD=link_friendly></BUTTON>

Click the Show Me button to see a working example.

DIV

A DIV element is useful for displaying a block of text. An example of a bound DIV is:

<DIV DATASRC=#dsoComposer DATAFLD=compsr_biography></DIV>

IMG

An IMG element applies the data supplied by a DSO to locate, load, and display the image typically pointed to by its SRC attribute. Supplying raw image data through the bound column is not supported.

An example of a bound IMG tag is:

<SPAN DATASRC=#dsoImages DATAFLD=image></SPAN>

Click the Show Me button to see a working example.

FRAME

A FRAME element applies the data supplied by a DSO to its HREF attribute; thus, the bound value should represent a URL. So that the binding occurs successfully, the data source object supplying data to a bound frame should be present in the HEAD section of the HTML file containing the FRAMESET. An example of a bound FRAME is:

<HTML>
<HEAD>
<<!-- Add DSO reference here -->
</HEAD>
<FRAMESET>
    <FRAME DATASRC=#dsoFAQ DATAFLD=frame_question ...>
    <FRAME DATASRC=#dsoFAQ DATAFLD=frame_answer ...>
</FRAMESET>
</HTML>

The code behind the following Show Me button implements a frame-based FAQ. The first frame displays the question; the second frame displays the answer; the third frame contains navigation buttons. The first and second frames are bound to a two-column table. The first column in the table contains relative paths to pages containing questions. The second column contains relative paths to pages containing the answers. Since the DSO is embedded in the HEAD of the outer page containing the FRAMESET, the code behind the navigation buttons drills out of the page in which it resides using the top object and references the DSO by its ID. top returns an object reference to the outermost containing window.

IFRAME

An IFRAME element applies the data supplied by a DSO to its HREF attribute; thus, the data should represent a URL. In contrast to the FRAME case, the DSO can be declared anywhere on the page. An example of a bound IFRAME is:

<IFRAME DATASRC=#DSC1 DATAFLD=iframe_url>

Click the Show Me button to see a working example.

LABEL

Use a LABEL element to describe another bound element on the page. A label applies the data supplied by a DSO to its caption. An example of a bound LABEL is:

<LABEL FOR=somecontrolid DATASRC=#DSC1 DATAFLD=label_col></LABEL>

Since a LABEL is associated with other elements indicated by its FOR attribute, using a bound LABEL within a repeated table can yield unexpected results. If the FOR attribute references another element within the repeated table, the LABEL tag will not be associated with the elements, since there will be multiple elements with the same ID/NAME as a result of the repetition.

MARQUEE

A MARQUEE element uses its bound data to replace the text that appears between its opening and closing tags.

An example of a bound MARQUEE is:

<MARQUEE DATASRC=#dsoComposer DATAFLD=bio DATAFORMATAS=HTML></MARQUEE>

Click the Show Me button to see a working example.

SPAN

Like a DIV, a SPAN is a read-only data consumer. Use a SPAN to display inline text or limited HTML text. If the SPAN is used to display HTML text, that text should not include any HTML block elements. When the current record or the underlying value in the bound column provided by the DSO changes, the SPAN reflects the change. An example of a bound SPAN is:

<SPAN DATASRC=#dsoComposer DATAFLD=compsr_last></SPAN>

Click the Show Me button to see a working example.

Elements that support update

The APPLET, INPUT (with the exception of the button type), SELECT, TEXTAREA, and OBJECT elements support updating the data to which they are bound if the underlying DSO supports update functionality. Descriptions of these individual elements follow.

INPUT

The INPUT element represents a set of HTML intrinsic controls. Each of the types that support data binding is detailed in the following sections.

RADIO

Radio buttons are used to select a single value from a set of alternatives. These can be used to select the value for an enumerated field in a database. One radio button is specified for each of the alternatives using a separate INPUT. The NAME attribute on the INPUT determines the logical grouping of alternatives. One value is bound for all the INPUTs with the same NAME attribute. All members of a group must specify the corresponding DATASRC and DATAFLD attributes.

An example of a bound radio button group is:

<INPUT TYPE=RADIO NAME=cards VALUE=mc
DATASRC=#dsoOrders DATAFLD=cardname>MasterCard
<INPUT TYPE=RADIO NAME=cards VALUE=amex
DATASRC=#dsoOrders DATAFLD=cardname >American Express
<INPUT TYPE=RADIO NAME=cards VALUE=visa
DATASRC=#dsoOrders DATAFLD=cardname >Visa

Click the Show Me button to see a working example.

CHECKBOX

Although check boxes allow a value attribute that is used when submitting an HTML form on a page, IE4/MSHTML uses check boxes as simple Boolean selections. Check boxes generate the Boolean values TRUE or FALSE depending on whether they are checked or not. The binding agent coerces the values to and from the underlying data set. The following coercions are supported based on the type of the bound column.

The following table describes the values that a bound check box expects a DSO to supply for various data types.

Data type | Expected True Value | Expected False Value
String | "True" | "1" | <non-empty string> | "False" | "0" | <zero-length string>
Integer | non-zero | 0
Float | non-zero | 0
Date | invalid | invalid
Currency | non-zero | 0

An example of a bound check box is as follows:

<INPUT TYPE=CHECKBOX DATASRC=#dsoSurvey DATAFLD=us_resident> U.S. Resident

Click the Show Me button to see a working example.

TEXT

The TEXT type is used as a simple text box. The value of the text box can be bound to a field in the data source using the DATASRC and DATAFLD attributes.

An example of a bound text box is:

<INPUT TYPE=TEXT DATASRC=#DSC1 DATAFLD=name>

HIDDEN

The HIDDEN type is used to store information in the page that isn't displayed to the user. The element is populated with data from the current record, but it cannot be modified.

An example of a bound hidden field is:

<INPUT TYPE=HIDDEN DATASRC=#DSC1 DATAFLD=key>

PASSWORD

The PASSWORD type is basically the same as the TEXT type except that the bound text is not displayed to the user. Use this input type with care since the associated data is fully accessible to scripts through the data-binding object model, as well as directly through the element's value.

An example of a bound password is:

<INPUT TYPE=PASSWORD DATASRC=#DSC1 DATAFLD=password>

SELECT

A SELECT element supplies the functionality of a drop-down list (combo box) or a list box. Internet Explorer supports binding to a single selected element; binding to multiple selections is not supported.

The items in a SELECT control are specified using OPTION tags. The document object model defines an options array that corresponds to the collection of OPTION tags for a SELECT. Each OPTION has a corresponding index, text, and value. The SELECT has a selectedIndex property that corresponds to the index of the OPTION currently selected. If no item is selected, the selectedIndex is set to -1. The text attribute of an OPTION corresponds to the text following the OPTION tag and represents the string that is displayed for that OPTION in the SELECT. The VALUE attribute provides the value that is to be returned when the HTML form is submitted. Value is also what is stored into the bound column of the data source.

Initially, the selectedIndex property of a bound SELECT control will be set to the index of the value in the options array corresponding to the field of the data source. If the value is not a member of the options array, the index property is set to -1 and, if the SELECT is a combo, no value is displayed. When a user changes the selected item, the corresponding OPTION value (attribute) is used to update the value of the bound field of the data source. Validation events are fired as with other controls.

An example of a bound SELECT is:

<SELECT DATASRC=#DSC1 DATAFLD=cardname>
<OPTION VALUE=mc>MasterCard
<OPTION VALUE=amex>American Express
<OPTION VALUE=visa>Visa
</SELECT>

Click the Show Me button to see a working example.

TEXTAREA

A TEXTAREA is a multirow text box for data input similar to the INPUT TYPE=text intrinsic. As such it supports the update of the data if the DSO supports the update feature.

An example of a bound TEXTAREA is:

<TEXTAREA DATASRC=#dsoComposer DATAFLD=bio></TEXTAREA>

Click the Show Me button to see a working example.

OBJECT

When DATASRC and DATAFLD are specified on an OBJECT, Internet Explorer 4.0 attempts to bind to the object's default property. The defaultbind attribute specified in an object's type information uniquely identifies the default property. If a default property is not specified in this way, Internet Explorer 4.0 uses the property with DISPID 0.

An example of binding the default value on the object tag is:

<OBJECT ID=oControl1 WIDTH=100 HEIGHT=100
    CLASSID="CLSID:xxxxxxxxx-xxxxx-xxxx-xxxx-xxxxxxxxxxxxx"
    DATASRC=#DSC1 DATAFLD=controlData>
</OBJECT>

Additionally, Internet Explorer 4.0 supports binding to arbitrary OBJECT properties through the object's contained PARAM tags. Apply the DATASRC and DATAFLD attributes to the PARAM tag. The property is initialized with the data supplied by the DSO.

An example of binding the PARAMs on the object tag is:

<OBJECT ID="oControl1" WIDTH=100 HEIGHT=100
    CLASSID="CLSID:xxxxxxxxx-xxxxx-xxxx-xxxx-xxxxxxxxxxxxx">
<PARAM NAME="ForeColor" DATASRC=#DSC1 DATAFLD=forecolor>
<PARAM NAME="BackColor" DATASRC=#DSC1 DATAFLD=backcolor>
</OBJECT>

Bindings can be simultaneously applied to both the object's default value as well as its PARAM tags.

APPLET

Internet Explorer 4.0 supports binding to the PARAM tags of an APPLET. For example, the following specifies a binding on the xyz property of the application:

<APPLET CODE=somecode>
    <PARAM NAME="xyz" VALUE="abc" DATASRC="#Ctrl1" DATAFLD="Column1">
    <PARAM NAME="Title" VALUE="BoundApplet">
</APPLET>

Property name resolution

The NAME attribute of the PARAM specifies the basename of the Java methods used to get and set the value of the property. This is termed basename since the method of the Java applet to retrieve the value of the property is get<basename>. Correspondingly, the method to set the value of the Java applet is set<basename>. This naming convention is consistent with the JavaBeans 1.0 specification. The applet used in the previous section is expected to have methods named getxyz and setxyz.

Notifications

Notifications are not fired by the application when property values change. Property changes are only detected when the current record is changed. During this transition, the binding agent interrogates the application and transfers a modified data value, after validation, to the data source. When values are changed directly in the data source, the binding agent is notified by the data source and transfers the value to the application immediately. See the section on data binding events for details about data binding extensions to the event model.

Name space co-mingling

The bound PARAM in the preceding example is the most complicated specification possible. That is, it addresses the case where there is a binding to a property specified by the NAME attribute, and there is a parameter to the application with the same NAME with a corresponding VALUE attribute. This essentially co-mingles two name spaces: the parameter name space for the application and the binding name space, since the NAME attribute is used for both. In such cases, the application ignores the unexpected DATASRC and DATAFLD attributes on the PARAM when fetching a parameter (applications explicitly fetch parameters using the getParameter method), and the binding agent recognizes the attributes and attempts binding using the get and set methods specified above.

The simplest example is one where there is no conflict between the parameter name space and the property name space. An example would be:

<APPLET>
<PARAM NAME="backcolor" DATASRC="#DSC1" DATAFLD="Color">
</APPLET>

Here, the backcolor property only has DATASRC and DATAFLD attributes. No VALUE attribute is specified.


Adding a Data Source Object to a Page

Once a Web author has identified the data that she wishes to display on a page, the next step is to choose the data source object (DSO) that will supply that data and to add a reference to that DSO to that page. Internet Explorer 4.0 ships with a number of data source objects. These include

  • Tabular Data Control (TDC)
  • Remote Data Service (formerly ADC)
  • JDBC Applet
  • XML Data Source
  • MSHTML Data Source

In addition to these data providers, Microsoft maintains a gallery of data source objects. Jump to this site to learn about other data providers as they become available.

A DSO can be implemented as an ActiveX control or as a Java applet. The OBJECT tag is used to embed an ActiveX control on the page; the APPLET tag is used to embed a Java applet on the page. In general, Web authors can copy and paste the appropriate OBJECT or APPLET declaration corresponding to the DSO of their choosing and modify the PARAM tags appropriately. So that elements on the page can bind to the data source, the declaration should include the ID attribute.

Because the data source object specification imposes no requirements on the DSO regarding the object model it exposes, Web authors should familiarize themselves with the documentation associated with the DSO they select to provide data to their page.

Tabular Data Control (TDC)

The TDC is a simple DSO that provides access to delimited text files. This is the DSO used in the majority of the samples provided with this section. Consider using the TDC if:

  • You have a simple data set to display. TDC supports some simple data types.
  • You need to browse your data offline. The file transmitted by the TDC can be cached on the client and read offline.
  • You want to prevent direct access to your DBMS. A server script can be written to dump data from your database into a delimited text file. In addition, most DBMSs support this feature.

The following example represents a declaration specific to the Tabular Data Control (TDC).

<OBJECT CLASSID="clsid:333C7BC4-460F-11D0-BC04-0080C7055A83"
    ID=dsoComposer WIDTH=0 HEIGHT=0>
    <PARAM NAME="DataURL" VALUE="composer.csv">
</OBJECT>

DataURL is a property specific to the TDC. The TDC uses this property to allow an author to specify the data set that should get loaded along with the page. For more information about the TDC, see the companion documentation for this component in the Component Library included with the Internet Client SDK.

Remote Data Service (RDS)

The Remote Data Service is a more sophisticated DSO that ships with Internet Explorer 4.0. RDS obtains its data from a database using OLE-DB or ODBC. Consider using RDS if:

  • You have existing data in an OLE-DB or ODBC-compliant database management system (DBMS) such as SQL Server, Microsoft® Access, or Oracle.
  • You want to specify the data using a SQL statement.
  • You need to provide update, insert, and delete capabilities.
  • You want direct, real-time access to the data.

A declaration specific to RDS follows:

<OBJECT classid="clsid:BD96C556-65A3-11D0-983A-00C04FC29E33"
    ID=dsoComposer HEIGHT=0 WIDTH=0>
    <PARAM NAME="Server"  VALUE="http://musicserver">
    <PARAM NAME="Connect" VALUE="dsn=music;uid=guest;pwd=">
    <PARAM NAME="SQL"     VALUE="select compsr_name from composer">
</OBJECT>

First, note the class identifier (CLSID) specific to RDS. Every ActiveX component requires a CLSID to differentiate it from other objects registered on the system. Next, note that the base properties exposed by RDS differ significantly from those exposed by the TDC. That's because the TDC derives its data from a flat text file, while the RDS is capable of retrieving and updating data from any OLE-DB or ODBC-compliant database. The following are the properties specified in the example declaration above:
Server | String identifying the protocol and the server that supplies the data.
Connect | Standard ODBC connection string identifying the data source name configured on the server.
SQL | SQL query identifying the table and columns to be selected from the database.

For the specifics on how to use RDS, see the companion documentation in the Component Library of the Internet Client SDK.

JDBC DataSource Applet

The JDBC DataSource Applet is a DSO available for download from the Microsoft Data Source Object Gallery. Consider using this applet if:

  • You have existing data in an ODBC-compliant database management system (DBMS) such as SQL Server, Microsoft® Access, or Oracle.
  • You want to specify the data using a SQL statement.
  • You need to provide update, insert, and delete capabilities.
<APPLET CODE=JDC.class NAME="DSA1" ID="DSA1" WIDTH=0 HEIGHT=0>
    <PARAM NAME=cabbase VALUE=
        "http://www.microsoft.com/gallery/files/datasrc/jdbcapplet/jdc.cab">
    <PARAM NAME=dbURL VALUE="jdbc:odbc:Northwind">
    <PARAM NAME=showUI VALUE=false>
    <PARAM NAME=sqlStatement VALUE="select ProductName, CompanyName,
        CategoryName from Products, Suppliers, Categories where
        Suppliers.SupplierID=Products.SupplierID and Categories.CategoryID =
        Products.CategoryID and Categories.CategoryID < 5">
    <PARAM NAME=allowInsert VALUE="true">
    <PARAM NAME=allowDelete VALUE="true">
    <PARAM NAME=allowUpdate VALUE="false">
    <PARAM NAME=user        VALUE="">
    <PARAM NAME=password    VALUE="">
</APPLET>

Instead of a CLSID, the CODE attribute uniquely identifies the DSO. Note that the basic properties exposed by this DSO differ from those exposed by the TDC or RDS. The following properties are specified in the example declaration above:
cabbase | General property, applicable to all applets, that specifies the location of the code for the applet. The code will be downloaded to the client if not already installed.
dbURL | Required string that identifies the ODBC data source name (DSN) configured in the user's control panel.
showUI | Optional Boolean value indicating whether a user interface should be displayed.
sqlStatement | SQL string identifying the table and columns to be selected from the database.
allowInsert | Boolean value indicating whether new records can be inserted into the data set.
allowDelete | Boolean value indicating whether existing records can be deleted.
allowUpdate | Boolean value indicating whether existing records can be updated.
user | Optional string identifying the user. Some ODBC data sources require authentication.
password | Optional string identifying the specified user's password.

XML Data Source

Extensible Markup Language (XML) describes data and structured text on the Web in a standard way. Internet Explorer 4.0 ships with an application that serves as an XML data provider. While the XML DSO is a read-only data provider, Web authors should consider using it to display hierarchical data.

To use the XML data source object, add an APPLET tag to your page, as in the following:

<APPLET
    CLASS=com.ms.xml.dso.XMLDSO.class
    ID=xmldso
    WIDTH=0
    WIDTH=0
    MAYSCRIPT=true>
    <PARAM NAME=URL VALUE="composer.xml">
</APPLET>

Since the DSO is implemented in Java, embedding it on the page requires the use of the APPLET tag. The CLASS attribute specifies the package in which the code is implemented. The URL property specifies the location of the data. The XML DSO retrieves the XML from this location, parses it, and provides the data to bound elements on the page. The data consuming elements are isolated from the details of XML.

Click the Show Me button to see a simple example that uses the XML DSO to display an XML data set in a tabular format.

Using the XML DSO to view hierarchical data

The following example shows how the XML DSO can be used to bind nested tables to hierarchical XML data. The XML data contains a list of CUSTOMERS. Each customer contains a list of ORDERS. Each order contains a list of ITEMS yielding three levels of repetition bound to three nested tables.

Additional XML resources

For additional information on XML, see the following resources:

  • Latest working draft published by the XML working group at the W3C
  • Information on the XML standard
  • W3C XML Resources

MSHTML Data Source

In addition to using external components as data source objects, Web authors can define their data sets within an HTML document and use MSHTML itself to provide read-only data to a page. For the purposes of this section, the page supplying the data is called the data page.

When MSHTML is used as a DSO, it parses through the data page in search of elements with an ID attribute. The set of unique IDs defines the columns in the data set, and Web authors use these ID attributes as the value for the DATAFLD attribute on elements of the bound page. For example, given the following SPAN from a data page, MSHTML interprets compsr_last as the name of a column and Mozart as data in that column.

<SPAN ID=compsr_last>Mozart</SPAN>

Multiple elements on the page sharing the same ID identify additional records in the data set. A column that is not represented is given the null value in the corresponding data set. Only elements with an opening and closing tag (for example, DIV, SPAN, H1) can be used to supply data. The following example defines a two-column table consisting of three records.

<<H1 ID=COMPSR_FIRST>Hector</H1>
<MARQUEE ID=COMPSR_LAST>Berlioz</MARQUEE>
<DIV ID=COMPSR_BIRTH>1803</DIV>
<H2 ID=COMPSR_FIRST>Modest</H2>
<H3 ID=COMPSR_LAST>Moussorgsky</H3>
<BUTTON ID=COMPSR_BIRTH>1839</BUTTON>
<TEXTAREA ID=COMPSR_FIRST>Franz</TEXTAREA>
<XMP ID=COMPSR_LAST>Liszt</XMP>
<SPAN ID=COMPSR_BIRTH>1811</SPAN>

Observe that the MSHTML DSO disregards the lack of consistency in the elements used. In the example above, the H1, H2, and TEXTAREA elements represent the data for the first name column in the data set; the P, H3, and XMP elements represent the last name column; the DIV, BUTTON, and SPAN elements represent the date of birth column.

Once the data page is defined, use an OBJECT tag on the data bound page to supply the data as follows:

<OBJECT ID=htmlComposer DATA="compdata.htm" HEIGHT=0 WIDTH=0>
</OBJECT>

The DATA attribute points to the data page and can specify a complete or relative URL.

Elements on the page used to present the data can be bound using the data binding extensions.

Click the Show Me button to see how the MSHTML DSO works.

Creating Custom Data Source Objects

While the components described above are implementations of data source objects (DSO) provided with Internet Explorer 4.0 and available through the DSO gallery, the specification is completely open and language independent so that independent software vendors (ISVs) can create their own data providers. For more information on creating a DSO, see the COM Objects as Data Providers document.


DHTML Event Model Support for Data Binding

The document object model exposes an extensive set of scriptable events that Web authors can use to customize the behavior of objects on an HTML page. The data binding architecture leverages this model by exposing an additional set of events that are of interest to authors creating data-driven pages. These events fall into three categories:

  • Those that apply to the data source object
  • Those that apply to the bound elements
  • Those that apply to the page

Web authors handle these events to maintain a finer grain of control over the page, especially those that support update. Events occur as the data is loaded and is manipulated by the DSO, as the user interacts with the data, and as the page unloads. The events allow the Web author to monitor changes in the state of the DSO, to perform field and record-level validation, and to execute cleanup processing as the page is unloaded.

The following table provides a quick reference on the events that are relevant to data binding; more detailed descriptions follow. For an overview on how to handle events in the document object model, see Understanding the Event Model.

Event Bubbles Canceleable Applies To

The Bubbles column indicates whether or not the event bubbles up the containment hierarchy. Most data-related events bubble. The onbeforeunload event does not bubble because it fires on the window object, which is at the top of the containment hierarchy.

The Canceleable column indicates whether the default action associated with the event can be canceled. The onbeforeupdate event, for example, can be canceled to allow the author to prevent the field to which a consumer is bound from being updated. The onafterupdate event cannot be canceled because the update has already occurred by the time the event fires. It would not have fired had the author canceled the onbeforeupdate event.

The Applies To column indicates the type of element from which the event originates. Bound elements are elements on the page that consume data from a DSO. DSO is any object or application that conforms to the specification for data source objects.

Events That Apply to the DSO

The DSO sends notifications when the data set has changed, as data becomes available, when the data is completely available, and before and after a record supplied by the DSO is committed to the data cache.

ondatasetchanged

The ondatasetchanged event fires under two circumstances:

  • After a new data set is requested.
  • When the current data set has been altered (for example, filtered or sorted).

When the event occurs, data may not be available, but the recordset can be used to obtain the metadata for the data set. Metadata includes the list of fields and their types. Web authors can create truly dynamic pages using metadata.

The following example code adds the list of fields provided by a DSO to a drop-down list, cboSort. When the user selects an item in the drop-down list, the data is sorted by the selected field.

This code handles the ondatasetchanged event for the DSO name dsoComposers.

<SCRIPT FOR=dsoComposers EVENT=ondatasetchanged>
    FillSortDropDownWithFields(cboSort, this.recordset);
</SCRIPT>

The following code loops through the collection of fields provided by the ADO recordset and adds each field name to the options collection.

<SCRIPT>
// Add specified value/text to the dropdown list
function AddItemToDropDown(oDropDown, cValue, cText)
{
    oOption = document.createElement('OPTION');
    oOption.value = cValue;
    oOption.text = cText;
    oDropDown.add(oOption);
}

// Fill dropdown with field names from the ADO RecordSet
function FillSortDropDownWithFields(oDropDown, oRecordSet)
{
// only fill once or let the caller clear list first
    if (oDropDown.options.length > 0)
        return;

    AddItemToDropDown(oDropDown, "None", "None"); // default
    // add each of the columns in the data set to the drop-down
    for (i = 0; i < oRecordSet.fields.count; i++)
    {
        oField = oRecordSet.fields(i);
        AddItemToDropDown(oDropDown, oField.name, oField.name);
    }
    cboSort.selectedIndex = 0;
}
</SCRIPT>

When the user selects an item from the drop-down list, the following code sets the DSO sort property equal to the appropriate filter or to the empty string if "None" was selected. Note that while the previous code samples work with any DSO, the following code is specific to the Tabular Data Control (TDC).

<SCRIPT FOR=cboSort EVENT=onchange>
    cValue = this.options[this.selectedIndex].value;
    tdcComposers.object.Sort = (cValue == 'None' ? '' : cValue);
    tdcComposers.Reset();
</SCRIPT>

ondataavailable

DSOs typically fire the ondataavailable event when they provide their data asynchronously, indicating that additional records are accessible. Web authors should not rely upon this event to fire but might instead use it to indicate progress to the user. The event may fire zero or more times.

ondatasetcomplete

The ondatasetcomplete event fires when a DSO has cached all its data on the client. The reason property of the event object indicates success (0), abort (1), or failure (2) of the download. A failure might result from an error or from an explicit user action, such as clicking the Stop button. If reason indicates success, all the data is programmatically accessible through the ADO Recordset object.

onreadystatechange

While onreadystatechange is not specific to a DSO, understanding the state of an object can be useful. When this event fires, the event-handling code can retrieve the current value of the readyState property. It is typically safe to access the properties of an object when it reaches a ready state of complete.

<SCRIPT FOR=tdcComposer EVENT=onreadystatechange>
if (this.readyState == 'complete')
{
    // perform some action
}
</SCRIPT>

onrowenter

The onrowenter event fires when the current record pointer has changed, for example, through ADO Recordset navigation. Web authors can use this event to preprocess the data in the current record.

onrowexit

The onrowexit event fires before the current record pointer changes. This might occur for the following reasons:

  • Calling a method on the DSO
  • Deleting the current record
  • Leaving the page

The Web author can perform record-level validation prior to moving to the next record. By returning FALSE from this event handler, the Web author can prevent the user from moving to the next record.

The following code performs a simple validation to ensure that the data indicates that the composer's birthday occurred before his death.

<SCRIPT FOR=dsoComposers EVENT=onrowexit>
if (txtBorn.value > txtDied.value)
{
    alert("Birth date must be less than or equal to deceased dates");
    return false;
}
</SCRIPT>

Events that Apply to Data Consumers

Bound elements fire events that allow page authors to perform field-level validation and to handle errors that occur during an update.

onbeforeupdate and onafterupdate

The onbeforeupdate event fires when the data in an element has been changed and that element is about to lose the focus. An element loses focus when the user tabs to the next or previous field in the tab order, uses the mouse to select a different control, or unloads the page. The events do not fire if the value of a bound control is set programmatically. Should the validation code associated with the event detect invalid data, an author can return FALSE to prevent the user from leaving the field.

The following code performs some basic validation on the value entered into a text box. If the value is nonnumeric or outside a specified range, the user is alerted and prevented from leaving the field.

<SCRIPT FOR=txtBorn EVENT=onbeforeupdate>
    dToday = new Date();
    fRet = ValidateDate(parseInt(this.value), 0, dToday.getFullYear());
    event.cancelBubble = true;
    return fRet;
</SCRIPT>

<SCRIPT>
// perform some basic validation on the date
function ValidateDate(nValue, nMin, nMax)
{
    if (isNaN(nValue))
    {
        alert("Year required");
        return false;
    }

    if (nValue < nMin || nValue > nMax)
    {
        alert("Invalid year");
        return false;
    }
    return true;
}

Both the original and the modified data can be obtained while handling the onbeforeupdate event because, while the control's value has been updated, the data has not been committed to the DSO. Use the ADO recordset supplied by the DSO to get the original value. Use the appropriate control property to obtain the current value as entered by the user. Here's an example that works for any text box.

<SCRIPT FOR=txtBorn EVENT=onbeforeupdate>
    curValue = this.value;
    origValue = dsoComposers.recordset.fields(this.dataFld).value;
</SCRIPT>

If the onbeforeupdate event is not canceled, onafterupdate fires after data is transferred from consumer to data provider.

onerrorupdate

The onerrorupdate event fires when an error occurs while transferring data from the data consumer to the data source object through some user interaction. By canceling this event, any system-provided error dialog boxes are suppressed.

Events That Apply to the Page

In addition to the events specified above for data bound elements and data source controls, the onbeforeunload event allows the Web author to save data changed on the page that has not been committed to the location from which the DSO obtains its data. The following user actions are among those that cause onbeforeunload to fire:

  • Hyperlink navigation
  • Clicking the Forward or Back button
  • Selecting a URL from Favorites
  • Clicking a Submit button
  • Refreshing the page

In addition to these user actions, a script that causes the page to unload will also trigger this event.

window.location.href = "http://www.microsoft.com/ie/ie40";

While the onbeforeunload event is not cancelable, a script writer can return a string from the event through the returnValue property. The string is displayed along with an informative message giving the user the opportunity to cancel the navigation. For example, to warn the user of potential data loss, handle the event as follows:

<SCRIPT FOR=window EVENT=onbeforeunload>
    if (g_fFieldsChanged > 0)
        event.returnValue = "Warning: Modified data has not been saved.";
</SCRIPT>

The g_fFieldsChanged flag used in the example indicates that the page has changed. Page authors can track changes to fields by handling the onafterupdate event:

<SCRIPT FOR=document EVENT=onafterupdate>
    g_fFieldsChanged = g_fFieldsChanged + 1
</SCRIPT>

Putting It All Together with the Data Binding Event Tracker

Click the Show Me button to launch a sample that demonstrates many of the events and concepts discussed in this section.

The sample uses the TDC, so no data will be committed back to the data file. Data can be modified in the local cache, however. By modifying the values within the elements on the page, navigating through the records using the navigation buttons, and changing the filter and sort order through the drop-down lists, the majority of the events will fire. Observe the events and the order in which they occur as they are logged to the TEXTAREA on the right half of the sample page. Clear the event log at any time by clicking the Clear Log button.


DHTML Object Model Support for Data Binding

In Internet Explorer 4.0, elements are exposed to scripts as objects. The attributes supported by those elements are exposed as properties. Just as a user can perform actions on most elements (clicking a button for example), scripts can call methods of the corresponding object. Scripts can also customize the behavior of elements by handling the events exposed by the corresponding object.

Web authors can achieve dramatic effects on their data bound pages by adding simple scripts that manipulate the properties, methods, and events exposed by the document object model. The document object model supports the following capabilities at run time:

Modifying the Binding of Elements to Data

Binding a Table at Run Time

Dynamically Adding Bound Elements and Data Providers

Dynamically Changing the Way Elements Render Data

Dynamically Controlling the Amount of Displayed Data

Manipulating Data with Active Data Objects (ADO)

This section discusses how to use these features. Because the event model exposed by the document object model for data binding is so extensive, it is treated in a separate section below.

Modifying the Binding of Elements to Data

The DATASRC and DATAFLD attributes, introduced above, allow an author to bind an HTML element to data. The document object model exposes these attributes as the properties dataSrc and dataFld, and their values can be modified at any time through scripts.

Web authors may want to perform the following operations on elements that support data binding:

  • Add a binding to an unbound element
  • Remove a binding from a currently bound element
  • Change the current binding of an element

The following sections assume that the element is not serving as a template element in a repeated table scenario. Dynamic tabular binding is discussed below.

Adding a binding to a single-valued element at run time

Given an element that supports data binding, such as a SPAN or TEXTAREA, adding a binding is as simple as setting the dataSrc and dataFld properties of that element. For example, to bind a span with ID span1 to the first name field in a data set provided by a DSO with id dsoComposer, use the following script:

span1.dataSrc = "#dsoComposer";
span1.dataFld = "compsr_first";

The same binding can be accomplished at design time using the following HTML code:

<SPAN DATASRC="#dsoComposer" DATAFLD="compsr_first"></SPAN>

In both cases compsr_first is the name of an actual field in the data set. The binding will not occur until both properties are set, and any prior value stored by the element will be lost. If the value is required at a later time, for example when the binding is removed, the page author must cache the value prior to binding the element.

Click the Show Me button to see an example.

Removing the binding from a bound element

To remove the binding from a currently bound element, simply set the dataSrc and dataFld properties to the empty string. For example:

span1.dataSrc = "";
span1.dataFld = "";

The previous Show Me button demonstrates this behavior.

Modifying the binding of a single-valued element at run time

Modifying an existing binding is similar to binding an unbound element. Two cases are described:

  • Binding an element to another field within the same data set.
  • Binding an element to another field in another data set.

To bind an element to another field in the same data set, modify the dataFld property. For example, given a SPAN with ID span1 that is currently bound to a composer's first name, the following code binds the SPAN to the composer's last name.

span1.dataFld = "compsr_last";

To bind an element to a field in a different data set:

  • Set the value of the dataSrc property to the DSO that provides the data.
  • Set the value of the dataFld property for the element if the name of the field in the data set provided by the DSO is different than that of previous the DSO.

Binding a Table at Run Time

The section on Binding HTML Elements to Data explained how to bind a table to data at design time. Binding a table at run time requires three steps:

  1. If the table is already bound to a data source, it must be unbound by setting the dataSrc property of the corresponding table object to the empty string.
  2. Modify the bindings of the template elements contained by the table by setting the dataFld property of the corresponding objects.
  3. Bind the table to the appropriate data source by setting the dataSrc property of the corresponding table object.

Note that modifying the bindings of any of the individual elements contained within a table requires that the entire table be unbound and then rebound to the DSO. This is necessary because while the table is bound, changes to elements inside the table are applied to the generated rows. Changes while the table is unbound affect the template. Click the Show Me button to see an example that modifies the binding at run time.

<SCRIPT FOR=cboField EVENT=onchange>
    cDSO = tblComposers.dataSrc; // remember the DSO
    tblComposers.dataSrc = ""; // unbind the table

    // set the binding for the contained element
    spanField.dataFld = this.options(this.selectedIndex).value;

    tblComposers.dataSrc = cDSO; // rebind the table
</SCRIPT>

<TABLE ID=tblComposers DATASRC=#dsoComposers>
    <THEAD><TR STYLE="font-weight:bold">
        <TD>Last Name</TD>
        <TD><SELECT ID=cboField>
            <OPTION VALUE=compsr_first SELECTED>First Name</OPTION>
            <OPTION VALUE=compsr_last>Last Name</OPTION>
            <OPTION VALUE=compsr_birth>Date of Birth</OPTION>
            <OPTION VALUE=compsr_death>Date of Death</OPTION>
            <OPTION VALUE=origin>Origin
           </SELECT>
         </TD>
    </TR></THEAD>
    <TR>
        <TD><SPAN DATAFLD=compsr_Last></SPAN></TD>
        <TD><SPAN ID=spanField DATAFLD=compsr_first></SPAN></TD>
    </TR>
</TABLE>

This example uses the drop-down list to dynamically set the binding of the second column of the table. When a value is selected in the drop-down list, the onchange event handler stores the table's previous binding in a temporary variable. It then unbinds the table by setting its dataSrc property to the empty string. Finally, the code rebinds the table to the DSO by setting the dataSrc property to the previous value.

Dynamically Adding Bound Elements and Data Providers

In addition to modifying the bindings of existing elements on the page, the document object model supports the dynamic addition of both data bound elements and data source objects at run time. By adding these elements at run time, Web authors can reduce the initial download time of their content and can use a single page to display various sets of data to the user.

Click the Show Me button to see an example that dynamically adds a data source object and bound elements to the page.

Dynamically Changing the Way Elements Render Data

The DATAFORMATAS attribute, introduced above, allows an author to change the way an element renders its data. The document object model exposes the dataFormatAs property on elements that support rendering in formats other than text. Click the Show Me button to see how it works.

Dynamically Controlling the Amount of Displayed Data

The DATAPAGESIZE attribute introduced above allows an author to restrict the number of records displayed by a tabular data consumer. The document object model exposes this attribute as the property dataPageSize, and its value can be modified at any time through scripts. In addition, the page author can control the currently viewed page of records displayed by a tabular consumer using the nextPage and previousPage methods.

Click the Show Me button to see how the dataPageSize property and accompanying methods work on a TABLE, a tabular data consumer.

Manipulating Data with Active Data Objects (ADO)

Previous sections have shown how to use HTML elements to bind and display the data provided by a DSO. Independent of the user interface, scripts can access and manipulate the data provided by a DSO in a consistent manner using the ADO recordset object. The recordset object is exposed by all data source objects through the extended recordset property.

Scripting the ADO recordset object, Web authors can add rich functionality to their pages, including:

  • Navigation
  • Insertion, deletion, and update of records

For complete information on ADO, see the accompanying Active Data Objects documentation.

Accessing the ADO recordset object from script

Given a reference to a data source object, accessing the ADO recordset is easy. The following code sample assumes that dsoComposer is a valid DSO.

var oRecordSet = dsoComposer.recordset;

When using a case-sensitive scripting language such as JScript, observe that the recordset property is completely lowercase.

Navigating through a data set

Data binding in Internet Explorer 4.0 uses the notion of a current record to indicate the record in a data set to be displayed by single-valued consumers. When a data set is first loaded, the first record is typically identified as the current record. The current record is affected by any filter or sort order applied to the data. Single-valued consumers always display the current record.

To change the current record and hence the data displayed by single-valued consumers, Web authors can provide users with a set of navigation buttons like the ones shown below.

The code behind these buttons calls the MoveFirst, MovePrevious, MoveNext, and MoveLast methods on the ADO recordset, respectively.

<INPUT ID=cmdNavFirst TYPE=BUTTON VALUE="<<"
    onclick="tdcComposers.recordset.MoveFirst()">

<INPUT ID=cmdNavPrev TYPE=BUTTON VALUE=" < "
    onclick="tdcComposers.recordset.MovePrevious();
    if (tdcComposers.recordset.BOF)
        tdcComposers.recordset.MoveFirst();">

<INPUT ID=cmdNavNext TYPE=BUTTON VALUE=" > "
    onclick="tdcComposers.recordset.MoveNext();
        if (tdcComposers.recordset.EOF)
            tdcComposers.recordset.MoveLast();">

<INPUT ID=cmdNavLast TYPE=BUTTON VALUE=">>"
    onclick="tdcComposers.recordset.MoveLast()">

Using the recordNumber property

If a page displays both single-valued and tabular data consumers on the page, the Web author can add functionality so that when the user clicks a row in the table, the current record and single-valued consumers are set to display the selected row. Likewise, when the user clicks navigation buttons on the page, the table can be synchronized to indicate the currently selected record. Click the Show Me button to see how it works.

The script behind the example uses the recordNumber property available on all repeated elements within a data bound table. This includes both bound and unbound elements. The property returns the number of the record displayed by the table row. In the example, when the user clicks any element within a table row, the click-handling code sets the AbsolutePosition property of the ADO recordset to the value of that element's recordNumber property.

In turn, if the user clicks a navigation button, the appropriate Move method is called on the ADO recordset. Then the highlighted row in the table is updated by searching for the table row with the recordNumber that corresponds to the value of the AbsolutePosition property on the ADO recordset. Once found, the background color of the table row is set to yellow.

Adding, deleting, and modifying records in a data set

To support the addition and deletion of records from a recordset, the ADO recordset object supports both AddNew and Delete methods. When AddNew is called from a script, the DSO adds a new record to the locally cached data set. When Delete is called, the current record is removed from the local data cache.

Bound elements are immediately updated to reflect the addition, removal, and modification of records through scripts. If the current record is removed, single-valued elements are updated to display the next record in the data set. If the last record in the data set is deleted, the previous record is displayed. Tabular data consumers are updated to no longer display the deleted record.

It is important to distinguish between operations that are performed on the local data cache and those that affect the back-end data set. While the TDC, for example, supports the modification of data in the local cache, it does not support committing those changes to the file from which the data was obtained. In contrast, the Remote Data Service (RDS) does support this feature.

Click the Show Me button to see an example that exercises the ADO object model to insert, delete, and update records in the local data cache.


AddAmbient Method

Description

Adds an ambient light to the Lights Filter Effect object. Ambient light is nondirectional light that sheds parallel beams perpendicular to the surface of the page. Ambient light has color and strength values and can be used to add more color to the page; it is often used in conjunction with other lights.

Syntax

call object.filters.Light.addAmbient(R,G,B,strength)

Parameter | Description
object | Name of the object to which the Light filter is applied.
R | Red value, integer from 0 to 255. 0 is lowest saturation, 255 is highest.
G | Green value, integer from 0 to 255. 0 is lowest saturation, 255 is highest.
B | Blue value, integer from 0 to 255. 0 is lowest saturation, 255 is highest.
strength | Intensity setting.

Remarks

This example shows how to create a blue ambient light with a fairly low intensity.

call object.filters.Light.addAmbient(0,0,255,10)

Applies To

Light Filter


AddCone Method

Description

Adds a cone light to the Lights Filter Effect object to cast a directional light on the page.

Syntax

call object.filters.Light.addCone(x1,y1,z1,x2,y2,R,G,B,strength,spread)

Parameter | Description
object | Name of the object to which the Light filter is applied.
x1, y1, z1 | Source light's coordinates.
x2, y2 | Target focus coordinates. Note: z2=0 is implied.
R | Red value, integer from 0 to 255. 0 is lowest saturation, 255 is highest.
G | Green value, integer from 0 to 255. 0 is lowest saturation, 255 is highest.
B | Blue value, integer from 0 to 255. 0 is lowest saturation, 255 is highest.
strength | Intensity setting. Integer value. Note: strength specified pertains to the target coordinates. When the light is later moved, the strength is re-scaled to still pertain to the new target.
spread | Angle of light spread in the relationship between the vertical position of the light source and the surface of the visual object. 0 to 90 degrees. Low spread (such as low integer values) produces a smaller shaped cone of light. High angle of spread produces an oblique oval or circle of light.

Remarks

The cone light fades with distance from the target x,y position. It displays a hard edge at the near edge of the cone light's focus and fades gradually as it reaches the cone light's distance threshold.

Applies To

Light Filter


AddPoint Method

Description

Adds a point light source, like a light bulb.

Syntax

call object.filters.Light.addPoint(x,y,z,R,G,B,strength)

Parameter | Description
object | Name of the object to which the Light filter is applied.
x, y, z | Point light's coordinates.
R | Red value, integer from 0 to 255. 0 is lowest saturation, 255 is highest.
G | Green value, integer from 0 to 255. 0 is lowest saturation, 255 is highest.
B | Blue value, integer from 0 to 255. 0 is lowest saturation, 255 is highest.
strength | Intensity setting. Integer value.

Remarks

Intensity on the page is controlled by the angle of light on the surface. Add several for great multipoint gradients.

Applies To

Light Filter


Alpha Filter Effect

Description

Sets the level of opacity for your visual object. The opacity can be set as uniform or graded, in a linear or radial fashion.

Syntax

{ FILTER: Alpha(Opacity=opacity, FinishOpacity=finishopacity, Style=style, StartX=startX, StartY=startY, FinishX=finishX, FinishY=finishY)"}

Parameter | Description
opacity | Level of the opacity. 0, the default, is fully transparent; 100 is fully opaque.
finishopacity | (Optional) Ranges from 0 (fully transparent) to 100 (fully opaque).
style | Specifies the shape characteristics of the opacity gradient. Possible values are 0 (uniform), 1 (linear), 2 (radial), or 3 (rectangular).
startX | X coordinate for opacity gradient to begin.
startY | Y coordinate for opacity gradient to begin.
finishX | X coordinate for opacity gradient to end.
finishY | Y coordinate for opacity gradient to end.


Apply Method

Description

Applies a transition to the designated object.

Syntax

Call object.filters.item(index).apply()

Parameter | Description
object | Identifier of the object to which the filter is to be applied.
index | Integer. Index (position in the collection of transitions for this object) number of the transition. Value can be 0-n, where n is the last transition made available to this object.

Applies to

Transition filters


Blend Transition Filter

Description

Performs a fade (in or out) of the selected visual object.

Syntax

{ filter: blendTrans(Duration=duration)}

Parameter | Description
duration | Length of time the transition should take to complete. Value, float. Value is expressed in seconds.milliseconds (0.000).

Remarks

This attribute is not inherited. An asterisk in the following applies to list indicates that a defined height, width, or absolute position is required.

Applies To

BODY, BUTTON, DIV*, IMG, INPUT, MARQUEE, SPAN*, TABLE, TD, TEXTAREA, TFOOT, TH, THEAD, TR

See Also

Reveal Transition Filter, Visual Filter, Properties, Methods, and Events Reference


Blur Filter Effect

Description

Averages the pixels of the visible object for a specified length and direction, creating the impression that the object is moving at high speed.

Syntax

{FILTER: Blur(Add=add, Direction=direction, Strength=strength)}

Parameter | Description
add | Boolean switch specifying whether to add the original image to the motion-blurred image. If true (nonzero integer), the image is added to the motion blurred image; if false (zero), the image is not added to the motion blurred image.
direction Direction of the motion blur clockwise from the vertical orientation of the object, rounded to 45-degree increments. The default value is 0 (straight up). Possible values are shown in the following table.
Value | Description
0 | Top
45 | Top right
90 | Right
135 | Bottom right
180 | Bottom
225 | Bottom left
270 | Left
315 | Top left
strength | Long value that specifies the number of pixels the blur will extend.

Remarks

You can create a nice effect for fonts by setting add to 1.

For the direction parameter, negative values or values larger than 360 degrees will wrap around to their equivalent angle (for example, -45 degrees is equivalent to 315-degree orientation). This allows mathematical manipulations to be carried out easily in code.


ChangeColor Method

Description

Changes the light color for any light on the page.

Syntax

call object.filters.Light.ChangeColor(lightnumber, r,g,b, fAbsolute)

Parameter | Description
object | Name of the object to which the Light filter is applied.
lightnumber | Identifying number for the light, for use in script.
r | Red value, integer from 0 to 255. 0 is lowest saturation, 255 is highest.
g | Green value, integer from 0 to 255. 0 is lowest saturation, 255 is highest.
b | Blue value, integer from 0 to 255. 0 is lowest saturation, 255 is highest.
fAbsolute | If this flag is true (nonzero), ChangeColor sets the value to be that new value. If this flag is false (zero), ChangeColor increments or decrements the color value by that amount.

Applies To

Light Filter


ChangeStrength Method

Description

Changes the intensity of the light.

Syntax

call object.filters.Light.ChangeStrength(lightnumber, strength, fAbsolute)

Parameter | Description
object | Name of the object to which the Light filter is applied.
lightnumber | Identifying number for the light, for use in script.
strength | New intensity.
fAbsolute | If this flag is true (nonzero), ChangeStrength sets the strength value to be the new value. If this flag is false (zero), ChangeStrength increments or decrements the strength value by that amount.

Applies To

Light Filter


Chroma Filter Effect

Description

Selectively renders a specific color transparent for the selected visual object.

Syntax

{FILTER: Chroma(Color=color)}

Parameter | Description
color | Value of the color to be subject to chromakey transparency. Color is expressed in #RRGGBB format, where RR is the red hexadecimal value, GG is the green hexadecimal value, and BB is the blue hexadecimal value.

Remarks

This effect is not recommended for files that have been dithered from 24 to 8 bit. In particular, JPEG files, as dithered and compressed files, do not produce an entirely solid chromakey color, resulting in uneven effects. Chromakey doesn't work well on anti-aliased sources, in which sharp lines are smoothed by blending the colors of surrounding pixels. Choosing a specific chromakey color will cause some colors that would otherwise be transparent to be fully opaque.


Clear Method

Description

Deletes all lights associated with the specified Lights Filter.

Syntax

call object.filters.Light.Clear

Parameter | Description
object | Name of the object to which the Light filter is applied.

Remarks

This will clear all light sources on the object.

Applies To

Light Filter


Drop Shadow Filter Effect

Description

Paints a solid silhouette of the selected visual object, offset in the specified direction. This creates the illusion that the visual object is floating above the page and is casting a shadow onto the page.

Syntax

{FILTER: DropShadow(Color=color, OffX=offX, OffY=offY, Positive=positive)}

Parameter | Description
color | Specific color for the drop shadow effect. Color is expressed in #RRGGBB format, where RR is the red hexadecimal value, GG is the green hexadecimal value, and BB is the blue hexadecimal value.
offX | Number of pixels the drop shadow is offset from the visual object, along the x-axis. Expressed in integers. Positive integers move the drop shadow to the right. Negative integers move the drop shadow to the left.
offY | Number of pixels the drop shadow is offset from the visual object, along the y-axis. Expressed in integers. Positive integers move the drop shadow down. Negative integers move the drop shadow up.
positive | Boolean. A true (nonzero) value, the default, creates a drop shadow of any nontransparent pixel of the visual object. If false (zero), drop shadows are created for any transparent pixel of the visual object.

Remarks

If you have a transparent object but still want the usual shadow effect, set positive to zero. The transparent object will have a drop shadow outside the transparent region, rather than a drop shadow inside the transparent region.


Duration Property

Description

Sets the default length of time the transition will take to complete.

Syntax

STYLE="FILTER: transitiontype(duration=duration, transition=transitionshape)"

Parameter | Description
duration | Length of time the transition should take to complete. Value, float. Value is expressed in seconds.milliseconds (0.000). Read-write at run time. If transition has been applied or is playing, read-only.
transitionshape | Shape of the transition (Reveal transition only). Integer. Value from 0 to 23. For information on the available transition shapes, see the Reveal Transition topic.

Remarks

A transition's playback duration can also be set as a parameter of the Play method.

Applies to

Transition filters


enabled

Description

Specifies whether the filter is enable or disabled

Syntax

status = object.filter.enabled=fValue

Parameter | Description
fValue | Boolean value indicating whether the filter is enabled (true) or disabled (false). The property is read-write.

Remarks

<img id=image1 src="sample.jpg" style="filter:blur(strength=50) flipv()">

<SCRIPT>
   image1.filters[1].enabled = false; // disable the flip filter
</SCRIPT>

Applies to

Transition filters


Flip Horizontal Filter Effect Flip Horizontal Filter Effect *
  * Previous Topic: Drop Shadow Filter Effect
  * Next Topic: Flip Vertical Filter Effect

Flip Horizontal Filter Effect

Description

Renders the visual object as a mirror image of itself along the horizontal plane.

Syntax

{FILTER: FlipH}


Flip Vertical Filter Effect Flip Vertical Filter Effect *
  * Previous Topic: Flip Horizontal Filter Effect
  * Next Topic: Glow Filter Effect

Flip Vertical Filter Effect

Description

Renders the visual object as a mirror image of itself along the vertical plane.

Syntax

{FILTER: FlipV}


Glow Filter Effect

Description

Adds radiance around the outside edges of the object, giving it the appearance of a glow.

Syntax

{FILTER: Glow(Color=color, Strength=strength)}

Parameter | Description
color | Specific color for the shadow effect. Color is expressed in the #RRGGBB format, where RR is the red value, GG is the green value, and BB is the blue value.
strength | Intensity of the glow. 1—255.


Grayscale Filter Effect

Description

Drops the color information from the visual object's color palette, rendering the object in grayscale.

Syntax

{FILTER: Gray}


Invert Filter Effect

Description

Reverses the hue, saturation, and brightness values of the visual object.

Syntax

{FILTER: Invert}


Light Filter Effect

Description

Simulates the projection of a light source onto the selected visual object.

Syntax

{FILTER: Light}

Remarks

Once you have defined your Light Filter effect collection for your object, you call its methods to set or change its properties.
Light Filter method | Description
AddAmbient Method | Adds ambient light source.
AddCone Method | Adds cone light source.
AddPoint Method | Adds point light source.
ChangeColor Method | Changes light color.
ChangeStrength Method | Changes light strength.
Clear Method | Clears all lights.
MoveLight Method | Moves light source.

You can control the virtual position of the light source, the x and y coordinates of the focus of the light, the type of light (point or cone) and whether the light has hard or diffuse edges, the color of the light, and its intensity. The maximum number of lights available to each Visual Filter control is 10, so to add more than 10 lights to your page, you will need multiple Visual Filter controls.

When a light effect is created, it has a default ambient light associated with it. The first light you add to the object replaces this default ambient light.

You can associate only one object per light effect. To light several different separate objects (for example, a text phrase and a bitmap image), you need a separate instance of the Lights Filter effect for each object. However, if you combine several objects into a single object by using a DIV tag, you can use one light object to light the combined object.


Mask Filter

Description

Takes the selected visual object, paints the transparent pixels a specific color, and makes a transparent mask from its nontransparent pixels.

Syntax

{FILTER: Mask(Color=color)}

Parameter | Description
color | Color that the transparent regions are painted. Color is expressed in #RRGGBB format, where RR is the red hexadecimal value, GG is the green hexadecimal value, and BB is the blue hexadecimal value.


MoveLight Method

Description

Moves the light effect on the page.

Syntax

call object.filters.Light.MoveLight(lightnumber, x, y, z, fAbsolute)

Parameter | Description
object | Name of the object to which the Light filter is applied.
lightnumber | Identifying number for the light, for use in script.
x, y, z | Location to move the light to.
fAbsolute | Whether the movement is absolute or relative.

Remarks

For cone lights, this method changes the position of the light's focus, the target x,y values. For point lights, this method changes the source location, the source x,y,z values. This method has no effect for ambient lights.

Applies To

Light Filter


Onfilterchange Event

Description

Fires when a visual filter changes state or completes a transition.

Remarks

This event will bubble. Events that bubble can be handled on any parent element of the object that fired the event.

If you have multiple objects with transitions on a page, you can determine which object fired the Object_onfilterchange event by checking Window.Event.srcElement. The filters and transitions that ship with Internet Explorer 4.0 fire the event when a transition completes, although the underlying architecture allows future filters to fire at any time their internal states change.

<HTML>
<HEAD>
<TITLE>Microsoft Cascading Style Sheets Controls Samples </TITLE>
</HEAD>
<Div ID = "TextRegion"
    STYLE="Position:absolute;LEFT: 0; TOP: 200; WIDTH: 100%; VISIBILITY: visible; FILTER: revealTrans(Transition = 1, Duration = 1.25)">
Some Text
</DIV>
<DIV ID="ImageRegion"
    STYLE="Position:absolute;LEFT: 0; TOP: 200; WIDTH: 100%; VISIBILITY: hidden; FILTER: revealTrans(Transition = 1, Duration = 1.25)">
<IMAGE SRC="Image1.jpg">
</DIV>
<SCRIPT LANGUAGE=VBScript>
Sub Window_onload
    Call TextRegion.filters.revealTrans.Apply ()
    Region.filters.RevealTrans(transition=23)
    Call ImageRegion.filters.revealTrans.Apply()
    Image1.filters.revealTrans(transition=12)
    Call Start
End Sub

Sub Start
    If TextRegion.style.visibility = "visible"   then
        ImageRegion.style.visibility = "hidden"
    Else
        ImageRegion.style.visibility = "visible"
        TextRegion.style.visibility = "hidden"
    End if
    Call TextRegion.Style.filters.revealTrans.Play(1.5)
End Sub

Sub Region_onfilterchange
Select case Window.Event.srcElement
    Case "Region"
        If Region.filters.revealTrans.Status = 0 then
                Call ImageRegion.filters.revealTrans.Play(1.5)
        End If
    End select
End Sub
</SCRIPT>
</BODY>
</HTML>

An asterisk in the following applies to list indicates that a defined height, width, or absolute position is required.

Applies To

BODY, BUTTON, DIV*, IMG, INPUT, MARQUEE, SPAN*, TABLE, TD, TEXTAREA, TFOOT, TH, THEAD, TR


Play Method

Description

Plays the transition.

Syntax

Call object.filters.item(index).play(duration)

Parameter | Description
object | Identifier of the object to which the filter has been applied.
duration | Float, seconds.milliseconds (0.000). Valid values are 0.0-N.n. Optional parameter, read-write at run time.

Remarks

If a playback duration is explicitly specified as a parameter of the this method, it will override the Duration property assigned to the transition for that instance of the transition's playback.

Applies to

Transition filters


Visual and Transition Filters Reference Visual and Transition Filters Reference *
  * Previous Topic: Filters and Transitions
  * Next Topic: Blend Transition Filter

Visual and Transition Filters Reference

Internet Explorer 4.0 ships with the following filters:
Blend Transition Filter
Reveal Transition Filter
Visual Filters


Visual Filter Effects Reference

Visual Filters allow you to manipulate the display of other visible objects, with any of several predefined filter effects. This section describes the specific filter effects.

Alpha Filter Effect
Blur Filter Effect
Chroma Filter Effect
Drop Shadow Filter Effect
Flip Horizontal Filter Effect
Flip Vertical Filter Effect
Glow Filter Effect
Grayscale Filter Effect
Invert Filter Effect
Light Filter Effect
Mask Filter
Shadow Filter Effect
Wave Filter Effect
XRay Filter Effect


Properties, Methods, and Events Reference

This section describes the properties, methods, and events associated with the visual and transition filters.
Properties
Duration
Status
enabled

Methods
Apply
Play
Stop
AddAmbient Method (Light Filter Effect)
AddCone Method (Light Filter Effect)
AddPoint Method (Light Filter Effect)
ChangeColor Method (Light Filter Effect)
ChangeStrength Method (Light Filter Effect)
Clear Method (Light Filter Effect)
MoveLight_Method (Light Filter Effect)

Event
Onfilterchange


Reveal Transition Filter

Description

Allows you to show or hide visual objects, using any of the 23 predefined types of patterns.

Syntax

{ filter: revealtrans(duration=duration, transition=transitionshape)}

Parameter | Description
duration | Length of time the transition should take to complete. Value, float. Value is expressed in seconds.milliseconds (0.000).
transitionshape Shape of the transition (Reveal transition only). Integer. A value from 0 to 23. The transition shape is determined by one of the values shown in the following table.
Transition type | Value
Box in | 0
Box out | 1
Circle in | 2
Circle out | 3
Wipe up | 4
Wipe down | 5
Wipe right | 6
Wipe left | 7
Vertical blinds | 8
Horizontal blinds | 9
Checkerboard across | 10
Checkerboard down | 11
Random dissolve | 12
Split vertical in | 13
Split vertical out | 14
Split horizontal in | 15
Split horizontal out | 16
Strips left down | 17
Strips left up | 18
Strips right down | 19
Strips right up | 20
Random bars horizontal | 21
Random bars vertical | 22
Random | 23

Remarks

An asterisk in the following applies to list indicates that a defined height, width, or absolute position is required.

Applies To

BODY, BUTTON, DIV*, IMG, INPUT, MARQUEE, SPAN*, TABLE, TD, TEXTAREA, TFOOT, TH, THEAD, TR

See Also

Blend Transition Filter, Visual Filter, Properties, Methods, and Events Reference


Shadow Filter Effect

Description

Paints a solid silhouette of the selected visual object along one of its edges, in the specified direction. This creates the illusion of a shadow around the visual object.

Syntax

{FILTER: Shadow(Color=color, Direction=direction)}

Parameter | Description
color | Specific color for the shadow effect. Color is expressed in #RRGGBB format, where RR is the red hexadecimal value, GG is the green hexadecimal value, and BB is the blue hexadecimal value.
direction Directional offset for the shadow effect. Direction is expressed in terms of degrees clockwise from vertical orientation of the object, in 45-degree increments. The default orientation is 225 degrees, which places the shadow to the bottom left side of the object.
Value | Description
0 | Top
45 | Top right
90 | Right
135 | Bottom right
180 | Bottom
225 | Bottom left
270 | Left
315 | Top left

Remarks

For the direction parameter, negative values or values larger than 360 degrees will wrap around to their equivalent angle (for example, -45 degrees is equivalent to 315-degree orientation). This allows mathematical manipulations to be carried out easily in code.


Status Property

Description

Returns the current status of the transition.

Syntax

nStatus = object.filter.Status

Parameter | Description
status | Integer. Values are 0 (transition stopped), 1 (transition applied), or 2 (transition playing). Read-only.

Applies to

Transition filters


Stop Method

Description

Stops transition playback.

Syntax

Call object.filters.item(index).stop()

Parameter | Description
object | Identifier of the object to which the filter is attached.
index | Index number of the transition whose playback is to be stopped.

Remarks

Fires the Onfilterchange event.

Applies to

Transition filters


Visual Filter

Description

Allows you to manipulate visible objects, with any of the several predefined filter effects listed below.

Syntax

{ filter: filtername(fparameter1, fparameter2...)}

Parameter Description
filtername Identifier for a particular visual effect. Possible values are shown in the following table.
Filter effect | Description
Alpha | Sets a transparency level.
Blur | Creates the impression of moving at high speed.
Chroma | Makes a specific color transparent.
DropShadow | Creates an offset solid silhouette.
FlipH | Creates a horizontal mirror image.
FlipV | Creates a vertical mirror image.
Glow | Adds radiance around the outside edges of the object.
Grayscale | Drops color information from the image.
Invert | Reverses the hue, saturation, and brightness values.
Light | Projects a light source onto an object.
Mask | Creates a transparent mask from an object.
Shadow | Creates a solid silhouette of the object.
Wave | Creates a sine wave distortion along the x-axis.
XRay | Shows just the edges of the object.

Remarks

The Visual Filter control can be applied to any visible object on the HTML page that supports the Filter property, such as DIV and IMG tags.

Visual filters can be chained together to produce interesting effects. To chain multiple filters together, simply set the filter attribute to include more than one filter. For example

<DIV STYLE="position:absolute;filter:blur(direction=315) dropshadow()">
   Fantastic Effects!
</DIV>

In this example, the blur is applied first and then the dropshadow. When working with filters and transitions, the order in which they are applied will often affect the results. Click the Show Me to see the difference.

Each visual object to be filtered requires its own visual filter control. You can apply a visual filter object to a DIV tag to utilize a single set of filter effects on all the visual objects in that region. Since each visual filter object can support multiple concurrent effects, you can use multiple filter effects on a particular object.

Remarks

An asterisk in the following applies to list indicates that a defined height, width, or absolute position is required.

Applies To

BODY, BUTTON, DIV*, IMG, INPUT, MARQUEE, SPAN*, TABLE, TD, TEXTAREA, TFOOT, TH, THEAD, TR

See Also

Reveal Transition Filter, Blend Transition Filter, Properties, Methods, and Events Reference


Wave Filter Effect

Description

Performs a sine wave distortion of the visual display of the object along the vertical axis.

Syntax

{FILTER: Wave(Add=add, Freq=freq, LightStrength=strength, Phase=phase, Strength=strength)}

Parameter | Description
add | Boolean. If true (nonzero value), adds the original image to the waved image. If false (0), it does not.
freq | Number of waves to appear in the visual distortion. Integer.
light | Strength of the light on the wave effect in percent, from 0 to 100.
phase | Phase offset for the start of the sine wave effect, which is normally 0 degrees. Value between 0 and 100, which expresses the percentage of the wavelength at which offset should start. For example, a value of 25 starts sine wave effect at 90 degrees. A value of 360 is the equivalent of 0.
strength | Intensity of the wave effect.

Remarks

Using a sequencer to change the phase parameter can create some interesting effects.


XRay Filter Effect

Description

Changes the color depth of the visual object and renders the object in black and white, making the visual display look like a black and white x-ray.

Syntax

{FILTER: Xray}


Document Object Model

The Dynamic HTML document object model allows authors direct, programmable access to the individual components of their Web documents, from individual elements to containers. This access, combined with the event model, allows the browser to react to user input, execute scripts on the fly, and display the new content without downloading additional documents from a server. The document object model puts sophisticated interactivity within easy reach of the average HTML author.

What Is the Object Model?

The object model is the mechanism that makes Dynamic HTML programmable. It doesn't require that authors learn new HTML tags, and it doesn't involve any new authoring technologies. In fact, the object model builds on functionality that authors have used for creating content for previous browsers. Remember setting the value for a form element in script, or adding mouseover events to links in Internet Explorer 3.0? If so, you've been using a limited form of the object model to access your HTML with script.

What's different in the current object model is that now every HTML element is programmable. This means that every HTML element on the page can have script behind it that can be used to interact with user actions and change the page content dynamically. This event model lets a document react when the user has done something on the page, such as move the mouse over a particular element, press a key, or enter information into a form input. Each event can be linked to a script that tells the browser to modify the content on the fly, without having to go back to the server for a new file. The advantages to this are that authors will be able to create interactive Web sites with fewer pages, and users will not have to wait for new pages to download from Web servers, increasing the speed of their browsing and the performance of the Internet as a whole.

Accessing Elements with Script

Every HTML element is a scriptable object in the object model , with its own set of properties, methods, and events. However, to write script for each element object, the author must know how to get to an element.

The object model is focused around collections of elements, a hierarchy of groupings that the elements fall into. The most important of these collections are the all collection and the children collection. A Dynamic HTML document is a structured arrangement of elements—for instance, in the following example, each element has a scope of influence that depends on where in the document the tags appear.

<HTML>
<BODY>
<DIV>
<P>Some text in a <B>paragraph</B>
<IMG id=image1 src="mygif.gif">
</DIV>
<IMG id=image2 src="mygif.gif">
</BODY>
</HTML>

The DIV element contains (and is the parent of) the P tag and the IMG called image1. Conversely, image1 and the P are children of the DIV. The IMG tag called image2, however, is a child of the BODY element. And all elements are children of the HTML element.

For each element object, there is an all collection that contains all the elements that are beneath that element in the hierarchy, and a children collection that contains only the elements that are direct descendants of that element. In the example above, the B would be in the DIV's all collection, but would not appear in the DIV's children collection. Similarly, the DIV is a member of BODY's children collection, but the P is not.

In addition to these collections for each element, the document itself (represented by the document object) has a number of element and non-element collections. The most important is an all collection that contains all the elements on the Web page. This collection is the primary way to access elements through script. For more information about using collections, see Scripting with Elements and Collections.

Events—Bubbling, Canceling, and Handling

Clicking a button, moving the mouse over part of the Web page, selecting some text on the page—these actions all fire events that a DHTML author can write code to run in response to the event. This particular piece of code is generally known as an event handler because that's what it does, handle events.

Event handling is not particular to Internet Explorer 4.0 or even Internet Explorer 3.x; Netscape Navigator 3.x and Communicator handle events as well. However, in Internet Explorer 4.0, the HTML elements on a Web page that are the source of the events, and the types of events that are generated, have been greatly expanded. Previously, only a small set of HTML elements could generate events: anchors, image maps, form elements, applications, and objects. With the Internet Explorer 4.0 event model, every HTML element on the page can be the source for a full set of mouse and keyboard events.

The following is a set of common events that every HTML element generates in Internet Explorer 4.0.

Mouse event | Generated when the user:
onmouseover | Moves the mouse pointer over (that is, enters) an element.
onmouseout | Moves the mouse off an element.
onmousedown | Presses any of the mouse buttons.
onmouseup | Releases any of the mouse buttons.
onmousemove | Moves the mouse pointer within an element.
onclick | Clicks the left mouse button on an element.
ondblclick Double-clicks the left mouse button on an element.

Keyboard event | Generated when the user:
onkeypress | Presses and releases a key (full down-and-up cycle). However, if a key is held down, multiple onkeypress events are fired.
onkeydown | Presses a key. Only a single event will be fired, even if the key is held down.
onkeyup | Releases a key.

To help authors build code that is compact, simpler, and easier to maintain, Internet Explorer 4.0 introduces a new way to handle events—event bubbling. Windows®, OS/2, OSF Motif, and almost every other GUI platform uses this technique for processing events in their user interfaces. However, event bubbling is new to HTML and provides an efficient model for authors to incorporate event handling in their Web documents.

Previously, if an HTML element generated an event but no event handler was registered for it, the event would just vaporize, never to be seen again. Event bubbling simply passes these unhandled events to the parent element for handling. The event continues up ("bubbles up") the element hierarchy until it is handled, or until it reaches the topmost object, the document object.

Event bubbling is useful because it:

  • Allows multiple common actions to be handled centrally.
  • Reduces the amount of overall code in the Web page.
  • Reduces the number of code changes required to update a document.

The following is a simple example of event bubbling in action.

<html>
<body>
<div id=OuterDiv style="background-color: red" onmouseover="alert(window.event.srcElement.id);">
This is some text
<img id=InnerImg>
</div>
</body>
</html>

On this page, when the user moves the mouse pointer over the text, a dialog box appears with the text "OuterDiv." If the mouse then moves over the image, another dialog box appears with the text "InnerImg".

The interesting thing here is that the onmouseover event for the IMG element was handled even though it does not have an event handler. Why is this? The onmouseover event from the IMG element bubbles up to its parent element, which is the DIV element. DIV does have an event handler registered for the onmouseover event, so it fires and generates the specified dialog window.

Every time an event is fired, a special property on the window object is created. This special property contains the event object. The event object contains context information about the event that just fired, including mouse location, keyboard status, and (most importantly) the source element of the event.

The source element is the element that caused the event to fire, and can be accessed using the srcElement property on the window.event object.

In the example above, the dialog displays the id property of the event's srcElement.

Handling Rollover Effects

An author creates a rollover effect to make part of a page react when the user moves the mouse over it. With Internet Explorer 4.0, the process of creating a rollover effect is greatly simplified.

<html>
<head>
<style>
.Item {
   cursor: hand;
   font-family: verdana;
   font-size: 20;
   font-style: normal;
   background-color: blue;
   color: white
 }
.Highlight {
   cursor: hand;
   font-family: verdana;
   font-size: 20;
   font-style: italic;
   background-color: white;
   color: blue
 }
</style>
</head>
<body>
<span class=Item>Milk</span>
<span class=Item>Cookies</span>
<span class=Item>Eggs</span>
<span class=Item>Ham</span>
<span class=Item>Cheese</span>
<span class=Item>Pasta</span>
<span class=Item>Chicken</span>

<script>
function rollon() {
  if (window.event.srcElement.className == "Item") {
     window.event.srcElement.className = "Highlight";
  }
}

document.onmouseover = rollon;

function rolloff() {
  if (window.event.srcElement.className == "Highlight") {
     window.event.srcElement.className = "Item";
  }
}

document.onmouseout = rolloff;
</script>
</body>
</html>

In this example, seven SPAN elements are initially set to use the class Item. When the mouse moves over any one of those elements, it will be changed to use the class Highlight.

Innovations in Internet Explorer 4.0 enable the following:

  • Events can now be generated from a SPAN element. Previously, an author would have had to wrap each SPAN in an anchor to get the right events.
  • With event bubbling, events can be captured at the document object level. You do not need to create separate event handlers for each element that will participate in the effect. For example, should the author add HTML to the page, these additional elements would participate in the event model without changing a single line of script. Note that the document object is the "super parent" for all elements in the document body.

Canceling Events

All events bubble to their parent element (and recursively all the way up to the document object) unless the event is canceled. To cancel an event, you must set the window.event.cancelBubble property to "true" in the event handler. Note that unless canceled, events will bubble up the hierarchy and be handled by all parent elements registered to the event, even if the event has already been handled.

Canceling event bubbling should not be confused with canceling the default action for the event. Some events (for example, the onclick event on an anchor) have a default action. When an anchor is clicked, its default action is to navigate the current window to the URL specified in the src property. Returning "false" from an event handler, or setting window.event.returnValue to "false", cancels the default action but does not cancel event bubbling unless window.event.cancelBubble is also set. Conversely, canceling an event's bubbling doesn't cancel its default action.

The last example showed how you could use event bubbling to apply a common effect to a set of elements. What if you wanted to exclude an element from that effect? Simply change the line:

<span class=Item>Ham</span>

to

<span class=Item onmouseover="window.event.cancelBubble = true;" onmouseout="window.event.cancelBubble = true;">Ham</span>

Now, no matter how many times you move your mouse over "Ham," it will not change style. This is both the onmouseover and onmouseout events were canceled; they did not bubble through to the document, so the document was never given the opportunity to handle those events for "Ham."

Special Considerations

At any one time, you can have an onmouseover event only on a single object. This means that in the following case:

<DIV id=MyDiv>
<IMG id=MyImg>
</DIV>

If you were to move your mouse over the IMG, the order of events would be as follows:

MyDiv:: onmouseover
MyDiv:: onmouseout
MyImg:: onmouseover

Moving your mouse off the IMG fires the MyDiv::onmouseover event again.

At times, the author might want to detect when the mouse moves outside a DIV to perform some special effect. It is not enough to simply trap the onmouseout event. To make this easier, Internet Explorer 4.0 indicates the source element (fromElement) and target element (toElement) for the onmouseover and onmouseout events. You can use these properties in combination with the contains method to tell when the mouse has moved outside a region.

The following example shows the use of these properties and methods.

<html>
<body id=Body>
<div id=OuterDiv style="width: 100px; height: 50px; background: red"
onmouseover="over();" onmouseout="out();">
<img id=Img1>
<img id=Img2>
<img id=Img3>
</div>
<script>
function over() {
  var s;
  s = "onmouseover: "+window.event.srcElement.id+" from: "+

window.event.fromElement.id+" to: "+window.event.toElement.id;
  alert(s);
}

function out() {
  var s;
  s = "onmouseout: "+window.event.srcElement.id+" from: "+

window.event.fromElement.id+" to: "+window.event.toElement.id;
  alert(s);

  if (!(OuterDiv.contains(window.event.toElement))) {
     alert("Out Now");
  }
}
</script>

</body>
</html>

Technical Topics

Working with Windows, Frames, and Dialogs

Scripting with Elements and Collections

Understanding the Event Model

Cross-Frame Scripting and Security


Understanding the Event Model

An event is a notification that occurs in response to an action, such as a change in state or as a result of the user clicking the mouse or pressing a key while viewing the document. An event handler is code, typically a function or routine written in a scripting language, that receives control when the corresponding event occurs. The following topics describe events and event handlers and explain how to use them in your documents.

The Life Cycle of an Event

Attaching an Event Handler

More About Event Bubbling

Returning Values and Canceling Default Actions

Event Handler Scoping

Event Object

Keyboard Events

Mouse Events

Focus and Selection Events

Load and Readystate Events

Other Events

The Life Cycle of an Event

An event has a life cycle that begins with the action or condition that initiates the event and ends with the final response to the event by an event handler or Internet Explorer. The life cycle of a typical event has these steps:

  1. The user action or condition associated with the event occurs.
  2. The event object is instantly updated to reflect the conditions of the event.
  3. The event fires. This is the actual notification in response to the event.
  4. The event handler associated with the source element is called. The event handler carries out its actions and returns.
  5. The event bubbles up to the next element in the hierarchy, and the event handler for that element is called. This step repeats until the event bubbles up to the window object or a handler cancels bubbling.
  6. The final default action (if any) is taken, but only if this action has not been canceled by a handler.

For events that bubble, if there is no event handler bound to the source element, the event handler for the next element up the hierarchy is called.

When an event handler carries out its actions, it uses the event object to retrieve information about the event, such as the position of the mouse, the state of the keyboard keys, the element in which the event occurred, and so on.

The following example defines an event handler, named "wasClicked", for the onclick event and associates it with the BODY element. When the user clicks the mouse button anywhere in this document, the event fires and the event handler displays the message "I was clicked", followed by the tag name of the element in which the event occurred.

<HTML>
<BODY onclick="wasClicked()">
<H1>Welcome!</H1>
<P>This is a very <B>short</B> document.
<SCRIPT LANGUAGE="JavaScript">
function wasClicked() {
    alert("I was clicked " + window.event.srcElement.tagName);
}
</SCRIPT>
</BODY>
</HTML>

The srcElement property of the event object specifies the element object in which the event occurred. This is useful for deciding what action the event handler should take in response to the event.

Attaching another event handler, "wasAlsoClicked", to the P element demonstrates the parent-child relationship of document elements.

<HTML>
<BODY onclick="wasClicked()">
<H1>Welcome!</H1>
<P onclick="wasAlsoClicked()">This is a very <B>short</B> document.
<SCRIPT LANGUAGE="JavaScript">
function wasClicked() {
    alert("I was clicked " + window.event.srcElement.tagName);
}
function wasAlsoClicked() {
    alert("You clicked me " + window.event.srcElement.tagName);
}
</SCRIPT>
</BODY>
</HTML>

As in the previous example, if the user clicks in the heading "Welcome!", the message "I was clicked H1" appears. But if the user clicks the word "short", two messages appear: "You clicked me B" followed by "I was clicked B". In the first instance, the click in "Welcome!" fires the onclick event, setting the H1 element as the source element of the event. There is no event handler for this element, so the event bubbles up to its parent element in the hierarchy, BODY, and its event handler, wasClicked, is called.

In the second case, when the user clicks in the word "short", the onclick event fires again. This time the B element is set as the source element. Since there is no event handler for B, the event bubbles up to the P element and its event handler, wasAlsoClicked, is called. But that's not the end of the event. After wasAlsoClicked returns, the event continues to bubble up the hierarchy to the next parent element, BODY, causing wasClicked to be called.

In some cases, you might not want the event to bubble up in the hierarchy. You can stop bubbling by setting the cancelBubble property of the event object to true in any event handler. After the handler returns, the event stops bubbling and comes to an immediate end. Note that this cancellation affects only the current event, not subsequent events. Subsequent events will bubble unless you explicitly cancel them.

Consider the following document. It defines two event handlers, setBodyStyle and setParaStyle, that are called when the user clicks in the document or in the paragraph, respectively. To ensure that only the style for the paragraph changes when the user clicks in the paragraph, the setParaStyle handler uses cancelBubble to prevent the event from bubbling up to BODY.

<HTML>
<BODY onclick="setBodyStyle()">
<H1>Welcome!</H1>
<P onclick="setParaStyle()">This is a very <B>short</B> document.
<SCRIPT LANGUAGE="JavaScript">
function setBodyStyle() { // Set all headings to green
    var coll = document.all.tags("H1");
    for (i=0; i<coll.length; i++)
        coll.item(i).style.color = "green";
}
function setParaStyle() { // Underline the paragraph
    var el = window.event.srcElement;
    while ((el != null) && (el.tagName != "P")) {
        el = el.parentElement;
    }
    if (el != null) el.style.textDecoration = "underline";
    window.event.cancelBubble = true;
}
</SCRIPT>
</BODY>
</HTML>

Notice that the above example does not automatically assume that the source element is P. Because the user might have clicked in the B element, the event handler must check the element before applying the style. In this case, the handler uses the parentElement property to move up the element hierarchy until the P element is found.

Attaching an Event Handler

You must associate an event handler to a specific event and specific element or object in order for the handler to be called when the event fires. You can associate an event handler by using any one of the following, essentially equivalent, methods.

Declare an event handler function and assign a call to that function in the appropriate inline event attribute of an HTML tag. For example, the following defines the JScript function named "flip" and associates it to the IMG element as the event handler for the onmouseover event.

<SCRIPT LANGUAGE="JavaScript">
function flip() {
    // Carry out some work
}
</SCRIPT>
    .
    .
    .
<IMG SRC="sample.gif" onmouseover="flip()">

This example shows an event handler function being bound; however, any expression can be used here to be evaluated each time the event fires. Note that since this is an expression, the parentheses following the function name are required.

Declare event handling code and use the FOR= and EVENT= attributes of the SCRIPT tag to associate the code with the event. The following example also defines JScript code and associates it as the onmouseover event handler for the IMG element having the identifier "MyImage".

<SCRIPT FOR=MyImage EVENT=onmouseover LANGUAGE="JavaScript">
    // Carry out some work
</SCRIPT>
    .
    .
    .
<IMG ID=MyImage SRC="sample.gif">

Declare an event handler function in VBScript and associate it with an event by giving it a name having this form: id_event. The following example defines a VBScript function that handles the IMG element as its onmouseover event handler.

<SCRIPT LANGUAGE="VBScript">
Function MyImage_onmouseover
    ' Carry out some work
End Function
</SCRIPT>
    .
    .
    .
<IMG ID=MyImage SRC="sample.gif">

As a general rule, you should always define and associate your event handlers as early in the document as possible. Depending on the method you use, the handler can begin handling events either while the document is loading or immediately after loading, as shown in the following list.
JScript event handler | When set using an inline event attribute, associates when the element is created.
FOR= and EVENT= event handling code | Associates when the document is fully loaded.
VBScript event handler | Associates when the document and all contained objects and applications have been loaded.

Some events can occur while the document is loading. If you need to handle events at this time, you can use JScript and an inline event attribute to associate the handler when the element is created.

You can associate the same event handler with more than one element in the document. This is useful if you want the same action to occur whenever the given event occurs in any of the elements. Typically, event handlers are written to handle only one type of event, but it is possible to create event handlers that can handle more than one.

You don't have to limit yourself to one event handler for each type of event. If the action you want to occur for a given event in one element is different than for the same event in another element, you can define two event handlers and associate each to its appropriate element. In general, you can define any number of event handlers for the same type of event and associate each with one or more elements in the document.

If you use a combination of handling methods in a document, you can also define more than one event handler for the same event in the same element. For example, you can declare both a JScript and a VBScript event handler and associate them both with the same event and element. If you associate more than one event handler in this way and the handlers are in different languages, all handlers will receive the event, but the order in which they receive the event is not specified.

If you associate two event handlers of the same language to the same event and element, only one handler receives the event. In most cases, this will be the first handler that you bound to the element. But any handler associated using the FOR= and EVENT= attributes always takes precedence over a handler associated using an inline event attribute.

When you associate with an inline attribute, you typically assign to the attribute a call to the event handler function, causing that function to be called when the event fires. But assigning a call to an event handler is not a requirement. You can instead assign any valid script code; this code is executed when the event fires. For example, the following BUTTON element displays the message "Hello World!" when you click it.

<BUTTON onclick="alert('Hello World!')" LANGUAGE="JavaScript">Click Me</BUTTON>

This method is convenient as long as the code is relatively short and uncomplicated. If you use an inline attribute in this way, you should also use the LANGUAGE= attribute to specify the scripting language for the code. If you don't specify the language, either the default language or the most recent language specified is assumed.

Attaching with Event Properties

The inline event attributes of an element are also available as properties. This means you can use the properties to dynamically change the event handling for an element at any time. For example, you can associate a handler to an element that didn't previously have one, or change the existing handler for an element to some other handler. Adding or changing event handlers is a useful way to make sure that the actions taken on an event reflect the current content of the element.

The following JScript example use the event property to associate the event handler, named setHeadStyle, to the H1 element. It assigns a call to the function to the onclick property of the element.

<H1 id=MyHeading>Welcome!</H1>
    .
    .
    .
<SCRIPT LANGUAGE="JavaScript">
function setHeadStyle() {
    window.event.srcElement.style.color = "green";
}

document.all.MyHeading.onclick="setHeadStyle()";
</SCRIPT>

An alternate way to associate the event handler is to assign the function pointer (rather than a function call) to the property as in the following example. VBScript does not support function pointers.

document.all.MyHeading.onclick=setHeadStyle;

Handling Custom Events or Events with Parameters

Using the FOR= and EVENT= attributes to associate events gives you access to custom events fired by embedded objects and to any parameters that an event generates. Unlike standard events that can be bound using attributes or properties, in the case of custom objects these are not available.

You use the FOR= attribute to specify which element or object to handle, assigning it an identifier or the name of an object, application, or control. If there is more than one element or object having the same identifier or name, only the first one is bound to the handler. Names take precedence over identifiers. If you don't specify this attribute, the handler is bound to the window by default. Note that JScript is case sensitive, so you must type the identifier or name exactly as it appears in the corresponding element or object.

You use the EVENT= attribute to specify which event to associate to, assigning it an event name. If the event generates parameters (few predefined events do), you can also specify a list of comma-separated parameter names enclosed in parentheses immediately after the event name. The parameters are untyped. Because JScript is case sensitive, make sure you always spell event names in lowercase letters. Also, if you give a parameter list, VBScript requires that all parameters defined for the event be listed, even if they are not used.

The following JScript example associates the event handling code with the onerror event for the window. This event fires when an error while loading the document is detected. The event generates parameters, so a parameter list is given, and the "lineno" parameter is used in the code.

<SCRIPT FOR=window EVENT="onerror(message, url, lineno)" LANGUAGE="JavaScript">
alert("An error has occurred on line " + lineno);
</SCRIPT>

The following JScript example associates the event handling code with a custom event, named "ondatechange", that the embedded object fires.

<OBJECT ID=myDateObject ... ></OBJECT>
<SCRIPT FOR=myDateObject EVENT="ondatechange()" LANGUAGE="JavaScript">
    // Carries out an action when the date changes
</SCRIPT>

An alternate way to handle custom events and to receive event parameters is to associate VBScript handlers. In this case, you use VBScript's id_event format for the event handler name and provide a parameter list if appropriate. The following VBScript example handles the onerror event and receives its parameters.

<SCRIPT LANGUAGE="VBScript">
Function window_onerror(message, url, lineno)
    alert "An error has occurred on line " & lineno
End Function
</SCRIPT>

Similarly, the following VBScript example handles the custom event, ondatechange, fired by the embedded object.

<OBJECT ID=myDateObject ... ></OBJECT>
<SCRIPT LANGUAGE="VBScript">
Function myDateObject_ondatechange()
    // Carries out an action when the date changes
End Function
</SCRIPT>

More About Event Bubbling

Event bubbling ensures that the event handlers for all elements in which an event occurs have an opportunity to respond to the event. Consider the following example.

<P onclick="doPara()">
Jump to a <B>sample</B> document.
</P>

The user might reasonably expect that clicking the word "sample" will cause the same action, a call to the event handler named "doPara", as clicking any other word in the P element. But if events did not bubble up from the source element, clicking "sample" would cause no action because there is no event handler bound to the B element. Because events do bubble up through the element hierarchy, every event handler on the element's parent hierarchy has a chance to respond, and in this case "doPara" is called when the user clicks "sample".

Unless you keep event bubbling in mind, you might initially be baffled by some results. For example, consider a document that uses onmouseover and onmouseout events to show and hide a collection of paragraphs, but also uses the events inside the list to highlight paragraphs in the collection.

<DIV onmouseover="showPara()" onmouseout="hidePara()">
My Menu
<P STYLE="display:none" onmouseover="highlight()" onmouseout="unhighlight()">Item 1
<P STYLE="display:none" onmouseover="highlight()" onmouseout="unhighlight()">Item 2
</DIV>

In the example above, suppose the user moves the mouse over the words "My Menu", then over the words "Item 1", and finally over the words "Item 2". Here's what happens:

  1. The mouse cursor moves over "My Menu".
  2. The onmouseover event fires for the DIV element, and "showPara" is called.
  3. The mouse cursor moves from "My Menu".
  4. The onmouseout event fires for the DIV element, and "hidePara" is called.
  5. The mouse cursor moves over "Item 1".
  6. The onmouseover event fires for the P element, and "highlight" is called.
  7. The onmouseover event bubbles up to the DIV element, and "showPara" is called with P as the source element.
  8. The mouse cursor moves from "Item 1".
  9. The onmouseout event fires for the P element, and "unhighlight" is called.
  10. The onmouseout event bubbles up to the DIV element, and "hidePara" is called with P as the source element.
  11. The mouse cursor moves over "Item 2".
  12. The onmouseover event fires for the P element, and "unhighlight" is called.
  13. The onmouseover event bubbles up to the DIV element, and "showPara" is called with the second P as the source element.

As you can see, whenever the user moves the mouse over and from a paragraph in the collection, the event handlers for DIV are called. If the handlers were written without taking this into account, the paragraphs might be hidden when they should not be.

In general, whenever you use nested event handlers in this way, you need to carefully consider whether the event handler should carry out an action each time it is called. One way to control the action is to use the cancelBubble property. In the previous example, the "highlight" and "unhighlight" event handlers could set cancelBubble to true to prevent the event from bubbling up to the DIV element. Another way is to check the source element for the event, the srcElement property of the event object, and pick an action that is appropriate to that element.

Returning Values and Canceling Default Actions

Event handlers can return values to the event either by using the return value mechanism defined for the language, such as the return statement for JScript, or by using the returnValue property of the event object.

Return values are useful for controlling the default actions associated with events. For example, clicking the A element causes the browser to load the document specified by the href attribute. You can cancel default actions such as these by returning false from your event handlers.

Not all scripting languages support return values. For these languages, you must use the returnValue property to set a return value. If a language supports return values, you can use either the language-defined method of returning a value or returnValue. If you use both methods, the property always takes precedence.

After all event bubbling is complete, any default action associated with the event is canceled if returnValue is false or, if this property is not set, the return value of the last function is false. Note that some events do not have default actions associated with them and might use the returnValue (or function return value) in other ways.

Canceling a default action is not the same as canceling event bubbling. You can cancel the default action and still allow the event to bubble up through the hierarchy.

Event Handler Scoping

Depending upon whether a script is written inside a FORM container or elsewhere in the document, different scoping rules are applied for executing event handlers and the elements that are available on the window object. The different scenarios are listed below.

When events are fired, a special object reference—the me pointer in VBScript and this in JScript—is set to the current element firing the event.

1) Event handler for a button outside a form

This is the basic case. You can use any of the handling mechanisms described earlier. The only rule is that you cannot access elements within a form block directly on the window object. Instead, you can access them from the document object or the particular form's elements collection.

2) Event handler not inside the FORM block for a button inside a form

If the button has a unique identifier to the entire document, the event handler can be written anywhere within the document. If the event handler is written outside the form block, the same rules apply for accessing elements on the window object as described in 1) above.

3) Event handler inside the FORM block for a button inside the form

If the button's identifier is not unique to the document, the event handler must be written within the form. When writing event handlers behind the form, using either inline attributes or the FOR= and EVENT= attributes (but not the VBScript id_event method) changes the scoping rules of the window object. Events defined this way can access elements behind the form directly from the window object. They can also access elements that are outside the form directly as long as they do not conflict with any of the form's element names.

When using the VBScriptid_event method of handling, only elements that are not within the form's scope can be accessed as properties of the window.

If there is no unique identifier within the form, the first element with the matching identifier is bound to the event handler when using the FOR= and EVENT= attributes of the SCRIPT element or the VBScript id_event mechanism of defining events.

4) Event handler inside the FORM block for a button outside the form

The event handler executes only if the VBScript id_event method of handling is used. Otherwise this code will not execute.

You can write an event handler for multiple elements. This can be done only when the elements are not within the same scope, where scope is defined as being inside the form or not inside the form. For example, if writing an event handler for id=genericButton in the document's scope, and adding a genericButton to the document and another within a form, the same click event is fired in both cases. The me pointer will point to the actual source of the event. These elements do not have to be of the same type for this to work.

If multiple elements have the same identifier and are within the same scope, only the first one fires the event.

Event Object

The event object, on the window object, is accessible to all event handlers and is the language-independent, preferred way for handlers to get and modify information about the event. For example, the following VBScript and JScript examples both use the object to display the tag name of the element in which the event occurred.

<SCRIPT LANGUAGE="VBScript">
Function document_onclick
    alert window.event.srcElement.tagName
End Function
</SCRIPT>

<SCRIPT LANGUAGE="JavaScript">
function doClick() {
    alert(window.event.srcElement.tagName);
}
</SCRIPT>

Note In VBScript, you must use the window keyword with event to avoid a conflict with the VBScript event keyword.

The srcElement property is one of the most important properties on event. Many event handlers use this property to determine an action to take based on the source of the event. For example, the following JScript event handler carries out an action whenever the user clicks any of the H1 elements in the document.

<SCRIPT FOR=document EVENT="onclick()" LANGUAGE="JavaScript">
    if ("H1" == event.srcElement.tagName) {
        // user clicked on a H1
    }
</SCRIPT>

Another important property is cancelBubble, which controls event bubbling for the given event and, if set to true, prevents the event from bubbling up the element hierarchy.

The returnValue property gives an event handler a language-independent way to return a value to the event. For many events, setting the return value to false cancels the default action for that event.

Some properties of the event object have meaning only for certain events. For example, the keyCode property is an integer specifying a standard numeric Unicode keycode for keyboard key events. For other events, this property is set to zero. Other examples are the toElement and fromElement properties, which represent the element that the mouse is going to and coming from for the onmouseover and onmouseout events. For other events, these properties are null.

When a mouse event occurs, such as onclick, the x and y properties specify the horizontal and vertical position of the mouse. If none of the elements containing the source element are positioned, the position of the mouse is relative to the BODY element. If a positioned element contains the source element, the position of the mouse is relative to that element. In addition to mouse position, the button property indicates which mouse buttons are pressed at the time of the event. It is 0 if no buttons are pressed, 1 for the left button, 2 for the right, and 3 for both.

The altKey, ctrlKey, and shiftKey properties are useful for all events. These specify whether the ALT, CTRL, and SHIFT keys were down or up at the time of the event. The property is true if the key was down. The following VBScript example cancels the default action for the A element if the SHIFT key is down when the event occurs.

<SCRIPT FOR=document EVENT="onclick()" LANGUAGE="VBScript">
    If (("A" = window.event.srcElement.tagName) and (window.event.shift)) Then
        event.returnValue = false
    End If
</SCRIPT>

The clientX and clientY properties are integers specifying the coordinates relative to the size of the client area, not including window decorations. The offsetX and offsetY properties are integers specifying container relative positions. These match the offsetTop and offsetLeft properties of the element. Use the offsetParent property to find the container that defines this positioning. The screenX and screenY properties are integers specifying the coordinates relative to the physical screen.

Note that properties such as returnValue and keyCode are read/write properties. This means an event handler can assign a new value to the property, overwriting the original value. The property retains this new value as the event bubbles up the element hierarchy. This makes it easy for an event handler bound at a low level in the hierarchy to modify events that are also handled at a higher level.

The event object gives you detailed information about where in the document an event occurs, so it is easy to write an event handler that can adapt its action based on the source of the event. If you associate the event handler on an element or object that contains all the elements in which the event might occur, event bubbling will ensure that the handler is called whenever the event occurs. This means you don't need to associate the event handler to each element.

Keyboard Events

Keyboard events occur when the user presses or releases a keyboard key. The onkeydown and onkeyup events fire when a key changes state, either being pressed (down) or released (up). These events fire for all keys on the keyboard, including shift state keys such as SHIFT, CTRL, and ALT.

The onkeypress event fires when the user's keyboard input is translated to a character. These occur, for example, when the user presses letter or number keys, or a combination of shift keys and letters and numbers.

When a keyboard event occurs, the keyCode property of the event object contains the Unicode keycode of the corresponding key. The altKey, ctrlKey, and shiftKey properties specify the state of the ALT, CTRL, and SHIFT keys.

You can change which key is associated with the event by either changing the value of the keyCode property or returning an integer value. You can cancel the event by returning zero or false.

The onhelp event is a special keyboard event that occurs when the user presses the help key (F1).

Mouse Events

Mouse events occur when the user moves the mouse or clicks the left button. The onmousemove event fires when the user moves the mouse, and onmouseover and onmouseout fire when the mouse moves in and out of an element. The onmousedown and onmouseup events fire when the left mouse button changes state, either being pressed (down) or released (up). The onclick and ondblclick events fire when the user single-clicks and double-clicks the button.

When a mouse event occurs, the button property of the event object identifies which mouse button (if any) is down. The x and y properties specify the location of the mouse at the time of the event. For the onmouseover and onmouseout events, the toElement and fromElement properties specify the elements the mouse is moving to and from.

Mouse Clicks

The onclick event fires when the user presses and releases the button. The ondblclick event occurs when the elapsed time between two consecutive onclick events is within a system-defined range.

Mouse click events are interspersed with onmousedown and onmouseup events. For example, the onclick event follows an onmouseup event. The ondblclick event occurs at the end of this sequence:
onmousedown
onmouseup
onclick
onmouseup
ondblclick

An onclick event can also occur when the user presses the ENTER key on a focusable element, such as a BUTTON element. In this case, the event fires without a preceding onmouseup event.

You can cancel a mouse click by returning false or setting the returnValue property to false.

Note For mice that have one button, the button is considered the left mouse button.

Moving Between Elements

The onmouseover and onmouseout events fire whenever the mouse cursor moves from one element to another. Consider the following document fragment.

<H1>Move from here</H1>
<P id=myP><B><I>To here</I></B></P>

In the above example, as the mouse moves from the H1 element to the words "To here", it crosses over the boundaries of the P, B, and I elements. However, the event sequence is simplified to the following: onmouseout on the H1 (which bubbles up the hierarchy), and onmouseover on the I element (again bubbling up the hierarchy).

The fromElement and toElement properties on the event object return the element object the mouse is coming from and going to. Through event bubbling, it is possible to determine each boundary that has been crossed by the mouse move.

When moving between elements, the onmouseout event fires first to indicate that the mouse has left the original element. Next the onmousemove event fires, indicating that the mouse has moved. Finally, onmouseover fires to indicate that the mouse has entered the new element.

Focus and Selection Events

The focus and selection events give you detailed information about what actions the user is taking in the document.

The focus events occur on elements such as BUTTON and various types of INPUT that can receive the input focus. For these elements, the onfocus event fires when an element receives the focus, and the onblur event fires when an element loses the focus. An element receives the input focus when the user clicks it with the mouse or navigates to it using the keyboard. These events are useful for knowing when to prepare an element to receive input from the user.

Note that the focus events fire whether moving the input focus between elements in the document or between frames in the window or even applications on the desktop. For example, if a control in the document has the focus and the user switches to another application, the onblur event fires for that control. When the user switches back to the document, the onfocus event fires. It is not possible to cancel the loss of focus.

The selection events occur when the user selects a portion of the document by using the mouse or keyboard. The onselectstart event fires when a selection is first initiated, for example, when the user clicks a character or object in the document. The onselect event fires when the user changes the selection, for example, by moving the mouse over a portion of the document while holding down the mouse button. The default action for the onselectstart event is to move the selection to the given character or object and highlight that selection. You can cancel this default action by returning false.

The ondragstart event fires when the user first begins to drag the selection. The user can drag a selection by holding down the mouse button on the current selection and moving the mouse. The default action for this event is to prepare the selection to be copied to another element. You can cancel this default action by returning false.

Load and Readystate Events

There are three events that signify the current state of the document: onreadystatechange, onload, and onunload.

The onreadystatechange event fires when the document changes from initializing to interactive, and from interactive to loaded. A document is interactive as soon as the user can interact with it by scrolling or clicking on anchors or elements. A document is loaded when all the content has been downloaded.

The onload event fires after the document is loaded and all the elements on the page have been completely downloaded. The onunload event fires immediately prior to the document being unloaded (when navigating to another document).

Specifying code for the onload and onunload events can be done on the body object. However, these events actually occur on the window. Therefore, when handling the onload event using the <SCRIPT FOR= EVENT=> syntax, <SCRIPT FOR=myBody Event=onLoad> will fail. Instead, you must use <SCRIPT FOR=window Event=onLoad>.

Other Events

There are a number of other useful events that you can use in your document. For a complete list, see the Events reference.


Scripting with Elements and Collections

Every HTML document consists of a combination of HTML tags and their attributes. These elements define the structure of the document and determine how the content is presented. Using the Dynamic HTML object model, you can examine and modify these elements and their modifying attributes. The following topics explain how to access the elements of the document using element collections.

The all Collection and the children Collection

More Collections

Using Collections

Creating new Collections: The tags Method

Accessing Element Properties

Examining the Element Hierarchy

Getting an Element's Position and Dimensions

Scrolling Elements into View

The all Collection and the children Collection

An HTML document is a hierarchical construct of tags that define the contents of the document. The all collection on the document object represents all the elements in the document hierarchy. Each element is represented as a programmable object appearing within the collection in source order. Individual element objects are accessed by index or identifier (unique name). The following document shows how to do this.

<HTML>
<HEAD><TITLE>Elements: Collecting</TITLE>
<SCRIPT LANGUAGE="JScript">
function showElements() {
    var tag_names = "";
    for (i=0; i<document.all.length; i++)
        tag_names = tag_names + document.all(i).tagName + " ";
    alert("This document contains: " + tag_names);
}
</SCRIPT>
</HEAD>
<BODY onload="showElements()">
<H1>Welcome!</H1>
<P>This document is <B>very</B> short.
</BODY>
</HTML>

When this document is loaded, the script (an event handler for the onload event) displays a list of the elements in the document by stepping through the all collection. It displays this message:

This document contains: HTML HEAD TITLE SCRIPT BODY H1 P B

You can see that each HTML element in the document is represented. Notice that the list does not show the end tags for the elements. This is because each element object represents both the start and end tags. Also, the collection does not directly indicate the hierarchy of the elements; that is, you can't tell which elements contain others. The collection lists the elements in the order in which they appear in the HTML source of the document.

In many ways, the all collection is like an array. It contains one or more items each of the same type—in this case, element objects. You access the items by using zero-based index values, or by name or identifier. The first item has index value 0, the second has 1, and so on. You can determine how many items are in the collection by using the length property.

Because each item in the all collection is an element object, you can apply properties and methods to these items. For example, you can use the tagName property to retrieve the HTML tag name of the element as was done in the previous example. Similarly, you can access properties and methods of the respective element by accessing this through the document.all collection.

The all collection always represents the current state of the document and is automatically updated to reflect any changes made to the document. For example, if you retrieve the collection and add or remove document content so that the HTML structure is different, the collection will automatically reflect the new HTML content in source order.

In some cases, the all collection might contain more elements than are actually in the document's file. In particular, the collection always contains the HTML, HEAD, TITLE, and BODY elements even if these are not present in the source. Similarly, the collection always contains a TBODY element for each TABLE regardless of whether TBODY was specified in the HTML source.

The all collection also includes comments (!) and unknown or invalid tags. The purpose is to give you an accurate picture of the content of the document. Unknown or invalid tags are typically misspelled or misplaced tags. Knowing what and where they are gives you an opportunity to replace them with valid tags. The all collection lists unknown and invalid start and end tags separately; it does not attempt to combine these into a single item. The following document displays the message "HTML HEAD TITLE SCRIPT BODY ! P ZZZ> /ZZZ> /B".

<HTML>
<HEAD><TITLE>Elements: Collecting</TITLE>
<SCRIPT LANGUAGE="JScript">
function showElements() {
    var tag_names = "";
    for (i=0; i<document.all.length; i++)
        tag_names = tag_names + document.all(i).tagName + " ";
    alert("This document contains: " + tag_names);
}
</SCRIPT>
</HEAD>
<BODY onload="showElements()">
<!-- A comment -->
<P>This document has an <ZZZ>unknown</ZZZ> and an invalid</B> tag.
</BODY>
</HTML>

In addition to the all collection on the document object, each individual element also exposes an all collection. Remember the hierarchical style of HTML—this helps to think about the all collection for each element. The all collection for an element contains all the elements contained by that element. For example, the all collection for the HTML element would contain everything in the source code except the HTML element (this being the only difference between the all collection for the HTML element and the document.all collection).

Each element also exposes a children collection, which contains only the elements that are direct descendants of the element in the HTML hierarchy. Another way of saying this is that the children collection would contain only those elements whose parentElement property would return that element. The content of the children collection is undefined for overlapping elements.

The following example returns the length and contents of the all and the children collections of the document. Notice that there are only two elements that are children of the HTML tag—HEAD and BODY. The TITLE and SCRIPT elements are children of the HEAD, not of the HTML tag.

<HTML id=theHTML>
<HEAD>
<TITLE> Look at the all and the children collection</TITLE>
<SCRIPT>
function showme() {
alert('all: ' + window.theHTML.all.length);
for (i=0; i < theHTML.all.length;i++)
{
alert(theHTML.all[i].tagName);
}
alert('children: ' + window.theHTML.children.length);
for (i=0; i < theHTML.children.length;i++)
{
alert(theHTML.children[i].tagName);
}
}
</SCRIPT>
</HEAD>
<BODY onload=showme()>
<DIV> Some text in a DIV. This DIV will be in
the all collection of the HTML element</DIV>
</BODY>
</HTML>

More Collections

The object model provides additional collections that you can use to access the elements of the document.

Collection | Applies to | Contains
anchors | document object | A elements having non-empty name property
applets | document | APPLET elements
areas | MAP element | AREA elements in the map
cells | TR element | TD or TH elements in the row
elements | FORM element | BUTTON, INPUT, SELECT, and /or TEXTAREA elements in the form
embeds | document | EMBED elements
filters | all elements | filter objects
forms | document | FORM elements
frames | document and window | window objects defined with FRAME and IFRAME elements
images | document | IMG elements
links | document | A elements having non-empty href properties
options | SELECT element | OPTION elements
rows | TABLE | TR elements in the table
scripts | document | SCRIPT elements
tbodies | TABLE | TBODY elements

Some scriptable collections are not really element collections, but collections of other scriptable objects.
Collection | Applies to | Contains
imports | styleSheet object | @import statements that are defined in a style sheet
styleSheets | document | styleSheet objects— represent instances of LINK and STYLE
filters | element | collection of CSS-defined filter attributes per element object
rules | styleSheet object | collection of style rules—combination of a CSS contextual selector and a style

Like the all collection, these collections are automatically updated as changes are made to the document.

Using Collections

Collections in the object model are similar to an array of variables created in a programming language. You can retrieve an item from the collection by providing an name or identifier for the item, or an ordinal index that specifies the position of the item in the collection. Collections indexes are zero-based, so the first item always has an index of zero. The following JScript example displays the tag name of the P element, the sixth element in the collection.

<HTML>
<HEAD><TITLE>Elements: Retrieving Items</TITLE>
<SCRIPT LANGUAGE="JScript">
function showSixth() {
    var el = document.all(5);
    alert("The sixth element is: " + el.tagName);
}
</SCRIPT>
</HEAD>
<BODY onload="showSixth()">
<P>This is a very simple document.
</BODY>
</HTML>

Because index values for collections are zero-based, the index for the last element in a collection is always one less than the length of the collection. So a quick way to get access to the last element in a collection is to subtract one from its length and use the result as the index value, as in the following example.

var elLast = document.all(document.all.length-1);
alert("The last element in this document is: " + elLast.tagName);

You can also retrieve items from a collection by specifying an identifier. In this case, the element must have a valid identifier, set using the ID= attribute. The following JScript example displays the tag name of the element that has the identifier "MyID".

<HTML>
<HEAD><TITLE>Elements: IDs as Indexes</TITLE>
<SCRIPT LANGUAGE="JScript">
function showElementWithID() {
    var el = document.all("MyID");
    alert("The element having the identifier MyID is: " + el.tagName);
}
</SCRIPT>
</HEAD>
<BODY onload="showElementWithID()">
<P ID="MyID">This is a very simple document.
</BODY>
</HTML>

Elements can also be accessed by name, but it is important to remember that the name attribute primarily applies only to the elements that participate in a form submission. The ID attribute is an identifier that applies to every element.

Be careful! While in theory ID means "unique identifier," in reality the uniqueness is not enforced. If more than one element has the same identifier, the result is a collection of elements with the same ID, rather than an individual element. The subsequent collection can only be accessed ordinally. If no element has the identifier, the result is null.

When using an identifier results in another collection, the elements in the new collection have the same order as they have in the document. To get access to these elements, you can use the item method to apply a zero-based index to the collection, as in the following example.

if (document.all("MyID").length != null)
    alert("The first element that has the identifier MyID: " + document.all("MyID").item(0).tagName);

If you already know that more than one element has the same identifier, you can skip a step and use the optional second parameter of item to retrieve an element without first retrieving the collection. The following JScript example displays the same message as the previous example.

var el = document.all.item("MyID",0);
if (el != null)
    alert("The first element that has the identifier MyID: " + el.tagName);

If you already know that more than one element has the same identifier, you can skip a step and use the optional second parameter of item to retrieve an element without first retrieving the collection. The following JScript example displays the same message as the previous example.

var el = document.all.item("MyID",0);
if (el != null)
    alert("The first element that has the identifier MyID: " + el.tagName);

When using scripting languages such as JScript and VBScript (Visual Basic® Scripting Edition), you can also access elements in collections by using the indexing syntax for that language. JScript offers three ways to index an array: an integer index enclosed in square brackets, an identifier given as a string enclosed in square brackets, and an identifier prefixed with a period. The following JScript statements show how to apply these.

var el = document.all[2];    // is the same as document.all.item(2)
var el = document.all["MyID"];   // is the same as document.all.item("MyID")
var el = document.all.MyID;      // is the same as document.all.item("MyID")

Again, be careful when using identifiers in this way. The collection returns another collection if there is more than one element having the given identifier. Always check the return value before you use it.

You can't use identifiers to access items in an imports collection—the collection consists of imported style sheets rather than HTML elements, so no identifiers are available. Use integer indexes instead. Although you can use names to access items in a frames collection, you should make certain that no two windows have the same name. If you don't, only the first window with the given name will be accessible.

Creating new Collections: The tags Method

The tags method creates a collection of elements that have a given tag name. The method filters an existing collection and creates a new collection of a given tag name. For example, the following JScript code applies the tags method to the all collection to retrieve a new collection containing only the TABLE elements in the document. It then applies a border to each table.

var doc_tables = document.all.tags("TABLE");
for (i=0; i<doc_tables.length; i++)
    doc_tables(i).border = 1;

The method searches for any tag name, even names that are not valid HTML. If it finds one or more elements having that name, it returns the collection. If it can't find an element having that name, it returns an empty collection. Use the length property to determine how many elements the collection contains. The collection is empty if its length is zero.

The tags method preserves the order of the elements as it creates the new collection. This means the first element in the new collection is also the first instance of the tag in the document.

Because the collection returned by the tags method is a subset of the all collection, the ordinal value that you use to access an element is different than you would use to access an element in the all collection. Sometimes it is useful to know both ordinal values. The sourceIndex property for the element returns the ordinal position of the element in the document's all collection.

Accessing Element Properties

Many element properties are named-value pairs that correspond to the HTML attributes of the element and to other values associated with the element. You can get the value of a property to determine how the corresponding attribute is set, and in many cases change the value of this property to dynamically affect the element. This is the key concept behind manipulating dynamic styles and dynamic content. Accessing the properties that let you change styles and content is done by accessing the element object through the collections exposed in the document object model. For example, you can center an H1 element by accessing the H1 element through the all collection on the document and then setting its align property to "center", the same value you would use with the ALIGN= attribute.

var coll = document.all.tags("H1");
if (coll.length>0)
    coll(0).align="center";

Similarly, you can change the image file name for an IMG element by setting its src property.

var coll = document.all.tags("IMG");
if (coll.length>0)
    coll(0).src="newimage.gif";

Most properties have the same name and take the same values as the corresponding attribute. This means most properties take strings, enumerated values, or numeric values. If a property name is different from its corresponding attribute, it is usually fairly close to the attribute name. For example, the className property corresponds to the CLASS= attribute. Name changes are done to avoid conflicts with keywords in common scripting languages, or to make sure that property names don't contain characters that are invalid in common scripting languages.

A few properties represent sub-objects. For example, style corresponds to the STYLE= attribute and represents a sub-object that gives you access to all the CSS attributes that can be applied to the element as an inline style. The style object itself takes properties, which you can set to alter the look and formatting of the element. The following example uses the style object to change the CSS color attribute of all H1 elements to green.

var coll = document.all.tags("H1");
for (i=0; i<coll.length; i++)
    coll[i].style.color = "green";

Some properties do not correspond to element attributes. These properties typically give additional information about the element that isn't available through attributes. For example, the tagName property specifies the HTML tag name of the element, and the sourceIndex property specifies the position of the element in the document's all collection.

Although you can get and set the values of many properties, some properties are "read-only" in that you can get the values but not set or change them. For example, the tagName property is a read-only property—changing the tag name of an element is not permitted.

Sometimes an HTML document will have invalid attributes, or invalid values assigned to attributes. If an invalid value is assigned to an attribute, the corresponding property is always set to its default value. For example, in the following document, "middle" is not a valid value for the ALIGN= attribute, so the document displays the message "left", the default value for the align property.

<HTML>
<HEAD><TITLE>Elements: Using Properties</TITLE>
<SCRIPT LANGUAGE="JScript">
function showAlignment() {
    var coll = document.all.tags("H1");
    for (coll.length>0)
        alert("The alignment for the first heading is " + coll(0).align);
}
</SCRIPT>
</HEAD>
<BODY onload="showAlignment()">
<H1 ALIGN="middle">Welcome!</H1>
<P>This document is <B>very</B> short.
</BODY>
</HTML>

The getAttribute, setAttribute, and removeAttribute methods give you access to the attributes of an element without using properties. You supply an attribute name, and these methods return or set the current value of the attribute, or remove the attribute.

For example, you can get and set the current value of the ALIGN= attribute (rather than retrieve the align property) by using getAttribute and setAttribute as in the following document. The document displays the current value of the attribute ("left"), then changes that value to "center", centering the H1 element.

<HTML>
<HEAD><TITLE>Elements: Using Methods</TITLE>
<SCRIPT LANGUAGE="JScript">
function showAndSetAlignment() {
    alert(document.all.MyHeading.getAttribute("align"));
    document.all.MyHeading.setAttribute("align","center");
}
</SCRIPT>
</HEAD>
<BODY onload="showAndSetAlignment()">
<H1 ID=MyHeading ALIGN="left">Welcome!</H1>
<P>This a short document.
</BODY>
</HTML>

The attribute methods are especially useful when working with unrecognized attributes and invalid values. For example, if an attribute has an invalid value, the getAttribute method retrieves that exact value rather than the default value for the attribute. This means you can use the method to examine what is really in the HTML document and make decisions based on that. The following document uses the methods to repair the alignment of the H1 element ("middle" is not a valid value).

<HTML>
<HEAD><TITLE>Elements: Invalid Values</TITLE>
<SCRIPT LANGUAGE="JScript">
function checkValues() {
    if (document.all.MyHeading.getAttribute("align")=="middle")
        document.all.MyHeading.setAttribute("align","center");
    if (document.all.MyHeading.getAttribute("xyz")!="123")
        document.all.MyHeading.setAttribute("xyz","123");
}
</SCRIPT>
</HEAD>
<BODY onload="checkValues()">
<H1 ID=MyHeading XyZ="123" ALIGN="middle">Welcome!</H1>
<P>This is a short document.
</BODY>
</HTML>

By default, these attribute methods are case insensitive when looking for an unknown attribute. So in the example above, even though "xyz" isn't identical to "XyZ", the methods get and set the attribute anyway. You can force the methods to search for an exact match by setting the optional case-sensitive parameter to true. For example, the following code, if placed in the previous example, displays "Not found" because "xyz" does not match "XyZ".

if (document.all.MyHeading.getAttribute("xyz", true)==null)
    alert("Not found");

If multiple matches are found for a case-sensitive usage of these methods, the actual item returned is not guaranteed to be consistent across platforms.

Examining the Element Hierarchy

The elements of an HTML document form a hierarchy in which some elements contain others. The HTML element, at the top of the hierarchy, contains all other elements in the document. The BODY element, contained by HTML, represents the document. Block elements, such as P, contain text and inline elements, which can themselves contain text and inline elements, and so on.

You can examine this structural hierarchy by using the contains method and the parentElement property. The all collection and the children collection (discussed previously) for each element can also help determine the document structure.

The contains method returns either true or false to indicate whether one element contains another. You apply the method to an element and supply another element as the parameter. For example, the following document displays the message "True!" because the BODY element contains P.

<HTML>
<HEAD><TITLE>Elements: Hierarchy</TITLE>
<SCRIPT LANGUAGE="JScript">
function showContains() {
    var el = document.all.tags("P").item(0);
    if (document.body.contains(el))
        alert("True!");
    else
        alert("False!");
}
</SCRIPT>
</HEAD>
<BODY onload="showContains()">
<P>This is a very simple document.
</BODY>
</HTML>

Note in the example above that the body property of the document object is used to retrieve the BODY object.

The parentElement property always identifies the next element in the hierarchy that contains the element. You can combine contains and parentElement in a more complicated script to determine the hierarchy of the elements document. The following document uses these to determine the hierarchy, then it displays a message that shows the hierarchy.

<HTML>
<HEAD><TITLE>Elements: Hierarchy</TITLE>
<SCRIPT LANGUAGE="JScript">
function showHierarchy() {
    var depth = 0;
    var msg = document.all(0).tagName;
    for (i=1; i<document.all.length; i++) {
        if (document.all(i-1).contains(document.all(i))==true) {
            depth = depth + 1;
        } else {
            var elParent = document.all(i-1).parentElement;
            for ( ; depth>0; depth--) {
                if (elParent.contains(document.all(i))==true)
                    break;
                elParent = elParent.parentElement;
            }
        }
        msg = msg + "\n";
        for (j=1; j<=depth; j++)
            msg = msg + "  ";
        msg = msg + document.all(i).tagName;
    }
    alert("This document contains:\n" + msg);
}
</SCRIPT>
</HEAD>
<BODY onload="showHierarchy()">
<H1>Welcome!</H1>
<P>This document is <B>very</B> short.
</BODY>
</HTML>

Getting an Element's Position and Dimensions

You can determine the location, width, and height of an element by using the offsetLeft, offsetTop, offsetHeight, and offsetWidth properties. These numeric properties specify the physical coordinates and dimensions of the element relative to the element's offset parent. For example, the following document is a simple clock that adjusts the size of its readout to fit the current width and height of the document body.

<HTML>
<HEAD><TITLE>A Simple Clock</TITLE>
<SCRIPT LANGUAGE="JScript">
function startClock() {
    window.setInterval("Clock_Tick()", 1000);
    Clock_Tick();
}

var ratio = 4;
function Clock_Tick()
{
    var s = Date();
    var t = s.substring(11,19);
    var doc_height = document.body.offsetHeight;
    var doc_width = document.body.offsetWidth;

    if ((doc_height*ratio)>doc_width)
        doc_height = doc_width / ratio;
    document.all.MyTime.innerText = t;
    document.all.MyTime.style.fontSize = doc_height;
}
</SCRIPT>
</HEAD>
<BODY onload="startClock()">
<P ID="MyTime">&nbsp;</P>
</BODY>
</HTML>

The offsetLeft and offsetTop property values are relative to the element specified by the offsetParent property for the element. Most of the time the property returns BODY. For example, in the following document, even though the TD element appears to the far right in the document, its position is (0,0) because its offset parent is the TR, not the document body.

<HTML>
<HEAD><TITLE>Elements: Positions</TITLE>
<SCRIPT LANGUAGE="JScript">
function showPosition() {
    var el = document.all.MyID;
    alert("The TD element is at (" + el.offsetLeft + "," + el.offsetTop + ")\n" +
        "The offset parent is " + el.offsetParent.tagName );
}
</SCRIPT>
</HEAD>
<BODY onload="showPosition()">
<P>This document contains a right-aligned table.
<TABLE BORDER=1 ALIGN=right>
<TR><TD ID=MyID>This is a small table
</TABLE>
</BODY>
</HTML>

Scrolling Elements into View

Another useful method is scrollIntoView. This scrolls the element into view within the window, placing it at either the top or bottom of the window. The method is useful for immediately showing the user the result of some action without requiring the user to manually scroll the document to find the result. The following example underlines the content of the fifth paragraph and scrolls it into view at the top of the window.

var coll = document.all.tags("P");
if (coll.length>=5) {
    coll(4).style.textDecoration = "underline";
    coll(4).scrollIntoView(true);
}


Working with Windows, Frames, and Dialogs

Microsoft® Internet Explorer creates a window object whenever it opens an HTML document. Because this object is the highest-level object in the object model, you use it to gain access to properties and sub-objects in the object model that you need to dynamically access the document content. The following topics explain how use the window object, create new window objects, and create special types of window objects.

Be sure to review Cross-Frame Scripting and Security for cross-window and frame scripting issues. Security considerations limit the cross-window access from scripts, and reading this section will help you understand what you can and cannot do through scripting.

Using the Window Object

Creating and Using Frames

Creating and Using Modal Dialog Boxes

Showing a Help Window

Using the Window Object

The window object is the root of the object hierarchy. All properties in the object model are either accessed as properties of the window object or as properties of those properties. For example, you access the document through the document property of the window object. Properties that have properties are often called objects or sub-objects, so document is referred to as the document object. For a complete list of properties of the window object, see Properties.

Because the current window object is implied, you do not need to prefix the property with the window keyword. However, many people prefer to use the keyword to ensure that their scripts are as clear and readable as possible. For example:

status = "hello";

is the same as saying:

window.status = "hello";

and both will work when referring to the current window object.

Many of the properties of the window object can be used to carry out simple tasks, such as displaying messages, prompting for input, and loading new documents into the window. For example, you can display a simple modal message box from the current window by using the alert method and change the text in the Internet Explorer status bar by using the status property, as in the following example.

<HTML>
<HEAD><TITLE>A Simple Document</TITLE>
<SCRIPT LANGUAGE="JScript">
function doAlert() {
    window.status = "Page is loaded!";
    alert("Page is loaded!");
}
</SCRIPT>
</HEAD>
<BODY onload="doAlert()">
<P>This is a very short document.
</BODY>
</HTML>

You can use the navigate method or the location object to load a new document into a window. The action is similar to the user clicking a link to the new document, but can be carried out from script. The following example uses the navigate method to load the new document named "sample.htm" after a 60-second timer (using the setTimeout method) elapses.

window.setTimeout("window.navigate('sample.htm')", 60000);

You can also use the location object to navigate within the current document. For example, the following statement jumps to the anchor in the document having the name "sample".

window.location.hash="#sample";

There can be more than one window object at a time. For example, the browser creates one window object for each frame defined within a document. From the scripting perspective, the current window object is always the one that contains the document that contains the script. To access window objects other than the current window object, you precede the property with a window reference. The window.open method returns a reference to this new window that is then used in scripts to access properties and methods of the new window.

The following document uses the method to open a window and load the document "sample.htm" when the user clicks the button.

<HTML>
<HEAD><TITLE>Creating a Window</TITLE>
</HEAD>
<BODY>
<P><BUTTON onclick="window.open('sample.htm')">Open Sample</BUTTON>
</BODY>
</HTML>

The new window is a separate instance of Internet Explorer, and the window object created for it is different than that of the original window. The new window can be referenced from the current window in script by the name "mysample". The following example creates a new window for the "sample.htm" document, then assigns the title of the new window's document to the status bar of the original window.

var new_window = window.open("sample.htm");
if (new_window != null)
    window.status = new_window.document.title;

Once a window creates another, it can manage that window in a variety of ways, from loading new documents in the window with the navigate method or location object to closing the window with the close method. Closing the window unloads the document and closes the separate instance of Internet Explorer.

Because the user can also close the new window at any time, you should always make sure that the window exists before attempting to access it. You can do this by checking the closed property, which is set to true when the window is closed.

You can assign a name to a window when you create it by using the optional second parameter of the open method. The name is useful to use as the target of a link, causing the document specified by the link to be loaded in the window. The following document creates a window named "Sample". The links later in the document use "Sample" as the target name.

<HTML>
<HEAD><TITLE>Linking to Sample</TITLE>
</HEAD>
<BODY onload="window.open('sample.htm','Sample')">
<P>Click the following links to view the documents in the Sample window:
<P><A HREF="abc.htm" TARGET="Sample">All About Abc</A>
<P><A HREF="xyz.htm" TARGET="Sample">Some Words on Xyz</A>
</BODY>
</HTML>

By default, the open method creates a window that has a default width and height and the standard menu, toolbar, and other features of Internet Explorer. You can alter this set of features by using the optional third parameter. This parameter is a string consisting of one or more feature settings, including settings for the position and dimension of the window. For example, the following creates a window that is 200-by-400 pixels, has a status bar, but does not have a toolbar, menu bar, or address field.

window.open("sample.htm",null,
    "height=200,width=400,status=yes,toolbar=no,menubar=no,location=no");

For more information about the window features, see open.

Creating and Using Frames

Frames are a way to organize and structure HTML documents, creating compound views that the user sees within the main window of Internet Explorer. Because each frame is itself a unique window within the main window, you use the window object to access the frame's content.

You create frames by using the IFRAME element or FRAMESET and FRAME elements. Each element creates a frame and loads a specified document. For example, the following document creates two equally sized rectangular frames that fill the main window.

<HTML>
<HEAD><TITLE>Two Equal Frames</TITLE>
</HEAD>
<FRAMESET COLS="50%,*">
<FRAME SRC=x.htm>
<FRAME SRC=y.htm>
</FRAMESET>
</HTML>

In a document within a frame, such as the "x.htm" and "y.htm" documents in the example above, you can use the window object as you would in a document within the main window. This means you can get access to the document and event objects for the frameset document and write script that will run from this frameset document. Note that if you use script, or need to instantiate an OBJECT from this frameset document, you need to define these in the HEAD section. Also note that a BODY element is mutually exclusive from a FRAMESET. Using both in a single document will result in the first one being instantiated and the second one ignored. Many authors try to use a BODY element to set the background color, and then instantiate a FRAMESET. Internet Explorer 4.0 will instantiate the BODY, and ignore the FRAMESET. Move the background color settings to the FRAMESET, and remove the BODY from this document, and the browser will intantiate the FRAMESET as you would expect.

You can also gain access to the window that created the frame (called the parent window) and to the other frames created by the parent by using the parent property and the frames collection. The following JScript example using these to display the URL of the documents in each frame.

for (i=0; i<window.parent.frames.length; i++)
    alert("Frame #" + i + " contains: " + window.parent.frames(i).location);

The frames collection contains window objects for each frame, so you can use the same properties and methods with these objects as you would within the current window. For example, you can gain access to the complete contents of the document in another frame by using frames, as in the following example, to display the title of each document.

for (i=0; i<window.parent.frames.length; i++)
    alert("The title of frame #" + i + " is: " + window.parent.frames(i).document.title);

Note Cross-frame security limits scripting to documents loaded from the same domain. Use the domain property to determine and/or set the domain of a document. See Cross-Frame Scripting and Security for more information on cross frame security and scripting considerations.

The frames collection also works this way for the document object. In this case, the frames collection from the document contains window objects for all frames created by IFRAME elements in a document. Consider the following document.

<HTML>
<HEAD><TITLE>Two Floating Frames</TITLE>
<SCRIPT>
function showFrames() {
    for (i=0; i<window.document.frames.length; i++)
        alert("The title of frame #" + i + " is: " +
            window.document.frames(i).document.title);
}
</SCRIPT>
</HEAD>
<BODY onload="showFrames()">
<IFRAME SRC="x.htm" ALIGN=LEFT></IFRAME> Here's some text to the right of a frame.
<BR CLEAR=LEFT>Here's some text beneath the frame.
<BR>
<IFRAME SRC="y.htm" ALIGN=RIGHT></IFRAME> Here's some text to the left of a frame.
<BR CLEAR=RIGHT>Here's some text beneath the frame.
</BODY>
</HTML>

The document above contains two floating frames, one aligned to the left and the other to the right. Once the document is loaded, the "showFrames" function uses the frames collection to access each frame and display the title of the corresponding document.

Unlike windows created using the open method, you cannot close the window associated with a frame. The frame is "closed" when the window that created it is unloaded. Also, properties that apply to the main window, such as status, have no purpose within a frame. Frames do not have status bars, so attempting to get or set status has no effect for the individual frames, and you should access the parent frameset document to set the status bar.

Notice that accessing the window object associated with a frame is not the same as accessing the FRAME or IFRAME element that created the frame. In particular, you cannot access the attributes of these elements by using the window object. Instead, you must use the object for the element, which you can get from the all collection for the document that contains the frame element. For example, if you want to remove the scroll bars from a frame, you have to set the scrolling property of the IFRAME element as follows:

document.all.tags("IFRAME").item(1).scrolling="no";

For more information about element objects and their properties, see Scripting with Elements and Collections.

Creating and Using Modal Dialog Boxes

A dialog box is a special window that you create by using the showModalDialog method on the window object. Dialog boxes are useful for soliciting input from the user in a way that does not obscure the information in the current window. They are also useful for displaying important information that the user should act upon or acknowledge before proceeding.

The showModalDialog method is similar to the open method in that it takes the URL of an HTML document and displays the document in a new window. One of the main differences, however, is that the dialog box is modal, meaning it does not release the input focus until it is closed. This means the user cannot switch back to the window that created the dialog box until she closes the dialog box. However, this does not prevent the user from switching to other windows or applications.

You typically create dialog boxes in response to user input, such as clicking a button or choosing an item in a menu. The following example calls showModalDialog directly from the onclick attribute of a BUTTON element.

<BUTTON onclick="window.showModalDialog('dialog.htm')">Search</BUTTON>

The method in the example above creates a dialog box having the standard dialog box size and features, and loads the document "dialog.htm" into the new window.

You can load any valid HTML document into a dialog box, but most dialog documents contain one or more controls with which the user supplies input or directs an action. For example, the following document provides a text control for letting the user specify a string to search for and buttons to confirm or cancel the search. Notice that the string is returned to the main window by assigning it to "returnValue".

<HTML>
<HEAD><TITLE>Search For</TITLE>
<SCRIPT LANGUAGE="JScript">
function doOK() {
    window.returnValue = window.document.all.MySearch.value;
    window.close();
}
function doCancel() {
    window.returnValue = "";
    window.close();
}
</SCRIPT>
</HEAD>
<BODY>
<P><B>Search For:</B> <INPUT ID=MySearch TYPE=text>
<CENTER>
<BUTTON onclick="doOK()">OK</BUTTON>&nbsp;
<BUTTON onclick="doCancel()">Cancel</BUTTON>
</CENTER>
</BODY>
</HTML>

When the document above is displayed, the user can type a string into the text control (identified by "MySearch") and click either the OK or Cancel button to carry out an action. Clicking OK calls the "doOK" function, which retrieves the text from the text control and assigns it to the returnValue property of the dialog box. Clicking Cancel calls "doCancel", which assigns an empty string to this property. Both functions then call the close method to close the dialog box and return the input focus to the original window.

The returnValue property on the window object specifies the value to be returned by the showModalDialog method after the dialog box closes. Setting this property is one way a dialog box can return information to the original window. Assuming the document in the previous example is in a file named "search.htm", the following example can use the returned string to carry out a search.

function doSearch() {
    var str = showModalDialog("search.htm");
    if (str == "")
        return;    // user canceled search
    else {
        // search for the string
     }
}

You can pass arguments to a dialog box by using the second parameter of showModalDialog. This parameter accepts any valid type, so an array can be passed just as easily as a discrete type.

   var aCafeArgs = new Array("Tall", "Decaf", "Non-fat", "Mocha");
   var cResult = window.showModalDialog("barista.htm", aCafeArgs);

A dialog box can retrieve the arguments through the dialogArguments property of the window object. Passing arguments is a useful way for the original window to specify the initial values for the controls in the dialog box. For example, consider the dialog document in the search example. By scripting the onload event of the BODY element to call the following function, the dialog can set the initial search string to a value supplied by the original window.

function doInit() {
    if (window.dialogArguments != null)
        window.document.all.MySearch.value = window.dialogArguments;
}
   .
   .
   .
<BODY onload="doInit()">

To set the initial search string to the words "Sample Text", the original window calls showModalDialog as in the following example.

var str = showModalDialog("search.htm", "Sample Text");

A better way to make use of the dialog arguments for this document is to store the search string in a variable within the document of the original window, as in the following example.

var str = "";
function doSearch() {
    str = showModalDialog("search.htm", str);
    if (str == "")
        return;    // user canceled search
    else {
        // search for the string
    }
}

Storing the returned string in the global variable ensures that the previous search string is available whenever the user requests another search. Remember that stored values are discarded when a document is unloaded, so you cannot store the previous string with the dialog document. This also means that the stored string in the original window is discarded when that document is unloaded.

In addition to setting initial values, you can also set the input focus to a specific control in the dialog box by using the focus method. This ensures that when the dialog document is loaded, the user can begin entering input immediately without first moving the focus to an appropriate control. The input focus is typically set in the same function that sets initial values for the dialog box. To set the focus to the text control in the previous example, use the following:

window.document.all.MySearch.focus();

If the original window has more that one value to exchange with the dialog box, it can do this by passing an object to the dialog as an argument. For example, the following dialog document prompts the user with both a "Match Case " check box and a "Search For" string. To receive the user's settings for these, the original window passes an object that the dialog sets when the user presses OK or Cancel.

<HTML>
<HEAD><TITLE>Search For</TITLE>
<SCRIPT LANGUAGE="JScript">
function doInit() {
    if (window.dialogArguments != null) {
        window.document.all.MySearch.value = window.dialogArguments.str;
        window.document.all.MatchCase.checked = window.dialogArguments.caseSensitive;
    }
    window.document.all.MySearch.focus();
    window.returnValue = false;
}
function doOK() {
    window.returnValue = true;
    if (window.dialogArguments != null) {
        window.dialogArguments.str = window.document.all.MySearch.value;
        window.dialogArguments.caseSensitive =
            window.document.all.MatchCase.checked;
    }
    window.close();
}
function doCancel() {
    window.returnValue = false;
    window.close();
}
</SCRIPT>
</HEAD>
<BODY onload="doInit()">
<INPUT ID=MatchCase TYPE=checkbox>&nbsp;<B>Match Case</B>
<P><B>Search For:</B> <INPUT ID=MySearch TYPE=text>
<CENTER>
<BUTTON onclick="doOK()">OK</BUTTON>&nbsp;
<BUTTON onclick="doCancel()">Cancel</BUTTON>
</CENTER>
</BODY>
</HTML>

Be careful! Any document that uses this dialog document needs to properly declare and initialize the object. The following example declares the "myDialog" object and initializes the object before calling showModalDialog.

function myDialog() {
    var str;
    var caseSensitive;
}
function doSearch() {
    myDialog.str = "";
    myDialog.caseSensitive = false;
    if (showModalDialog("search.htm", myDialog)==false)
        return;    // user canceled search
    else {
        // search for the string
    }
}

An alternate way to pass multiple values between the original window and the dialog box is to concatenate those values into a single string, and leave it to the documents to parse the string and extract the values.

The appearance and size of a dialog box can be set from the third parameter of the showModalDialog method. The following example creates a dialog box that uses a default font size of 10 pixels and a dialog width and height of 10 ems.

window.showModalDialog("dialog.htm",null,
    "font-size:10px;dialogWidth:10em;dialogHeight:10em")

As you can see in the example above, the third parameter takes a string, consisting of one or more settings separated by semicolons (;). Each setting consists of a name and a value separated by a colon (:) or equal sign (=). The value depends on the ornament. If it is a number, it takes a units designator, such as "px" or "em".

You use the dialogWidth and dialogHeight names to set the initial width and height of the dialog box. Similarly, you can use dialogLeft and dialogTop to set the initial position of the dialog box relative to the upper-left corner of the desktop (not the parent window). If you don't want to calculate the left and top positions for the dialog box, you can center it in the desktop by using the center keyword.

Although the position, width, and height of a dialog box are typically set by the parent document, you can retrieve and change these settings from within the dialog box itself by using the dialogLeft, dialogTop, dialogWidth, and dialogHeight properties. Changing these settings is important, for example, if you want to expand the content of the dialog box to show additional options that the user can choose from.

You can set the default typeface, font size, weight, and style for text in the dialog box by using the font, font-size, font-weight, and font-style names. These take the same values as the CSS attributes of the same name. The default settings apply only to text in the dialog box that does not already have explicit font settings.

Showing a Help Window

You can show help files in the browser using the showHelp method on the window object. The following example creates a help window that would display an HTML help file. For HTMLHelp, there are no modifying parameters, and only defaults will apply to the new window.

<BUTTON onclick="window.showHelp('helpinfo.htm')">Show Help</BUTTON>

The showHelp method can also be used to display WinHelp files. To display WinHelp files, the first parameter of the method specifies an .hlp file, the second parameter specifies a context identifier, and the third (optional) parameter can be used to specify "popup". The default view for help files is to show the help file in the main browser window. If "popup" is specified for WinHelp files, the help file is displayed in a separate window.


Cross-Frame Scripting and Security

With Dynamic HTML, content in different windows and frames can interact in powerful ways by scripting with the object model. However, since it is possible for a browser to simultaneously display unrelated documents in its various windows and frames, certain rules must be enforced to protect data integrity and privacy of information.

This section describes how and why these restrictions apply in the DHTML object model. All rules about script interaction apply equally to windows, dialog boxes, FRAMESETs, FRAMEs, and IFRAMEs.

For most content, only interactions with content from the same domain are allowed. For example, a typical page on http://www.microsoft.com/ can freely script content on any other page on http://www.microsoft.com/ but cannot script to pages that are located on a different Web domain. The DHTML object model uses the document.domain property to enforce this restriction: only pages with identical domain properties are allowed free interaction. The protocol of the URL must also match. For instance, an HTTP page cannot access HTTPS content.

The range of permissible access for a page can be expanded when a script assigns the document.domain property to a suffix of the site name space, up to the second-level domain. For example, a page on http://www.microsoft.com/ can assign the document.domain property—initially "www.microsoft.com"—to be "microsoft.com" to broaden access to include pages in http://home.microsoft.com or any other site, as long as the other pages also set the document.domain property to the identical value. Since only pages from a site whose name ends with "microsoft.com" will permit this domain to be set, it is assured that content from the same provider mutually agrees to interact and is free to do so. Domain suffixes shorter than the second-level domain (such as just "com") are disallowed because they expose beyond a single provider. For international site names such as http://www.microsoft.co.jp/, the second-level domain for widest access would be "microsoft.co.jp" (not "co.jp").

Since it is important to be able to navigate windows or frames to any URL beyond the domain restriction, these types of accesses are always permitted. Only access that attempts to read-out or modify content is restricted. For instance, the window.location might be assigned to cause navigation to occur, but this property cannot be read if the URL is of a different domain. This would allow one page to learn where the user has been browsing, and to allow this is a breach of the user's privacy. Some restrictions that apply to pages of different domains include:
window.location | Property can be set to navigate, but cannot read.
Other location | Functionality is blocked.
document.href | Property can be set to navigate but cannot read.
Other document | Functionality is blocked.
<IFRAME> | src property can be set to navigate but cannot read

Scripts that attempt to access parts of the object model to which they do not have access will be blocked with a "permission denied" error.

While domain security can prevent certain types of content interaction, it is important to understand that this restriction is necessary to ensure security. For example, without domain security, a rogue page could "snoop" on other pages or, using DHTML, manipulate its content.

For more information, see Asynchronous and URL Monikers Overview.


DHTML Tutorials

Following is a list of articles that walk you, step by step, through the implementation of common Web authoring tasks using Dynamic HTML. Each article ends with a pointer to a sample demonstrating the technique just described, as well as links to related topics. Familiarity with a scripting language, preferrably JScript or VBScript, and its programming concepts is recommended.

How to Fly Text
Make text fly across your page either with the help of a MARQUEE control or by manipulating its position directly through CSS positioning. This article demonstrates both ways of flying text vertically or horizontally on a page.

How to Fly Text in Geometric Patterns
Learn step by step how to fly text diagonally across the page. This article introduces the sophisticated CSS (cascading style sheets) positioning capabilities of Microsoft® Internet Explorer 4.0.

How to Fly Text Through an Oval Path
Fly your text through an oval path with very few lines of code, using the DirectAnimation™ path control. The article describes how simply specifying a target object to be moved causes the path control to move the object around the page over time, in a geometric pattern.

How to Animate a Sequence of Elements
Make your page come alive with animation. The article describes how a series of elements displayed sequentially on a page over a timer or on a mouse click brings life to a slide show presentation.

How to Apply a Transition on an Image
Implement fast and easy visual effects on your pages with the help of transitions. This article teaches you how to apply transitions to an image with simple HTML and very minimal script.

How to Create a Dynamic Table of Contents
Use the power of CSS (cascading style sheets) to create a table of contents that expands and collapses in response to mouse clicks. This article demonstrates how to reassign style sheets on the fly in order to display or hide information on demand.

How to Change Text Color Character by Character
Add some flash to your pages by changing the colors of a group of objects at a set speed. This article models how to use JScript switch statements, timers, CSS (cascading style sheets), and HTML in creating this effect.

How to Manipulate Text Effects in Response to Mouse Events
Animate text using minimal scripting by following the steps presented in this article. The technique described, creating the mouseover highlight, provides an excellent introduction to using CSS (cascading style sheets).


JScript & VBScript Tutorials and References JScript & VBScript Tutorials and References *
  * Previous Topic: DHTML Tutorials
  * Next Topic: Multimedia

JScript & VBScript Tutorials and References

JScript Tutorial

JScript Language Reference

VBScript Tutorial

VBScript Language Reference


Multimedia

DirectAnimation is a set of multimedia controls and scripting methods that animate Web pages and provide integration with Dynamic HTML. DirectAnimation has comprehensive support for media types such as 2-D vector graphics, images and sprites, 3-D geometry, video, and sound.

The DirectAnimation controls provide access to many of the DirectAnimation scripting functions and libraries. These controls allow you to deliver impressive vector graphics, image, and animation content over the Web with little code and short download times.

The DirectAnimation controls consist of the following:

Path Control Move objects around the page over time using splines, geometric primitives, text outlines or shapes that change dynamically over time with control over speed of motion, looping, forward or reverse playback, and bouncing behavior.

Sequencer Control Create complex sequences of action involving ActiveX™ controls, scripts, or dynamic HTML elements.

Sprite Control Add still and animated images to your Web page with control over playback speed, forward or reverse playback, dynamic seeking to different positions in the sprite playback, and user interactivity on a frame-by-frame basis.

Structured Graphics Control Add extremely lightweight vector graphics to your Web page, fully capable of being scaled or rotated in three dimensions, and then easily apply solid colors, patterns, gradient fills or bitmap textures to these graphics.

To see reference documentation for each DirectAnimation control, click here.

DirectAnimation can be accessed in different ways by different user groups. HTML authors can integrate multimedia using the DirectAnimation controls. Web authors can add animations (3-D, movies, sound, etc.) using JScript, VBScript, or Java.

The Microsoft DirectAnimation SDK provides documentation, samples, and tutorials to help users get up and running with DirectAnimation. The Exercises and Templates sections of the samples contain many small, simple scripting examples that perform one animation task and can be cut and pasted. For example, HWorldJS.htm demonstrates basic text animation as a windowless control. Crop.htm demonstrates a cropped animated image that overlays a variation of itself. Clrswtch.htm demonstrates using Visual Basic buttons to color an animation. DanTrapz.htm demonstrates rectangles with time-varying colors that chase each other along a path.


CSS Attributes Reference CSS Attributes Reference *
  * Previous Topic: Character Set Recognition
  * Next Topic: CSS Attributes

CSS Attributes Reference

CSS Attributes


DHTML References

These links provide Web authors with easy access to the set of reference material that will help them create compelling content for the Web.

Document Object Model References

Objects

Properties

Methods

Events

Collections

HTML References

Elements

Character Sets

CSS References

CSS Attributes

Additional References

Color Table

Tips and Tricks


Document Object Model References Document Object Model References *
  * Previous Topic: DHTML References
  * Next Topic: Objects

Document Object Model References

Objects

Properties

Methods

Events

Collections


HTML References HTML References *
  * Previous Topic: tbodies
  * Next Topic: HTML Elements

HTML References

HTML Elements

HTML Character Sets


Additional References Additional References *
  * Previous Topic: z-index
  * Next Topic: Color Table

Additional References

Color Table

Tips and Tricks


ISO Latin-1 Character Set

The following table contains the complete ISO Latin-1 character set, corresponding to the first 256 entries of the Unicode character repertoire in Internet Explorer 4.0. The table describes each character, its decimal code, and its named entity reference for HTML, and also provides a brief description.
Character | Decimal code | Named entity | Description
--- &#00; --- Unused
--- &#01; --- Unused
--- &#02; --- Unused
--- &#03; --- Unused
--- &#04; --- Unused
--- &#05; --- Unused
--- &#06; --- Unused
--- &#07; --- Unused
--- &#08; --- Unused
--- &#09; --- Horizontal tab
--- &#10; --- Line feed
--- &#11; --- Unused
--- &#12; --- Unused
--- &#13; --- Carriage Return
--- &#14; --- Unused
--- &#15; --- Unused
--- &#16; --- Unused
--- &#17; --- Unused
--- &#18; --- Unused
--- &#19; --- Unused
--- &#20; --- Unused
--- &#21; --- Unused
--- &#22; --- Unused
--- &#23; --- Unused
--- &#24; --- Unused
--- &#25; --- Unused
--- &#26; --- Unused
--- &#27; --- Unused
--- &#28; --- Unused
--- &#29; --- Unused
--- &#30; --- Unused
--- &#31; --- Unused
&#32; --- Space
! &#33; --- Exclamation mark
" &#34; &quot; Quotation mark
# &#35; --- Number sign
$ &#36; --- Dollar sign
% &#37; --- Percent sign
& &#38; &amp; Ampersand
' &#39; --- Apostrophe
( &#40; --- Left parenthesis
) &#41; --- Right parenthesis
* &#42; --- Asterisk
+ &#43; --- Plus sign
, &#44; --- Comma
- &#45; --- Hyphen
. &#46; --- Period (fullstop)
/ &#47; --- Solidus (slash)
0 &#48; --- Digit 0
1 &#49; --- Digit 1
2 &#50; --- Digit 2
3 &#51; --- Digit 3
4 &#52; --- Digit 4
5 &#53; --- Digit 5
6 &#54; --- Digit 6
7 &#55; --- Digit 7
8 &#56; --- Digit 8
9 &#57; --- Digit 9
: &#58; --- Colon
; &#59; --- Semicolon
< &#60; &lt; Less than
= &#61; --- Equals sign
> &#62; &gt; Greater than
? &#63; --- Question mark
@ &#64; --- Commercial at
A &#65; --- Capital A
B &#66; --- Capital B
C &#67; --- Capital C
D &#68; --- Capital D
E &#69; --- Capital E
F &#70; --- Capital F
G &#71; --- Capital G
H &#72; --- Capital H
I &#73; --- Capital I
J &#74; --- Capital J
K &#75; --- Capital K
L &#76; --- Capital L
M &#77; --- Capital M
N &#78; --- Capital N
O &#79; --- Capital O
P &#80; --- Capital P
Q &#81; --- Capital Q
R &#82; --- Capital R
S &#83; --- Capital S
T &#84; --- Capital T
U &#85; --- Capital U
V &#86; --- Capital V
W &#87; --- Capital W
X &#88; --- Capital X
Y &#89; --- Capital Y
Z &#90; --- Capital Z
[ &#91; --- Left square bracket
\ &#92; --- Reverse solidus (backslash)
] &#93; --- Right square bracket
^ &#94; --- Caret
_ &#95; --- Horizontal bar (underscore)
` &#96; --- Acute accent
a &#97; --- Small a
b &#98; --- Small b
c &#99; --- Small c
d &#100; --- Small d
e &#101; --- Small e
f &#102; --- Small f
g &#103; --- Small g
h &#104; --- Small h
i &#105; --- Small i
j &#106; --- Small j
k &#107; --- Small k
l &#108; --- Small l
m &#109; --- Small m
n &#110; --- Small n
o &#111; --- Small o
p &#112; --- Small p
q &#113; --- Small q
r &#114; --- Small r
s &#115; --- Small s
t &#116; --- Small t
u &#117; --- Small u
v &#118; --- Small v
w &#119; --- Small w
x &#120; --- Small x
y &#121; --- Small y
z &#122; --- Small z
{ &#123; --- Left curly brace
| &#124; --- Vertical bar
} &#125; --- Right curly brace
~ &#126; --- Tilde
 &#127; --- Unused
€ &#128; --- Unused
&#160; | &nbsp; | Nonbreaking space
¡ &#161; &iexcl; Inverted exclamation
¢ &#162; &cent; Cent sign
£ &#163; &pound; Pound sterling
¤ &#164; &curren; General currency sign
¥ &#165; &yen; Yen sign
¦ &#166; &brvbar; or &brkbar; Broken vertical bar
§ &#167; &sect; Section sign
¨ &#168; &uml; or &die; Diæresis / Umlaut
© &#169; &copy; Copyright
ª | &#170; | &ordf; | Feminine ordinal
« &#171; &laquo; Left angle quote, guillemot left
¬ &#172; &not Not sign
&#173; | &shy; | Soft hyphen
® &#174; &reg; Registered trademark
¯ &#175; &macr; or &hibar; Macron accent
° &#176; &deg; Degree sign
± &#177; &plusmn; Plus or minus
² | &#178; | &sup2; | Superscript two
³ | &#179; | &sup3; | Superscript three
´ &#180; &acute; Acute accent
µ | &#181; | &micro; | Micro sign
¶ &#182; &para; Paragraph sign
· &#183; &middot; Middle dot
¸ &#184; &cedil; Cedilla
¹ | &#185; | &sup1; | Superscript one
º | &#186; | &ordm; | Masculine ordinal
» &#187; &raquo; Right angle quote, guillemot right
¼ | &#188; | &frac14; | Fraction one-fourth
½ | &#189; | &frac12; | Fraction one-half
¾ | &#190; | &frac34; | Fraction three-fourths
¿ &#191; &iquest; Inverted question mark
À | &#192; | &Agrave; | Capital A, grave accent
Á | &#193; | &Aacute; | Capital A, acute accent
Â | &#194; | &Acirc; | Capital A, circumflex
Ã | &#195; | &Atilde; | Capital A, tilde
Ä | &#196; | &Auml; | Capital A, diæresis / umlaut
Å | &#197; | &Aring; | Capital A, ring
Æ | &#198; | &AElig; | Capital AE ligature
Ç | &#199; | &Ccedil; | Capital C, cedilla
È | &#200; | &Egrave; | Capital E, grave accent
É | &#201; | &Eacute; | Capital E, acute accent
Ê | &#202; | &Ecirc; | Capital E, circumflex
Ë | &#203; | &Euml; | Capital E, diæresis / umlaut
Ì | &#204; | &Igrave; | Capital I, grave accent
Í | &#205; | &Iacute; | Capital I, acute accent
Î | &#206; | &Icirc; | Capital I, circumflex
Ï | &#207; | &Iuml; | Capital I, diæresis / umlaut
Ð | &#208; | &ETH; | Capital Eth, Icelandic
Ñ | &#209; | &Ntilde; | Capital N, tilde
Ò | &#210; | &Ograve; | Capital O, grave accent
Ó | &#211; | &Oacute; | Capital O, acute accent
Ô | &#212; | &Ocirc; | Capital O, circumflex
Õ | &#213; | &Otilde; | Capital O, tilde
Ö | &#214; | &Ouml; | Capital O, diæresis / umlaut
× &#215; &times; Multiply sign
Ø | &#216; | &Oslash; | Capital O, slash
Ù | &#217; | &Ugrave; | Capital U, grave accent
Ú | &#218; | &Uacute; | Capital U, acute accent
Û | &#219; | &Ucirc; | Capital U, circumflex
Ü | &#220; | &Uuml; | Capital U, diæresis / umlaut
Ý | &#221; | &Yacute; | Capital Y, acute accent
Þ | &#222; | &THORN; | Capital Thorn, Icelandic
ß | &#223; | &szlig; | Small sharp s, German sz
à | &#224; | &agrave; | Small a, grave accent
á | &#225; | &aacute; | Small a, acute accent
â | &#226; | &acirc; | Small a, circumflex
ã | &#227; | &atilde; | Small a, tilde
ä | &#228; | &auml; | Small a, diæresis / umlaut
å | &#229; | &aring; | Small a, ring
æ | &#230; | &aelig; | Small ae ligature
ç | &#231; | &ccedil; | Small c, cedilla
è | &#232; | &egrave; | Small e, grave accent
é | &#233; | &eacute; | Small e, acute accent
ê | &#234; | &ecirc; | Small e, circumflex
ë | &#235; | &euml; | Small e, diæresis / umlaut
ì | &#236; | &igrave; | Small i, grave accent
í | &#237; | &iacute; | Small i, acute accent
î | &#238; | &icirc; | Small i, circumflex
ï | &#239; | &iuml; | Small i, diæresis / umlaut
ð | &#240; | &eth; | Small eth, Icelandic
ñ | &#241; | &ntilde; | Small n, tilde
ò | &#242; | &ograve; | Small o, grave accent
ó | &#243; | &oacute; | Small o, acute accent
ô | &#244; | &ocirc; | Small o, circumflex
õ | &#245; | &otilde; | Small o, tilde
ö | &#246; | &ouml; | Small o, diæresis / umlaut
÷ &#247; &divide; Division sign
ø | &#248; | &oslash; | Small o, slash
ù | &#249; | &ugrave; | Small u, grave accent
ú | &#250; | &uacute; | Small u, acute accent
û | &#251; | &ucirc; | Small u, circumflex
ü | &#252; | &uuml; | Small u, diæresis / umlaut
ý | &#253; | &yacute; | Small y, acute accent
þ | &#254; | &thorn; | Small thorn, Icelandic
ÿ | &#255; | &yuml; | Small y, diæresis / umlaut


Additional Named Entities for HTML

The following table contains additional named entities, their numeric character reference, and a description of each.
Character | Named entity | Numeric character reference | Description
Latin Extended-B
ƒ | &fnof | &#402; | latin small f with hook, =function, =florin, U0192 ISOtech
Greek
Α | &Alpha | &#913; | greek capital letter alpha, U0391
Β | &Beta | &#914; | greek capital letter beta, U0392
Γ | &Gamma | &#915; | greek capital letter gamma, U0393 ISOgrk3
Δ | &Delta | &#916; | greek capital letter delta, U0394 ISOgrk3
Ε | &Epsilon | &#917; | greek capital letter epsilon, U0395
Ζ | &Zeta | &#918; | greek capital letter zeta, U0396
Η | &Eta | &#919; | greek capital letter eta, U0397
Θ | &Theta | &#920; | greek capital letter theta, U0398 ISOgrk3
Ι | &Iota | &#921; | greek capital letter iota, U0399
Κ | &Kappa | &#922; | greek capital letter kappa, U039A
Λ | &Lambda | &#923; | greek capital letter lambda, U039B ISOgrk3
Μ | &Mu | &#924; | greek capital letter mu, U039C
Ν | &Nu | &#925; | greek capital letter nu, U039D
Ξ | &Xi | &#926; | greek capital letter xi, U039E ISOgrk3
Ο | &Omicron | &#927; | greek capital letter omicron, U039F
Π | &Pi | &#928; | greek capital letter pi, U03A0 ISOgrk3
Ρ | &Rho | &#929; | greek capital letter rho, U03A1
Σ | &Sigma | &#931; | greek capital letter sigma, U03A3 ISOgrk3
Τ | &Tau | &#932; | greek capital letter tau, U03A4
Υ | &Upsilon | &#933; | greek capital letter upsilon, U03A5 ISOgrk3
Φ | &Phi | &#934; | greek capital letter phi, U03A6 ISOgrk3
Χ | &Chi | &#935; | greek capital letter chi, U03A7
Ψ | &Psi | &#936; | greek capital letter psi, U03A8 ISOgrk3
Ω | &Omega | &#937; | greek capital letter omega, U03A9 ISOgrk3
a | &alpha | &#945; | greek small letter alpha, U03B1 ISOgrk3
b | &beta | &#946; | greek small letter beta, U03B2 ISOgrk3
g | &gamma | &#947; | greek small letter gamma, U03B3 ISOgrk3
d | &delta | &#948; | greek small letter delta, U03B4 ISOgrk3
ε | &epsilon | &#949; | greek small letter epsilon, U03B5 ISOgrk3
ζ | &zeta | &#950; | greek small letter zeta, U03B6 ISOgrk3
η | &eta | &#951; | greek small letter eta, U03B7 ISOgrk3
θ | &theta | &#952; | greek small letter theta, U03B8 ISOgrk3
ι | &iota | &#953; | greek small letter iota, U03B9 ISOgrk3
κ | &kappa | &#954; | greek small letter kappa, U03BA ISOgrk3
λ | &lambda | &#955; | greek small letter lambda, U03BB ISOgrk3
μ | &mu | &#956; | greek small letter mu, U03BC ISOgrk3
ν | &nu | &#957; | greek small letter nu, U03BD ISOgrk3
ξ | &xi | &#958; | greek small letter xi, U03BE ISOgrk3
ο | &omicron | &#959; | greek small letter omicron, U03BF NEW
p | &pi | &#960; | greek small letter pi, U03C0 ISOgrk3
ρ | &rho | &#961; | greek small letter rho, U03C1 ISOgrk3
ς | &sigmaf | &#962; | greek small letter final sigma, U03C2 ISOgrk3
σ | &sigma | &#963; | greek small letter sigma, U03C3 ISOgrk3
τ | &tau | &#964; | greek small letter tau, U03C4 ISOgrk3
υ | &upsilon | &#965; | greek small letter upsilon, U03C5 ISOgrk3
φ | &phi | &#966; | greek small letter phi, U03C6 ISOgrk3
χ | &chi | &#967; | greek small letter chi, U03C7 ISOgrk3
ψ | &psi | &#968; | greek small letter psi, U03C8 ISOgrk3
ω | &omega | &#969; | greek small letter omega, U03C9 ISOgrk3
ϑ | &thetasym | &#977; | greek small letter theta symbol, U03D1 NEW
ϒ | &upsih | &#978; | greek upsilon with hook symbol, U03D2 NEW
ϖ | &piv | &#982; | greek pi symbol, U03D6 ISOgrk3
General Punctuation
• &bull &#8226; bullet, =black small circle, U2022 ISOpub
… &hellip &#8230; horizontal ellipsis, =three dot leader, U2026 ISOpub
′ &prime &#8242; prime, =minutes, =feet, U2032 ISOtech
″ &Prime &#8243; double prime, =seconds, =inches, U2033 ISOtech
‾ &oline &#8254; overline, =spacing overscore, U203E NEW
⁄ &frasl &#8260; fraction slash, U2044 NEW
Letterlike Symbols
℘ &weierp &#8472; script capital P, =power set, =Weierstrass p, U2118 ISOamso
ℑ | &image | &#8465; | blackletter capital I, =imaginary part, U2111 ISOamso
ℜ | &real | &#8476; | blackletter capital R, =real part symbol, U211C ISOamso
™ &trade &#8482; trade mark sign, U2122 ISOnum
ℵ | &alefsym | &#8501; | alef symbol, =first transfinite cardinal, U2135 NEW
Arrows
← &larr &#8592; leftward arrow, U2190 ISOnum
↑ &uarr &#8593; upward arrow, U2191 ISOnum
→ &rarr &#8594; rightward arrow, U2192 ISOnum
↓ &darr &#8595; downward arrow, U2193 ISOnum
↔ &harr &#8596; left right arrow, U2194 ISOamsa
↵ &crarr &#8629; downward arrow with corner leftward, =carriage return, U21B5 NEW
⇐ &lArr &#8656; leftward double arrow, U21D0 ISOtech
⇑ &uArr &#8657; upward double arrow, U21D1 ISOamsa
⇒ &rArr &#8658; rightward double arrow, U21D2 ISOtech
⇓ &dArr &#8659; downward double arrow, U21D3 ISOamsa
⇔ &hArr &#8660; left right double arrow, U21D4 ISOamsa
Mathematical Operators
∀ &forall &#8704; for all, U2200 ISOtech
∂ &part &#8706; partial differential, U2202 ISOtech
∃ &exist &#8707; there exists, U2203 ISOtech
∅ &empty &#8709; empty set, =null set, =diameter, U2205 ISOamso
∇ &nabla &#8711; nabla, =backward difference, U2207 ISOtech
∈ &isin &#8712; element of, U2208 ISOtech
∉ &notin &#8713; not an element of, U2209 ISOtech
∋ &ni &#8715; contains as member, U220B ISOtech
∏ &prod &#8719; n-ary product, =product sign, U220F ISOamsb
∑ &sum &#8722; n-ary sumation, U2211 ISOamsb
− &minus &#8722; minus sign, U2212 ISOtech
∗ &lowast &#8727; asterisk operator, U2217 ISOtech
√ &radic &#8730; square root, =radical sign, U221A ISOtech
∝ &prop &#8733; proportional to, U221D ISOtech
∞ &infin &#8734; infinity, U221E ISOtech
∠ &ang &#8736; angle, U2220 ISOamso
∧ &and &#8869; logical and, =wedge, U2227 ISOtech
∨ &or &#8870; logical or, =vee, U2228 ISOtech
∩ &cap &#8745; intersection, =cap, U2229 ISOtech
∪ &cup &#8746; union, =cup, U222A ISOtech
∫ &int &#8747; integral, U222B ISOtech
∴ &there4 &#8756; therefore, U2234 ISOtech
∼ &sim &#8764; tilde operator, =varies with, =similar to, U223C ISOtech
≅ &cong &#8773; approximately equal to, U2245 ISOtech
≈ &asymp &#8773; almost equal to, =asymptotic to, U2248 ISOamsr
≠ &ne &#8800; not equal to, U2260 ISOtech
≡ &equiv &#8801; identical to, U2261 ISOtech
≤ &le &#8804; less-than or equal to, U2264 ISOtech
≥ &ge &#8805; greater-than or equal to, U2265 ISOtech
⊂ &sub &#8834; subset of, U2282 ISOtech
⊃ &sup &#8835; superset of, U2283 ISOtech
⊄ &nsub &#8836; not a subset of, U2284 ISOamsn
⊆ &sube &#8838; subset of or equal to, U2286 ISOtech
⊇ &supe &#8839; superset of or equal to, U2287 ISOtech
⊕ &oplus &#8853; circled plus, =direct sum, U2295 ISOamsb
⊗ &otimes &#8855; circled times, =vector product, U2297 ISOamsb
⊥ &perp &#8869; up tack, =orthogonal to, =perpendicular, U22A5 ISOtech
⋅ &sdot &#8901; dot operator, U22C5 ISOamsb
Miscellaneous Technical
⌈ &lceil &#8968; left ceiling, =apl upstile, U2308, ISOamsc
⌉ &rceil &#8969; right ceiling, U2309, ISOamsc
⌊ &lfloor &#8970; left floor, =apl downstile, U230A, ISOamsc
⌋ &rfloor &#8971; right floor, U230B, ISOamsc
⟨ &lang &#9001; left-pointing angle bracket, =bra, U2329 ISOtech
⟩ &rang &#9002; right-pointing angle bracket, =ket, U232A ISOtech
Geometric Shapes
◊ &loz &#9674; lozenge, U25CA ISOpub
Miscellaneous Symbols
♠ &spades &#9824; black spade suit, U2660 ISOpub
♣ &clubs &#9827; black club suit, =shamrock, U2663 ISOpub
♥ &hearts &#9829; black heart suit, =valentine, U2665 ISOpub
♦ &diams &#9830; black diamond suit, U2666 ISOpub


Character Entities for Special Symbols and BIDI Text

Using NE | NE | NCR | Using NCR
C0 Controls and Basic Latin
" &quot &#34; quotation mark, =apl quote, U0022 ISOnum
& &amp &#38; ampersand, U0026 ISOnum
< &lt &#60; less-than sign, U003C ISOnum
> &gt &#62; greater-than sign, U003E ISOnum
Latin Extended-A
Œ | &OElig | &#338; | latin capital ligature oe, U0152 ISOlat2
œ | &oelig | &#339; | latin small ligature oe, U0153 ISOlat2
Š | &Scaron | &#352; | latin capital letter s with caron, U0160 ISOlat2
š | &scaron | &#353; | latin small letter s with caron, U0161 ISOlat2
Ÿ | &Yuml | &#376; | latin capital letter y with diaeresis, U0178 ISOlat2
Spacing Modifier Letters
ˆ | &circ | &#710; | modifier letter circumflex accent, U02C6 ISOpub
˜ &tilde &#732; small tilde, U02DC ISOdia
General Punctuation
  &ensp | &#8194; | en space, U2002 ISOpub
  &emsp | &#8195; | em space, U2003 ISOpub
  &thinsp | &#8201; | thin space, U2009 ISOpub
‌ &zwnj &#8204; zero width non-joiner, U200C NEW RFC 2070
‍ &zwj &#8205; zero width joiner, U200D NEW RFC 2070
‎ &lrm &#8206; left-to-right mark, U200E NEW RFC 2070
‏ &rlm &#8207; right-to-left mark, U200F NEW RFC 2070
– &ndash &#8211; en dash, U2013 ISOpub
— &mdash &#8212; em dash, U2014 ISOpub
‘ &lsquo &#8216; left single quotation mark, U2018 ISOnum
’ &rsquo &#8217; right single quotation mark, U2019 ISOnum
‚ &sbquo &#8218; single low-9 quotation mark, U201A NEW
“ &ldquo &#8220; left double quotation mark, U201C ISOnum
” &rdquo &#8221; right double quotation mark, U201D ISOnum
„ &bdquo &#8222; double low-9 quotation mark, U201E NEW
† &dagger &#8224; dagger, U2020 ISOpub
‡ &Dagger &#8225; double dagger, U2021 ISOpub
‰ &permil &#8240; per mille sign, U2030 ISOtech
‹ &lsaquo &#8249; single left-pointing angle quotation mark, U2039 ISO proposed
› &rsaquo &#8250; single right-pointing angle quotation mark, U203A ISO proposed


Character Set Recognition

Internet Explorer uses the character set specified for a document to determine how to translate the bytes in the document into characters on the screen or paper. By default, Internet Explorer uses the character set specified in the HTTP content type returned by the server to determine this translation. If this parameter is not given, Internet Explorer uses the character set specified by the META element in the document. It uses the user's preferences if no META element is given.

You can use the META element to explicitly set the character set for a document. In this case, you set the HTTP-EQUIV= attribute to "Content-Type" and specify a character set identifier in the CONTENT= attribute. For example, the following META element identifies Windows-1251 as the character set for the document.

<META HTTP-EQUIV="Content-Type"
  CONTENT="text/html; CHARSET=Windows-1251">

As long as you place the META element before the BODY element, it affects the whole document, including the TITLE element. For clarity it should appear as the first element after HEAD so that all readers know the encoding before the first displayable is parsed. Note that the META element applies to the document containing it. This means, for example, that a compound document (a document consisting of two or more documents in a set of frames) can use different character sets in different frames.

Windows Codepage # | Display name | Preferred ID on SAVE | Internet Explorer 4 Aliases
1252 Western iso-8859-1
except when 128-159 is used, use "Windows-1252" 		iso8859-1, iso_8859-1, iso-8859-1, ANSI_X3.4-1968, iso-ir-6, ANSI_X3.4-1986, ISO_646, irv:1991, ISO646-US, us, IBM367, cp367, csASCII, latin1, iso_8859-1:1987, iso-ir-100, ibm819, cp819, Windows-1252
20105 | us-ascii | us-acii, ascii
28592 | Central European (ISO) | iso-8859-2 | iso8859-2, iso-8859-2, iso_8859-2, latin2, iso_8859-2:1987, iso-ir-101, l2, csISOLatin2
1250 | Central European (Windows) | Windows-1250 | Windows-1250, x-cp1250
1251 | Cyrillic (Windows) | Windows-1251 | Windows-1251, x-cp1251
1253 | Greek (Windows) | Windows-1253 | Windows-1253
1254 | Turkish (Windows) | Windows-1254 | Windows-1254
932 | Japanese (Shift-JIS) | shift_jis | shift_jis, x-sjis, ms_Kanji, csShiftJIS, x-ms-cp932
51932 | Japanese (EUC) | x-euc-jp | Extended_UNIX_Code_Packed_Format_for_Japanese, csEUCPkdFmtJapanese, x-euc-jp, x-euc
50220 | Japanese (JIS) | iso-2022-jp | csISO2022JP, iso-2022-jp
1257 | Baltic (Windows) | Windows-1257 | windows-1257
950 | Traditional Chinese (BIG5) | big5 | big5, csbig5, x-x-big5
936 | Simplified Chinese (GB2312) | gb2312 | GB_2312-80, iso-ir-58, chinese, csISO58GB231280, csGB2312, gb2312
20866 | Cyrillic (KOI8-R) | koi8-r | csKOI8R, koi8-r
949 | Korean (KSC5601) | ks_c_5601 | ks_c_5601, ks_c_5601-1987, korean, csKSC56011987
1255 (logical) | Hebrew (ISO-logical) | Windows-1255 | iso-8859-8i
1255 (visual) | Hebrew (ISO-Visual) | iso-8859-8 | ISO-8859-8 Visual, ISO-8859-8 , ISO_8859-8, visual
862 | Hebrew (DOS) | dos-862 | dos-862
1256 | Arabic (Windows) | Windows-1256 | Windows-1256
720 | Arabic (DOS) | dos-720 | dos-720
874 | Thai | Windows-874 | Windows-874
1258 | Vietnamese | Windows-1258 | Windows-1258
65001 | Unicode UTF-8 | UTF-8 | UTF-8, unicode-1-1-utf-8, unicode-2-0-utf-8
65000 | Unicode UTF-7 | UNICODE-1-1-UTF-7 | utf-7, UNICODE-1-1-UTF-7, csUnicode11UTF7, utf-7
50225 | Korean (ISO) | ISO-2022-KR | ISO-2022-KR, csISO2022KR
52936 | Simplified Chinese (HZ) | HZ-GB-2312 | HZ-GB-2312
28594 | Baltic (ISO) | iso-8869-4 | ISO_8859-4:1988, iso-ir-110, ISO_8859-4, ISO-8859-4, latin4, l4, csISOLatin4
28585 | Cyrillic (ISO) | iso_8859-5 | ISO_8859-5:1988, iso-ir-144, ISO_8859-5, ISO-8859-5, cyrillic, csISOLatinCyrillic, csISOLatin5
28597 | Greek (ISO) | iso-8859-7 | ISO_8859-7:1987, iso-ir-126, ISO_8859-7, ISO-8859-7, ELOT_928, ECMA-118, greek, greek8, csISOLatinGreek
28599 | Turkish (ISO) | iso-8859-9 | ISO_8859-9:1989, iso-ir-148, ISO_8859-9, ISO-8859-9, latin5, l5, csISOLatin5


HTML Character Sets

Character sets determine how the bytes that represent the text of your HTML document are translated to readable characters. Microsoft® Internet Explorer interprets the bytes in your document according to the applied character set translations. It interprets numeric character references ("&#12345;") as ISO10646 code points, consistent with the Unicode Standard, version 2.0, and independent of the chosen character set. Named entities ("&") are displayed independently of the chosen character set as well. The display of an arbitrary numeric character reference requires the existence of a font that is able to display that particular character on the user's system. Accordingly, the content in the first column of the following tables may not render as expected on all systems.

ISO Latin-1 Character Set

Additional Named Entities for HTML

Character Entities for Special Symbols and BIDI Text

Character Set Recognition


all

Description

Returns an object reference to the collection of elements contained by the object.

Syntax

object.all(index)

Parameter | Description
object | An object that can contain elements such as the document.
(index) | Optional. An integer or a string specifying the index value of the element to retrieve. Integer indexes are zero-based, meaning the first element in the collection has index 0. A string index is valid only if the string is a name or identifier of at least one element in the document.

Remarks

The all collection includes one element object for each valid HTML tag. If a valid tag has a matching end tag, both tags are represented by the same element object.

The collection returned by the document's all property always includes a reference to the HTML, HEAD, TITLE, and BODY objects regardless of whether the tags are present in the document.

If the document contains invalid or unknown tags, the collection includes one element object for each. Unlike valid end tags, unknown end tags are represented by their own element objects. The order of the element objects is the HTML source order. Although the collection indicates the order of tags, it does not indicate hierarchy.

Examples

The following JScript example displays the names of all tags in the document in the order the tags appear in the document.

for(i=0; i<document.all.length; i++) {
    alert(document.all(i).tagName);
}

The following JScript example uses the item method on the all collection to retrieve all element objects for which the name or ID attribute is set to "sample". Depending on how many times the name or ID is defined in the document, the item method may return null, a single element object, or a collection of element objects. The example uses the length property of the collection to determine whether item returned a collection or a single object.

var a = document.all.item("sample");
if (a!=null) {
    if (a.length!=null) {
        for (i=0; i<a.length; i++) {
            alert(a(i).tagName);
        }
    } else
        alert(a.tagName);
}

Property

length

Methods

item, tags

Applies To

A, ACRONYM, ADDRESS, APPLET, AREA, B, BASE, BASEFONT, BGSOUND, BIG, BLOCKQUOTE, BODY, BR, BUTTON, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, COMMENT, DD, DEL, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FONT, FORM, FRAME, FRAMESET, H1, H2, H3, H4, H5, H6, HEAD, HR, HTML, I, IFRAME, IMG, INPUT, INS, KBD, LABEL, LEGEND, LI, LINK, LISTING, MAP, MARQUEE, MENU, OBJECT, OL, P, PLAINTEXT, PRE, Q, S, SAMP, SCRIPT, SELECT, SMALL, SPAN, STRIKE, STRONG, STYLE, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TITLE, TR, TT, U, UL, VAR, XMP


anchors

Description

Retrieves a collection of all A elements that have a NAME= and/or ID= attribute. Elements in this collection are in HTML source order.

Syntax

object.anchors(index)

Parameter | Description
object | The document object.
(index) | Optional. An integer or a string specifying the index value of the element to retrieve. Integer indexes are zero-based, meaning the first element in the collection has index 0. A string index is valid only if the string is a name or identifier of at least one element in the document.

Remarks

This collection is indexed first by name, then by identifier. If duplicate names are found, a collection of those named items is returned. Collections of duplicate names must subsequently be referenced by ordinal position.

Example

The following example displays the NAME= attribute of the third anchor defined in the document.

alert(document.anchors(2).name);

Property

length

Methods

item, tags

Applies To

document


applets

Description

Retrieves a collection of all APPLET objects in the document.

Syntax

object.applets(index)

Parameter | Description
object | The document object.
(index) | Optional. An integer or a string specifying the index value of the object to retrieve. Integer indexes are zero-based, meaning the first object in the collection has index 0. A string index is valid only if the string is a name or identifier of one object in the document.

Remarks

This collection is indexed first by name, then by identifier. If duplicate names are found, a collection of those named items is returned. Collections of duplicate names must subsequently be referenced by ordinal position.

Property

length

Methods

item, tags

Applies To

document


areas

Description

Retrieves a collection of the AREA elements defined for the given MAP element.

Syntax

object.areas(index)

Parameter | Description
object | A MAP element.
(index) | Optional. An integer or a string specifying the index value of the element to retrieve. Integer indexes are zero-based, meaning the first element in the collection has index 0. A string index is valid only if the string is an identifier of at least one element in the document.

Remarks

Areas may be added to or removed from the collection. If duplicate identifiers are found, a collection of those items is returned. Collections of duplicates must subsequently be referenced by ordinal position.

Property

length

Methods

add, item, remove, tags

Applies To

MAP


cells

Description

Retrieves a collection of all cells in the row of a table. This is a collection of TH and TD elements.

Note When a cell spans multiple rows, that cell appears only in the cells collection for the first of the rows that the cell spans.

Syntax

object.cells(index)

Parameter | Description
object | A TR element.
index | Optional. An integer or a string specifying the index value of the element to retrieve. Integer indexes are zero-based, meaning the first element in the collection has index 0. A string index is valid only if the string is an identifier of at least one element in the document.

Remarks

If duplicate identifiers are found, a collection of those items is returned. Collections of duplicates must subsequently be referenced by ordinal position.

Example

The following example uses the rows collection on the TABLE and the cells collection to insert a number into each cell of the table.

<HTML>
<SCRIPT LANGUAGE="JScript">
function numberCells() {
    var count=0;
    for (i=0; i < document.all.mytable.rows.length; i++) {
        for (j=0; j < document.all.mytable.rows(i).cells.length; j++) {
            document.all.mytable.rows(i).cells(j).innerText = count;
            count++;
        }
    }
}
</SCRIPT>
<BODY onload="numberCells()">
<TABLE id=mytable border=1>
<TR><TH>&nbsp;</TH><TH>&nbsp;</TH><TH>&nbsp;</TH><TH>&nbsp;</TH></TR>
<TR><TD>&nbsp;</TD><TD>&nbsp;</TD><TD>&nbsp;</TD><TD>&nbsp;</TD></TR>
<TR><TD>&nbsp;</TD><TD>&nbsp;</TD><TD>&nbsp;</TD><TD>&nbsp;</TD></TR>
</TABLE>
</BODY>
</HTML>

Applies To

TR

Property

length

Methods

item, tags


children

Description

Retrieves only the direct descendants of an element. The elements contained in this collection are undefined if the child elements are overlapping tags. Similar to the all collection.

Syntax

object.children(index)

Parameter | Description
object | The document object.
(index) | Optional. An integer or a string specifying the index value of the element to retrieve. Integer indexes are zero-based, meaning the first element in the collection has index 0. A string index is valid only if the string is a name or identifier of at least one element in the document.

Remarks

The following example illustrates what this collection would return.

<DIV id=divONE>
<IMG src=mygif.gif>
<DIV id=divTWO>
<p>Some text in a paragraph
</DIV>
<BUTTON> The label for the button </BUTTON>
</DIV>

The children collection for divONE would include IMG, DIV, and BUTTON. The children collection for divTWO would include P.

Applies To

A, ACRONYM, ADDRESS, APPLET, AREA, B, BASE, BASEFONT, BGSOUND, BIG, BLOCKQUOTE, BODY, BR, BUTTON, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, COMMENT, DD, DEL, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FONT, FORM, FRAME, FRAMESET, H1, H2, H3, H4, H5, H6, HEAD, HR, HTML, I, IFRAME, IMG, INPUT, INS, KBD, LABEL, LEGEND, LI, LINK, LISTING, MAP, MARQUEE, MENU, OBJECT, OL, OPTION, P, PLAINTEXT, PRE, Q, S, SAMP, SCRIPT, SELECT, SMALL, SPAN, STRIKE, STRONG, STYLE, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TITLE, TR, TT, U, UL, VAR, XMP


Collections

all anchors applets areas
cells children elements embeds
filters forms frames images
imports links options plugins
rows rules scripts styleSheets
tbodies


elements

Description

Retrieves a collection, in source order, of all elements in a given form. This collection can contain any combination of INPUT, SELECT, and TEXTAREA elements.

Syntax

object.elements(index)

Parameter | Description
object | A FORM element.
(index) | Optional. An integer or a string specifying the index value of the element to retrieve. Integer indexes are zero-based, meaning the first element in the collection has index 0. A string index is valid only if the string is a name or identifier of at least one element in the document.

Remarks

This collection is indexed first by name, then by identifier. If duplicate names are found, a collection of those named items is returned. Collections of duplicate names must subsequently be referenced by ordinal position.

Property

length

Methods

item, tags

Applies To

FORM


embeds

Description

Retrieves a collection of all EMBED elements on the document.

Syntax

object.embeds(index)

Parameter | Description
object | The document object.
(index) | Optional. An integer or a string specifying the index value of the element to retrieve. Integer indexes are zero-based, meaning the first element in the collection has index 0. A string index is valid only if the string is an identifier of at least one element in the document.

Remarks

If duplicate identifiers are found, a collection of those items is returned. Collections of duplicates must subsequently be referenced by ordinal position.

Property

length

Methods

item, tags

Applies To

document


filters

Description

Retrieves a collection of filter objects for an element.

Syntax

object.filters(index)

Parameter | Description
object | An element object.
(index) | Optional. An integer specifying the index value of the filter to retrieve. Integer indexes are zero-based, meaning the first filter in the collection has index 0.

Remarks

An asterisk in the following applies to list indicates that a defined height, width, or absolute position is required.

Property

length

Methods

item

Applies To

BODY, BUTTON, DIV*, IMG, INPUT, MARQUEE, SPAN*, TABLE, TD, TEXTAREA, TFOOT, TH, THEAD, TR


forms

Description

Retrieves a collection, in source order, of all FORM elements in the document.

Syntax

object.forms(index)

Parameter | Description
object | The document object.
(index) | Optional. An integer or a string specifying the index value of the element to retrieve. Integer indexes are zero-based, meaning the first element in the collection has index 0. A string index is valid only if the string is a name or identifier of at least one element in the document.

Remarks

This collection is indexed first by name, then by identifier. If duplicate names are found, a collection of those named items is returned. Collections of duplicate names must subsequently be referenced by ordinal position.

Property

length

Methods

item, tags

Applies To

document


frames

Description

Retrieves a collection of all window objects defined by the given document or defined by the document associated with the given window.

Syntax

object.frames(index)

Parameter | Description
object | Either the document or window object.
(index) | Optional. An integer or a string specifying the index value of the window to retrieve. Integer indexes are zero-based, meaning the first window in the collection has index 0. A string index is valid only if the string is the name of one window in the document.

Remarks

If the HTML source document contains a BODY tag, the collection contains one window for each IFRAME element in the document. If the source document contains FRAMESET tags, the collection contains one window for each FRAME tag in the document. In both cases, the order is determined by the HTML source.

This collection contains window objects only and does not provide access to the corresponding FRAME and IFRAME elements. To access these elements, use the all collection for the document containing the elements.

Although you can use names with the item method on this collection, the method never returns a collection. Instead, it always returns the first window having the given name. To ensure that all windows are accessible, you should always make sure that no two windows in a document have the same name.

Examples

The following JScript example displays the URLs of the HTML documents contained in windows created by the IFRAME elements in the document.

var frm = document.frames;
for (i=0; i<frm.length; i++)
    alert(frm(i).location);

The following JScript example displays the names of each window defined by FRAME tags in the parent window of the current document.

var frm = window.parent.frames;
for (i=0; i < frm.length; i++)
    alert(frm(i).name);
}

Property

length

Methods

item

Applies To

document, window


images

Description

Retrieves a collection, in source order, of IMG elements in the document.

Syntax

object.images(index)

Parameter | Description
object | The document object.
(index) | Optional. An integer or a string specifying the index value of the element to retrieve. Integer indexes are zero-based, meaning the first element in the collection has index 0. A string index is valid only if the string is a name or identifier of at least one element in the document.

Remarks

This collection is indexed first by name, then by identifier. If duplicate names are found, a collection of those named items is returned. Collections of duplicate names must subsequently be referenced by ordinal position.

Property

length

Methods

item, tags

Applies To

document


imports

Description

Retrieves a collection of all the imported style sheets defined for the respective styleSheet object. An imported style sheet is one that is brought into the document using the @import attribute in CSS.

Syntax

object.imports(index)

Parameter | Description
object | A styleSheet object.
(index) | Optional. An integer or a string specifying the index value of the style sheet to retrieve. Integer indexes are zero-based, meaning the first style sheet in the collection has index 0.

Example

The following example displays the URLs of the imported style sheets in the document.

for (i=0; i<document.styleSheets.length; i++) {
    if (document.styleSheets(i).owningElement.tagName == "STYLE") {
        for (j=0; j<document.styleSheets(i).imports.length; j++)
            alert("Imported style sheet " + j + " is at " + document.styleSheets(i).imports(j).href);
    }
}

Property

length

Methods

item

Applies To

styleSheet


links

Description

Retrieves a collection of all A elements that specify the HREF= attribute and all AREA elements in the document.

Syntax

object.links(index)

Parameter | Description
object | The document object.
(index) | Optional. An integer or a string specifying the index value of the element to retrieve. Integer indexes are zero-based, meaning the first element in the collection has index 0. A string index is valid only if the string is a name or identifier of at least one element in the document.

Remarks

This collection is indexed first by name, then by identifier. If duplicate names are found, a collection of those named items is returned. Collections of duplicate names must subsequently be referenced by ordinal position.

This collection includes A elements that have a NAME= or ID= attribute as long as they also have an HREF= attribute.

Example

The following example displays the HREF= attribute of the third link defined in the document.

alert(document.anchors(2).href);

Property

length

Methods

item, tags

Applies To

document


options

Description

Retrieves a collection of the OPTION elements in a SELECT object.

Syntax

object.options(index)

Parameter | Description
object | A SELECT element.
(index) | Optional. An integer or a string specifying the index value of the element to retrieve. Integer indexes are zero-based, meaning the first element in the collection has index 0. A string index is valid only if the string is an identifier of at least one element in the document.

Remarks

To delete an option from a SELECT object, you assign the option a null value. This compresses the array.

If duplicate identifiers are found, a collection of those items is returned. Collections of duplicates must subsequently be referenced by ordinal position.

Example

The following example displays the text and values of all OPTION elements in the first SELECT element in the document.

var coll = document.all.tags("SELECT");
if (coll.length>0) {
    for (i=0; i< coll(0).options.length; i++)
        alert("Element " + i + " is " + coll(0).options(i).text + " and has the value " + coll(0).options(i).value);
}

Property

length

Methods

add, item, remove, tags

Applies To

SELECT


plugins

Description

This is an alias for the embeds collection on the document.

Syntax

object.plugins(index)

Parameter | Description
object | The document object.
(index) | Optional. An integer or a string specifying the index value of the element to retrieve. Integer indexes are zero-based, meaning the first element in the collection has index 0. A string index is valid only if the string is a name or identifier of at least one element in the document.

Remarks

This collection is indexed first by name, then by identifier. If duplicate names are found, a collection of those named items is returned. Collections of duplicate names must subsequently be referenced by ordinal position.

Property

length

Methods

item, tags

Applies To

document


rows

Description

Retrieves a collection of rows (TR elements) in the table. The scope of this collection is for the THEAD, TBODY, or TFOOT of the table. In addition, there is also a rows collection for the TABLE, which contains all the rows for the entire table. A row that appears in one of the table sections also appears in the rows collection for the TABLE. The TR has two index properties, "rowIndex" and "sectionRowIndex", which indicate where, with respect to the rows collection for the given table section, and where with respect to the rows collection for the table in which the TR appears.

Syntax

object.rows(index)

Parameter | Description
object | A TABLE, TBODY, THEAD, or TFOOT element.
index | Optional. An integer or a string specifying the index value of the element to retrieve. Integer indexes are zero-based, meaning the first element in the collection has index 0. A string index is valid only if the string is an identifier of at least one element in the document.

Remarks

If duplicate identifiers are found, a collection of those items is returned. Collections of duplicates must subsequently be referenced by ordinal position.

Example

The following example uses the rows and cells collections to insert a number into each cell of the table.

<HTML>
<SCRIPT LANGUAGE="JScript">
function numberCells() {
    var count=0;
    for (i=0; i < document.all.mytable.rows.length; i++) {
        for (j=0; j < document.all.mytable.rows(i).cells.length; j++) {
            document.all.mytable.rows(i).cells(j).innerText = count;
            count++;
        }
    }
}
</SCRIPT>
<BODY onload="numberCells()">
<TABLE id=mytable border=1>
<TR><TH>&nbsp;</TH><TH>&nbsp;</TH><TH>&nbsp;</TH><TH>&nbsp;</TH></TR>
<TR><TD>&nbsp;</TD><TD>&nbsp;</TD><TD>&nbsp;</TD><TD>&nbsp;</TD></TR>
<TR><TD>&nbsp;</TD><TD>&nbsp;</TD><TD>&nbsp;</TD><TD>&nbsp;</TD></TR>
</TABLE>
</BODY>
</HTML>

Applies To

table, TBODY, TFOOT, THEAD

Property

length

Methods

item, tags


rules

Description

Retrieves a collection of rules that are defined in the style sheet. This collection is always accessible, and can be accessed even if the style sheet is not enabled. Rules are added and removed from the rules collection with add and remove methods on the individual style sheet. A rule that is added to a disabled style sheet will not apply to the document unless the style sheet's disabled property is changed to false.

The rules in this collection are in the source order of the document. Style rules linked in using the "@import" syntax of CSS should be expanded in-place in this collection according to the CSS1 specification.

As rules are added or deleted through the Cascading Style Sheets Object Model, a rule's absolute position in the rules collection might change, but its position relative to other rules will remain the same. The default location to add a new rule (without specifying an index) is at the end of the collection, which is the highest precedence (not accounting for selector specificity, as according to the CSS specification) and is applied to the document last. If an index is supplied, the rule should be inserted before the rule currently in that ordinal position in the collection, or, if the index is larger than the number of rules in the collection, it should be added to the end.

Syntax

object.rules(index)

Parameter | Description
(index) | Optional. An integer or a string specifying the index value of the element to retrieve. Integer indexes are zero-based, meaning the first element in the collection has index 0. A string index is valid only if the string is an identifier of at least one element in the document.

Property

length

Applies To

styleSheet


scripts

Description

Retrieves a collection of all SCRIPT elements in the document.

Syntax

object.scripts(index)

Parameter | Description
object | The document object.
(index) | Optional. An integer or a string specifying the index value of the element to retrieve. Integer indexes are zero-based, meaning the first element in the collection has index 0. A string index is valid only if the string is an identifier of at least one element in the document.

Remarks

This collection contains all the scripts in the document in source order regardless of the script's location in the document (whether in the HEAD or BODY).

If duplicate identifiers are found, a collection of those items is returned. Collections of duplicates must subsequently be referenced by ordinal position.

Property

length

Methods

item, tags

Applies To

document


styleSheets

Description

Retrieves a collection of styleSheets objects representing the style sheets corresponding to each instance of a LINK or STYLE element in the document. Imported style sheets are contained within a STYLE element and are available through the imports collection.

Syntax

object.styleSheets(index)

Parameter | Description
object | The document object.
(index) | Optional. An integer or a string specifying the index value of the style sheet to retrieve. Integer indexes are zero-based, meaning the first style sheet in the collection has index 0.

Example

The following example displays the titles of the style sheets in the document.

for (i=0; i<document.styleSheets.length; i++) {
    alert("Style sheet " + i + " is titled " + document.styleSheets(i).title);
}

Property

length

Methods

item

Applies To

document


tbodies

Description

Retrieves a collection of all TBODY elements in the table. Elements in this collection are in HTML source order.

Syntax

object.tbodies(index)

Parameter | Description
object | The table object.
index An integer or a string specifying the index value of the element to retrieve. Integer indexes are zero-based, meaning the first element in the collection has index 0. A string index is valid if the string is an identifier of at least one element in the scope of the collection.

This collection can be indexed by name (ID). If duplicate names are found, a collection of those named items is returned. Collections of duplicate names must subsequently be referenced by ordinal position.

Example

The following example puts text in the first cell in the first row of the first TBODY element in the TABLE. For each TABLE, an initial TBODY element is synthesized in the HTML tree even if one does not exist in the HTML source.

document.all.mytable.tbodies[0].rows[0].cells[0].innerText="Text for the first table cell";

Applies To

table

Property

length

Methods

item, tags


Color Table

This section lists and displays the colors supported by Microsoft® Internet Explorer 4.0.

You can specify colors in two ways—by using a color name, or by using numbers to denote a red-green-blue (RGB) color value.

In Internet Explorer 4.0, the supported colors appear as follows.

ALICEBLUE
(#F0F8FF) 		ANTIQUEWHITE
(#FAEBD7) 		AQUA
(#00FFFF) 		AQUAMARINE
(#7FFFD4)
AZURE
(#F0FFFF) 		BEIGE
(#F5F5DC) 		BISQUE
(#FFE4C4) 		BLACK
(#000000)
BLANCHEDALMOND
(#FFEBCD) 		BLUE
(#0000FF) 		BLUEVIOLET
(#8A2BE2) 		BROWN
(#A52A2A)
BURLYWOOD
(#DEB887) 		CADETBLUE
(#5F9EA0) 		CHARTREUSE
(#7FFF00) 		CHOCOLATE
(#D2691E)
CORAL
(#FF7F50) 		CORNFLOWER
(#6495ED) 		CORNSILK
(#FFF8DC) 		CRIMSON
(#DC143C)
CYAN
(#00FFFF) 		DARKBLUE
(#00008B) 		DARKCYAN
(#008B8B) 		DARKGOLDENROD
(#B8860B)
DARKGRAY
(#A9A9A9) 		DARKGREEN
(#006400) 		DARKKHAKI
(#BDB76B) 		DARKMAGENTA
(#8B008B)
DARKOLIVEGREEN
(#556B2F) 		DARKORANGE
(#FF8C00) 		DARKORCHID
(#9932CC) 		DARKRED
(#8B0000)
DARKSALMON
(#E9967A) 		DARKSEAGREEN
(#8FBC8B) 		DARKSLATEBLUE
(#483D8B) 		DARKSLATEGRAY
(#2F4F4F)
DARKTURQUOISE
(#00CED1) 		DARKVIOLET
(#9400D3) 		DEEPPINK
(#FF1493) 		DEEPSKYBLUE
(#00BFFF)
DIMGRAY
(#696969) 		DODGERBLUE
(#1E90FF) 		FIREBRICK
(#B22222) 		FLORALWHITE
(#FFFAF0)
FORESTGREEN
(#228B22) 		FUCHIA
(#FF00FF) 		GAINSBORO
(#DCDCDC) 		GHOSTWHITE
(#F8F8FF)
GOLD
(#FFD700) 		GOLDENROD
(#DAA520) 		GRAY
(#808080) 		GREEN
(#008000)
GREENYELLOW
(#ADFF2F) 		HONEYDEW
(#F0FFF0) 		HOTPINK
(#FF69B4) 		INDIANRED
(#CD5C5C)
INDIGO
(#4B0082) 		IVORY
(#FFFFF0) 		KHAKI
(#F0E68C) 		LAVENDER
(#E6E6FA)
LAVENDERBLUSH
(#FFF0F5) 		LAWNGREEN
(#7CFC00) 		LEMONCHIFFON
(#FFFACD) 		LIGHTBLUE
(#ADD8E6)
LIGHTCORAL
(#F08080) 		LIGHTCYAN
(#E0FFFF) 		LIGHTGOLDENRODYELLOW
(#FAFAD2) 		LIGHTGREEN
(#90EE90)
LIGHTGREY
(#D3D3D3) 		LIGHTPINK
(#FFB6C1) 		LIGHTSALMON
(#FFA07A) 		LIGHTSEAGREEN
(#20B2AA)
LIGHTSKYBLUE
(#87CEFA) 		LIGHTSLATEGRAY
(#778899) 		LIGHTSTEELBLUE
(#B0C4DE) 		LIGHTYELLOW
(#FFFFE0)
LIME
(#00FF00) 		LIMEGREEN
(#32CD32) 		LINEN
(#FAF0E6) 		MAGENTA
(#FF00FF)
MAROON
(#800000) 		MEDIUMAQUAMARINE
(#66CDAA) 		MEDIUMBLUE
(#0000CD) 		MEDIUMORCHID
(#BA55D3)
MEDIUMPURPLE
(#9370DB) 		MEDIUMSEAGREEN
(#3CB371) 		MEDIUMSLATEBLUE
(#7B68EE) 		MEDIUMSPRINGGREEN
(#00FA9A)
MEDIUMTURQUOISE
(#48D1CC) 		MEDIUMVIOLETRED
(#C71585) 		MIDNIGHTBLUE
(#191970) 		MINTCREAM
(#F5FFFA)
MISTYROSE
(#FFE4E1) 		MOCCASIN
(#FFE4B5) 		NAVAJOWHITE
(#FFDEAD) 		NAVY
(#000080)
OLDLACE
(#FDF5E6) 		OLIVE
(#808000) 		OLIVEDRAB
(#6B8E23) 		ORANGE
(#FFA500)
ORANGERED
(#FF4500) 		ORCHID
(#DA70D6) 		PALEGOLDENROD
(#EEE8AA) 		PALEGREEN
(#98FB98)
PALETURQUOISE
(#AFEEEE) 		PALEVIOLETRED
(#DB7093) 		PAPAYAWHIP
(#FFEFD5) 		PEACHPUFF
(#FFDAB9)
PERU
(#CD853F) 		PINK
(#FFC0CB) 		PLUM
(#DDA0DD) 		POWDERBLUE
(#B0E0E6)
PURPLE
(#800080) 		RED
(#FF0000) 		ROSYBROWN
(#BC8F8F) 		ROYALBLUE
(#4169E1)
SADDLEBROWN
(#8B4513) 		SALMON
(#FA8072) 		SANDYBROWN
(#F4A460) 		SEAGREEN
(#2E8B57)
SEASHELL
(#FFF5EE) 		SIENNA
(#A0522D) 		SILVER
(#C0C0C0) 		SKYBLUE
(#87CEEB)
SLATEBLUE
(#6A5ACD) 		SLATEGRAY
(#708090) 		SNOW
(#FFFAFA) 		SPRINGGREEN
(#00FF7F)
STEELBLUE
(#4682B4) 		TAN
(#D2B48C) 		TEAL
(#008080) 		THISTLE
(#D8BFD8)
TOMATO
(#FF6347) 		TURQUOISE
(#40E0D0) 		VIOLET
(#EE82EE) 		WHEAT
(#F5DEB3)
WHITE
(#FFFFFF) 		WHITESMOKE
(#F5F5F5) 		YELLOW
(#FFFF00) 		YELLOWGREEN
(#9ACD32)

User-Defined System Colors:

ACTIVEBORDER | ACTIVECAPTION | APPWORKSPACE | BACKGROUND
BUTTONFACE | BUTTONHIGHLIGHT | BUTTONSHADOW | BUTTONTEXT
CAPTIONTEXT | GRAYTEXT | HIGHLIGHT | HIGHLIGHTTEXT
INACTIVEBORDER | INACTIVECAPTION | INACTIVECAPTIONTEXT | INFOBACKGROUND
INFOTEXT | MENU | MENUTEXT | SCROLLBAR
THREEDDARKSHADOW | THREEDFACE | THREEDHIGHLIGHT | THREEDLIGHTSHADOW
THREEDSHADOW | WINDOW | WINDOWFRAME | WINDOWTEXT

Note These color names might not be recognized by other browsers, but the RBG color values should be displayed accurately.

An RGB color value consists of three two-digit hexadecimal numbers, with each number specifying the intensity of the corresponding color. For example, the color value #FF0000 is red because the red number is set to its highest value, FF (255 in the decimal, or base 10, system). Green and blue are set to zero. Similarly, #00FF00 is green and #0000FF is blue. The pound sign (#) is optional. In the following example, the HTML code displays a red horizontal rule.

<HR COLOR="#FF0000">

Although RGB color values theoretically allow for many thousands of colors, the actual number of colors available for your HTML document depends on the color capabilities of the devices the document will be viewed on. Many personal computers can display only 16 colors due to the type of video display adapter they use. Always choose colors carefully and, whenever possible, test your color choices on a variety of computers.


active

Description

Sets the style of anchor (A) elements when the link is engaged or "active".

Remarks

Active means that the user is currently navigating the link. Setting the active pseudo-class is often used in conjunction with setting specific styles for the other states of a link: link, visited, hover. Using pseudo-classes on elements other than the A element has no effect.

Example

Note that the syntax in the following example uses a colon (:) to specify a pseudo-class.

A:active {text-decoration:overline;color:purple}

Applies To

A

See Also

hover, link, visited


CSS Attributes

This section defines the cascading style sheet (CSS) attributes that are supported in Microsoft® Internet Explorer 4.0.

Font and Text Properties | font-family
font-style
font-variant
font-weight
font-size
@font-face
font
letter-spacing
line-height
text-decoration
text-transform
text-align
text-indent
vertical-align
Color and Background Properties | color
background-color
background-image
background-repeat
background-attachment
background-position
background
Layout Properties | margin-top
margin-right
margin-bottom
margin-left
margin
padding-top
padding-right
padding-bottom
padding-left
padding
border-top-width
border-right-width
border-bottom-width
border-left-width
border-width
border-top-color
border-right-color
border-bottom-color
border-left-color
border-color
border-top-style
border-right-style
border-bottom-style
border-left-style
border-style
border-top
border-right
border-bottom
border-left
border
float
clear
Classification Properties | display
list-style-type
list-style-image
list-style-position
list-style
Positioning Properties | clip
height
left
overflow
position
top
visibility
width
z-index
Printing Properties | page-break-before
page-break-after
Filter Properties | filter
Pseudo-Classes and Other Properties | active
hover
@import
!important
cursor
link
visited
Unsupported CSS Attributes | word-spacing
first-letter pseudo
first-line pseudo
white-space


background

Description

Sets all background attributes (image, attachment, color, repeat, position) for an element at once.

Syntax

{ background: background-color || background-image || background-repeat || background-attachment || background-position}

Remarks

While separate attributes can be used to specify the individual background properties, it is often more convenient to set them in one place using this composite property.

Individual background properties not set by the composite background property will be set to their default values. For example, the default value for "background-image" is none. Setting "background: white" is identical to saying "background: white none repeat scroll 0% 0%". So, in addition to setting the background color to white, it will clear any background-image, background-repeat, background-attachment, or background-position that has been previously set.

For more information on supported colors, see Color Table.

This property does not inherit, but the parent element's background will display through by default due to the default transparent value.

Examples

The first example below sets the background-color for DIV elements to red and sets all other background properties to their default values. The second example sets the background for the BODY element to show an image. This image will stay fixed as if it were a watermark on a page. Assuming the image is transparent, the color blue will bleed through.

DIV {background: red}

BODY {background: blue url(sample.gif) fixed}

Applies To

A, ADDRESS, B, BIG, BLOCKQUOTE, BODY, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, DD, DFN, DIR, DIV, DL, DT, EM, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HTML, I, IMG, INPUT, INPUT type=button, INPUT type=checkbox, INPUT type=file, INPUT type=image, INPUT type=password, INPUT type=radio, INPUT type=reset, INPUT type=submit, INPUT type=text, TEXTAREA, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, S, SAMP, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP

Scripting Property

background


background-attachment

Description

Determines if the background image is fixed with regard to the content or if it scrolls with the content.

Syntax

{ background-attachment: scroll | fixed}

Remarks

This attribute is not inherited.

Applies To

BODY, HTML

Scripting Property

backgroundAttachment


background-color

Description

Sets the background color of an element.

Syntax

{ background-color: color | transparent}

Remarks

This attribute is not inherited.

Applies To

A, ADDRESS, B, BIG, BLOCKQUOTE, BODY, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, DD, DFN, DIR, DIV, DL, DT, EM, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HTML, I, IMG, INPUT, INPUT type=button, INPUT type=checkbox, INPUT type=file, INPUT type=image, INPUT type=password, INPUT type=radio, INPUT type=reset, INPUT type=submit, INPUT type=text, TEXTAREA, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP

Scripting Property

backgroundColor


background-image

Description

Sets the background image of an element.

Syntax

{ background-image: url | none}

Remarks

This attribute is not inherited.

When setting a background image, one should also set a background color that will be used when the image is unavailable. When the image is available, it is overlaid on top of the background color.

Example

BODY { background-image: url(marble.gif) }
P { background-image: none }

Applies To

A, ADDRESS, B, BIG, BLOCKQUOTE, BODY, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, DD, DFN, DIR, DIV, DL, DT, EM, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HTML, I, IMG, INPUT, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, S, SAMP, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP, INPUT type=button, INPUT type=file, INPUT type=reset, INPUT type=submit, INPUT type=text, INPUT type=image, INPUT type=checkbox, INPUT type=radio, INPUT type=password

Scripting Property

backgroundImage


background-position

Description

Specifies the initial position of the background image for the element.

Syntax

{ background-position: [percentage | length]{1,2} | [top | center | bottom] || [left | center | right]}

Remarks

The attribute has no effect if no background image has been specified for the element.

This attribute is not inherited.

Examples

Sets the background image at these x,y coordinates of the object.

{background-position: 20px 40px}

Positions the background image at the top vertical position and the center horizontal position.

{background-position: top center}

Applies To

A, ADDRESS, B, BIG, BLOCKQUOTE, BODY, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, DD, DFN, DIR, DIV, DL, DT, EM, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HTML, I, IMG, INPUT, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, S, SAMP, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP, INPUT type=button, INPUT type=file, INPUT type=reset, INPUT type=submit, INPUT type=text, INPUT type=image, INPUT type=checkbox, INPUT type=radio, INPUT type=password

Scripting Property

backgroundPosition, backgroundPositionX, backgroundPositionY


background-repeat

Description

Determines how the background image of an element is repeated.

Syntax

{ background-repeat: repeat | repeat-x | repeat-y | no-repeat}

Remarks

The attribute only has an effect if a background image has been specified.

A value of repeat means that the image is repeated both horizontally and vertically. The repeat-x (repeat-y) value makes the image repeat horizontally (vertically), to create a single band of images from one side to the other. With a value of no-repeat, the image is not repeated.

This attribute is not inherited.

Example

In the following example, the image will only be repeated vertically.

BODY {background: red url(pendant.gif);
      background-repeat: repeat-y;}

Applies To

A, ADDRESS, B, BIG, BLOCKQUOTE, BODY, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, DD, DFN, DIR, DIV, DL, DT, EM, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HTML, I, IMG, INPUT, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, S, SAMP, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP, INPUT type=button, INPUT type=file, INPUT type=reset, INPUT type=submit, INPUT type=text, INPUT type=image, INPUT type=checkbox, INPUT type=radio, INPUT type=password

Scripting Property

backgroundRepeat


border

Description

Specifies the border to display around the element. The border property is a shorthand (composite) property for setting border width, color, and style for all four sides of an object. If a border-color is not specified, the text color is used. Supported on block and replaced elements only.

All individual border properties not set by the composite border property will be set to their initial values. For example, the initial value for border-width is medium. Setting border: thin is identical to saying border: thin none; the initial value for color picks up the text color if one isn't initially set. So, in addition to setting the border width to thin, it will clear any border-style or border-color that has been previously set.

Syntax

{ border: border-width || border-style || color}

Remarks

This attribute is not inherited.

Example

Creates a border for all four sides of the object, where all four sides show a 20 pixel blue border with an inset style. Use the individual properties to control the border for individual sides of the object.

{border: 20px inset blue}

Applies To

BLOCKQUOTE, BODY, CENTER, DD, DIR, DIV, DL, DT, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, TABLE, TD, TH, TR, UL, XMP, CAPTION, TEXTAREA, IFRAME, SPAN, IMG, EMBED, OBJECT, INPUT

Scripting Property

border

See Also

border-width, border-style, border-color border-right, border-left, border-top, border-bottom


border-bottom

Description

Specifies the bottom border. Values that are not present are set to their initial values. Supported on block and replaced elements only.

For more information on supported colors, see Color Table.

Syntax

{ border-bottom: border-bottom-width || border-style || color}

Remarks

This attribute is not inherited.

Example

In this example, the border will be a solid green line.

{border-bottom: 20px outset green}

Applies To

BLOCKQUOTE, BODY, CENTER, DD, DIR, DIV, DL, DT, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, TABLE, TD, TH, TR, UL, XMP, CAPTION, TEXTAREA, IFRAME, SPAN, IMG, EMBED, OBJECT, INPUT

Scripting Property

borderBottom

See Also

border-bottom-width, border-bottom-style, border-bottom-color, border, border-top


border-bottom-color

Description

Sets the color of an element's bottom border. Supported on block and replaced elements only. See the Color Table for a list of supported color values.

Syntax

{ border-bottom-color: border-color}

Remarks

For more information on supported colors, see Color Table.

This attribute is not inherited.

Applies To

BLOCKQUOTE, BODY, CENTER, DD, DIR, DIV, DL, DT, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, TABLE, TD, TH, TR, UL, XMP, CAPTION, TEXTAREA, IFRAME, SPAN, IMG, EMBED, OBJECT, INPUT

Scripting Property

borderBottomColor

See Also

border-top-color, border-left-color, border-right-color, border-color


border-bottom-style

Description

Sets the style of an element's bottom border. Supported on block and replaced elements only. Dotted and dashed are treated as solid.

The border styles are defined as follows:
none | No border is drawn (regardless of any border-width).
solid | Border is a solid line.
double | Border is a double line drawn on top of the background of the element. The sum of the two single lines and the space between equals the border-width value. Border width must be at least 3 pixels wide to draw a double border.
groove | 3-D groove is drawn in colors based on the value.
ridge | 3-D ridge is drawn in colors based on the value.
inset | 3-D inset is drawn in colors based on the value.
outset | 3-D outset is drawn in colors based on the value.

Syntax

{ border-bottom-style: none | dotted | dashed | solid | double | groove | ridge | inset | outset }

Remarks

This attribute is not inherited.

Applies To

BLOCKQUOTE, BODY, CENTER, DD, DIR, DIV, DL, DT, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, TABLE, TD, TH, TR, UL, XMP, CAPTION, TEXTAREA, IFRAME, SPAN, IMG, EMBED, OBJECT, INPUT

Scripting Property

borderBottomStyle

See Also

border-top-style, border-left-style, border-right-style, border-style


border-bottom-width

Description

Sets the width of an element's bottom border. Supported on block and replaced elements only.

Syntax

{ border-bottom-width: thin | medium | thick | length}

Remarks

This attribute is not inherited.

Applies To

BLOCKQUOTE, BODY, CENTER, DD, DIR, DIV, DL, DT, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, TABLE, TD, TH, TR, UL, XMP, CAPTION, TEXTAREA, IFRAME, SPAN, IMG, EMBED, OBJECT, INPUT

Scripting Property

borderBottomWidth

See Also

border-top-width, border-left-width, border-right-width, border-width


border-color

Description

Sets the color of the four borders.

"{1,4}" indicates that up to four different colors can be specified. If one color is supplied, it is used for all four sides. If two colors are supplied, the first is used for the top and bottom, and the second is used for left and right. If three colors are supplied, they are used for top, right and left, and bottom, respectively. Supported on block and replaced elements only. See Color Table for a list of supported color values.

Syntax

{ border-color:border-color{1,4}}

Remarks

This attribute is not inherited.

Applies To

BLOCKQUOTE, BODY, CENTER, DD, DIR, DIV, DL, DT, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, TABLE, TD, TH, TR, UL, XMP, CAPTION, TEXTAREA, IFRAME, SPAN, IMG, EMBED, OBJECT, INPUT

Scripting Property

borderColor

See Also

border-top-color, border-left-color, border-right-color, border-bottom-color


border-left

Description

Sets the left border. Values that are not present are set to their initial values. Supported on block and replaced elements only.

For more information on supported colors, see Color Table.

Syntax

{ border-left: border-left-width || border-left-style || border-left-color}

Remarks

This attribute is not inherited.

Applies To

BLOCKQUOTE, BODY, CENTER, DD, DIR, DIV, DL, DT, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, TABLE, TD, TH, TR, UL, XMP, CAPTION, TEXTAREA, IFRAME, SPAN, IMG, EMBED, OBJECT, INPUT

Scripting Property

borderLeft

See Also

border-left-width, border-left-color, border-left-style, border-right, border-top, border-bottom


border-left-color

Description

Sets the color of an element's left border. Supported on block and replaced elements only. See Color Table for a list of supported color values.

Syntax

{ border-left-color: border-color}

Remarks

This attribute is not inherited.

Applies To

BLOCKQUOTE, BODY, CENTER, DD, DIR, DIV, DL, DT, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, TABLE, TD, TH, TR, UL, XMP, CAPTION, TEXTAREA, IFRAME, SPAN, IMG, EMBED, OBJECT, INPUT

Scripting Property

borderLeftColor

See Also

border-right-color, border-top-color, border-bottom-color, border-color


border-left-style

Description

Sets the style of an element's left border. Dotted and dashed are treated as solid. Supported on block and replaced elements only.

The border styles are defined as follows:
none | No border is drawn (regardless of any border-width).
solid | Border is a solid line.
double | Border is a double line drawn on top of the background of the element. The sum of the two single lines and the space between equals the border-width value. Border width must be at least 3 pixels wide to draw a double border.
groove | 3-D groove is drawn in colors based on the value.
ridge | 3-D ridge is drawn in colors based on the value.
inset | 3-D inset is drawn in colors based on the value.
outset | 3-D outset is drawn in colors based on the value.

Syntax

{ border-left-style: none | dotted | dashed | solid | double | groove | ridge | inset | outset }

Remarks

This attribute is not inherited.

Applies To

BLOCKQUOTE, BODY, CENTER, DD, DIR, DIV, DL, DT, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, TABLE, TD, TH, TR, UL, XMP, CAPTION, TEXTAREA, IFRAME, SPAN, IMG, EMBED, OBJECT, INPUT

Scripting Property

borderLeftStyle

See Also

border-right-style, border-top-style, border-bottom-style, border-style


border-left-width

Description

Sets the width of an element's left border. Supported on block and replaced elements only.

Syntax

{ border-left-width: thin | medium | thick | length}

Remarks

This attribute is not inherited.

Applies To

BLOCKQUOTE, BODY, CENTER, DD, DIR, DIV, DL, DT, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, TABLE, TD, TH, TR, UL, XMP, CAPTION, TEXTAREA, IFRAME, SPAN, IMG, EMBED, OBJECT, INPUT

Scripting Property

borderLeftWidth

See Also

border-right-width, border-top-width, border-bottom-width, border-width


border-right

Description

Sets the right border. Values that are not present are set to their initial values. Supported on block and replaced elements only.

For more information on supported colors, see Color Table.

Syntax

{ border-right: border-right-width || border-right-style || border-right-color}

Remarks

This attribute is not inherited.

Applies To

BLOCKQUOTE, BODY, CENTER, DD, DIR, DIV, DL, DT, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, TABLE, TD, TH, TR, UL, XMP, CAPTION, TEXTAREA, IFRAME, SPAN, IMG, EMBED, OBJECT, INPUT

Scripting Property

borderRight

See Also

border-left, border-top, border-bottom, border


border-right-color

Description

Sets the color of an element's right border. Supported on block and replaced elements only. See Color Table for a list of supported color values.

Syntax

{ border-right-color: border-color}

Remarks

This attribute is not inherited.

Applies To

BLOCKQUOTE, BODY, CENTER, DD, DIR, DIV, DL, DT, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, TABLE, TD, TH, TR, UL, XMP, CAPTION, TEXTAREA, IFRAME, SPAN, IMG, EMBED, OBJECT, INPUT

Scripting Property

borderRightColor

See Also

border-top-color, border-bottom-color, border-left-color, border-color


border-right-style

Description

Sets the style of an element's right border. Dotted and dashed are treated as solid. Supported on block and replaced elements only.

The border styles are defined as follows:
none | No border is drawn (regardless of any border-width).
solid | Border is a solid line.
double | Border is a double line drawn on top of the background of the element. The sum of the two single lines and the space between equals the border-width value. Border width must be at least 3 pixels wide to draw a double border.
groove | 3-D groove is drawn in colors based on the value.
ridge | 3-D ridge is drawn in colors based on the value.
inset | 3-D inset is drawn in colors based on the value.
outset | 3-D outset is drawn in colors based on the value.

Syntax

{ border-right-style: none | dotted | dashed | solid | double | groove | ridge | inset | outset }

Remarks

This attribute is not inherited.

Applies To

BLOCKQUOTE, BODY, CENTER, DD, DIR, DIV, DL, DT, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, TABLE, TD, TH, TR, UL, XMP, CAPTION, TEXTAREA, IFRAME, SPAN, IMG, EMBED, OBJECT, INPUT

Scripting Property

borderRightStyle

See Also

border-left-style, border-top-style, border-bottom-style, border-style


border-right-width

Description

Sets the width of an element's right border. Supported on block and replaced elements only.

Syntax

{ border-right-width: thin | medium | thick | length}

Remarks

This attribute is not inherited.

Applies To

BLOCKQUOTE, BODY, CENTER, DD, DIR, DIV, DL, DT, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, TABLE, TD, TH, TR, UL, XMP, CAPTION, TEXTAREA, IFRAME, SPAN, IMG, EMBED, OBJECT, INPUT

Scripting Property

borderRightWidth

See Also

border-top-width, border-bottom-width, border-left-width, border-width


border-style

Description

Sets the style of the borders. Dotted and dashed are treated as solid. Supported on block and replaced elements only.

The border styles are defined as follows:
none | No border is drawn (regardless of any border-width).
solid | Border is a solid line.
double | Border is a double line drawn on top of the background of the element. The sum of the two single lines and the space between equals the border-width value. Border width must be at least 3 pixels wide to draw a double border.
groove | 3-D groove is drawn in colors based on the value.
ridge | 3-D ridge is drawn in colors based on the value.
inset | 3-D inset is drawn in colors based on the value.
outset | 3-D outset is drawn in colors based on the value.

Syntax

{ border-style: none | dotted | dashed | solid | double | groove | ridge | inset | outset}

Remarks

This attribute is not inherited.

Applies To

BLOCKQUOTE, BODY, CENTER, DD, DIR, DIV, DL, DT, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, TABLE, TD, TH, TR, UL, XMP, CAPTION, IFRAME, SPAN, IMG, EMBED, OBJECT, INPUT, TEXTAREA

Scripting Property

borderStyle

See Also

border-width, border-color, border


border-top

Description

Describes the top border. Values that are not present are set to their initial values. Supported on block and replaced elements only.

Syntax

{ border-top: border-top-width || border-top-style || border-top-color}

Remarks

For more information on supported colors, see Color Table.

This attribute is not inherited.

Applies To

BLOCKQUOTE, BODY, CENTER, DD, DIR, DIV, DL, DT, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, TABLE, TD, TH, TR, UL, XMP, CAPTION, TEXTAREA, IFRAME, SPAN, IMG, EMBED, OBJECT, INPUT

Scripting Property

borderTop

See Also

border-bottom, border-left, border-right


border-top-color

Description

Sets the color of an element's top border. Supported on block and replaced elements only. See Color Table for a list of supported color values.

Syntax

{ border-top-color: border-color}

Remarks

This attribute is not inherited.

Applies To

BLOCKQUOTE, BODY, CENTER, DD, DIR, DIV, DL, DT, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, TABLE, TD, TH, TR, UL, XMP, CAPTION, TEXTAREA, IFRAME, SPAN, IMG, EMBED, OBJECT, INPUT

Scripting Property

borderTopColor

See Also

border-bottom-color, border-left-color, border-right-color, border-color


border-top-style

Description

Sets the style of an element's top border. Dotted and dashed are treated as solid. Supported on block and replaced elements only.

The border styles are defined as follows:
none | No border is drawn (regardless of any border-width).
solid | Border is a solid line.
double | Border is a double line drawn on top of the background of the element. The sum of the two single lines and the space between equals the border-width value. Border width must be at least 3 pixels wide to draw a double border.
groove | 3-D groove is drawn in colors based on the value.
ridge | 3-D ridge is drawn in colors based on the value.
inset | 3-D inset is drawn in colors based on the value.
outset | 3-D outset is drawn in colors based on the value.

Syntax

{ border-top-style: none | dotted | dashed | solid | double | groove | ridge | inset | outset }

Remarks

This attribute is not inherited.

Applies To

BLOCKQUOTE, BODY, CENTER, DD, DIR, DIV, DL, DT, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, TABLE, TD, TH, TR, UL, XMP, CAPTION, TEXTAREA, IFRAME, SPAN, IMG, EMBED, OBJECT, INPUT

Scripting Property

borderTopStyle

See Also

border-bottom-style, border-left-style, border-right-style, border-style


border-top-width

Description

Sets the width of an element's top border. Supported on block and replaced elements only.

Syntax

{ border-top-width: thin | medium | thick | length}

Remarks

This attribute is not inherited.

Applies To

BLOCKQUOTE, BODY, CENTER, DD, DIR, DIV, DL, DT, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, TABLE, TD, TH, TR, UL, XMP, CAPTION, TEXTAREA, IFRAME, SPAN, IMG, EMBED, OBJECT, INPUT

Scripting Property

borderTopWidth

See Also

border-bottom-width, border-left-width, border-right-width, border-width


border-width

Description

Sets the width of the four borders at the same place in the style sheet.

"{1,4}" indicates that up to four different widths can be specified. If one width is supplied, it is used for all four sides. If two widths are supplied, the first is used for the top and bottom, and the second is used for left and right. If three widths are supplied, they are used for top, right and left, and bottom, respectively. Supported on block and replaced elements only.

Syntax

{ border-width: [thin | medium | thick | length]{1,4}}

Remarks

This attribute is not inherited.

Applies To

BLOCKQUOTE, BODY, CENTER, DD, DIR, DIV, DL, DT, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, TABLE, TD, TH, TR, UL, XMP, CAPTION, TEXTAREA, IFRAME, SPAN, IMG, EMBED, OBJECT, INPUT

Scripting Property

borderWidth

See Also

border-color, border-style, border


clear

Description

Specifies if elements allow floating elements (normally images) to the left or right.

Syntax

{ clear: none | left | right | both}

Remarks

The value of this property lists the sides where floating elements are not accepted. With clear set to left, an element will be moved below any floating element on the left side. With clear set to none, floating elements are allowed on all sides.

This attribute is not inherited.

Example

H1 { clear: left }

Applies To

A, ADDRESS, APPLET, B, BIG, BLOCKQUOTE, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, DD, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FORM, FRAME, FRAMESET, H1, H2, H3, H4, H5, H6, HR, I, IFRAME, IMG, INPUT, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OBJECT, OL, OPTION, P, PLAINTEXT, PRE, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP, INPUT type=button, INPUT type=file, INPUT type=reset, INPUT type=submit, INPUT type=text, INPUT type=checkbox, INPUT type=radio, INPUT type=image

Scripting Property

clear


clip

Description

Defines a clipping region shape and size for a positioned element.

The clipping region defines the part of the element that is visible. Any part of the element that is outside the clipping region is transparent. Any coordinate can be replaced by the value auto, which causes the clipping rectangle to match the element's opposite side. The default value is to clip to expose the entire element. Note the order of the values: clip:rect(0,0,50,50) would render the element invisible, as it would set both the top and the right positions of the clipping region to 0. To achieve a 50-by-50 view port, the syntax should be clip:rect(0, 50, 50, 0).

Syntax

{ clip: shape | auto }

Syntax

shape:rect (top | right | bottom | left)

Remarks

<top>, <right>, <bottom>, and <left> specify either auto or a length value.

Remarks

This attribute is not inherited.

Applies To

DIV, TEXTAREA, SPAN, INPUT type=button, FIELDSET, IMG, MARQUEE, INPUT, TABLE

Scripting Property

clip


color

Description

Describes the text color of an element, that is, the foreground color.

Syntax

{ color: color}

Remarks

This attribute is inherited.

For more information on supported colors, see Color Table.

Examples

The following examples are different ways to specify red.

EM { color: red }              /* natural language / CNS */
EM { color: #F00 }             /* #RGB */
EM { color: #FF0000 }          /* #RRGGBB */
EM { color: rgb 1.0 0.0 0.0 }  /* float range: 0.0 - 1.0 */

Applies To

A, ADDRESS, APPLET, B, BIG, BLOCKQUOTE, BODY, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, DD, DFN, DIR, DIV, DL, DT, EM, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HTML, I, INPUT, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP, INPUT type=button, INPUT type=file, INPUT type=reset, INPUT type=submit, INPUT type=text

Scripting Property

color


cursor

Description

Specifies the type of cursor to be displayed for the mouse pointer.

Syntax

{ cursor: auto | crosshair | default | hand | move | e-resize | ne-resize | nw-resize | n-resize | se-resize | sw-resize | s-resize | w-resize | text | wait | help}

Remarks

The following types are defined:

auto
Browser determines the cursor to display based on the current context.
crosshair
Simple cross hair.
default
Platform-dependent default cursor. Usually an arrow.
hand
Hand.
move
Something is to be moved.
*-resize
Edge is to be moved.
text
Editable text. Usually an I-bar.
wait
Cursor to indicate that the program is busy and the user should wait. Usually a watch or hourglass.

This attribute is inherited.

Applies To

A, ADDRESS, APPLET, B, BIG, BLOCKQUOTE, BODY, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, DD, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, HTML, I, IFRAME, IMG, INPUT, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OBJECT, OL, P, PLAINTEXT, PRE, S, SAMP, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP, INPUT type=button, INPUT type=file, INPUT type=reset, INPUT type=submit, INPUT type=text, INPUT type=checkbox, INPUT type=radio, INPUT type=image

Scripting Property

cursor


display

Description

Indicates whether an element is rendered. If set to none, the element is not rendered. If set to one of the other values, the element is rendered. The default is to render the element.

Note Values for block, inline and list-item are not supported explicitly, but are useful in setting the display property to be on. In contrast to the visibility attribute, display:none reserves no space for the element on the screen.

Syntax

{ display: none | block | inline | list-item}

Remarks

For values other than none, the element will display with its normal display type.

This attribute is not inherited.

Applies To

TABLE, INPUT, TEXTAREA, INPUT type=button, DIV, SPAN, IFRAME, IMG, BODY, MARQUEE, SELECT

Scripting Property

display


filter

Description

Specifies one or more filters applied to an element.

Internet Explorer supports the following built-in filter types: Visual Filter, Reveal Transition Filter, or Blend Transition Filter. For detailed information, see Creating Multimedia Effects with Visual Filters and Transitions. The filter mechanism is extensible and allows additional filters to be developed and added later.

Syntax

{ filter: filtertype1(parameter1, parameter2,...) [filtertype2([parameter1, parameter2)]...}

Remarks

An asterisk in the following applies to list indicates that a defined height, width, or absolute position is required.

Remarks

This attribute is not inherited.

Applies To

BODY, BUTTON, DIV*, IMG, INPUT, MARQUEE, SPAN*, TABLE, TD, TEXTAREA, TFOOT, TH, THEAD, TR


float

Description

Specifies whether the object floats, causing text to flow around it.

Syntax

{ float: left | right | none}

Remarks

With the value none, the element will be displayed where it appears in the text. With a value of left (right), the margin properties will decide the horizontal positioning of the image and the text will flow on the right (left) side of the image. With a value of left or right, the element is treated as block-level (that is, the display property is ignored).

This attribute is not inherited.

Example

The following example demonstrates the float attribute.

<html>
<head>
<title>case for float</title>
</head>
<body>
<p>This is an example of float. "image1" should float to the left and "image2" should float to the right.
<img src=" http://www.microsoft.com/image1.gif" style="float:left">
<img src="http://www.microsoft.com/image2.gif" style="float:right">
<p>
</body>
</html>

Applies To

TABLE, INPUT, TEXTAREA, INPUT type=button, DIV, SPAN, OBJECT, APPLET, EMBED, IFRAMES, MARQUEE, SELECT

Scripting Property

styleFloat


font

Description

Defines the separate font attributes (font-style, font-variant, font-weight, font-size, line-height, and font-family).

Syntax

{ font: [ font-style || font-variant || font-weight ] font-size [ line-height ] font-family}

Remarks

Values that are not present are set to their default values. Font-size and font-family are required.

This attribute is inherited.

Example

The following example sets the font-family to Comic Sans MS and the font-size to 24 point for all SPAN elements within the document.

SPAN {font: 24 'Comic Sans MS'}

Applies To

A, ADDRESS, APPLET, B, BIG, BLOCKQUOTE, BODY, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, DD, DFN, DIR, DIV, DL, DT, EM, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HTML, I, INPUT, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, S, SAMP, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP, INPUT type=button, INPUT type=file, INPUT type=reset, INPUT type=submit, INPUT type=text

Scripting Property

font


@font-face

Description

Specifies a font to embed into your HTML document.

This feature allows you to use specific fonts that might not be available on your local system. The URL should point to an embedded OpenType file (.eot or .ote format). The file contains compressed font data that is converted to a TrueType font. For more information on the font embedding feature and pointers to a tool for creating .eot files, see Font Embedding.

Syntax

@font-face {font-family: font-family, src url(URL);}

Example

The following example shows how to embed a font in an HTML document by referencing its source from another site.

<html>
<head>
<style>
@font-face {font-family:comic; src:url(http://valid_url/some_font_file.eot);}
</style>
<title>Font embedding using @font-face</title>
</head>
<body>
<p style="font-family:comic;font-size:18pt">This line uses @font-face defined in the above style element section using comic sans ms bold in 18pt.</p>
</body>
</html>


font-family

Description

Specifies the typeface name of the font used for text in the element.

Syntax

{ font-family: [[ family-name | generic-family ] , ]* [ family-name | generic-family ]}

Remarks

The value associated with this attribute is a prioritized list of font family names and/or generic family names. List items are separated by commas to minimize confusion between multiple-word font family names. If the font family name contains white space, it is recommended that it is quoted with single or double quotation marks.

This attribute is inherited.

Example

The following generic families are defined, with an example name in parentheses.

'serif' (Times)
'sans-serif' (Helvetica)
'cursive' (Zapf-Chancery)
'fantasy' (Western)
'monospace' (Courier)

Not knowing which fonts users will have installed on their computers, authors should provide a list of alternatives with a generic font-family at the end of the list. This list can include embedded fonts. See @font-face for more information on embedding fonts.

BODY { font-family: univers, helvetica, sans-serif }
BODY { font-family: 'new century schoolbook', serif }

Applies To

A, ADDRESS, APPLET, B, BIG, BLOCKQUOTE, BODY, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, DD, DFN, DIR, DIV, DL, DT, EM, FIELDSET, FORM, H1, H2, H3, < A HREF="../objects/H4.htm#H4">H4, H5, H6, HTML, I, INPUT, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP, INPUT type=button, INPUT type=file, INPUT type=reset, INPUT type=submit, INPUT type=text

Scripting Property

fontFamily


font-size

Description

Specifies the size of the font to be used when rendering the text displayed by an element.

Syntax

{ font-size: absolute-size | relative-size | length | percentage |}

Remarks

Initial value is medium. Negative values are not allowed.

Font sizes are computed based on the font size of the parent element. Therefore, a font size of "10em" means that the size of the "em" is based on the font used by the parent element.

The values for font size are shown below:
absolute-size | A set of keywords that indicate predefined font sizes. Possible keywords include [xx-small | x-small | small | medium | large | x-large | xx-large]. Named font sizes scale according to the user's font setting preferences.
relative-size | A set of keywords that are interpreted as relative to the font size of the parent element. Possible values include [ larger | smaller].
length | An absolute value for the font size.
percentage | A percentage value of the parent element's font size.

This attribute is inherited.

Applies To

A, ADDRESS, APPLET, B, BIG, BLOCKQUOTE, BODY, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, DD, DFN, DIR, DIV, DL, DT, EM, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HTML, I, INPUT, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP, INPUT type=button, INPUT type=file, INPUT type=reset, INPUT type=submit, INPUT type=text

Scripting Property

fontSize


font-style

Description

Sets the font style. Internet Explorer 4.0 implements italic and oblique identically.

Syntax

{ font-style: normal | italic | oblique}

Remarks

This attribute is inherited.

Applies To

A, ADDRESS, APPLET, B, BIG, BLOCKQUOTE, BODY, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, DD, DFN, DIR, DIV, DL, DT, EM, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HTML, I, INPUT, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP, INPUT type=button, INPUT type=file, INPUT type=reset, INPUT type=submit, INPUT type=text

Scripting Property

fontStyle


font-variant

Description

Sets the font variation to small-caps in the current font family.

Syntax

{ font-variant: normal | small-caps}

Remarks

Internet Explorer 4.0 renders small-caps as uppercase letters in a smaller size.

This attribute is inherited.

Applies To

A, ADDRESS, APPLET, B, BIG, BLOCKQUOTE, BODY, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, DD, DFN, DIR, DIV, DL, DT, EM, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HTML, I, INPUT, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, S, SAMP, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP, INPUT type=button, INPUT type=file, INPUT type=reset, INPUT type=submit, INPUT type=text

Scripting Property

fontVariant


font-weight

Description

Sets the weight (boldness) of the text.

Syntax

{ font-weight: normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900}

Remarks

The key words for font-weight values are mapped to specific font variations depending on the fonts that are installed on the user's computer. In many cases, the user will not see the difference between different font-weight settings because the system will choose the closest match, which may be the same as the next relative font-weight setting that was previously set on the page. In any case, Internet Explorer 4.0 will always render a bolder font at least the same if not darker than a lighter font.

Setting the font-weight to 400 is equivalent to normal. Setting the font-weight to 700 is the equivalent to bold.

A font-weight of bolder or lighter is interpreted relative to the parent element's weight. A value of bolder for text whose parent is normal would set the text to bold.

Internet Explorer currently supports only normal | bold.

This attribute is inherited.

Applies To

A, ADDRESS, APPLET, B, BIG, BLOCKQUOTE, BODY, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, DD, DFN, DIR, DIV, DL, DT, EM, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HTML, I, INPUT, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP, INPUT type=button, INPUT type=file, INPUT type=reset, INPUT type=submit, INPUT type=text

Scripting Property

fontWeight


height

Description

Specifies the height of a positioned element. Percentage values are based on the width of the parent element.

The height attribute, like all other CSS attributes, specifies a string value. When scripting the height property, use either the pixelHeight or posHeight property for numeric manipulation of a height value.

Syntax

{ height: length | percentage | auto}

Remarks

This attribute is not inherited.

Applies To

TABLE, INPUT, TEXTAREA, INPUT type=button, DIV, SPAN, OBJECT, APPLET, EMBED, IFRAME, IMG, HR, MARQUEE, FIELDSET

Scripting Property

height

See Also

width, top, left, posHeight, pixelHeight


hover

Description

Sets the style of the anchor (A) elements when the user's mouse hovers over the link.

Remarks

Hover means that the user has the mouse positioned over the link and has hesitated. The style will not change if the mouse is simply passed over the link. Setting the hover pseudo-class is often used in conjunction with setting specific styles for the other states of a link: active, link, visited. Note the syntax in the example below uses a colon (:) to specify a pseudo-class.

Example

When a user hovers over a hyperlink contained within a document to which the following style sheet has been applied, the text is displayed in red, is converted to uppercase, and is spaced one centimeter apart.

<style>
a:hover {color:red;text-transform:uppercase;letter-spacing:1cm}
</style>

Applies To

A

See Also

active, link, visited


@import

Description

Specifies a style sheet to import.

Syntax

@import url (URL);

Remarks

This differs from using the LINK element in that the @import statement is used as part of a style sheet definition inside a LINK or a STYLE tag. In the scripting model, this means that the owningElement property of the styleSheet object that represents a style sheet defined through @import will be either a STYLE or a LINK element. The statement should occur at the start of a style sheet, before any declarations. While Internet Explorer 4.0 allows @import statements to be anywhere within the style sheet definition, the rules contained within the @import style sheet will be applied to the document before any other rules defined for the containing style sheet. This can affect expected cascading affects.

Rules in the style sheet override rules in the imported style sheet.

Example

<STYLE type="css/text">
@import url(http://anotherStyleSheet.css)
P {color:blue}
</STYLE>

See Also

link, style, styleSheet, imports


!important

Description

Increases the weight or importance of a particular rule.

Example

The following example illustrates this feature.

<style>
p {color:red!important}
</style>
<p style="color:green">This will be red </p>

In this example, normally the color of the <p> will be green (because inline overrules the rule set in a style tag). But, because of the !important in the style rule, the <p> tag will be red.

Applies To

A, ADDRESS, APPLET, B, BIG, BLOCKQUOTE, BODY, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, DD, DFN, DIR, DIV, DL, DT, EM, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HTML, I, INPUT, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, S, SAMP, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP, INPUT type=button, INPUT type=file, INPUT type=reset, INPUT type=submit, INPUT type=text


left

Description

Specifies the position of the element relative to the left of the document.

Syntax

{ left: length | percentage | auto}

Remarks

left is used with the position attribute. This value corresponds to the offsetLeft property of the element, and does not include the border of the parent element (noteworthy for the BODY that draws the border inside the client region). auto is the default position of the element according to the regular HTML layout of the page. Percentage values are based on the parent's position.

This attribute, like all other CSS attributes, specifies a string value. When scripting the left property, use either the pixelLeft or posLeft property for numeric manipulation of a top value.

This attribute is not inherited.

Applies To

A, ADDRESS, APPLET, B, BIG, BLOCKQUOTE, CENTER, CITE, CODE, DD, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, I, IFRAME, IMG, INPUT, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OBJECT, OL, P, PRE, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TEXTAREA, TT, U, UL, VAR, XMP, INPUT type=button, INPUT type=file, INPUT type=reset, INPUT type=submit, INPUT type=text, INPUT type=checkbox, INPUT type=radio, INPUT type=image

Scripting Property

left

See Also

top, height, width, posLeft, pixelLeft


letter-spacing

Description

Specifies additional space between letters.

Syntax

{ letter-spacing: normal | length}

Remarks

This attribute will add the appropriate letter spacing after each character. If you do not want the end of a word to be affected by the spacing, you need to place the last character outside the closing element tag. Letter spacing can be influenced by justification . The length value indicates an addition to the default space between characters. Negative values are permitted.

This attribute is inherited.

Example

In the following example, the word-spacing between each character in BLOCKQUOTE elements would be increased with '1.0em'.

BLOCKQUOTE { letter-spacing: 1.0em }

Applies To

A, ADDRESS, B, BIG, BLOCKQUOTE, BODY, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, DD, DFN, DIR, DIV, DL, DT, EM, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HTML, I, INPUT, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, S, SAMP, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP, INPUT type=button, INPUT type=file, INPUT type=reset, INPUT type=submit, INPUT type=text

Scripting Property

letterSpacing


line-height

Description

Specifies how far apart the lines in a paragraph are. Line height measures the distance between the descender of the font to the top of the internal leading of the font.

Syntax

{ line-height: normal | number | length | percentage}

Remarks

If there is more than one element on a formatted line, the maximum line height applies. Negative values are not allowed.

This attribute is inherited.

Example

The three rules in this example are identical. If the value is set to normal, the line height is set to the default line height for the element's font.

DIV { line-height: 1.2%; font-size: 10pt }   /* number */
DIV { line-height: 1.2em; font-size: 10pt } /* length */
DIV { line-height: 120%; font-size: 10pt } /* percentage */

Applies To

A, ADDRESS, B, BIG, BLOCKQUOTE, BODY, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, DD, DFN, DIR, DIV, DL, DT, EM, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HTML, I, INPUT, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, S, SAMP, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP, INPUT type=button, INPUT type=file, INPUT type=reset, INPUT type=submit, INPUT type=text

Scripting Property

lineHeight


link

Description

Sets the style of the anchor (A) elements for the link's default (unvisited) state.

Remarks

The link attribute takes effect when the link has not been visited and it is not actively being navigated or has a mouse positioned over it. Setting the hover pseudo-class is often used in conjunction with setting specific styles for the other states of a link: active, visited, and hover. Note the syntax in the example below uses a colon (:) to specify a pseudo-class.

Example

The following example sets unvisited links to red and visited links to blue.

A:link   { color: red }           /* unvisited link */
A:visited  { color: blue }       /* visited links */

Applies To

A

See Also

active, hover, visited


list-style

Description

Sets three properties (list-style-type, list-style-image, and list-style-position) at once.

Syntax

{ list-style: keyword || position || url}

Remarks

A URL can be combined with a list-style-type; if available, the image will replace the marker type.

This attribute is inherited.

Example

In the following example, the "disc" image will be used if the image cannot be found.

UL {list-style: url(http://some_image.gif) disc}

Applies To

LI, OL, UL

Scripting Property

listStyle


list-style-image

Description

Specifies an image to use as a list item marker.

Syntax

{ list-style-image: url | none}

Remarks

When the image is available, it will replace the marker set with the list-style-type marker. The default value is none.

This attribute is inherited.

Applies To

LI, OL, UL

Scripting Property

listStyleImage


list-style-position

Description

Determines how the list item marker is drawn with regard to the content.

Syntax

{ list-style-position: inside | outside}

Remarks

This attribute is applicable only on elements with a display value of list-item. If the value is set to inside, any wrapping text in the list item will wrap directly under the marker. If the value is set to outside, the wrapping text maintains the same left indent as the first line of the list item's text.

This attribute is inherited.

Applies To

LI, OL, UL

Scripting Property

listStylePosition


list-style-type

Description

Specifies a predefined list item marker.

Syntax

{ list-style-type: disc | circle | square | decimal | lower-roman | upper-roman | lower-alpha | upper-alpha | none}

Remarks

Determines the appearance of the list item marker if list-style-image is none or if the image pointed to by the URL cannot be displayed. The default value is disc.

This attribute is inherited.

Applies To

LI, OL, UL

Scripting Property

listStyleType


margin

Description

Sets the margin on all four sides of an object with a single style sheet rule.

Syntax

{ margin: [ length | percentage | auto] {1,4}}

Remarks

This is a composite property. The "{1,4}" means that up to four values can be specified. Specifying one value applies that value to all four sides; specifying two values applies the first value to the top and bottom, and the second value to the left and right. Specifying three values applies the first to the top, the second to the right and left, and the third to the bottom. Negative margins are supported except for top and bottom margins on inline elements. Percentage values refer to the parent element's width.

This attribute is not inherited.

Applies To

BLOCKQUOTE, BODY, CAPTION, CENTER, DD, DIR, DIV, DL, DT, EMBED, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, IFRAME, IMG, INPUT, LEGEND, LI, LISTING, MARQUEE, MENU, OBJECT, OL, P, PLAINTEXT, PRE, SPAN, TABLE, TEXTAREA, TD, TH, TR, UL, XMP

Scripting Property

margin

See Also

margin-bottom, margin-left, margin-right, margin-top


margin-bottom

Description

Specifies the bottom margin for the element. Negative margins are supported except for top and bottom margins on inline elements.

Syntax

{ margin-bottom: [ length | percentage | auto]}

Remarks

This attribute is not inherited.

Applies To

BLOCKQUOTE, BODY, CENTER, DD, DIR, DIV, DL, DT, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, TABLE, TD, TH, TR, UL, XMP, CAPTION, TEXTAREA, IFRAME, SPAN, IMG, EMBED, OBJECT, INPUT

Scripting Property

marginBottom

See Also

margin, margin-left, margin-right, margin-top


margin-left

Description

Specifies the left margin for the element. Negative margins are supported except for top and bottom margins on inline elements.

Syntax

{ margin-left: [ length | percentage | auto]}

Remarks

This attribute is not inherited.

Applies To

BLOCKQUOTE, BODY, CENTER, DD, DIR, DIV, DL, DT, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, TABLE, TD, TH, TR, UL, XMP, CAPTION, TEXTAREA, IFRAME, SPAN, IMG, EMBED, OBJECT, INPUT

Scripting Property

marginLeft

See Also

margin, margin-bottom, margin-right, margin-top


margin-right

Description

Specifies the right margin for the element. Negative margins are supported except for top and bottom margins on inline elements.

Syntax

{ margin-right: [ length | percentage | auto]}

Remarks

This attribute is not inherited.

Applies To

BLOCKQUOTE, BODY, CENTER, DD, DIR, DIV, DL, DT, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, TABLE, TD, TH, TR, UL, XMP, CAPTION, TEXTAREA, IFRAME, SPAN, IMG, EMBED, OBJECT, INPUT

Scripting Property

marginRight

See Also

margin, margin-bottom, margin-left, margin-top


margin-top

Description

Specifies the top margin for the element. Negative margins are supported except for top and bottom margins on inline elements.

Syntax

{ margin-top: [ length | percentage | auto]}

Remarks

This attribute is not inherited.

Applies To

BLOCKQUOTE, BODY, CAPTION, CENTER, DD, DIR, DIV, DL, DT, EMBED, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, INPUT, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, TABLE, TD, TH, TR, UL, XMP, TEXTAREA, IFRAME, SPAN, IMG, OBJECT

Scripting Property

marginTop

See Also

margin, margin-bottom, margin-left, margin-right


overflow

Description

Determines what to do when the element's content exceeds the height and width of the element.

By default, overflowing content is visible. This means the element does not observe its specified height and width. If the attribute is set to scroll, the content is clipped to the height and width specified on the element, and the overflowing content is accessible through scroll bars. If the attribute is set to hidden, the content of the element is clipped to the height and width of the element, and no scroll bars appear to access the hidden content. Applies to positioned elements.

Syntax

{ overflow: scroll | hidden | visible | auto }

Remarks

This attribute is not inherited.

For the TEXTAREA element, only the hidden value is valid. Setting the overflow to hidden on a TEXTAREA element hides its scrollbars.

Example

The following example illustrates this attribute.

<DIV STYLE="position:relative;height:100;width:100;
      top:0;left:0;background-color:green;overflow:scroll">
put enough text in here that will take up more than 100 x 100
pixels worth of space. View this, and you will see that you
will need to use the scroll bars to see the content that won't
fit within a 100 x 100 window.
</DIV>

Applies To

DIV, TEXTAREA, SPAN, FIELDSET

Scripting Property

overflow


padding

Description

Specifies the padding-top, padding-bottom, padding-left, and padding-right in one style sheet rule. Padding describes how much space to insert between the element and its margin, or if there is a border, between the element and its border.

Syntax

{ padding: [ length | percentage ] {1,4}}

Remarks

This is a composite property. The "{1,4}" means that up to four values can be specified. The order is top, right, bottom, left. If there is only one value specified, it applies to all sides; if there are two or three, the missing values are taken from the opposite side. Negative values are not allowed. This property is supported on block and replaced elements only.

This attribute is not inherited.

Applies To

BODY, CAPTION, DIV, FIELDSET, IFRAME, LEGEND, MARQUEE, TABLE, TD, TEXTAREA, TR

Scripting Property

padding


padding-bottom

Description

Sets the bottom padding of an element. Padding values cannot be negative.

Supported on block and replaced elements only.

Syntax

{ padding-bottom: length | percentage}

Remarks

This attribute is not inherited.

Applies To

TABLE, TD, TR, CAPTION, TEXTAREA, IFRAME, BODY, MARQUEE, DIV

Scripting Property

paddingBottom

See Also

padding-top, padding-left, padding-right, padding


padding-left

Description

Sets the left padding of an element. Padding values cannot be negative.

Supported on block and replaced elements only.

Syntax

{ padding-left: length | percentage}

Remarks

This attribute is not inherited.

Applies To

TABLE, TD, TR, CAPTION, TEXTAREA, IFRAME, BODY, MARQUEE, DIV

Scripting Property

paddingLeft

See Also

padding-top, padding-bottom, padding-right, padding


padding-right

Description

Sets the right padding of an element. Padding values cannot be negative.

Supported on block and replaced elements only.

Syntax

{ padding-right: length | percentage}

Remarks

This attribute is not inherited.

Applies To

TABLE, TD, TR, CAPTION, TEXTAREA, IFRAME, BODY, MARQUEE, DIV

Scripting Property

paddingRight

See Also

padding-top, padding-left, padding-bottom, padding


padding-top

Description

Sets the top padding of an element. Padding values cannot be negative.

Supported on block and replaced elements only.

Syntax

{ padding-top: length | percentage}

Remarks

This attribute is not inherited.

Applies To

TABLE, TD, TR, CAPTION, TEXTAREA, IFRAME, BODY, MARQUEE, DIV

Scripting Property

paddingTop

See Also

padding-bottom, padding-left, padding-right, padding


page-break-after

Description

Indicates where to set a page break and on which page (left or right) the subsequent content should resume.

Syntax

{ page-break-after: auto | always | left | right}

Remarks

The values are defined as follows:

auto
Insert a page break after the element only if necessary.
always
Always insert a page break after the element.
left
Insert one or two page breaks after the element until a blank left page is reached.
right
Insert one or two page breaks after the element until a blank right page is reached.

If there are conflicts between page-break-after and the page-break-before value on the previous element (as formatted on the canvas), the value that results in the largest number of page breaks will be used.

This attribute is not inherited.

Example

In the following example, a hard page break is inserted in the document with the BR tag.

<STYLE>
    BR.page { page-break-after: always }
</STYLE>
  ...
<BR CLASS=page>
  ...

Applies To

BLOCKQUOTE, BODY, CENTER, DD, DIR, DIV, DL, DT, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, UL, XMP

Scripting Property

pageBreakAfter


page-break-before

Description

Indicates where to set a page break and on which page (left or right) the subsequent content should resume.

Syntax

{ page-break-before: auto | always | left | right}

Remarks

The values are defined as follows:

auto
Insert a page break before the element only if necessary.
always
Always insert a page break before the element.
left
Insert one or two page breaks before the element until a blank left page is reached.
right
Insert one or two page breaks before the element until a blank right page is reached.

If there are conflicts between this property and the page-break-after value on the next element (as formatted on the canvas), the value that results in the largest number of page breaks will be used.

This attribute is not inherited.

Example

In the following example, a page break is inserted in the document before all H1 elements.

<STYLE>
    H1 { page-break-before: always }
</STYLE>
  ...
<H1 CLASS=chapter>
  ...

Applies To

BLOCKQUOTE, BODY, CENTER, DD, DIR, DIV, DL, DT, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, UL, XMP

Scripting Property

pageBreakBefore


position

Description

Specifies the type of positioning for an element. The initial state is static, which means no special positioning and simply obeys the layout rules of HTML.

Syntax

{ position: absolute | relative | static}

Remarks

An absolutely positioned element is always relative to either the next positioned parent or, if there isn't one, the BODY by default. Values for left and top are relative to the upper-left corner of the next positioned element in the hierarchy.

This attribute is not inherited.

Examples

To place an image at the top left corner of the document, set the attributes to 0.

<IMG SRC="sample.gif" STYLE="position:absolute; left:0; top:0">

Setting an absolute position pulls the element out of the "flow" of the document and positions it irrespective of the layout of surrounding elements. If other elements already occupy the given position, they do not affect the positioned element, nor does the positioned element affect them. Instead, all elements are drawn at the same place, causing the objects to overlap. You can control this overlap by using the z-index attribute.

Setting the CSS position attribute to relative places the element in the natural HTML flow of the document but offsets the position of the element based on the preceding content. For example, placing a piece of text within a paragraph with relative positioning will render the text relative to the text in the paragraph that precedes it.

<p>The superscript in this name<SPAN STYLE="position: relative; top:-3px">xyz</SPAN> is "xyz".

Text and elements that follow a relatively positioned element occupy their own space and do not overlap the natural space for the positioned element. Contrast this with an absolutely positioned element, where subsequent text and elements occupy what would have been the natural space for the positioned element before the positioned element was pulled out of the flow.

See Positioning for an overview on how to use dynamic positioning.

Be sure to note the Applies To listings for elements that can be relatively and absolutely positioned.

Applies To

For position:absolute

TABLE, INPUT, SELECT, TEXTAREA, INPUT type=button, DIV, SPAN, OBJECT, APPLET, EMBED, IFRAME, IMG, HR, MARQUEE, FIELDSET

For position:relative

A, ADDRESS, APPLET, B, BIG, BLOCKQUOTE, CENTER, CITE, CODE, DD, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, I, IFRAME, IMG, INPUT, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OBJECT, OL, P, PRE, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TEXTAREA, TT, U, UL, VAR, XMP, INPUT type=button, INPUT type=file, INPUT type=reset, INPUT type=submit, INPUT type=text, INPUT type=checkbox, INPUT type=radio, INPUT type=image

Scripting Property

position

See Also

top, left, height, width, z-index


text-align

Description

Describes how text is aligned within the element.

Since this property is inherited, all block-level elements inside the DIV element with CLASS=center will be centered.

Syntax

{ text-align: left | right | center | justify}

Remarks

This attribute is inherited.

Example

The following example centers the text.

DIV.center { text-align: center }

Applies To

BLOCKQUOTE, BODY, CENTER, DD, DIR, DIV, DL, DT, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, TABLE, TD, TH, TR, UL, XMP

Scripting Property

textAlign


text-decoration

Description

Describes decorations that are added to the text of an element.

Syntax

{ text-decoration: none | [ underline || overline || line-through || blink]}

Remarks

Internet Explorer 4.0 supports the keyword blink, but does not render the blink effect.

If the element has no text (for example, the IMG element in HTML) or is an empty element (for example, <EM> </EM>"), this property has no effect.

This attribute is not inherited.

Example

This example would underline the text of all links in all states of navigation.

A:link, A:visited, A:active, A:hover { text-decoration: underline }

Applies To

A, ADDRESS, B, BIG, BLOCKQUOTE, BODY, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, DD, DFN, DIR, DIV, DL, DT, EM, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HTML, I, INPUT, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP, INPUT type=button, INPUT type=file, INPUT type=reset, INPUT type=submit, INPUT type=text

Scripting Property

textDecoration, textDecorationLineThrough, textDecorationOverline, textDecorationUnderline


text-indent

Description

Specifies the indent that appears before the first formatted line. This property can be negative. An indent is not inserted in the middle of an element that was broken by another (such as BR in HTML).

Syntax

{ text-indent: length | percentage}

Remarks

This attribute is inherited.

Example

This example indents text by 3 ems.

P { text-indent: 3em }

Applies To

BLOCKQUOTE, BODY, CENTER, DD, DIR, DIV, DL, DT, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, TABLE, TD, TH, TR, UL, XMP

Scripting Property

textIndent


text-transform

Description

Changes the rendering of text.

Syntax

{ text-transform: capitalize | uppercase | lowercase | none}

Remarks

The values are defined as follows:
capitalize | Transforms the first character of each word to uppercase.
uppercase | Transforms all the characters to uppercase characters.
lowercase | Transforms all the characters to lowercase characters.

This attribute is inherited.

Example

This example puts H1 elements in uppercase text.

H1 { text-transform: uppercase }

Applies To

A, ADDRESS, B, BIG, BLOCKQUOTE, BODY, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, DD, DFN, DIR, DIV, DL, DT, EM, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HTML, I, INPUT, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP, INPUT type=button, INPUT type=file, INPUT type=reset, INPUT type=submit, INPUT type=text

Scripting Property

textTransform


top

Description

Specifies the position of the element relative to the top of the document.

Syntax

{ top: length | percentage | auto}

Remarks

Used with the position attribute.

This value corresponds to the offsetTop property of the element, and does not include the border of the parent element (noteworthy for the BODY that draws the border inside the client region). auto is the default position of the element according to the regular HTML layout of the page. Percentage values are based on the parent's position.

This attribute, like all other CSS attributes, specifies a string value. When scripting the top property, use either the pixelTop or posTop property for numeric manipulation of a top value.

This attribute is not inherited.

Applies To

A, ADDRESS, APPLET, B, BIG, BLOCKQUOTE, CENTER, CITE, CODE, DD, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, I, IFRAME, IMG, INPUT, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OBJECT, OL, P, PRE, S, SAMP, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TEXTAREA, TT, U, UL, VAR, XMP, INPUT type=button, INPUT type=file, INPUT type=reset, INPUT type=submit, INPUT type=text, INPUT type=checkbox, INPUT type=radio, INPUT type=image

Scripting Property

top

See Also

width, height, left, posTop, pixelTop


vertical-align

Description

Affects the vertical positioning of the element. The sub value vertically aligns as subscript. The super value vertically aligns as superscript.

Syntax

{ vertical-align: sub | super }

Example

This example aligns the text as subscript.

SPAN.subscript { vertical-align: sub }

Applies To

CAPTION, COL, IMG, SPAN,TBODY, TABLE, TD, TH, THEAD, TFOOT, TR

This attribute is not inherited.

Scripting Property

verticalAlign


visibility

Description

Indicates whether the content of a positioned element is displayed.

Syntax

{ visibility: visible | hidden | inherit}

Remarks

Unlike display:none, elements that are not visible still reserve the same physical space in the content layout as they would if they were visible. Changing the visibility through scripting is useful for showing and hiding content based on a user interaction. Note that for a child element to be visible, the parent element must also be visible. See Dynamic Styles for document style scripting information.

This attribute is not inherited.

Applies To

A, ADDRESS, APPLET, B, BIG, BLOCKQUOTE, BODY, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, DD, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, HTML, I, IFRAME, IMG, INPUT, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OBJECT, OL, P, PRE, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP, INPUT type=button, INPUT type=file, INPUT type=reset, INPUT type=submit, INPUT type=text, INPUT type=checkbox, INPUT type=radio, INPUT type=image

Scripting Property

visibility

See Also

display


visited

Description

Sets the style of anchor (A) elements for previously visited links.

Remarks

The visited pseudo-class is often used in conjunction with others to define the various states of a link: active, link, and hover.

When the mouse is over a hyperlink to which the visited style has been applied, the hover pseudo-class takes precendence.

Using pseudo-classes on elements other than the A element has no effect.

Example

The following code sets unvisited links to red and visited links to blue. The example below uses a colon (:) to specify a pseudo-class.

A:link   { color: red }           /* unvisited link */
A:visited  { color: blue }       /* visited links */

Applies To

A

See Also

active, hover, link


width

Description

Specifies the width of the element. DIV and SPAN cannot be positioned unless a width is provided. Percentage values are based on the width of the parent element.

Syntax

{ width: length | percentage | auto}

Remarks

The width attribute, like all other CSS attributes, specifies a string value. When scripting the width property, use either the pixelWidth or posWidth property for numeric manipulation of a width value.

This attribute is not inherited.

Applies To

APPLET, DIV, EMBED, FIELDSET, HR, IFRAME, IMG, INPUT, INPUT type=button, MARQUEE, OBJECT, SELECT, SPAN, TABLE, TEXTAREA

Scripting Property

width

See Also

height, left, position, top


z-index

Description

Specifies the stacking order of positioned elements.

Syntax

{ z-index: integer | auto }

Remarks

By default (auto), the stacking order is bottom-to-top in the order that they appear in the HTML source. Positive z-index values are positioned above a negative (or lesser value) z-index. Two elements with the same z-index are stacked according to source order.

This attribute is not inherited.

Applies To

A, ADDRESS, APPLET, B, BIG, BLOCKQUOTE, BODY, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, DD, DFN, DIR, DIV, DL, DT, EM, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HTML, I, INPUT, INPUT type=button, INPUT type=file, INPUT type=reset, INPUT type=submit, INPUT type=text, TEXTAREA, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, S, SAMP, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP

Scripting Property

zIndex

See Also

position


Events

onabort onafterupdate onbeforeunload onbeforeupdate
onblur onbounce onchange onclick
ondataavailable ondatasetchanged ondatasetcomplete ondblclick
ondragstart onerror onerrorupdate onfilterchange
onfinish onfocus onhelp onkeydown
onkeypress onkeyup onload onmousedown
onmousemove onmouseout onmouseover onmouseup
onreadystatechange onreset onresize onrowenter
onrowexit onscroll onselect onselectstart
onstart onsubmit onunload

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


onabort

Description

Fires when the user aborts the download of the image.

Remarks

An image can be aborted by clicking a link, clicking the Stop button, and so on. This event will not bubble. Events that do not bubble can only be handled on the individual object that fired the event

Applies To

IMG


onafterupdate

Description

Fires after the transfer of data from the element to the data provider (after a successful onbeforeupdate).

Remarks

This event only fires when the object is databound and an onbeforeupdate event has fired (the element's data has changed). This event cannot be canceled. This event will bubble. Events that bubble can be handled on any parent element of the object that fired the event.

Applies To

APPLET, BODY, BUTTON, CAPTION, DIV, EMBED, IMG, INPUT, MAP, MARQUEE, OBJECT, SELECT, TABLE, TD, TEXTAREA, TR

See Also

onbeforeupdate


onbeforeunload

Description

Fires prior to a page being unloaded.

Remarks

This event gives you a chance to request that the user not leave the page. By returning a string to this event, a dialog box is displayed that gives the user the option to stay on the page. The returned string is displayed in a predefined area to provide the user with the reason.

This event also fires when a document.open is done and when a frameset is created.

Applies To

FRAMESET, window

See Also

onunload


onbeforeupdate

Description

Fires before the transfer of data from the element to the data provider. Fires when an element loses focus or the page is attempting to unload when the value of the element has changed from the value that was in the element at the time it received the focus.

Remarks

This event can be canceled. This allows the programmer to fail the validation and leave the content of the field as well as the cursor intact. All subsequent events are not fired when this event is canceled. This event will bubble. Events that bubble can be handled on any parent element of the object that fired the event.

Applies To

APPLET, BODY, BUTTON, CAPTION, DIV, EMBED, HR, IMG, INPUT, MAP, OBJECT, SELECT, TABLE, TD, TEXTAREA, TR

See Also

onafterupdate


onblur

Description

Fires when an object, such as a button or check box, loses the input focus.

Remarks

This event is fired even when clicking another control or the background of the page, switching applications, or opening another window within the browser. This event will not bubble. Events that do not bubble can only be handled on the individual object that fired the event

Applies To

A, APPLET, AREA, BUTTON, DIV, EMBED, HR, IMG, INPUT, MARQUEE, OBJECT, SELECT, SPAN, TABLE, TD, TEXTAREA, TR, window


onbounce

Description

Fires when the behavior property of the MARQUEE element is set to "alternate" and the contents of the marquee reach a side.

Remarks

This event will not bubble. Events that do not bubble can only be handled on the individual object that fired the event.

Applies To

MARQUEE


onchange

Description

Fires when the contents of the object have changed.

Remarks

This event is fired when the contents are committed, not while the value is changing. For example, on a text box, this event is not fired while the user is typing, but rather when the user commits the change by pressing ENTER or leaving the text box focus. This event will not bubble. Events that do not bubble can only be handled on the individual object that fired the event.

This code is executed before the code specified by onblur, if the control is also losing the focus.

Applies To

INPUT, SELECT, TEXTAREA

See Also

onkeypress


onclick

Description

Fires when the user presses and releases the left mouse button, or when the user presses keys, such as ENTER and ESC, in a form.

Remarks

The following actions cause an onclick event.

  • Click the left mouse button.
  • Press ENTER when either the submit control or a nonbutton control in the form has focus.
  • Press the ESC key when any control in the form has the focus.
  • Press the SPACEBAR when a checkbox, radio, reset, or submit control has focus or a BUTTON or TEXTAREA element has focus.
  • Press the access key specified by the accessKey property for a checkbox, radio, reset, or submit control or a BUTTON, OPTION, SELECT, or TEXTAREA element.

The default action of an onclick event depends on the object that receives the click. For example, clicking an A element causes the browser to load the document specified by the href property. You can cancel the default behavior by setting the returnValue property of the event object to FALSE.

If the user clicks the left mouse button, the onclick event for an object occurs only if the mouse pointer is over the object and both an onmousedown and an onmouseup event occur in order. For example, if the user presses down in the object but moves the mouse pointer out of the object before releasing, no onclick event occurs.

If the user clicks an object that can receive the input focus but does not already have the focus, the onfocus event occurs for that object before the onclick event. If the user double-clicks the left mouse button in a control, an ondblclick event occurs immediately after the onclick event.

Although the onclick event is available on a large number of HTML tags, its use should be restricted to the <A>, <INPUT>, <AREA>, and <BUTTON> tags. These elements automatically allow keyboard access via the TAB key, making Web pages that use them accessible to keyboard users. For more information, please see the section on Writing Accessible Dynamic HTML.

This event will bubble. Events that bubble can be handled on any parent element of the object that fired the event.

Examples

The following JScript example is an onclick event handler for the document. It uses the event object to display the tag name of the element in which the click occurred.

<SCRIPT>
function clickit() {
    alert("Clicked in " + window.event.srcElement.tagName);
}
</SCRIPT>

<BODY onclick="clickit()">

The following VBScript example is an onclick event handler for the document. It uses the event object to determine whether the click occurred in an A element and then cancels the event (and prevents a jump) if the SHIFT key is down.

<SCRIPT LANGUAGE="VBScript">
Function document_onclick()
    If window.event.srcElement.tagName = "A" And window.event.shiftKey Then
        window.event.returnValue = False
    End If
End Function
</SCRIPT>

Applies To

A, ADDRESS, APPLET, AREA, B, BIG, BLOCKQUOTE, BODY, BUTTON, CAPTION, CENTER, CITE, CODE, DD, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET FONT, FORM, H1, H2, H3, H4, H5, H6, HR, I, IMG, INPUT, KBD, LABEL, LEGEND, LI, LISTING, MAP, MARQUEE, MENU, OBJECT, OL, OPTION, P, PLAINTEXT, PRE, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP, document

See Also

click


ondataavailable

Description

Fires periodically as data arrives for data source objects that transmit their data asynchronously. Frequency of firing is dependent upon the data source object.

Remarks

This event fires for objects and applications that are data source objects. There is a qualifier property on the event object; the qualifier will always be set to "" for Internet Explorer 4.0. This event cannot be canceled. This event will bubble. Events that bubble can be handled on any parent element of the object that fired the event.

Applies To

APPLET, IMG, MAP, OBJECT


ondatasetchanged

Description

Fires when the data set exposed by a data source object changes—for example, when a filter operation takes place. Also fires when initial data is available from a data source object.

Remarks

This event fires for objects and applications that are data source objects. There is a qualifier property on the event object; the qualifier will always be set to "" for Internet Explorer 4.0. This event cannot be canceled. This event will bubble. Events that bubble can be handled on any parent element of the object that fired the event.

Applies To

APPLET, IMG, MAP, OBJECT


ondatasetcomplete

Description

Fires to indicate that all data is available from the data source object.

Remarks

This event fires for objects and applications that are data source objects. There is a qualifier property and a reason property on the event object. The qualifier will always be set to "" for Internet Explorer 4.0. This event cannot be canceled. This event will bubble. Events that bubble can be handled on any parent element of the object that fired the event.

The reason property is set to indicate the reason for completion and is one of these values:
0 | Data transmitted successfully.
1 | Data transfer aborted.
2 | Data transfer in error.

Applies To

APPLET, IMG, MAP, OBJECT


ondblclick

Description

Fires when the user clicks twice over an object.

Return Value

Returns TRUE or FALSE. Returning FALSE cancels the default action.

Remarks

The ondblclick event occurs when the user clicks twice (presses and releases the left mouse button and then presses and releases it again) over an object. The two clicks must occur within the time limit specified by the system's double-click speed setting. This event will bubble. Events that bubble can be handled on any parent element of the object that fired the event.

The order of events leading to the ondblclick event is:

  1. onmousedown
  2. onmouseup
  3. onclick
  4. onmouseup
  5. ondblclick

Applies To

A, ADDRESS, APPLET, AREA, B, BIG, BLOCKQUOTE, BODY, BUTTON, CAPTION, CENTER, CITE, CODE, DD, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FONT, FORM, H1, H2, H3, H4, H5, H6, HR, I, IMG, INPUT, KBD, LABEL, LEGEND, LI, LISTING, MAP, MARQUEE, MENU, OBJECT, OL, P, PLAINTEXT, PRE, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP, document


ondragstart

Description

Fires when the user first starts to drag a selection or selected element.

Remarks

For the INPUT element, the only types supported for this event are file, image, password, and text.

This event can be canceled. This event will bubble. Events that bubble can be handled on any parent element of the object that fired the event.

Applies To

A, ACRONYM, ADDRESS, AREA, B, BIG, BLOCKQUOTE, BODY, BUTTON, CAPTION, CENTER, CITE, CODE, DD, DEL, DFN, DIR, DIV, DL, DT, EM, FONT, FORM, H1, H2, H3, H4, H5, H6, HR, I, IMG, INPUT, KBD, LABEL, LI, LISTING, MAP, MARQUEE, MENU, OBJECT, OL, OPTION, P, PLAINTEXT, PRE, Q, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP, document


onerror

Description

Fires when a scripting error occurs (for example, when there are security problems during the loading process or when there is a problem in the code).

Remarks

When programming in VBScript, you can create an event handler that receives event parameters by defining a subroutine having this form:

Sub window_onerror(message, url, line)
    window.event.returnValue=true

The line parameter is an integer specifying the line number at which the error occurred, url is a string specifying the URL of the document containing the error, and the optional message is a message string. Returning true for the event prevents the default error message for Internet Explorer from displaying.

The following example uses JScript.

function errortrap(msg,url,line){
    alert(msg);
    return true;
}
onerror=errortrap;

This event will not bubble. Events that do not bubble can only be handled on the individual object that fired the event.

Applies To

window

See Also

onerror event for other objects


onerror

Description

Fires when an error occurs loading the image or other object.

Remarks

You can suppress error messages that occur when an image fails to load by setting the onerror attribute in the element to "null". This event will not bubble. Events that do not bubble can only be handled on the individual object that fired the event.

Applies To

IMG, LINK, OBJECT, SCRIPT, STYLE


onerrorupdate

Description

Fires when the onbeforeupdate event handler specified for the element has canceled the data transfer and is fired instead of the onafterupdate event.

Remarks

This event only fires when an onbeforeupdate event has fired (the element's data has changed). This event cannot be canceled. This event will bubble. Events that bubble can be handled on any parent element of the object that fired the event.

Applies To

A, APPLET, MAP, OBJECT, SELECT, TEXTAREA


onfilterchange

Description

Fires when a visual filter changes state or completes a transition.

Remarks

This event will bubble. Events that bubble can be handled on any parent element of the object that fired the event.

An asterisk in the following applies to list indicates that a defined height, width, or absolute position is required.

Applies To

BODY, BUTTON, DIV*, IMG, INPUT, MARQUEE, SPAN*, TABLE, TD, TEXTAREA, TFOOT, TH, THEAD, TR


onfinish

Description

Fires when looping is complete.

Remarks

This event will not bubble. Events that do not bubble can only be handled on the individual object that fired the event.

Applies To

MARQUEE


onfocus

Description

Fires when a control receives the focus. This event also fires for some noncontrol elements such as HR.

Remarks

This event will not bubble. Events that do not bubble can only be handled on the individual object that fired the event.

Applies To

A, APPLET, AREA, BUTTON, DIV, EMBED, HR, IMG, INPUT, MARQUEE, OBJECT, SELECT, SPAN, TABLE, TD, TEXTAREA, TR, window

See Also

focus


onhelp

Description

Fires when the user presses the F1 or Help key on the browser.

Remarks

This event will not bubble. Events that do not bubble can only be handled on the individual object that fired the event.

Applies To

A, ADDRESS, APPLET, AREA, B, BIG, BLOCKQUOTE, BUTTON, CAPTION, CENTER, CITE, CODE, DD, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FONT, FORM, H1, H2, H3, H4, H5, H6, HR, I, IMG, INPUT, KBD, LABEL, LEGEND, LI, LISTING, MAP, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP, document, window


onkeydown

Description

Fires when the user presses a key.

Return Value

Returns a number specifying the keycode of the key that was pressed.

Remarks

The return value can be used to override the keycode value. This event will bubble. Events that bubble can be handled on any parent element of the object that fired the event.

To cancel the keystroke, use the following code in the onkeydown event:

event.returnValue=false;

Applies To

A, ACRONYM, ADDRESS, APPLET, AREA, B, BIG, BLOCKQUOTE, BODY, BUTTON, CAPTION, CENTER, CITE, CODE, DD, DEL, DFN, DIR, DIV, DT, EM, FIELDSET, FONT, FORM, H1, H2, H3, H4, H5, H6, HR, I, IMG, INPUT, KBD, LABEL, LEGEND, LI, LISTING, MAP, MARQUEE, MENU, OBJECT, OL, P, PLAINTEXT, PRE, Q, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP, document


onkeypress

Description

Fires when a user presses a key.

Return Value

Returns a number specifying the Unicode value of the key that was pressed.

Remarks

The return value can be used to override the keycode value. This event will bubble. Events that bubble can be handled on any parent element of the object that fired the event.

To cancel the keystroke, use the following code in the onkeypress event:

event.returnValue=false;

Applies To

A, ACRONYM, ADDRESS, APPLET, AREA, B, BIG, BLOCKQUOTE, BODY, BUTTON, CAPTION, CENTER, CITE, CODE, DD, DEL, DFN, DIR, DIV, DT, EM, FIELDSET, FONT, FORM, H1, H2, H3, H4, H5, H6, HR, I, IMG, INPUT, KBD, LABEL, LEGEND, LI, LISTING, MAP, MARQUEE, MENU, OBJECT, OL, P, PLAINTEXT, PRE, Q, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP, document

See Also

onchange


onkeyup

Description

Fires when the user releases a key.

Return Value

Returns a number specifying the keycode of the key released.

Remarks

The return value can be used to override the keycode value. This event will bubble. Events that bubble can be handled on any parent element of the object that fired the event.

To cancel the keystroke, use the following code in the onkeyup event:

event.returnValue=false;

Applies To

A, ACRONYM, ADDRESS, APPLET, AREA, B, BIG, BLOCKQUOTE, BODY, BUTTON, CAPTION, CENTER, CITE, CODE, DD, DEL, DFN, DIR, DIV, DT, EM, FIELDSET, FONT, FORM, H1, H2, H3, H4, H5, H6, HR, I, IMG, INPUT, KBD, LABEL, LEGEND, LI, LISTING, MAP, MARQUEE, MENU, OBJECT, OL, P, PLAINTEXT, PRE, Q, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP, document


onload

Description

Fires immediately after the browser loads the given object.

Remarks

The browser loads applications, embedded objects, and images as soon as it encounters the APPLET, EMBED, and IMG elements during parsing. This means that the onload event for these objects occurs before the browser parses any subsequent elements. To ensure that an event handler receives the onload event for these elements, you must place the SCRIPT element that defines the event handler before the element and use the onload attribute in the element to set the handler.

The onload attribute of the BODY element sets an onload event handler for the window. Setting an onload event handler for the window object by any other means will override the handler set using the onload attribute if the handlers are in the same script language.

This event will not bubble. Events that do not bubble can only be handled on the individual object that fired the event.

Examples

The following JScript example is an onload event handler for the window.

<SCRIPT FOR=window EVENT=onload LANGUAGE="JScript">
    window.status = "Page is loaded!";
</SCRIPT>

The following JScript example sets an onload event handler for an IMG element. The handler uses the event object to retrieve the URL of the image.

<SCRIPT LANGUAGE="JScript">
function imageLoaded()
{
    window.status = "Image \"" + window.event.srcElement.src + "\" is loaded";
}
</SCRIPT>
<IMG SRC="sample.gif" onload="imageLoaded()">

Applies To

APPLET, EMBED, FRAMESET, IMG, LINK, SCRIPT, STYLE, window


onmousedown

Description

Fires when the user presses a button on a pointer device, such as the mouse.

Remarks

The event ordering for mouse-related events is:

  1. onmousedown
  2. onmouseup
  3. onclick
  4. ondblclick
  5. onmouseup

This event will bubble. Events that bubble can be handled on any parent element of the object that fired the event.

Applies To

A, ADDRESS, APPLET, AREA, B, BIG, BLOCKQUOTE, BODY, BUTTON, CAPTION, CENTER, CITE, CODE, DD, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FONT, FORM, H1, H2, H3, H4, H5, H6, HR, I, IMG, INPUT, KBD, LABEL, LEGEND, LI, LISTING, MAP, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP, document

See Also

ondblclick, onmousemove, onmouseup


onmousemove

Description

Fires when the user moves the mouse.

Remarks

The event ordering for moving the mouse is:

  1. onmouseover
  2. onmousemove
  3. onmouseout

This event will bubble. Events that bubble can be handled on any parent element of the object that fired the event.

Applies To

A, ADDRESS, APPLET, AREA, B, BIG, BLOCKQUOTE, BODY, BUTTON, CAPTION, CENTER, CITE, CODE, DD, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FONT, FORM, H1, H2, H3, H4, H5, H6, HR, I, IMG, INPUT, KBD, LABEL, LEGEND, LI, LISTING, MAP, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP, document

See Also

onmousedown, onmouseup


onmouseout

Description

Fires when the user moves the mouse pointer out of an element.

Remarks

When the user moves the mouse pointer into an element, one onmouseover event occurs, followed by one or more onmousemove events as the user moves the pointer within the element, and finally one onmouseout event when the user moves the pointer out of the element. This event will bubble. Events that bubble can be handled on any parent element of the object that fired the event.

Examples

The following JScript example sets the onmouseout event handler for an element having the identifier "para_1". The handler changes the color of the text in the element when the mouse pointer leaves the element.

<SCRIPT FOR=para_1 EVENT=onmouseout LANGUAGE="JScript">
var el = window.event.srcElement;
for ( ; el.id != "para_1"; el = el.parentElement);
el.style.color = "silver";
</SCRIPT>

The following JScript example sets the onmouseout event handler for an IMG element. The handler changes the image source file for the element when the mouse pointer leaves the element.

<IMG SRC="inactive.gif" onmouseover="flipImage('active.gif')" onmouseout="flipImage('inactive.gif')">
    .
    .
    .
<SCRIPT LANGUAGE="JScript">
function flipImage(url)
{
    if (window.event.srcElement.tagName == "IMG" ) {
        window.event.srcElement.src = url;
    }
}
</SCRIPT>

Applies To

A, ADDRESS, APPLET, AREA, B, BIG, BLOCKQUOTE, BODY, BUTTON, CAPTION, CENTER, CITE, CODE, DD, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FONT, FORM, H1, H2, H3, H4, H5, H6, HR, I, IMG, INPUT, KBD, LABEL, LEGEND, LI, LISTING, MAP, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP, document


onmouseover

Description

Fires when the user moves the mouse pointer into an element. The event occurs when the pointer first enters the element and does not repeat unless the user moves the pointer out of the element and then back into it.

Remarks

When the user moves the mouse pointer into an element, one onmouseover event occurs, followed by one or more onmousemove events as the user moves the pointer within the element, and finally one onmouseout event when the user moves the pointer out of the element. This event will bubble. Events that bubble can be handled on any parent element of the object that fired the event.

Examples

The following JScript example sets the onmouseover event handler for an element having the identifier "para_1". The handler changes the color of the text in the element when the mouse pointer enters the element.

<SCRIPT FOR=para_1 EVENT=onmouseover LANGUAGE="JScript">
var el = window.event.srcElement;
for ( ; el.id != "para_1"; el = el.parentElement);
el.style.color = "black";
</SCRIPT>

The following JScript example sets the onmouseover event handler for an IMG element. The handler changes the image source file for the element when the mouse pointer enters the element.

<IMG SRC="inactive.gif" onmouseover="flipImage('active.gif')" onmouseout="flipImage('inactive.gif')">
    .
    .
    .
<SCRIPT LANGUAGE="JScript">
function flipImage(url)
{
    if (window.event.srcElement.tagName == "IMG" ) {
        window.event.srcElement.src = url;
    }
}
</SCRIPT>

Applies To

A, ADDRESS, APPLET, AREA, B, BIG, BLOCKQUOTE, BODY, BUTTON, CAPTION, CENTER, CITE, CODE, DD, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FONT, FORM, H1, H2, H3, H4, H5, H6, HR, I, IMG, INPUT, KBD, LABEL, LEGEND, LI, LISTING, MAP, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP, document


onmouseup

Description

Fires when the user releases a mouse button.

Remarks

This event will bubble. Events that bubble can be handled on any parent element of the object that fired the event.

Applies To

A, ADDRESS, APPLET, AREA, B, BIG, BLOCKQUOTE, BODY, BUTTON, CAPTION, CENTER, CITE, CODE, DD, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FONT, FORM, H1, H2, H3, H4, H5, H6, HR, I, IMG, INPUT, KBD, LABEL, LEGEND, LI, LISTING, MAP, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP, document

See Also

ondblclick, onmousedown, onmousemove


onreadystatechange

Description

Fires whenever the ready state for the object has changed.

Remarks

Each object can choose to expose which set of ready states it is exposing. This event should be fired whenever the ready state is changed.

When an element changes to the loaded state, this event fires immediately before the firing of the load event. This event will not bubble. Events that do not bubble can only be handled on the individual object that fired the event.

Applies To

APPLET, EMBED, IMG, LINK, OBJECT, SCRIPT, STYLE, document

See Also

onload, readyState

GE


onreset

Description

Fires when a user resets a form (clicks a Reset button). The onreset event handler executes code when a reset event occurs.

Remarks

This event will not bubble. Events that do not bubble can only be handled on the individual object that fired the event.

Applies To

FORM


onresize

Description

Fires at the beginning of a resize operation.

Remarks

This event will not bubble. Events that do not bubble can only be handled on the individual object that fired the event. This event will not fire for files with embedded controls.

Applies To

APPLET, BUTTON, CAPTION, DIV, EMBED, FRAMESET, HR, IMG, MARQUEE, SELECT, TABLE, TD, TR, TEXTAREA, window


onrowenter

Description

Fires to indicate that the current row has changed and new data values are available.

Remarks

This event only fires when the object is databound. This event applies only to objects that identify themselves as a data provider. This event will not bubble. Events that do not bubble can only be handled on the individual object that fired the event.

Applies To

APPLET, BODY, BUTTON, CAPTION, DIV, EMBED, HR, IMG, MAP, MARQUEE, OBJECT, SELECT, TABLE, TD, TEXTAREA, TR


onrowexit

Description

Fires just prior to the data source control changing the current row.

Remarks

This event only fires when the object is databound. This event applies only to objects that identify themselves as a data provider. This event will not bubble. Events that do not bubble can only be handled on the individual object that fired the event.

Applies To

APPLET, BODY, BUTTON, CAPTION, DIV, EMBED, HR, IMG, MAP, MARQUEE, OBJECT, SELECT, TABLE, TD, TEXTAREA, TR


onscroll

Description

Fires when the scroll box is repositioned.

Remarks

This notification event fires for the window object and all elements that scroll. This event cannot be canceled and will not bubble. Events that do not bubble can only be handled on the individual object that fired the event.

Applies To

DIV, FIELDSET, IMG, MARQUEE, SPAN, TEXTAREA, window


onselect

Description

Fires when the current selection changes.

Remarks

This event will fire as the mouse moves from character to character during a drag selection. This event will not bubble. Events that do not bubble can only be handled on the individual object that fired the event.

Applies To

INPUT, TEXTAREA

See Also

select


onselectstart

Description

Fires at the beginning of an element selection.

Remarks

This event will fire as the mouse starts the selection of one or more elements. The element at the beginning of the selection fires the event. This event can be canceled. This event will bubble. Events that bubble can be handled on any parent element of the object that fired the event.

Applies To

A, ACRONYM, ADDRESS, AREA, B, BIG, BLOCKQUOTE, BODY, BUTTON, CAPTION, CENTER, CITE, CODE, DD, DEL, DFN, DIR, DIV, DL, DT, EM, FONT, FORM, H1, H2, H3, H4, H5, H6, HR, I, IMG, INPUT, KBD, LABEL, LI, LISTING, MAP, MARQUEE, MENU, OBJECT, OL, OPTION, P, PLAINTEXT, PRE, Q, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP

See Also

select


onstart

Description

Fires at the beginning of every loop, and when a bounce cycle begins for alternate behavior.

Remarks

This event will not bubble. Events that do not bubble can only be handled on the individual object that fired the event.

Applies To

MARQUEE


onsubmit

Description

Fires when a form is about to be submitted.

Return Value

Returns TRUE or FALSE.

Remarks

The onsubmit event default action is to submit the form. This event can be overridden by returning FALSE in the event handler. The purpose of this is to allow the developer to do validation of the data on the client side and prevent invalid data from being submitted to the server. This event will not bubble. Events that do not bubble can only be handled on the individual object that fired the event.

Applies To

FORM


onunload

Description

Fires immediately prior to the page being unloaded.

Remarks

The onunload attribute of the BODY element sets an onunload event handler for the window. This event will not bubble. Events that do not bubble can only be handled on the individual object that fired the event.

Applies To

FRAMESET, window


A

Description

Designates the start or destination of a hypertext link. The anchor element requires the HREF= or the NAME= attribute to be specified.

Syntax

<A
 ACCESSKEY=key
CLASS=classname
DATAFLD=colname
DATASRC=#ID
HREF=url
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
 METHODS=http-method
NAME=name
REL="stylesheet"
 REV="stylesheet"
 STYLE=css1-properties
TABINDEX=n
TARGET=window_name | _blank | _parent | _self | _top
TITLE=text
URN=urn
event = script
>

Parameter | Description
ACCESSKEY=key | Accelerator for the element. Pressing ALT-key selects this element in the user's browser.
CLASS=classname | Class of the tag being defined. This is used to associate a subclassed style sheet with the tag.
DATAFLD=colname | Column name from the data source object that supplies the bound data.
DATASRC=#ID | ID of the data source object that supplies the data that is bound to this element.
HREF=url | Destination URL or anchor point. If HREF is set to an empty string (""), then hyperlinking will cause the base URL to be opened. For example, if the current file is "http://microsoft.com/home/hello.html", then "http://microsoft.com/home/" will be opened.
ID=value | SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underscore character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The script is written in JScript.
VBS, VBSCRIPT | The script is written in VBScript.
METHODS=http-method | METHODS attributes of anchors and links provide information about the functions that the user may perform on an object. These are more accurately given by the HTTP protocol when it is used, but it may, for similar reasons as for the TITLE attribute, be useful to include the information in advance in the link. For example, the HTML user agent may choose a different rendering as a function of the methods allowed; for example, something that is searchable may get a different icon.
NAME=name | Name of the anchor.
REL="stylesheet" | Gives the relationship(s) described by the hypertext link from the anchor to the target. The value is a comma-separated list of relationship values. The values and their semantics will be registered by the HTML registration authority. The default relationship if none other is given is void. The REL attribute is only used when the HREF= attribute is present.
REV="stylesheet" | Same as the REL attribute, but the semantics of the link type are in the reverse direction. A link from A to B with REL="X" expresses the same relationship as a link from B to A with REV="X". An anchor may have both REL and REV attributes.
STYLE=css1-properties | Inline style sheet for the tag.
TABINDEX=n | Sets the tab order position for the object.
TARGET=window_name | _blank | _parent | _self | _top Window or frame at which to target the contents. If no frame or window exists that matches the specified target, a new window is opened for the specified link. If no target is specified, the default is "_self" for a link within the same site or "_top" if the site is external. Special target values are:
_blank | Specifies to load the link into a new unnamed window.
_parent | Specifies to load the link into the immediate parent of the document the link is in.
_self | Specifies to load the link into the same window the link was clicked in.
_top | Specifies to load the link into the full body of the current window.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a tooltip during the onmouseover event.
event Can be one or more of these events:
onblur onclick
ondblclick ondragstart
onfocus onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

Text and/or images may be within an anchor. To represent images that are anchors, a border in the visited or not visited color is displayed.

Both the start and end tags are required.

Example

<A HREF="http://www.microsoft.com">This is a link to Microsoft.</A>

<A HREF="home.htm">This link points to a file called home.htm in the same directory as this page.</A>

<A TARGET="viewer" HREF="sample.htm">Click here to load the link into "viewer" window.</A>

<A HREF="http://www.microsoft.com"><IMG SRC="images/bullet.gif">This link contains an image</A>

<A HREF="javascript:window.open()">This link opens a new window using the open method in javascript</A>

Scripting Object

A


ACRONYM

Description

Indicates an acronym.

Syntax

<ACRONYM
 CLASS=classname
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
 STYLE=css1-properties
TITLE=text
event = script
>

Parameter | Description
CLASS=classname | Class of the tag being defined. This is used to associate a subclassed style sheet with the tag.
ID=value | SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underscore character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The script is written in JScript.
VBS, VBSCRIPT | The script is written in VBScript.
STYLE=css1-properties | Inline style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a tooltip during the onmouseover event.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

Both the start and end tags are required. This tag does not affect how text appears in the browser.

Example

<ACRONYM>MSN</ACRONYM>

Scripting Object

ACRONYM

See Also

ADDRESS, CITE, DFN, EM, STRONG


ADDRESS

Description

The Address element is used to specify information such as address, signature and authorship.

Syntax

<ADDRESS
 CLASS=classname
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
STYLE=css1-properties
TITLE=text
event = script
>

Parameter | Description
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

This element is a block element.

Both the start and end tags are required.

Example

<ADDRESS>This text will be in italic.</ADDRESS>

Scripting Object

ADDRESS

See Also

ACRONYM, CITE, DFN, EM, STRONG


APPLET

Description

Places executable content on the page.

Syntax

<APPLET
 ALIGN=ABSBOTTOM | ABSMIDDLE | BASELINE | BOTTOM | LEFT | MIDDLE | RIGHT | TEXTTOP | TOP
 ALT=text
CLASS=classname
CODE=filename
CODEBASE=url
DATAFLD=colname
DATASRC=#ID
HEIGHT=n
HSPACE=n
ID=value
NAME=name
SRC=url
STYLE=css1-properties
TITLE=text
VSPACE=n
WIDTH=n
event = script
>

Parameter | Description
ALIGN=ABSBOTTOM | ABSMIDDLE | BASELINE | BOTTOM | LEFT | MIDDLE | RIGHT | TEXTTOP | TOP | Specifies the alignment for the control-like element.
ALT=text | Optional text as an alternative to the application if it cannot be executed.
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
CODE=filename | The name of the file containing the compiled Java class.
CODEBASE=url | This is an optional parameter that specifies the base URL for the application.
DATAFLD=colname | The column name from the data source object that supplies the bound data. This can only be used on the contained PARAM elements.
DATASRC=#ID | Indicates the ID of the data source object that supplies the data that is bound to this element.
HEIGHT=n | Along with WIDTH=, specifies the size at which the element is drawn. This attribute may be initially set in pixels or percentages.
HSPACE=n | Along with VSPACE=, specifies margins for the element.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID names must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created and can only be referenced by ordinal position.
NAME=name | Specifies the name of the application.
SRC=url | Specifies a URL for the associated file.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
VSPACE=n | Along with HSPACE=, specifies margins for the element.
WIDTH=n | Along with HEIGHT=, specifies the size at which the element is drawn. This attribute may be initially set in pixels or percentages.
event Can be one or more of these events:
onafterupdate onbeforeupdate
onblur onclick
ondataavailable ondatasetchanged
ondatasetcomplete ondblclick
onerrorupdate ondragstart
onfocus onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onreadystatechange onresize
onrowenter onrowexit

Remarks

This element is a block element.

Both the start and end tags are required.

Scripting Object

APPLET

See Also

EMBED, OBJECT, PARAM


AREA

Description

Specifies the shape of a hyperlink "hot spot" in a client-side image map.

Syntax

<AREA
 ALT=text
CLASS=classname
COORDS=coordinates
HREF=url
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
 NOHREF
 SHAPE=CIRC | CIRCLE | POLY | POLYGON | RECT | RECTANGLE
 STYLE=css1-properties
TABINDEX=n
TARGET=window_name | _blank | _parent | _self | _top
TITLE=text
event = script
>

Parameter | Description
ALT=text | Optional text as an alternative to the graphic for rendering in non-graphical environments. Alternate text should be provided whenever the graphic is not rendered. Alternate text is mandatory for Level 0 documents.
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
COORDS=coordinates | Coordinates that define the hot spot's shape.
HREF=url | Specifies the destination URL or anchor point.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
NOHREF | Indicates that clicks in this region should cause no action.
SHAPE=CIRC | CIRCLE | POLY | POLYGON | RECT | RECTANGLE | Specifies the type of shape used in the image map.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TABINDEX=n | Sets the tab order position for the object.
TARGET=window_name | _blank | _parent | _self | _top Specifies the window or frame to target the contents at. If no frame or window exists that matches the specified target, a new window is opened for the specified link. If no target is specified, the default is "_self" for a link within the same site or "_top" if the site is external. Special target values are listed below:
_blank | Specifies to load the link into a new unnamed window.
_parent | Specifies to load the link into the immediate parent of the document the link is in.
_self | Specifies to load the link into the same window the link was clicked in.
_top | Specifies to load the link into the full body of the current window.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
event Can be one or more of these events:
onblur onclick
ondblclick ondragstart
onfocus onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

This is an empty element and does not require a closing tag.

Examples

<AREA SHAPE="RECT" COORDS="0, 0, 58, 31" HREF="http://www.microsoft.com/ie/">

<AREA TARGET="viewer" HREF="sample.htm" SHAPE="CIRCLE" COORDS="73, 15, 10">

<AREA SHAPE="RECT" COORDS="58, 0, 88, 31" NOHREF>

Scripting Object

AREA

See Also

MAP, IMG


B

Description

The Bold element specifies that the text should be rendered in boldface, where available. The end tag turns off the bold formatting.

Syntax

<B
 CLASS=classname
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
STYLE=css1-properties
TITLE=text
event = script
>

Parameter | Description
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

Both the start and end tags are required.

Example

<B>Displayed in a bold typeface.</B>

Scripting Object

B

See Also

STRONG


BASE

Description

Specifies the document's base URL.

Syntax

<BASE
 HREF=url
TARGET=window_name | _blank | _parent | _self | _top
>

Parameter | Description
HREF=url | Specifies the document's reference URL for associating relative URLs with the proper document path.
TARGET=window_name | _blank | _parent | _self | _top Specifies the window or frame to target the contents at. If no frame or window exists that matches the specified target, a new window is opened for the specified link. If no target is specified, the default is "_self" for a link within the same site or "_top" if the site is external. Special target values are listed below:
_blank | Specifies to load the link into a new unnamed window.
_parent | Specifies to load the link into the immediate parent of the document the link is in.
_self | Specifies to load the link into the same window the link was clicked in.
_top | Specifies to load the link into the full body of the current window.

Remarks

Base is used to ensure that your document's relative links are associated with the proper document path.

This element may only be used within the HEAD tag.

This is an empty element and does not require a closing tag.

Example

<BASE HREF="http://www.sample.com/hello.htm">

Scripting Object

BASE


BASEFONT

Description

Sets a base font value to be used as the default font when rendering text.

Syntax

<BASEFONT
 CLASS=classname
COLOR=color
FACE=font
ID=value
LANG=language
SIZE=n
>

Parameter | Description
CLASS=classname | Class of the tag being defined. This is used to associate a subclassed style sheet with the tag.
COLOR=color | Color to be used by the font or horizontal rule. For a complete list of colors, see the Internet Explorer color table.
FACE=font | Current font typeface.
ID=value | SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underscore character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
SIZE=n | Font size between 1 and 7 (7 is largest).

Remarks

This is an empty element and does not require a closing tag. This element may be used within the BODY tag or the HEAD tag. BASEFONT should appear before any displayed text in the BODY of the document.

Example

<BASEFONT SIZE=3> This sets the base font size to 3.
<FONT SIZE=+4> Now the font size is 7.
<FONT SIZE=-1> Now the font size is 2.

Scripting Object

BASEFONT


BGSOUND

Description

The BGSOUND tag allows you to create pages with background sounds or "soundtracks."

Syntax

<BGSOUND
 BALANCE=n
CLASS=classname
ID=value
LANG=language
LOOP=n
SRC=url
TITLE=text
VOLUME=n
>

Parameter | Description
BALANCE=n | Determines how the available volume will be divided between the left and right speakers. Valid values for this attribute are in the range of -10,000 to +10,000, with 0 being "Wave Output" center balanced.
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LOOP=n | Specifies how many times a sound will loop when activated.
SRC=url | Specifies the URL of a sound to be played.
TITLE=text | Used to provide advisory information.
VOLUME=n | Determines the loudness of a page's background sound. Valid values for this attribute are in the range of -10,000 to 0, with 0 being full "Wave Output" volume.

Remarks

This element may be used within the HEAD tag.

The start tag is required, and the end tag is optional.

Scripting Object

BGSOUND


BIG

Description

Specifies that the enclosed text should be displayed in a relatively bigger font than the current font.

Syntax

<BIG
 CLASS=classname
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
STYLE=css1-properties
TITLE=text
event = script
>

Parameter | Description
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

Both the start and end tags are required.

Example

<BIG>This text is larger.</BIG>

Scripting Object

BIG


BLOCKQUOTE

Description

Sets apart a long quotation in text.

Syntax

<BLOCKQUOTE
 CLASS=classname
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
STYLE=css1-properties
TITLE=text
event = script
>

Parameter | Description
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

This element is a block element.

Both the start and end tags are required.

Example

<P>He said,
<BLOCKQUOTE>"Hi there!"</BLOCKQUOTE>

Scripting Object

BLOCKQUOTE

See Also

Q


BODY

Description

Specifies beginning and end of document body. This element can be used to set the background image, the background color, the link color and the top and left margins of the page. The end tag is required.

Syntax

<BODY
 ALINK=color
BACKGROUND=url
BGCOLOR=color
BGPROPERTIES=FIXED
 BOTTOMMARGIN=pixels
CLASS=classname
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
LEFTMARGIN=pixels
LINK=color
RIGHTMARGIN=pixels
SCROLL=YES|NO
 STYLE=css1-properties
TEXT=color
TITLE=string
TOPMARGIN=n
VLINK=color
event = script
>

Parameter | Description
ALINK=color | The color for the active link. For a complete list of colors, look at the Internet Explorer color table.
BACKGROUND=url | Specifies a background picture. The picture is tiled behind the text and graphics on the page.
BGCOLOR=color | Sets the background color of the page. For a complete list of colors, look at the Internet Explorer color table.
BGPROPERTIES= | Specifies a watermark, which is a background picture that does not scroll.
BOTTOMMARGIN= | Specifies the bottom margin for the entire body of the page and overrides the default margin. If set to "0" or "", the bottom margin will be exactly on the bottom edge of the window or frame.
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
LEFTMARGIN=pixels | Specifies the left margin for the entire body of the page and overrides the default margin. If set to "0" or "", the left margin will be exactly on the left edge of the window or frame.
LINK=color | The color of shortcuts that have not yet been visited. For a complete list of colors, look at the Internet Explorer color table.
RIGHTMARGIN=pixels | Specifies the right margin for the entire body of the page and overrides the default margin. If set to "0" or "", the right margin will be exactly on the right edge of the window or frame.
SCROLL=YES | NO | Turns on or off the scrollbars. The default is YES.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TEXT=color | Sets the color of text on the page. For a complete list of colors, look at the Internet Explorer color table.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
TOPMARGIN=pixels | Specifies the margin for the top of the page and overrides the default margin. If set to "0" or "", the top margin will be exactly on the top edge of the window or frame.
VLINK=color | The color of shortcuts that have already been visited. For a complete list of colors, look at the Internet Explorer color table.
event Can be one or more of these events:
onafterupdate onbeforeunload
onbeforeupdate onclick
ondblclick ondragstart
onhelp onkeydown
onkeypress onkeyup
onload onmousedown
onmousemove onmouseout
onmouseover onmouseup
onrowenter onrowexit
onscroll onselect
onselectstart onunload

Remarks

This element is a block element.

Examples

This is the HTML used to insert the background image of this page.

<BODY BACKGROUND="http://www.microsoft.com/ie/images/watermrk.gif" BGPROPERTIES=FIXED
BGCOLOR=#FFFFFF TEXT=#000000 LINK=#ff6600 VLINK=#330099>

<HTML><BODY>Here's a Web page!</BODY></HTML>

Scripting Object

BODY


BR

Description

Inserts a line break.

Syntax

<BR
 CLASS=classname
CLEAR=ALL |LEFT | RIGHT
 ID=value
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
STYLE=css1-properties
TITLE=text
>

Parameter | Description
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
CLEAR=ALL | LEFT | RIGHT | Inserts vertical space so that the next text displayed will be past left- or right-aligned floating images.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information.

Scripting Object

BR

See Also

WBR


BUTTON

Description

Renders an HTML button, displaying the text between the start and end tags as the label within the button.

Syntax

<BUTTON
 ACCESSKEY=string
CLASS=classname
DATAFLD=colname
DATAFORMATAS=HTML | TEXT
 DATASRC=#ID
DISABLED
 ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
 STYLE=css1-properties
TITLE=text
TYPE=BUTTON | RESET | SUBMIT
 event = script
>

Parameter | Description
ACCESSKEY=key | Specifies an accelerator for the element. Pressing alt-key selects this element in the user's browser.
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
DATAFLD=colname | The column name from the data source object that supplies the bound data.
DATAFORMATAS=HTML | TEXT | Indicates whether bound data is plain text or HTML.
DATASRC=#ID | Indicates the ID of the data source object that supplies the data that is bound to this element.
DISABLED | Used to disable an element. This attribute prevents an element from receiving the focus, and causes the element to appear "grayed out."
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
TYPE=BUTTON | RESET | SUBMIT Defines a button that indicates a default for the ENTER key (with a dark border). The possible values are:
BUTTON | Command button to be used in a script.
RESET | When pressed, this button resets the form's fields to their specified initial values. The label to be displayed on the button may be specified just as for the SUBMIT button.
SUBMIT | Submits the form. The default label is application-specific. If a SUBMIT button is pressed in order to submit the form, and that button has a NAME attribute specified, then that button contributes a name/value pair to the submitted data. Otherwise, a SUBMIT button makes no contribution to the submitted data.
event Can be one or more of these events:
onafterupdate onbeforeupdate
onblur onclick
ondblclick ondragstart
onfocus onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onresize onrowenter
onrowexit onselectstart

Remarks

You should not include the SELECT, BUTTON, INPUT, or A within the BUTTON tag.

This element is a block element.

Both the start and end tags are required.

Scripting Object

BUTTON


CAPTION

Description

Specifies a caption for a TABLE .

Syntax

<CAPTION
 ALIGN=BOTTOM | CENTER | LEFT | RIGHT | TOP
 CLASS=classname
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
 STYLE=css1-properties
TITLE=text
VALIGN=BOTTOM | TOP
 event = script
>

Parameter | Description
ALIGN= BOTTOM | CENTER | LEFT | RIGHT | TOP Specifies the alignment of the caption.
BOTTOM | Aligns the caption bottom center.
CENTER | Centers the caption.
LEFT | Left aligns the caption.
RIGHT | Right aligns the caption.
TOP | Aligns the caption top center.
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
VALIGN=BOTTOM | TOP | Specifies whether the caption appears at the top or bottom.
event Can be one or more of these events:
onafterupdate onbeforeupdate
onblur onchange
onclick ondblclick
ondragstart onfocus
onhelp onkeydown
onkeypress onkeyup
onmousedown onmousemove
onmouseout onmouseover
onmouseup onresize
onrowenter onrowexit
onselect onselectstart

Remarks

This element is a block element.

Both the start and end tags are required.

Example

<TABLE>
<CAPTION VALIGN=BOTTOM>
This caption will appear below the table.
</CAPTION>
<TR>
....
</TR>
</TABLE>

Scripting Object

CAPTION


CENTER

Description

Causes subsequent text and images to be centered. The required end tag returns the alignment to its previous state. This element has the same effect as using the element <DIV ALIGN=CENTER>.

Syntax

<CENTER
 CLASS=classname
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
 STYLE=css1-properties
TITLE=text
event = script
>

Parameter | Description
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

This element is a block element.

Both the start and end tags are required.

Example

<CENTER>This text appears centered on the page.</CENTER>

Scripting Object

CENTER


CITE

Description

Indicates a citation. Refers to a book, paper, or other published source material. The text for citations is rendered in italics.

Syntax

<CITE
 CLASS=classname
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
 STYLE=css1-properties
TITLE=text
event = script
>

Parameter | Description
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

Both the start and end tags are required.

Example

<CITE>Book Title.</CITE>

Scripting Object

CITE

See Also

ACRONYM, ADDRESS, DFN, EM, STRONG


CODE

Description

Specifies a code sample. The text is rendered in a small font.

By default, the font used is fixed-width. If a font face is specified with the FONT or BASEFONT elements preceding CODE, that font is used instead.

Syntax

<CODE
 CLASS=classname
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
 STYLE=css1-properties
TITLE=text
event = script
>

Parameter | Description
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

Both the start and end tags are required.

Example

<CODE>Here is some text in a small, fixed-width font.</CODE>

Scripting Object

CODE

See Also

SAMP


COL

Description

Used to specify column based defaults for the table properties.

Syntax

<COL
 ALIGN=CENTER | LEFT | RIGHT
 CLASS=classname
ID=value
SPAN=n
STYLE=css1-properties
TITLE=text
VALIGN=BASELINE | BOTTOM | MIDDLE | TOP
 WIDTH=n
>

Parameter | Description
ALIGN=CENTER | LEFT | RIGHT | Displays the element left flush, right flush, or centered relative to the display or table.
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
SPAN=n | Specifies how many columns are in the group.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
VALIGN=BASELINE | BOTTOM | MIDDLE | TOP Displays the elements aligned at the top or bottom within the element.
BASELINE | Vertical align to the baseline of the font.
BOTTOM | Vertical align to the bottom of the element.
MIDDLE | Vertical align to the middle of the element.
TOP | Vertical align to the top of the element.
WIDTH=n | Sets the initial width of the element. This attribute may be initially set in pixels or percentages.

Remarks

This element is a block element.

Example

<TABLE>
<COLGROUP>
<COL ALIGN=RIGHT>
<COL ALIGN=LEFT>
<COLGROUP>
<COL ALIGN=CENTER>
<TBODY>
<TR>
<TD>This is the first column in the group and is right-aligned.</TD>
<TD>This is the second column in the group and is left-aligned.</TD>
<TD>This column is in a new group and is centered.</TD>
</TR>
</TABLE>

Scripting Object

COL

See Also

COLGROUP


COLGROUP

Description

Used as a container for a group of columns.

Syntax

<COLGROUP
 ALIGN=CENTER | LEFT | RIGHT
 CLASS=classname
ID=value
SPAN=n
STYLE=css1-properties
TITLE=text
VALIGN=BASELINE | BOTTOM | MIDDLE | TOP
 WIDTH=n
>

Parameter | Description
ALIGN= CENTER | LEFT | RIGHT | Displays the element left flush, right flush, or centered relative to the display or table.
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
SPAN=n | Specifies how many columns are in the group.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information.
VALIGN=BASELINE | BOTTOM | MIDDLE | TOP Displays the elements aligned at the top or bottom within the element.
BASELINE | Vertical align to the baseline of the font.
BOTTOM | Vertical align to the bottom of the element.
MIDDLE | Vertical align to the middle of the element.
TOP | Vertical align to the top of the element.
WIDTH=n | Sets the initial width of the element. This attribute may be initially set in pixels or percentages.

Remarks

End tags are optional.

Example

<TABLE>
<COLGROUP ALIGN=RIGHT>
<COLGROUP SPAN=2 ALIGN=LEFT>
<TBODY>
<TR>
<TD>This column is in the first group and is right-aligned.</TD>
<TD>This column is in the second group and is left-aligned.</TD>
<TD>This column is in the second group and is left-aligned.</TD>
</TR>
</TABLE>

Scripting Object

COLGROUP

See Also

COL


COMMENT

Description

This element is no longer recommended. Indicates a comment that will not be displayed. This element is provided for backward compatibility. When authoring documents, use the <!-- --> comment element for comments instead.

Syntax

<COMMENT
 ID=value
LANG=language
TITLE=text
>

Parameter | Description
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
TITLE= | Used to provide advisory information.

Remarks

Both the start and end tags are required.

Scripting Object

COMMENT

See Also

!-- --


DD

Description

The definition in a definition list. Usually indented from the definition list, and displayed in the right-hand column of a definition list.

Syntax

<DD
 CLASS=classname
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
 STYLE=css1-properties
TITLE=text
event = script
>

Parameter | Description
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

This element is a block element.

The start tag is required, and the end tag is optional.

Example

<DL><DT>Cat<DD>A small domesticated mammal.
<DT>Lizard<DD>A reptile generally found in dry areas.</DL>

Scripting Object

DD

See Also

DL, DT


DEL

Description

Indicates text that has been deleted from the document.

Syntax

<DEL
 CLASS=classname
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
 STYLE=css1-properties
TITLE=text
event = script
>

Parameter | Description
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

Both the start and end tags are required.

Example

<DEL>This text has been revised.</DEL>

Scripting Object

DEL

See Also

INS


DFN

Description

Indicates the defining instance of a term. Formats a term for its first appearance in a document.

Syntax

<DFN
 CLASS=classname
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
 STYLE=css1-properties
TITLE=text
event = script
>

Parameter | Description
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

This element is a block element.

Both the start and end tags are required.

Example

<DFN>HTML stands for hypertext markup language.</DFN>

Scripting Object

DFN

See Also

ACRONYM, ADDRESS, CITE, STRONG


DIR

Description

Denotes a directory list. The following text is a directory list that consists of individual items, each beginning with an LI element and none containing more than 20 characters.

Syntax

<DIR
 CLASS=classname
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
 STYLE=css1-properties
TITLE=text
event = script
>

Parameter | Description
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

This element is a block element.

Both the start and end tags are required.

Example

<DIR><LI>Art
<LI>History
<LI>Literature
<LI>Sports
<LI>Entertainment
<LI>Science
</DIR>

Scripting Object

DIR


DIV

Description

The DIV element is used to represent different kinds of containers in a document such as chapter, section, abstract, appendix, etc.

Syntax

<DIV
 ALIGN=CENTER | LEFT | RIGHT
 CLASS=classname
DATAFLD=colname
DATAFORMATAS=HTML | TEXT
 DATASRC=#ID
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
STYLE=css1-properties
TITLE=text

event = script
>

Parameter | Description
ALIGN=CENTER | LEFT | RIGHT | Displays the element left flush, right flush, or centered relative to the display or table.
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
DATAFLD=colname | The column name from the data source object that supplies the bound data.
DATAFORMATAS=HTML | TEXT | Indicates whether bound data is plain text or HTML.
DATASRC=#ID | Indicates the ID of the data source object that supplies the data that is bound to this element.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
event Can be one or more of these events:
onafterupdate onbeforeupdate
onblur onclick
ondblclick ondragstart
onfocus onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onresize onrowenter
onrowexit onscroll
onselectstart

Remarks

This element is a block element.

Both the start and end tags are required.

Example

<DIV>
This text represents a section.
</DIV>

<DIV ALIGN=CENTER>
This text represents another section, and its text is centered.
</DIV>

Scripting Object

DIV


DL

Description

Denotes a definition list. The text is formatted as a list of terms on the left and their definitions indented below. The DT and DD elements can be used to define the elements within a directory list.

Syntax

<DL
 CLASS=classname
COMPACT
 ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
 STYLE=css1-properties
TITLE=text
event = script
>

Parameter | Description
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
COMPACT | Specifies that the list should be compacted to remove extra space between list elements.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onmousedown onmousemove
onmouseout onmouseover
onmouseup onselectstart

Remarks

This element is a block element.

Both the start and end tags are required.

Example

<DL>
<DT>Cat
<DD> A small domesticated mammal.
<DT>Lizard
<DD>A reptile generally found in dry areas.
</DL>

Scripting Object

DL

See Also

DD, DT


!DOCTYPE

Description

Specifies the HTML DTD that the document corresponds to.

Syntax

<!DOCTYPE>

Remarks

Different versions can be used depending on the level of compatibility the author wishes to indicate. In the examples below, the first indicates compatibility with the HTML 3.2 DTD; the second indicates a strict adherence to the HTML 4.0 DTD.

Examples

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Strict//EN">


DT

Description

A definition term within a definition list. The text is a term to be defined, and should be displayed in the left-hand column of a definition list. The corresponding definition should be indicated with the DD element.

Syntax

<DT
 CLASS=classname
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
 STYLE=css1-properties
TITLE=text
event = script
>

Parameter | Description
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

This element is a block element.

The start tag is required, and the end tag is optional.

Example

<DL>
<DT>Cat
<DD> A small domesticated mammal.
<DT>Lizard
<DD>A reptile generally found in dry areas.
</DL>

Scripting Object

DT

See Also

DD, DL


HTML Elements

<!-- --> !DOCTYPE A ACRONYM ADDRESS APPLET
AREA B BASE BASEFONT BGSOUND BIG
BLOCKQUOTE BODY BR BUTTON CAPTION CENTER
CITE CODE COL COLGROUP COMMENT DD
DEL DFN DIR DIV DL DT
EM EMBED FIELDSET FONT FORM FRAME
FRAMESET HEAD H1 H2 H3 H4
H5 H6 HR HTML I IFRAME
IMG INPUT INS ISINDEX KBD LABEL
LEGEND LI LINK LISTING MAP MARQUEE
MENU META NOBR NOFRAMES NOSCRIPT OBJECT
OL OPTION P PARAM PLAINTEXT PRE
Q S SAMP SCRIPT SELECT SMALL
SPAN STRIKE STRONG STYLE SUB SUP
TABLE TBODY TD TEXTAREA TFOOT
TH THEAD TITLE TR TT U
UL VAR WBR XMP

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


EM

Description

Used to emphasize text. Usually renders text in italics.

Syntax

<EM
 CLASS=classname
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
 STYLE=css1-properties
TITLE=text
event = script
>

Parameter | Description
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

Both the start and end tags are required.

Example

<EM>This text is emphasized, often shown in italics.</EM>

Scripting Object

EM

See Also

ACRONYM, ADDRESS, CITE, STRONG


EMBED

Description

Allows you to embed documents of any type. The user needs to have an application which can view the data installed correctly on their machine.

Syntax

<EMBED
 ALIGN=ABSBOTTOM | ABSMIDDLE | BASELINE | BOTTOM | LEFT | MIDDLE | RIGHT | TEXTTOP | TOP
 ALT=text
CLASS=classname
CODE=filename
CODEBASE=url
HEIGHT=n
HSPACE=n
ID=value
NAME=name
SRC=url
STYLE=css1-properties
TITLE=text
UNITS=value
VSPACE=n
WIDTH=n

>

Parameter | Description
ALIGN=ABSBOTTOM | ABSMIDDLE | BASELINE | BOTTOM | LEFT | MIDDLE | RIGHT | TEXTTOP | TOP | Specifies the alignment for the control-like element.
ALT=text | Optional text as an alternative to the application if it cannot be executed.
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
CODE=filename | The name of the file containing the compiled Java class.
CODEBASE=url | This is an optional parameter that specifies the base URL for the application.
HEIGHT=n | Along with WIDTH, specifies the size at which the element is drawn. This attribute may be initially set in pixels or percentages.
HSPACE=n | Along with VSPACE=, specifies margins for the element.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID names must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created and can only be referenced by ordinal position.
NAME=name | Specifies the name of the application.
SRC=url | Specifies a URL for the associated file.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
UNITS=value | Defines the units for the height and width of the EMBED element, expressed as pixels (px) or ems (em).
VSPACE=n | Along with HSPACE=, specifies margins for the element.
WIDTH=n | Along with HEIGHT, specifies the size at which the element is drawn. This attribute may be initially set in pixels or percentages.

Remarks

This element is a block element.

Both the start and end tags are required.

Scripting Object

EMBED

See Also

APPLET, OBJECT, PARAM


FIELDSET

Description

The FIELDSET element is similar to the DIV element but is for the specific purpose of grouping related fields. It is a container and it is nestable. It can contain a single LEGEND that must immediately follow the FIELDSET tag. The legend is used to identify the contained set of fields. This is especially useful to speech-based browsers which can then provide users with a way to move from group to group. This element renders as a box around the group and transposes the legend over the upper-left or lower-left portion of the box depending upon the ALIGN= attribute value on the LEGEND element. The legend element must be the first element within the field set. If it is not, the legend text cannot be rendered as part of the FIELDSET border.

Syntax

<FIELDSET
 ALIGN= LEFT | CENTER | RIGHT
 CLASS=classname
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
STYLE=css1-properties
TITLE=text
event = script
>

Parameter | Description
ALIGN=LEFT | CENTER | RIGHT | Displays the element left flush, right flush, or centered, relative to the display or table.
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID names must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created and can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE= | Specifies an in-line style sheet for the tag.
TITLE= | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
event Can be one or more of these events:
onblur onchange
onclick ondblclick
ondragstart onfilterchange
onfocus onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onresize onscroll
onselect onselectstart

Remarks

Both the start and end tags are required.

Scripting Object

FIELDSET

See Also

CAPTION, LEGEND


FONT

Description

Specifies a new font face, size, and color to be used for rendering the enclosed text.

Syntax

<FONT
 CLASS=classname
COLOR=color
FACE=font
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
SIZE=n
STYLE=css1-properties
TITLE=text
event = script
>

Parameter | Description
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
COLOR=color | Set the color to be used by the font or horizontal rule. For a complete list of colors, look at the Internet Explorer color table.
FACE=font | Sets the current font typeface.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
SIZE=n | Specifies font size between 1 and 7 (7 is largest).
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

Both the start and end tags are required.

Scripting Object

FONT


FORM

Description

Specifies that the contained controls take part in a form.

Syntax

<FORM
 ACTION=url
CLASS=classname
ENCTYPE=encoding
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
METHOD=GET | POST
 NAME=name
STYLE=css1-properties
TARGET=window_name | _blank | _parent | _self | _top
TITLE=text
event = script
>

Parameter | Description
ACTION=url | Specifies the address to be used to carry out the action of the form. If none is specified, the base URL of the document is used.
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ENCTYPE=encoding | Specifies the format of the data being submitted by the form.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
METHOD=GET | POST | Indicates how the form data should be sent to the server; either GET or POST
NAME=name | Specifies the name of the control, bookmark, or application.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TARGET=window_name | _blank | _parent | _self | _top Specifies the window or frame to target the contents at. If no frame or window exists that matches the specified target, a new window is opened for the specified link. If no target is specified, the default is "_self" for a link within the same site or "_top" if the site is external. Special target values are listed below:
_blank | Specifies to load the link into a new unnamed window.
_parent | Specifies to load the link into the immediate parent of the document the link is in.
_self | Specifies to load the link into the same window the link was clicked in.
_top | Specifies to load the link into the full body of the current window.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onreset onselectstart
onsubmit

Remarks

When programming the form, all control-like elements are added to the form as named items. In addition, these items are exposed through the Item method on the form.

This element is a block element.

Both the start and end tags are required.

Example

<FORM TARGET="viewer" ACTION="http://www.sample.com/bin/search">
...
</FORM>

Scripting Object

FORM


FRAME

Description

Specifies an individual frame within a FRAMESET .

Syntax

<FRAME
 BORDERCOLOR=color
CLASS=classname
DATAFLD=colname
DATASRC=#ID
FRAMEBORDER=NO | YES | 0 | 1
 HEIGHT=n
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
MARGINHEIGHT=pixels
MARGINWIDTH=pixels
NAME=window_name | _blank | _parent | _self | _top
NORESIZE=NORESIZE | RESIZE
 SCROLLING=AUTO | NO | YES
 SRC=url
TITLE=text
WIDTH=n
event = script
>

Parameter | Description
BORDERCOLOR=color | Sets border color and must be used with the BORDER attribute, except for frames. For a complete list of colors, look at the Internet Explorer color table.
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
DATAFLD=colname | The column name from the data source object that supplies the bound data.
DATASRC=#ID | Indicates the ID of the data source object that supplies the data that is bound to this element.
FRAMEBORDER=NO | YES | 0 | 1 | Specifies whether or not to display a border for the frame.
HEIGHT=n | Along with WIDTH, specifies the size at which the element is drawn. This attribute may be initially set in pixels or percentages.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
MARGINHEIGHT=pixels | Sets the amount of top and bottom margin should be set before displaying the text in a frame.
MARGINWIDTH=pixels | Sets the amount of left and right margin should be set before displaying the text in a frame.
NAME=window_name | _blank | _parent | _self | _top Specifies the window or frame to target the contents at. If no frame or window exists that matches the specified target, a new window is opened for the specified link. If no target is specified, the default is "_self" for a link within the same site or "_top" if the site is external. Special target values are listed below:
_blank | Specifies to load the link into a new unnamed window.
_parent | Specifies to load the link into the immediate parent of the document the link is in.
_self | Specifies to load the link into the same window the link was clicked in.
_top | Specifies to load the link into the full body of the current window.
NORESIZE | When this attribute is supplied, the frame is not resizable by the user. The default behavior allows the user to resize the frame.
SCROLLING=AUTO | NO | YES | Specifies that the frame can be scrolled. If set to "AUTO," the browser determines whether scrollbars are necessary.
SRC=url | Specifies a URL for the associated file.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
WIDTH=n | Along with HEIGHT, sets the initial size of the element. This attribute may be initially set in pixels or percentages.
event Can be this event:
onreadystatechange

Remarks

This element is a block element.

Example

<FRAME FRAMEBORDER=0 SCROLLING=NO SRC="sample.htm">

Scripting Object

FRAME

See Also

FRAMESET, NOFRAMES


FRAMESET

Description

Sets the number and size of vertical and horizontal frames for a compound document. Use the FRAME element within FRAMESET to define the content and properties of the individual frames. You can also nest FRAMESET elements to create frames within a frame.

Syntax

<FRAMESET
 BORDER=pixels
BORDERCOLOR=color

CLASS=classname
COLS=col-widths
FRAMEBORDER=NO | YES | 0 | 1
FRAMESPACING=spacing
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
ROWS=row-heights
TITLE=text
>

Parameter | Description
BORDER=pixels | Defines the space between the frames in pixels, including the 3D border. For nested FRAMESETS, the border can only be defined for the top-level FRAMESET element.
BORDERCOLOR=color | Sets border color and must be used with the BORDER attribute, except for frames. For a complete list of colors, look at the Internet Explorer color table.
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
COLS=col-widths | A comma delimited list of frames to create. Each item in the list contains the initial size of the column. You can specify the column dimensions by percentage (%), pixels, or a relative size (*)
FRAMEBORDER=NO | YES | 0 | 1 | Specifies whether or not to display a border for the frame. "YES" or 1 causes a border to be displayed (default). "NO" or 0 displays no border.
FRAMESPACING=spacing | Creates additional space between the frames in pixels.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
ROWS=row-heights | A comma delimited list of frames to create. Each item in the list contains the initial size of the row. You can specify the row dimensions by percentage (%), pixels, or a relative size (*).
TITLE=text | Used to provide advisory information.

Remarks

A frameset organizes multiple frames on the screen. Only frames, nested FRAMESETelements, and the NOFRAMES tag are valid within a frameset.

This element is a block element.

Both the start and end tags are required.

Example

<FRAMESET COLS="25%, 50%, *">
<FRAME SRC="contents.htm">
<FRAME SRC="info.htm">
<FRAME SCROLLING=NO SRC="graphic.htm">
</FRAMESET>

Scripting Object

FRAMESET

See Also

FRAME, NOFRAMES


HEAD

Description

An unordered collection of information that marks the document heading.

Syntax

<HEAD
 CLASS=classname
ID=value
TITLE=text
>

Parameter | Description
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.

Remarks

The HEAD provides information that does not effect the rendering of the document, but may be of use to the browser. The HEAD falls before the BODY of the document is specified. The following tags are valid in the HEAD block:

  • BASE
  • LINK
  • TITLE
  • META
  • BASEFONT
  • BGSOUND

The TITLE tag is the only information that is required as part of a HEAD block.

Example

<HEAD>
<TITLE>A Simple Document</TITLE>
</HEAD>

Scripting Object

HEAD


Hn

Description

Renders text in heading style. Use H1 through H6 to specify different sizes and styles of headings. The end tag is required to restore the formatting to normal.

Syntax

<Hn
 ALIGN=CENTER | LEFT | RIGHT
 CLASS=classname
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
STYLE=css1-properties
TITLE=text
event = script
>

Parameter | Description
n | Sets the heading level. This is an integer from 1 to 6.
ALIGN= | Displays the element left flush, right flush, or centered relative to the display or table.
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

This element is a block element.

Both the start and end tags are required.

Example

<H1>Welcome to Internet Explorer!</H1>

Scripting Objects

H1 H2 H3
H4 H5 H6

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


HR

Description

Draws a horizontal rule.

Syntax

<HR
 ALIGN=CENTER | LEFT | RIGHT
 CLASS=classname
COLOR=color
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
NOSHADE
SIZE=n
STYLE=css1-properties
TITLE=text
WIDTH=n
event = script
>

Parameter | Description
ALIGN=CENTER | LEFT | RIGHT | Displays the element left flush, right flush, or centered relative to the display or table.
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
COLOR=color | Set the color to be used by the font or horizontal rule. For a complete list of colors, look at the Internet Explorer color table.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
NOSHADE | Draws the horizontal rule without 3-D shading.
SIZE=n | Sets the height of the <HR > element in pixels.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
WIDTH=n | Sets the initial width of the element. This attribute may be initially set in pixels or percentages.
event Can be one or more of these events:
onbeforeupdate onblur
onclick ondblclick
ondragstart onfocus
onhelp onkeydown
onkeypress onkeyup
onmousedown onmousemove
onmouseout onmouseover
onmouseup onresize
onrowenter onrowexit
onselectstart

Remarks

This element is a block element.

Scripting Object

HR


HTML

Description

This element identifies the document as containing HTML elements. The begin tag typically appears after the !DOCTYPE element. The end tag comes after all HTML elements in the document.

Syntax

<HTML
 TITLE=text
>

Parameter | Description
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
TITLE= | Used to provide advisory information.

Remarks

Example

<HTML>
<BODY>
<P>This is an HTML document.
</BODY>
</HTML>

Scripting Object

HTML


!-- --

Description

Comments are ignored by the HTML parser. Text between the beginning of the comment <!-- and the end tag --> is not displayed in the browser window.

Syntax

<!-- -->

Remarks

Comments can contain other HTML elements. Comments do not nest.

Both the start and end tags are required.

See Also

COMMENT


I

Description

The Italic element specifies that the text should be rendered in italic font, where available.

Syntax

<I
 CLASS=classname
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
STYLE=css1-properties
TITLE=text
event = script
>

Parameter | Description
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

Both the start and end tags are required.

Example

<I>This text will be in italic.</I>

Scripting Object

I

See Also

ADDRESS, CITE, DFN, EM


IFRAME

Description

Used to create in-line floating frames.

Syntax

<IFRAME
 ALIGN=ABSBOTTOM | ABSMIDDLE | BASELINE | BOTTOM | LEFT | MIDDLE | RIGHT | TEXTTOP | TOP
 BORDER=pixels
BORDERCOLOR=color
CLASS=classname
DATAFLD=colname
DATASRC=#ID
FRAMEBORDER=NO | YES | 0 | 1
 FRAMESPACING=pixels
HEIGHT=n
HSPACE=pixels
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
MARGINHEIGHT=pixels
MARGINWIDTH=pixels
NAME=window_name | _blank | _parent | _self | _top
 NORESIZE=NORESIZE | RESIZE
 SCROLLING=AUTO | NO | YES
 SRC=url
STYLE=css1-properties
TITLE=text
VSPACE=pixels
WIDTH=n
>

Parameter | Description
ALIGN=ABSBOTTOM | ABSMIDDLE | BASELINE | BOTTOM | LEFT | MIDDLE | RIGHT | TEXTTOP | TOP | Specifies the alignment for the control-like element.
BORDER=pixels | Specifies the thickness of a border to be drawn around the element. The default is 0.
BORDERCOLOR=color | Sets border color and must be used with the BORDER attribute, except for frames. For a complete list of colors, look at the Internet Explorer color table.
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
DATAFLD=colname | The column name from the data source object that supplies the bound data.
DATASRC=#ID | Indicates the ID of the data source object that supplies the data that is bound to this element.
FRAMEBORDER=NO | YES | 0 | 1 | Specifies whether or not to display a 3-D border around the frame. "YES" or 1 causes a border to be displayed (default). "NO" or 0 displays no border.
FRAMESPACING=pixels | Creates additional space between the frames.
HEIGHT=n | Along with WIDTH, specifies the size at which the element is drawn. This attribute may be initially set in pixels or percentages.
HSPACE=pixels | Along with VSPACE, specifies margins for the element.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
MARGINHEIGHT=pixels | Sets the amount of top and bottom margin should be set before displaying the text in a frame.
MARGINWIDTH=pixels | Sets the amount of left and right margin should be set before displaying the text in a frame.
NAME=window_name | _blank | _parent | _self | _top Specifies the window or frame to target the contents at. If no frame or window exists that matches the specified target, a new window is opened for the specified link. If no target is specified, the default is "_self" for a link within the same site or "_top" if the site is external. Special target values are listed below:
_blank | Specifies to load the link into a new unnamed window.
_parent | Specifies to load the link into the immediate parent of the document the link is in.
_self | Specifies to load the link into the same window the link was clicked in.
_top | Specifies to load the link into the full body of the current window.
NORESIZE | When this attribute is supplied, the frame is not resizable by the user. The default behavior allows the user to resize the frame.
SCROLLING=AUTO | NO | YES | Specifies that the frame can be scrolled. If set to "AUTO," the browser determines whether scrollbars are necessary (default).
SRC=url | Specifies a URL for the associated file to be displayed in the frame.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information.
VSPACE=pixels | Along with HSPACE, specifies margins for the element.
WIDTH=n | Along with HEIGHT, sets the initial size of the element. This attribute may be initially set in pixels or percentages.

Remarks

This element is a block element.

Both the start and end tags are required.

Example

<IFRAME FRAMEBORDER=0 SCROLLING=NO SRC="sample.htm"></IFRAME>

Scripting Object

IFRAME


IMG

Description

Embeds an image or a video clip in the document.

Syntax

<IMG
 ALIGN=ABSBOTTOM | ABSMIDDLE | BASELINE | BOTTOM | LEFT | MIDDLE | RIGHT | TEXTTOP | TOP
 ALT=text
BORDER=n
CLASS=classname
DATAFLD=colname
DATASRC=#ID
DYNSRC=url
HEIGHT=n
HSPACE=n
ID=value
ISMAP
 LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
LOOP=n
LOWSRC=url
NAME=name
SRC=url
STYLE=css1-properties
TITLE=text
USEMAP=url
VSPACE=n
WIDTH=n
event = script
>

Parameter | Description
ALIGN=ABSBOTTOM | ABSMIDDLE | BASELINE | BOTTOM | LEFT | MIDDLE | RIGHT | TEXTTOP | TOP | Specifies the alignment for the image.
ALT=text | Optional text as an alternative to the graphic for rendering in non-graphical environments. Alternate text should be provided whenever the graphic is not rendered. Alternate text is mandatory for Level 0 documents.
BORDER=n | Specifies the thickness of a border to be drawn around the element.
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
DATAFLD=colname | The column name from the data source object that supplies the bound data.
DATASRC=#ID | Indicates the ID of the data source object that supplies the data that is bound to this element.
DYNSRC=url | Specifies the address of a video clip or VRML world to be displayed in the window. Stands for Dynamic Source.
HEIGHT=n | Along with WIDTH, specifies the size at which the element is drawn. This attribute may be initially set in pixels or percentages.
HSPACE=n | Along with VSPACE, specifies margins for the element.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
ISMAP | Identifies the picture as a server-side image map. Image maps allow users to access other documents by clicking different areas in an image. Server-side image maps require a script or other service on the server to process click information. When the user clicks on the image, the server receives the coordinates of the user's click along with the URL of the map. Internet Explorer appends a "?" and a comma-separated pair of x-y coordinates to the HREF attribute in the A element. For further information regarding server-side maps and the content of the map file, check your HTTP server documentation.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
LOOP=n | Specifies how many times a sound or video will loop when activated. Also specifies how many times the marquee should loop.
LOWSRC=url | Specifies a lower resolution image to display.
NAME=name | Specifies the name of the control.
SRC=url | Specifies a URL for the associated file.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
USEMAP=url | Identifies the picture as a client-side image map and specifies a MAP to use for responding to the user's clicks. Use the MAP and AREA elements to create the client-side mapping information.
VSPACE=n | Along with HSPACE, specifies margins for the element.
WIDTH=n | Along with HEIGHT, sets the initial size of the element. This attribute may be initially set in pixels or percentages.
event Can be one or more of these events:
onabort onafterupdate
onbeforeupdate onblur
onclick ondblclick
ondragstart onerror
onfocus onhelp
onkeydown onkeypress
onkeyup onload
onmousedown onmousemove
onmouseout onmouseover
onmouseup onresize
onrowenter onrowexit
onselectstart

Example

<IMG SRC=mygraphic.bmp>

Scripting Object

IMG

See Also

AREA, INPUT, MAP


INPUT

Description

Specifies a form input control.

Syntax

<INPUT
ACCESSKEY=key
ALIGN=LEFT | CENTER | RIGHT
ALT=text
CLASS=classname
DISABLED
DYNSRC=url
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
LOWSRC=url
MAXLENGTH=n
NAME=name
READONLY
SIZE=n
SRC=url
STYLE=css1-properties
TABINDEX=n
TITLE=text
TYPE=BUTTON | CHECKBOX | FILE | HIDDEN | IMAGE | PASSWORD | RADIO | RESET | SUBMIT | TEXT
VALUE=value
event = script
>

Parameter | Description
ACCESSKEY=key | Specifies an accelerator for the element. Pressing alt-key selects this element in the user's browser. This attribute applies to the BUTTON, CHECKBOX, FILE, PASSWORD, RADIO, RESET, SUBMIT, and TEXT input types.
ALIGN=LEFT | CENTER | RIGHT | Displays the element left flush, right flush, or centered relative to the display or table when TYPE=IMAGE..
ALT=text | When TYPE=IMAGE, optional text as an alternative to the graphic for rendering in non-graphical environments. Alternate text should be provided whenever the graphic is not rendered. Alternate text is mandatory for Level 0 documents.
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
DISABLED | Used to disable an element. This attribute prevents an element from receiving the focus, and causes the element to appear "grayed out."
DYNSRC=url | Specifies the address of a video clip or VRML world to be displayed in the window. Stands for Dynamic Source. Applies to type=image only.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
LOWSRC=url | Specifies a lower resolution image to display. Applies to type=image only.
MAXLENGTH=n | Indicates the maximum number of characters that can be entered into a text control. This attribute applies to the PASSWORD and TEXT input types.
NAME=name | Specifies the name of the control, bookmark, or application.
READONLY | Causes the element's contents to be read only. The INPUT element can still receive the focus. This attribute applies to the PASSWORD and TEXT input types.
SIZE=n | Specifies the size of the control.
SRC=url | Specifies a URL for the associated file. This attribute applies to the IMAGE type.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TABINDEX=n | Sets the tab order position for the object. This attribute applies to the BUTTON, CHECKBOX, FILE, PASSWORD, RADIO, RESET, SUBMIT, and TEXT input types.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
TYPE=BUTTON | CHECKBOX | FILE | HIDDEN | IMAGE | PASSWORD | RADIO | RESET | SUBMIT | TEXT Specifies the type of intrinsic control. The default is TEXT.
BUTTON | A button on the HTML form.
CHECKBOX | Used for simple Boolean attributes or for attributes that can take multiple values at the same time. It is represented by a number of check box fields, each of which has the same name. Each selected check box generates a separate name/value pair in the submitted data, even if this results in duplicate names. The default value for check boxes is on.
FILE | A file upload element that allows the user to supply a file as the input.
HIDDEN | No field is presented to the user, but the content of the field is sent with the submitted form. This value can be used to transmit state information about client/server interaction.
IMAGE | An image field that you can click, causing the form to be immediately submitted. The coordinates of the selected point are measured in pixel units from the upper-left corner of the image, and are returned (along with the other contents of the form) in two name/value pairs. The x-coordinate is submitted under the name of the field with ".x" appended, and the y-coordinate is submitted under the name of the field with ".y" appended. Any VALUE= attribute is ignored. The image itself is specified by the SRC= attribute, exactly as for the IMG element.
PASSWORD | The same as the TEXT input type, except that text is not displayed as the user enters it.
RADIO | Used for attributes that accept a single value from a set of alternatives. Each radio-button field in the group should be given the same name. Only the selected radio button in the group generates a name/value pair in the submitted data. Radio buttons require an explicit VALUE= attribute.
RESET | When pressed, this button resets the form's fields to their specified initial values. The label to be displayed on the button may be specified just as for the SUBMIT button.
SUBMIT | Submits the form. The default label is application-specific. If a SUBMIT button is pressed in order to submit the form, and that button has a NAME attribute specified, then that button contributes a name/value pair to the submitted data. Otherwise, a SUBMIT button makes no contribution to the submitted data.
TEXT | Used for a single-line text-entry field. Use in conjunction with the SIZE= and MAXLENGTH= attributes.
VALUE=value | For textual/numerical controls, specifies the default value of the control. For Boolean controls, specifies the value to be returned when the control is turned on. This attribute applies to the BUTTON, CHECKBOX, HIDDEN, PASSWORD, RADIO, RESET, SUBMIT, and TEXT input types.
event Can be one or more of these events:
onafterupdate onbeforeupdate
onblur onchange
onclick ondblclick
ondragstart onfocus
onhelp onkeydown
onkeypress onkeyup
onmousedown onmousemove
onmouseout onmouseover
onmouseup onselect
onselectstart

Remarks

Objects can be submitted in forms. The NAME is the identifier of the object tag (i.e., <OBJECT NAME=slider CLASSID=...>), and the VALUE is obtained by getting the value of the default property of the control. If any of the following conditions occur, then the object will not become part of the submit string:
Object did not instantiate
Object does not have an identifier
Object does not have a default property to get
Default property cannot be coerced into a string

Example

<FORM ACTION="http://intranet/survey" METHOD=POST>
<P>Name
<BR><INPUT NAME="CONTROL1" TYPE=TEXT VALUE="Your Name">
<P>Password
<BR><INPUT TYPE="PASSWORD" NAME="CONTROL2">
<P>Color
<BR><INPUT TYPE="RADIO" NAME="CONTROL3" VALUE="0" CHECKED>Red
<INPUT TYPE="RADIO" NAME="CONTROL3" VALUE="1">Green
<INPUT TYPE="RADIO" NAME="CONTROL3" VALUE="2">Blue
<P>Comments
<BR><INPUT TYPE="TEXT" NAME="CONTROL4" SIZE="20,5" MAXLENGTH="250">
<P><INPUT NAME="CONTROL5" TYPE=CHECKBOX CHECKED>Send receipt
<P><INPUT TYPE="SUBMIT" VALUE="OK"><INPUT TYPE="RESET" VALUE="Reset">
</FORM>

Scripting Object

INPUT

See Also

TEXT, BUTTON, IMG, TEXTAREA, OBJECT


INS

Description

Indicates text that has been added to the document.

Syntax

<INS
 CLASS=classname
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
 STYLE=css1-properties
TITLE=text
event = script
>

Parameter | Description
CLASS=classname | Class of the tag being defined. This is used to associate a subclassed style sheet with the tag.
ID=value | SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underscore character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The script is written in JScript.
VBS, VBSCRIPT | The script is written in VBScript.
STYLE=css1-properties | Inline style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a tooltip during the onmouseover event.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup

Remarks

Both the start and end tags are required.

Example

<INS datetime="1997-10-01T12:15:30-05:00">This text has been revised.</INS>

Scripting Object

INS

See Also

DEL


ISINDEX

Description

Causes the browser to prompt the user for a single line of input with a dialog window.

Syntax

<ISINDEX
 CLASS=classname
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
STYLE=css1-properties
PROMPT=text
>

Parameter | Description
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
PROMPT=text | Specifies a text prompt message for the input field.

Remarks

With HTML 4 this element will be deprecated, with INPUT recommended for use instead.


KBD

Description

Indicates text to be entered at the keyboard. Renders text in bold with a fixed-width font.

Syntax

<KBD
 CLASS=classname
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
STYLE=css1-properties
TITLE=text
event = script
>

Parameter | Description
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

Both the start and end tags are required.

Example

<KBD>The user should enter this text.</KBD>

Scripting Object

KBD


LABEL

Description

Specifies a label for a control-like element. The content between the start and end tags defines the label text.

Syntax

<LABEL
 ACCESSKEY=key
CLASS=classname
DATAFLD=colname
DATAFORMATAS=HTML | TEXT
 DATASRC=#ID
FOR=ID
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
STYLE=css1-properties
TITLE=text
event = script
>

Parameter | Description
ACCESSKEY=key | Specifies an accelerator for the element. Pressing alt-key selects this element in the user's browser.
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
DATAFLD=colname | The column name from the data source object that supplies the bound data.
DATAFORMATAS=HTML | TEXT | Indicates whether bound data is plain text or HTML.
DATASRC=#ID | Indicates the ID of the data source object that supplies the data that is bound to this element.
FOR=ID | Specifies the ID for the control-like element the label is for. This is optional when the label is wrapped around the control the label applies to.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

Labels cannot be nested.

Both the start and end tags are required.

Scripting Object

LABEL


LEGEND

Description

Identifies a contained set of fields defined in the FIELDSET element. The LEGEND element must be the first element within the FIELDSET element.

Syntax

<LEGEND
 ALIGN=BOTTOM | CENTER | LEFT | RIGHT | TOP
 CLASS=classname
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
 STYLE=css1-properties
TITLE=text
VALIGN=BOTTOM | TOP
 event = script
>

Parameter | Description
ALIGN= BOTTOM | CENTER | LEFT | RIGHT | TOP Specifies the alignment of the legend text.
BOTTOM | Aligns the legend text bottom center.
CENTER | Centers the legend text.
LEFT | Left aligns the legend text.
RIGHT | Right aligns the legend text.
TOP | Aligns the legend text top center.
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
VALIGN=BOTTOM | TOP | Specifies whether the legend text appears at the top or bottom.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup

Remarks

This element is a block element.

Both the start and end tags are required.

Scripting Object

LEGEND


LI

Description

Denotes one item of a list. This element is used inside a DIR, MENU, OL, or UL block.

Syntax

<LI
 CLASS=classname
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
STYLE=css1-properties
TITLE=text
TYPE=1 | a | A | i | I
 VALUE=value
event = script
>

Parameter | Description
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
TYPE=1 | a | A | i | I Changes the style of the list.
1 | List items are numbered.
a | List items are labeled with lowercase letters.
A | List items are labeled with uppercase letters.
i | List items are labeled with lowercase roman numerals.
I | List items are labeled with uppercase roman numerals.
VALUE=value | Changes the count of ordered lists as they progress.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

This element is a block element.

The start tag is required, and the end tag is optional.

Example

<DIR> <LI>Art
<LI>History
<LI>Literature
<LI>Sports
<LI>Entertainment
<LI>Science</DIR>

Scripting Object

LI

See Also

DIR, MENU, OL, UL


LINK

Description

Used to specify a typed hyperlink between the document and some other resource.

Syntax

<LINK
 DISABLED
 HREF=url
ID=value
MEDIA=SCREEN | PRINT | ALL
 REL=STYLESHEET
 TITLE=text
TYPE="text/css"
>

Parameter | Description
DISABLED | Used to disable an element. This attribute prevents an element from receiving the focus, and causes the element to appear "grayed out."
HREF=url | Specifies the destination URL or anchor point.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
MEDIA= SCREEN | PRINT | ALL Describes the output device for the document. A value of "PRINT" does not affect the on-screen layout. Default value is ALL.
SCREEN | Output is intended for non-paged computer screens.
PRINT | Output is intended for paged, opaque material and for documents on screen viewed in print preview mode.
ALL | Applies to all devices.
REL=STYLESHEET | The REL attribute gives the relationship(s) described by the hypertext link from the anchor to the target. Values and their semantics will be registered by the HTML registration authority. The default relationship if none other is given is void. The REL attribute is only used when the HREF= attribute is present.
TITLE=text | Used to provide advisory information.
TYPE="text/css" | Indicates the type of style sheet.

Remarks

This element may only be used within the HEAD tag.

Example

<LINK REL=stylesheet HREF="styles.css" TYPE="text/css">

Scripting Object

LINK


LISTING

Description

This element is no longer recommended and should not be used in new documents. LISTING renders text in fixed-width type. When authoring new documents, use the PRE element.

Syntax

<LISTING
 CLASS=classname
ID=string
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
STYLE=css1-properties
TITLE=text
event = script
>

Parameter | Description
ALIGN= | Displays the element left flush, right flush, or centered relative to the display or table.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

This element is a block element.

Both the start and end tags are required.

Scripting Object

LISTING

See Also

PRE


MAP

Description

Specifies a collection of hot spots for a client-side image map

Syntax

<MAP
 CLASS=classname
ID=value
LANG=language
NAME=name
STYLE=css1-properties
TITLE=text
event = script
>

Parameter | Description
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
NAME=name | Specifies the name of the window.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

Both the start and end tags are required.

This example shows a client-side image map having two hot spots and an area that is not hot. These hot spots can be applied to an image by using the name "map1" with the USEMAP= attribute of the IMG element.

Scripting Object

MAP


MARQUEE

Description

Enables you to create a scrolling text marquee.

Syntax

<MARQUEE
 BEHAVIOR=ALTERNATE | SCROLL | SLIDE
 BGCOLOR=color
CLASS=classname
DATAFLD=colname
DATAFORMATAS=HTML | TEXT
 DATASRC=#ID
DIRECTION=DOWN | LEFT | RIGHT | UP
 HEIGHT=n
HSPACE=n
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
LOOP=n
SCROLLAMOUNT=n
SCROLLDELAY=milliseconds
STYLE=css1-properties
TITLE=text
TRUESPEED
 VSPACE=n
WIDTH=n
event = script
>

Parameter | Description
BEHAVIOR=ALTERNATE | SCROLL | SLIDE How the text scrolls in the marquee.
Alternate | The marquee text alternates left and right.
Scroll | The marquee text scrolls in the direction specified in the DIRECTION= attribute. The text scrolls off the end and starts over.
Slide | The marquee text scrolls in the direction specified in the DIRECTION= attribute and stops when it reaches the end.
BGCOLOR=color | Background color behind the element. For a complete list of colors, see the Internet Explorer color table.
CLASS=classname | Class of the tag being defined. This is used to associate a subclassed style sheet with the tag.
DATAFLD=colname | Column name from the data source object that supplies the bound data.
DATAFORMATAS=HTML | TEXT | Indicates whether bound data is plain text or HTML.
DATASRC=#ID | ID of the data source object that supplies the data that is bound to this element.
DIRECTION=DOWN | LEFT | RIGHT | UP | Which direction the text should scroll.
HEIGHT=n | HEIGHT of the MARQUEE in pixels or as a percentage of the screen height.
HSPACE=n | Along with VSPACE, specifies margins for the element.
ID=value | SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underscore character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The script is written in JScript.
VBS, VBSCRIPT | The script is written in VBScript.
LOOP=n | Number of times the marquee text will loop.
SCROLLAMOUNT=n | Number of pixels the text scrolls between each subsequent drawing of the MARQUEE.
SCROLLDELAY=milliseconds | Speed the MARQUEE scrolls in milliseconds.
STYLE=css1-properties | Inline style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a tooltip during the onmouseover event.
TRUESPEED | When present, this attribute indicates that the exact scroll delay value specified is used to move the marquee text. Without this attribute, all scroll delay values of 59 or less are rounded to 60 milliseconds.
VSPACE=n | Along with HSPACE, specifies margins for the element in pixels.
WIDTH=n | Returns the calculated width of the marquee in window coordinates. In HTML, this attribute may be initially set in pixels or percentages.
event Can be one or more of these events:
onafterupdate onblur
onbounce onclick
ondblclick ondragstart
onfinish onfocus
onhelp onkeydown
onkeypress onkeyup
onmousedown onmousemove
onmouseout onmouseover
onmouseup onresize
onrowenter onrowexit
onselectstart onstart

Remarks

Both the start and end tags are required.

Example

<MARQUEE DIRECTION=RIGHT BEHAVIOR=SCROLL SCROLLAMOUNT=10 SCROLLDELAY=200>
This is a scrolling marquee.
</MARQUEE>

Scripting Object

MARQUEE


MENU

Description

Specifies that the following block consists of individual items that begin with the LI element.

Syntax

<MENU
 CLASS=classname
ID=value
LANG=language
STYLE=css1-properties
TITLE=text
event = script
>

Parameter | Description
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

This element is a block element.

Both the start and end tags are required.

Example

<MENU>
<LI>This is the first item in the menu.
<LI>And this is the second item in the menu.
</MENU>

Scripting Object

MENU


META

Description

Provides information about an HTML document to browsers, search engines, and other applications

Syntax

<META
 CONTENT=description
HTTP-EQUIV=response
NAME=text
TITLE=text
URL=url
>

Parameter | Description
CONTENT=description | Specifies meta-information to be associated with the given name or HTTP response header.
HTTP-EQUIV=response | Used to bind the CONTENT of the element to an HTTP response header. This information is then used based on the application reading the header.
NAME=name | Specifies the name of the control, bookmark, or application.
TITLE=text | Used to provide advisory information.
URL=url | If a URL is specifies, the URL will be loaded after the specified time has elapsed.

Remarks

This element may only be used within the HEAD tag.

The start tag is required, and the end tag is optional.

The value of the CONTENT= attribute depends on the HTTP-EQUIV= attribute. The following lists some of these values.
HTTP-EQUIV CONTENT
REFRESH delay[;url]

The delay is the number of seconds that the browser waits before reloading a document. The optional url specifies the document to reload. If no url is given, the browser reloads the current document.

Content-Type text/html; CHARSET=character-set

The character-set specifies one of the character set aliases listed in HTML Character Sets.

Examples

The following example sets the character set for the document.

<META HTTP-EQUIV="Content-Type"
  CONTENT="text/html; CHARSET=Windows-1251">

The following example causes the browser to reload the document every two seconds.

<META HTTP-EQUIV="REFRESH" CONTENT=2>

The following example causes the browser to load the new document, http://www.sample.com/next.htm, after a five second delay.

<META HTTP-EQUIV="REFRESH" CONTENT="5; URL=http://www.sample.com/next.htm">

The following example causes the server to include the given content in the HTTP response to a GET or HEAD request for the document.

<META HTTP-EQUIV="Expires"
CONTENT="Tue, 04 Dec 1996 21:29:02 GMT">
<meta http-equiv="Keywords" CONTENT="HTML, Reference">
<META HTTP-EQUIV="Reply-to"
content="anybody@microsoft.com">

The HTTP response includes the following header fields.

Expires: Tue, 04 Dec 1996 21:29:02 GMT
Keywords: HTML, Reference
Reply-to: anybody@microsoft.com

Scripting Object

META


NOBR

Description

Renders text without line breaking.

Syntax

<NOBR
 ID=value
STYLE=css1-properties
TITLE=text
>

Parameter | Description
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information.

Remarks

The start tag is required, and the end tag is optional.

Example

<NOBR>Here's a line of text I don't want to be broken . . . here's the end of the line.</NOBR>


NOFRAMES

Description

Used to contain HTML for browsers that do not support FRAMESET elements.

Syntax

<NOFRAMES
 ID=value
STYLE=css1-properties
TITLE=text
>

Parameter | Description
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information.

Remarks

This element is a block element.

Both the start and end tags are required.

Example

<FRAMESET>
<NOFRAMES>You need Internet Explorer 3.0 to view frames!</NOFRAMES>
</FRAMESET>

See Also

FRAME, FRAMESET


NOSCRIPT

Description

Specifies HTML to be displayed in browsers that do not support scripting.

Syntax

<NOSCRIPT
>

Remarks

This element is a block element.

Both the start and end tags are required.


OBJECT

Description

Inserts an object, such as an image, document, application, or control, into the HTML document. An object can contain any elements ordinarily used within the body of an HTML document, including section headings, paragraphs, lists, forms, and nested objects.

Syntax

<OBJECT
 ACCESSKEY=key
ALIGN=ABSBOTTOM | ABSMIDDLE | BASELINE | BOTTOM | LEFT | MIDDLE | RIGHT | TEXTTOP | TOP
 CLASS=classname
CLASSID=id
CODE=url
CODEBASE=url
CODETYPE=media-type
DATA=url
DATAFLD=colname
DATASRC=#ID
HEIGHT=n
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
NAME=name
STYLE=css1-properties
TABINDEX=n
TITLE=text
TYPE=MIME-type
WIDTH=n
event = script
>

Parameter | Description
ACCESSKEY=key | Specifies an accelerator for the element. Pressing alt-key selects this element in the user's browser.
ALIGN=ABSBOTTOM | ABSMIDDLE | BASELINE | BOTTOM | LEFT | MIDDLE | RIGHT | TEXTTOP | TOP | Specifies the alignment for the control-like element.
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
CLASSID=id | Identifies the object implementation. For example, the syntax is CLSID:class-identifier for registered ActiveX controls.
CODE=url | The name of the file containing the compiled Java class.
CODEBASE=url | Specifies a URL referencing where to find the implementation of the object.
CODETYPE=media-type | Specifies the Internet media type for code.
DATA=url | Specifies a URL referencing the object's data.
DATAFLD=colname | The column name from the data source object that supplies the bound data. This attribute can be used on both the OBJECT element and the PARAM elements it contains.
DATASRC=#ID | Indicates the ID of the data source object that supplies the data that is bound to this element.
HEIGHT=n | Along with WIDTH, specifies the size at which the element is drawn. This attribute may be initially set in pixels or percentages.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
NAME=name | Specifies the name of the control, bookmark, or application.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TABINDEX=n | Sets the tab order position for the object.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
TYPE=MIME-type | Specifies the MIME type for the associated scripting engine; will override any LANGUAGE value.
WIDTH=n | Along with HEIGHT, sets the initial size of the element. This attribute may be initially set in pixels or percentages.
event Can be one or more of these events:
onafterupdate onbeforeupdate
onblur onclick
ondblclick ondragstart
onfocus onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onreadystatechange onresize
onrowenter onrowexit
onselectstart

Remarks

Objects can be submitted in forms. See INPUT.

This element is a block element. Both the start and end tags are required.

Scripting Object

OBJECT

See Also

APPLET, EMBED, PARAM


OL

Description

Draws lines of text as an ordered list.

Syntax

<OL
 CLASS=classname
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
START=n
STYLE=css1-properties
TITLE=text
TYPE=1 | a | A | i | I
 event = script
>

Parameter | Description
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
START=n | Specifies the starting number for a list.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
TYPE=1 | a | A | i | I Changes the style of the list.
1 | List items are numbered.
a | List items are labeled with lowercase letters.
A | List items are labeled with uppercase letters.
i | List items are labeled with lowercase roman numerals.
I | List items are labeled with uppercase roman numerals.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

This element is a block element.

Both the start and end tags are required.

Example

<OL>
<LI>This is the first item in the list.
<LI>And this is the second item in the list.
</OL>

<OL START=3>
<LI>This is item number 3.
</OL>

<OL TYPE=A>
<LI>This is item A.
</OL>

Scripting Object

OL

See Also

LI


OPTION

Description

Denotes one choice in a SELECT block.

Syntax

<OPTION
 CLASS=classname
ID=value
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
SELECTED
 VALUE=value
event = script
>

Parameter | Description
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
SELECTED | Indicates that this item is the default. If not present, the first item is selected by default.
VALUE=value | For textual/numerical controls, specifies the default value of the control. For Boolean controls, specifies the value to be returned when the control is turned on.
event Can be one or more of these events:
ondragstart onselectstart

Remarks

This element is a block element.

The start tag is required, and the end tag is optional.

Example

<SELECT NAME="Cars" SIZE="1">
<OPTION VALUE="1">BMW
<OPTION VALUE="2">PORSCHE
<OPTION VALUE="3" SELECTED>MERCEDES
</SELECT>

Scripting Object

OPTION

See Also

SELECT


P

Description

Denotes a paragraph.

Syntax

<P
 ALIGN=CENTER | LEFT | RIGHT
 CLASS=classname
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
STYLE=css1-properties
TITLE=text
event = script
>

Parameter | Description
ALIGN=CENTER | LEFT | RIGHT | Displays the element left flush, right flush, or centered relative to the display or table.
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

This element is a block element.

The start tag is required, and the end tag is optional.

Example

<P>This is a paragraph.</P>

Scripting Object

P


PARAM

Description

Sets the property value for a given object. This element valid within the APPLET, EMBED, and OBJECT elements.

Syntax

<PARAM
 DATAFLD=colname
DATAFORMATAS=HTML | TEXT
 DATASRC=#ID
NAME=name
VALUE=value
>

Parameter | Description
DATAFLD=colname | The column name from the data source object that supplies the bound data.
DATAFORMATAS=HTML | TEXT | Indicates whether bound data is plain text or HTML.
DATASRC=#ID | Indicates the ID of the data source object that supplies the data that is bound to this element.
NAME=name | Specifies the name of the parameter.
VALUE=value | Specifies the property value. The value is passed to the object without change except that any character or numeric character entities are replaced with their corresponding character values.

See Also

APPLET, EMBED, OBJECT


PLAINTEXT

Description

Renders text in fixed-width type without processing tags and disables HTML parsing for the rest of the document. Although a </PLAINTEXT> tag is required, it does not close the container and is rendered on-screen. This element has been deprecated and may not be supported in a consistent manner by all browsers. It is recommended that the PRE element be used instead.

Syntax

<PLAINTEXT
 CLASS=classname
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
STYLE=css1-properties
TITLE=text
event = script

>

Parameter | Description
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

This element is a block element.

Both the start and end tags are required.

Scripting Object

PLAINTEXT


PRE

Description

Renders text in fixed-width type.

Syntax

<PRE
 CLASS=classname
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
STYLE=css1-properties
TITLE=text
event = script
>

Parameter | Description
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

This element is a block element.

Both the start and end tags are required.

Example

<PRE>Here's some plain text.</PRE>

Scripting Object

PRE


Q

Description

Sets apart a short quotation in text.

Syntax

<Q
 CLASS=classname
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
STYLE=css1-properties
TITLE=text
event = script
>

Parameter | Description
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

This element is a block element.

Both the start and end tags are required.

Example

<P>He said,
<Q>"Hi there!"</Q>

Scripting Object

Q

See Also

BLOCKQUOTE


S

Description

Renders text in strikethrough type.

Syntax

<S
 CLASS=classname
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
STYLE=css1-properties
TITLE=text
event = script
>

Parameter | Description
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

Both the start and end tags are required.

Example

<S>This text has a line through it.</S>

Scripting Object

S

See Also

STRIKE


SAMP

Description

Specifies sample text and renders it in a small font. The required end tag restores the text formatting to normal. By default, the font used is fixed-width. If a font face is specified in a FONT or BASEFONT element preceding SAMP, that font is used instead.

Syntax

<SAMP
 CLASS=classname
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
STYLE=css1-properties
TITLE=text
event = script
>

Parameter | Description
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

Both the start and end tags are required.

Example

<SAMP>Here is some text in a small fixed-width font.</SAMP>

Scripting Object

SAMP

See Also

CODE


SCRIPT

Description

Specifies a script for the page that will be interpreted by a script engine.

Syntax

<SCRIPT
 CLASS=classname
DEFER
EVENT=eventname
FOR=element
ID=value
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
SRC=url
TITLE=text
TYPE=MIME-type
>

Parameter | Description
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
DEFER | Indicates the script block contains only functions and no in-line script. Deferring the parsing of scripts until they are needed can improve performance by decreasing the time it takes to load a document.
EVENT=eventname | Specifies the event the script is being written for.
FOR=element | Specifies which element is being bound to the event script. A scripting object or element ID can be specified as the element value.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT. This attribute overrides any TYPE= value.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
SRC=url | Specifies a URL for the associated file.
TITLE=text | Used to provide advisory information.
TYPE=MIME-type | Specifies the MIME type for the associated scripting engine.

Remarks

Code within the SCRIPT block that are not contained within a function are executed immediately as the page is loaded. To keep scripts from being displayed on down-level browsers, the SCRIPT block should be nested within a comment block.

This element is a block element.

Both the start and end tags are required.

Scripting Object

SCRIPT


SELECT

Description

Denotes a list box or dropdown list. The end tag encloses any OPTION elements that may appear within the SELECT element.

Syntax

<SELECT
 ACCESSKEY=key
ALIGN=ABSBOTTOM | ABSMIDDLE | BASELINE | BOTTOM | LEFT | MIDDLE | RIGHT | TEXTTOP | TOP
 CLASS=classname
DATAFLD=colname
DATASRC=#ID
DISABLED
 ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
MULTIPLE
 NAME=name
SIZE=n
STYLE=css1-properties
TABINDEX=n
event = script
>

Parameter | Description
ACCESSKEY=key | Specifies an accelerator for the element. Pressing alt-key selects this element in the user's browser.
ALIGN=ABSBOTTOM | ABSMIDDLE | BASELINE | BOTTOM | LEFT | MIDDLE | RIGHT | TEXTTOP | TOP | Specifies the alignment for the control-like element.
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
DATAFLD=colname | The column name from the data source object that supplies the bound data.
DATASRC=#ID | Indicates the ID of the data source object that supplies the data that is bound to this element.
DISABLED | Used to disable an element. This attribute prevents an element from receiving the focus, and causes the element to appear "grayed out."
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
MULTIPLE | Indicates that multiple items in the list can be selected.
NAME=name | Specifies the name of the control, bookmark, or application.
SIZE=n | Specifies the size of the control.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TABINDEX=n | Sets the tab order position for the object.
event Can be one or more of these events:
onafterupdate onbeforeupdate
onblur onchange
onclick ondblclick
ondragstart onfocus
onhelp onkeydown
onkeypress onkeyup
onmousedown onmousemove
onmouseout onmouseover
onmouseup onresize
onrowenter onrowexit
onselectstart

Remarks

Both the start and end tags are required.

Example

<SELECT NAME="Cars" SIZE="1">
<OPTION VALUE="1">BMW
<OPTION VALUE="2">PORSCHE
<OPTION VALUE="3" SELECTED>MERCEDES
</SELECT>

Scripting Object

SELECT

See Also

OPTION


SMALL

Description

Specifies that the enclosed text should be displayed with a relatively smaller font than the current font.

Syntax

<SMALL
 CLASS=classname
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
STYLE=css1-properties
TITLE=text
event = script
>

Parameter | Description
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

Both the start and end tags are required.

Example

<SMALL>This text is smaller.</SMALL>

Scripting Object

SMALL


SPAN

Description

This does not have any structural role or established rendering convention. It allows a user to define their own method of rendering using style sheets.

Syntax

<SPAN
 CLASS=classname
DATAFLD=colname
DATAFORMATAS=HTML | TEXT
 DATASRC=#ID
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
STYLE=css1-properties
TITLE=text
event = script
>

Parameter | Description
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
DATAFLD=colname | The column name from the data source object that supplies the bound data.
DATAFORMATAS=HTML | TEXT | Indicates whether bound data is plain text or HTML.
DATASRC=#ID | Indicates the ID of the data source object that supplies the data that is bound to this element.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

Both the start and end tags are required.

Example

<P>This paragraph contains a single <SPAN STYLE="color: blue">blue</SPAN> word.

Scripting Object

SPAN


STRIKE

Description

Renders text in strikethrough type.

Syntax

<STRIKE
 CLASS=classname
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
STYLE=css1-properties
TITLE=text
event = script
>

Parameter | Description
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

Both the start and end tags are required.

Example

<STRIKE>This text has a line through it.</STRIKE>

Scripting Object

STRIKE

See Also

S


STRONG

Description

Renders text with a strong emphasis, often shown in boldface.

Syntax

<STRONG
 CLASS=classname
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
STYLE=css1-properties
TITLE=text
event = script
>

Parameter | Description
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

Both the start and end tags are required.

Example

<STRONG>This text is strongly emphasized, shown as bold.</STRONG>

Scripting Object

STRONG

See Also

ACRONYM, ADDRESS, CITE, EM


STYLE

Description

Specifies the style sheet for the page.

Syntax

<STYLE
 DISABLED
 MEDIA=SCREEN | PRINT | ALL
 TITLE=text
TYPE="text/css"
>

Parameter | Description
DISABLED | Used to disable an element. This attribute prevents an element from receiving the focus, and causes the element to appear "grayed out."
MEDIA= SCREEN | PRINT | ALL Describes the output device for the document. A value of "PRINT" does not affect the on-screen layout. Default value is ALL.
SCREEN | Output is intended for non-paged computer screens.
PRINT | Output is intended for paged, opaque material and for documents on screen viewed in print preview mode.
ALL | Applies to all devices.
TITLE=text | Used to provide advisory information.
TYPE="text/css" | Indicates the type of style sheet.

Remarks

This element may be used within the BODY tag.

Both the start and end tags are required.

Example

<STYLE>
   BODY {background: white; color: black}
   H1 {font: 8pt Arial bold}
   P {font: 10pt Arial; text-indent: 0.5in}
   A {text-decoration: none; color: blue}
</STYLE>

Scripting Object

STYLE


SUB

Description

The enclosed text should be displayed in subscript, and using a smaller font than the current font.

Syntax

<SUB
 CLASS=classname
ID=value

LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
STYLE=css1-properties
TITLE=text
event = script
>

Parameter | Description
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

Both the start and end tags are required.

Example

(X<SUB>1</SUB>,Y<SUB>1</SUB>)

Scripting Object

SUB

See Also

SUP


SUP

Description

The enclosed text should be displayed in SuperScript and in a smaller font relative to the current font.

Syntax

<SUP
 CLASS=classname
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
STYLE=css1-properties
TITLE=text
event = script
>

Parameter | Description
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

Both the start and end tags are required.

Example

X<SUP>2</SUP> + Y<SUP>2</SUP>

Scripting Object

SUP

See Also

SUB


TABLE

Description

Used to specify that the contained content is organized into a table with rows and columns. Use the TR, TD, and TH elements in the container to create the rows, columns, and cells.

The optional CAPTION, THEAD, TBODY, TFOOT, COLGROUP, and COL elements can be used to organize a table and apply attributes across columns and groups of columns.

Syntax

<TABLE
 ALIGN=CENTER | LEFT | RIGHT
 BACKGROUND=url
BGCOLOR=color
BORDER=n
BORDERCOLOR=color
BORDERCOLORDARK=color
BORDERCOLORLIGHT=color
CELLPADDING=n
CELLSPACING=n
CLASS=classname
COLS=n
DATAPAGESIZE=n
DATASRC=#ID
FRAME=ABOVE | BELOW | BORDER | BOX | INSIDES | LHS | RHS | VOID | VSIDES
 HEIGHT=n
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
RULES=ALL | COLS | GROUPS | NONE | ROWS
 STYLE=css1-properties
TITLE=text
WIDTH=n
event = script
>

Parameter | Description
ALIGN=CENTER | LEFT | RIGHT | Specifies how the table should be aligned.
BACKGROUND=url | Specifies a background picture for the table. The picture is tiled behind the text and graphics in the table, table head, or table cell.
BGCOLOR=color | Sets the background color behind the element. For a complete list of colors, look at the Internet Explorer color table.
BORDER=n | Specifies the thickness of a border to be drawn around the element.
BORDERCOLOR=color | Sets border color and must be used with the BORDER attribute, except for frames. For a complete list of colors, look at the Internet Explorer color table.
BORDERCOLORDARK=color | Sets independent border color control over one of the two colors used to draw a 3-D border, opposite of BORDERCOLORLIGHT, and must be used with the BORDER attribute.
BORDERCOLORLIGHT=color | Sets independent border color control over one of the two colors used to draw a 3-D border, opposite of BORDERCOLORDARK, and must be used with the BORDER attribute.
CELLPADDING=n | Specifies the amount of space between the border of the cell and the contents of the cell.
CELLSPACING=n | Specifies the amount of space between cells in a table.
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
COLS=n | The number of columns in the table.
DATAPAGESIZE=n | Sets the number of records displayed in a data bound repeated table.
DATASRC=#ID | Indicates the ID of the data source object that supplies the data that is bound to this element.
FRAME= ABOVE | BELOW | BORDER | BOX | INSIDES | LHS | RHS | VOID | VSIDES Specifies which sides of a frame (outside borders) are displayed. The possible values are:
BORDER | Displays a border on all sides of the table frame. This is the default.
VOID | Removes all outside table borders.
ABOVE | Displays a border on the top side of the table frame.
BELOW | Displays a border on the bottom side of the table frame.
HSIDES | Displays a border on the top and bottom sides of the table frame.
LHS | Displays a border on the left-hand side of the table frame.
RHS | Displays a border on the right-hand side of the table frame.
VSIDES | Displays a border on the left and right sides of the table frame.
BOX | Displays a border on all sides of the table frame.
HEIGHT=n | Along with WIDTH, specifies the size at which the element is drawn. This attribute may be initially set in pixels or percentages.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
RULES=ALL | COLS | GROUPS | NONE | ROWS | Specifies which dividing lines are displayed (inside borders).
Specifies which dividing lines (inside borders) are displayed. The possible values are:
NONE | Removes all interior table borders. This is the default.
GROUPS | Displays horizontal borders between all table groups. Groups are specified by the THEAD, TBODY, TFOOT, and COLGROUP elements.
ROWS | Displays horizontal borders between all table rows.
COLS | Displays vertical borders between all table columns.
ALL | Displays a border on all rows and columns.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
WIDTH=n | Along with HEIGHT, sets the initial size of the element. This attribute may be initially set in pixels or percentages.
event Can be one or more of these events:
onafterupdate onbeforeupdate
onblur onclick
ondblclick ondragstart
onfocus onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onresize onrowenter
onrowexit onscroll
onselectstart

Remarks

Valid tags within a table include:

  • TR
  • CAPTION
  • THEAD
  • TBODY
  • TFOOT
  • COLGROUP
  • COL

This element is a block element.

Both the start and end tags are required.

Example

<TABLE BORDER=1 WIDTH=80%>
<THEAD>
<TR>
<TH>Heading 1</TH>
<TH>Heading 2</TH>
</TR>
<TBODY>
<TR>
<TD>Row 1, Column 1 text.</TD>
<TD>Row 1, Column 2 text.</TD>
</TR>
<TR>
<TD>Row 2, Column 1 text.</TD>
<TD>Row 2, Column 2 text.</TD>
</TR>
</TABLE>

Scripting Object

TABLE

See Also

TD, TR


TBODY

Description

Creates multiple sections when rules are needed between groups of table rows. If a table does not have a header or footer (does not have a THEAD or TFOOT element), the TBODY element is optional. The end tag is optional.

You can use the TBODY element more than once in a table. This is useful for dividing lengthy tables into smaller units and for controlling the placement of horizontal rules.

Syntax

<TBODY
 ALIGN=CENTER | LEFT | RIGHT
 BGCOLOR=color
CLASS=classname
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
 STYLE=css1-properties
TITLE=text
VALIGN=BASELINE | BOTTOM | CENTER | TOP
 event = script
>

Parameter | Description
ALIGN=CENTER | LEFT | RIGHT | Displays the element left flush, right flush, or centered relative to the display or table.
BGCOLOR=color | Sets the background color behind the element. For a complete list of colors, look at the Internet Explorer color table.
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
VALIGN=BASELINE | BOTTOM | CENTER | TOP Displays the elements aligned at the top or bottom within the element.
BASELINE | Vertical align to the baseline of the font.
BOTTOM | Vertical align to the bottom of the element.
MIDDLE | Vertical align to the middle of the element.
TOP | Vertical align to the top of the element.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

This element is exposed for all tables, even if the table did not explicitly define a TBODY element.

This element is a block element.

The end tags are optional.

Example

<TABLE>
<THEAD>
<TR>
...
</TR>
<TBODY>
<TR>
...
</TR>
</TBODY>
</TABLE>

Scripting Object

TBODY


TD

Description

Specifies a cell in a table. This element is valid only within a row in a table. You must use a TR element before using TD. All attributes are optional.

Syntax

<TD
 ALIGN=CENTER | LEFT | RIGHT
 BACKGROUND=url
BGCOLOR=color
BORDERCOLOR=color
BORDERCOLORDARK=color
BORDERCOLORLIGHT=color
CLASS=classname
COLSPAN=n
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
 NOWRAP
 ROWSPAN=n
STYLE=css1-properties
TITLE=text
VALIGN=BASELINE | BOTTOM | CENTER | TOP
 event = script
>

Parameter | Description
ALIGN=CENTER | LEFT | RIGHT | Displays the element left flush, right flush, or centered relative to the display or table.
BACKGROUND=url | Specifies a background picture for the table. The picture is tiled behind the text and graphics in the table, table head, or table cell.
BGCOLOR=color | Sets the background color behind the element. For a complete list of colors, look at the Internet Explorer color table.
BORDERCOLOR=color | Sets border color and must be used with the BORDER attribute, except for frames. For a complete list of colors, look at the Internet Explorer color table.
BORDERCOLORDARK=color | Sets independent border color control over one of the two colors used to draw a 3-D border, opposite of BORDERCOLORLIGHT, and must be used with the BORDER attribute. For a complete list of colors, look at the Internet Explorer color table.
BORDERCOLORLIGHT=color | Sets independent border color control over one of the two colors used to draw a 3-D border, opposite of BORDERCOLORDARK, and must be used with the BORDER attribute. For a complete list of colors, look at the Internet Explorer color table.
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
COLSPAN=n | Specifies how many columns in the TABLE this cell should span.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
NOWRAP | The NOWRAP attribute is used when you do not want the browser to automatically perform word wrap.
ROWSPAN=n | Specifies how many rows in a TABLE this cell should span.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
VALIGN=BASELINE | BOTTOM | CENTER | TOP Displays the elements aligned at the top or bottom within the element.
BASELINE | Vertical align to the baseline of the font.
BOTTOM | Vertical align to the bottom of the element.
MIDDLE | Vertical align to the middle of the element.
TOP | Vertical align to the top of the element.
event Can be one or more of these events:
onafterupdate onbeforeupdate
onblur onclick
ondblclick ondragstart
onfocus onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onresize onrowenter
onrowexit onscroll
onselectstart

Remarks

This element is a block element.

Both the start and end tags are required.

Scripting Object

TD

See Also

TABLE, TH, TR


TEXTAREA

Description

Creates a multiline text entry control in which the user can type and edit text. The end tag is required. Any text between the start tag and end tag is used as the initial value for the control.

Syntax

<TEXTAREA
 ACCESSKEY=key
ALIGN=ABSBOTTOM | ABSMIDDLE | BASELINE | BOTTOM | LEFT | MIDDLE | RIGHT | TEXTTOP | TOP
 CLASS=classname
COLS=n
DATAFLD=colname
DATASRC=#ID
DISABLED
 ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
 NAME=name
READONLY
 ROWS=n
STYLE=css1-properties
TABINDEX=n
TITLE=text
WRAP=OFF | PHYSICAL | VIRTUAL
 event = script
>

Parameter | Description
ACCESSKEY=key | Specifies an accelerator for the element. Pressing alt-key selects this element in the user's browser.
ALIGN=ABSBOTTOM | ABSMIDDLE | BASELINE | BOTTOM | LEFT | MIDDLE | RIGHT | TEXTTOP | TOP | Specifies the alignment for the control-like element.
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
COLS=n | Specifies how many characters wide the text area is.
DATAFLD=colname | The column name from the data source object that supplies the bound data.
DATASRC=#ID | Indicates the ID of the data source object that supplies the data that is bound to this element.
DISABLED | Used to disable an element. This attribute prevents an element from receiving the focus, and causes the element to appear "grayed out."
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
NAME=name | Specifies the name of the control, bookmark, or application.
READONLY | Causes the element's contents to be read only.
ROWS=n | Specifies the number of rows tall the text area control should be.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TABINDEX=n | Sets the tab order position for the object.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
WRAP=OFF | PHYSICAL | VIRTUAL Specifies how to handle word-wrapping inside the text area.
OFF | Word-wrapping is disabled (default).
PHYSICAL | The text is displayed and submitted word-wrapped
VIRTUAL | The text is displayed word-wrapped, but is submitted as typed.
event Can be one or more of these events:
onafterupdate onbeforeupdate
onblur onchange
onclick ondblclick
ondragstart onfocus
onhelp onkeydown
onkeypress onkeyup
onmousedown onmousemove
onmouseout onmouseover
onmouseup onresize
onrowenter onrowexit
onscroll onstart
onselectstart

Remarks

The default font is fixed pitch.

Both the start and end tags are required.

Scripting Object

TEXTAREA

See Also

INPUT


TFOOT

Description

Defines the table footer. Use TFOOT to duplicate footers when breaking a table across page boundaries, or for static headers when body sections are rendered in a scrolling panel. The end tag is optional.

The table footer is optional; if given, only one footer is allowed. The TFOOT element is valid only within a table; you must use a TABLE element before using this element.

Syntax

<TFOOT
 ALIGN=CENTER | LEFT | RIGHT
 BGCOLOR=color
CLASS=classname
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
 STYLE=css1-properties
TITLE=text
VALIGN=BASELINE | BOTTOM | CENTER | TOP
 event = script
>

Parameter | Description
ALIGN=CENTER | LEFT | RIGHT | Displays the element left flush, right flush, or centered relative to the display or table.
BGCOLOR=color | Sets the background color behind the element. For a complete list of colors, look at the Internet Explorer color table.
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
VALIGN=BASELINE | BOTTOM | CENTER | TOP Displays the elements aligned at the top or bottom within the element.
BASELINE | Vertical align to the baseline of the font.
BOTTOM | Vertical align to the bottom of the element.
MIDDLE | Vertical align to the middle of the element.
TOP | Vertical align to the top of the element.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

This element is a block element.

Example

<TABLE>
<TBODY>
<TR>
...
</TR>
<TFOOT>
<TR>
...
</TR>
</TABLE>

Scripting Object

TFOOT


TH

Description

Creates a row or column heading in a table. The element is similar to the TD element but emphasizes the text in the cell to distinguish it from text in TD cells. The end tag is optional.

Syntax

<TH
 ALIGN=CENTER | LEFT | RIGHT
 BACKGROUND=url
BGCOLOR=color
BORDERCOLOR=color
BORDERCOLORDARK=color
BORDERCOLORLIGHT=color
CLASS=classname
COLSPAN=n
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
NOWRAP
 ROWSPAN=n

STYLE=css1-properties
TITLE=text
VALIGN=BASELINE | BOTTOM | CENTER | TOP
 event = script
>

Parameter | Description
ALIGN=CENTER | LEFT | RIGHT | Displays the element left flush, right flush, or centered relative to the display or table.
BACKGROUND=url | Specifies a background picture for the table. The picture is tiled behind the text and graphics in the table, table head, or table cell.
BGCOLOR=color | Sets the background color behind the element. For a complete list of colors, look at the Internet Explorer color table.
BORDERCOLOR=color | Sets border color and must be used with the BORDER attribute, except for frames. For a complete list of colors, look at the Internet Explorer color table.
BORDERCOLORDARK=color | Sets independent border color control over one of the two colors used to draw a 3-D border, opposite of BORDERCOLORLIGHT, and must be used with the BORDER attribute. For a complete list of colors, look at the Internet Explorer color table.
BORDERCOLORLIGHT=color | Sets independent border color control over one of the two colors used to draw a 3-D border, opposite of BORDERCOLORDARK, and must be used with the BORDER attribute. For a complete list of colors, look at the Internet Explorer color table.
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
COLSPAN=n | Specifies how many columns in the TABLE this cell should span.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
NOWRAP | The NOWRAP attribute is used when you do not want the browser to automatically perform word wrap.
ROWSPAN=n | Specifies how many rows in a TABLE this cell should span.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
VALIGN=BASELINE | BOTTOM | CENTER | TOP Displays the elements aligned at the top or bottom within the element.
BASELINE | Vertical align to the baseline of the font.
BOTTOM | Vertical align to the bottom of the element.
MIDDLE | Vertical align to the middle of the element.
TOP | Vertical align to the top of the element.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onscroll onselectstart

Remarks

This element is a block element.

Both the start and end tags are required.

Scripting Object

TH

See Also

TD, TR


THEAD

Description

Defines the table heading. Use THEAD to duplicate headings when breaking tables across page boundaries, or for static headings when body sections are rendered in a scrolling panel. The end tag is optional.

The table heading is optional; if given, only one heading is allowed. The THEAD element is valid only within a table; you must use a TABLE element before using this element.

Syntax

<THEAD
 ALIGN=CENTER | LEFT | RIGHT
 BGCOLOR=color
CLASS=classname
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
 STYLE=css1-properties
TITLE=text
VALIGN=BASELINE | BOTTOM | CENTER | TOP
 event = script
>

Parameter | Description
ALIGN=CENTER | LEFT | RIGHT | Displays the element left flush, right flush, or centered relative to the display or table.
BGCOLOR=color | Sets the background color behind the element. For a complete list of colors, look at the Internet Explorer color table.
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
VALIGN=BASELINE | BOTTOM | CENTER | TOP Displays the elements aligned at the top or bottom within the element.
BASELINE | Vertical align to the baseline of the font.
BOTTOM | Vertical align to the bottom of the element.
MIDDLE | Vertical align to the middle of the element.
TOP | Vertical align to the top of the element.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

This element is a block element.

Example

<TABLE>
<THEAD>
<TR>
...
</TR>
<TBODY>
<TR>
...
</TR>
</TABLE>

Scripting Object

THEAD


TITLE

Description

Identifies the contents of the document in a global context.

Syntax

<TITLE
 ID=value
TITLE=string
>

Parameter | Description
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
TITLE= | Used to provide advisory information.

Remarks

This element may only be used within the HEAD tag.

This element is a block element.

Both the start and end tags are required.

Example

<HEAD>
<TITLE>"Welcome To Internet Explorer!"</TITLE>
</HEAD>

Scripting Object

TITLE


TR

Description

Creates a row in a table. The row can contain one or more TD elements.

Syntax

<TR
 ALIGN=CENTER | LEFT | RIGHT
 BGCOLOR=color
BORDERCOLOR=color
BORDERCOLORDARK=color
BORDERCOLORLIGHT=color
CLASS=classname
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
 STYLE=css1-properties
TITLE=text
VALIGN=BASELINE | BOTTOM | CENTER | TOP
 event = script
>

Parameter | Description
ALIGN=CENTER | LEFT | RIGHT | Displays the element left flush, right flush, or centered relative to the display or table.
BGCOLOR=color | Sets the background color behind the element. For a complete list of colors, look at the Internet Explorer color table.
BORDERCOLOR=color | Sets border color and must be used with the BORDER attribute, except for frames. For a complete list of colors, look at the Internet Explorer color table.
BORDERCOLORDARK=color | Sets independent border color control over one of the two colors used to draw a 3-D border, opposite of BORDERCOLORLIGHT, and must be used with the BORDER attribute. For a complete list of colors, look at the Internet Explorer color table.
BORDERCOLORLIGHT=color | Sets independent border color control over one of the two colors used to draw a 3-D border, opposite of BORDERCOLORDARK, and must be used with the BORDER attribute. For a complete list of colors, look at the Internet Explorer color table.
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
VALIGN=BASELINE | BOTTOM | CENTER | TOP Displays the elements aligned at the top or bottom within the element.
BASELINE | Vertical align to the baseline of the font.
BOTTOM | Vertical align to the bottom of the element.
MIDDLE | Vertical align to the middle of the element.
TOP | Vertical align to the top of the element.
event Can be one or more of these events:
onafterupdate onbeforeupdate
onblur onclick
ondblclick ondragstart
onfocus onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onresize onrowenter
onrowexit onselectstart

Remarks

Within a row, the following tags are valid:

  • TD
  • TH

This element is a block element.

Both the start and end tags are required.

Example

<TABLE>
<TR>
...
</TR>
<TR>
...
</TR>
</TABLE>

Scripting Object

TR

See Also

TABLE, TD, TH


TT

Description

Indicates teletype. Renders text in fixed-width type. The required end tag returns the text formatting to normal.

Syntax

<TT
 CLASS=classname
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
STYLE=css1-properties
TITLE=text
event = script
>

Parameter | Description
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

Both the start and end tags are required.

Example

<TT>Here's some plain text.</TT>

Scripting Object

TT


U

Description

Renders underlined text. The required end tag restores the text to normal.

Syntax

<U
 CLASS=classname
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
STYLE=css1-properties
TITLE=text
event = script
>

Parameter | Description
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

Both the start and end tags are required.

Example

<U>This text is underlined.</U>

Scripting Object

U


UL

Description

Specifies that the following block of text is a bulleted (or unordered) list. Each item begins with a LI tag. The end tag is required.

Syntax

<UL
 CLASS=classname
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
STYLE=css1-properties
TITLE=text
TYPE=1 | a | A | i | I
 event = script
>

Parameter | Description
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
TYPE=1 | a | A | i | I Changes the style of the list.
1 | List items are numbered.
a | List items are labeled with lowercase letters.
A | List items are labeled with uppercase letters.
i | List items are labeled with lowercase roman numerals.
I | List items are labeled with uppercase roman numerals.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

This element is a block element.

Both the start and end tags are required.

Example

<UL>
<LI>This is the first bulleted item in the list.
<LI>And this is the second bulleted item in the list.
</UL>

Scripting Object

UL

See Also

LI


VAR

Description

Indicates placeholder text for a variable. Displays text in a small, fixed-width type. The required end tag restores the formatting to normal.

Syntax

<VAR
 CLASS=classname
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
STYLE=css1-properties
TITLE=text
event = script
>

Parameter | Description
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

Both the start and end tags are required.

Example

Enter the <VAR>filename</VAR> in the dialog box.

Scripting Object

VAR


WBR

Description

Inserts a soft line break in a block of NOBR text.

Syntax

<WBR
 CLASS=classname

ID=value
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS
STYLE=css1-properties
TITLE=text
>

Parameter | Description
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information.

Remarks

The start tag is required, and the end tag is optional.

Example

<NOBR>This line of text will not break, no matter how narrow the window gets.
<WBR>This one, however, will.</NOBR>

See Also

BR


XMP

Description

This tag is no longer recommended. Instead, the PRE or SAMP tags should be used. XMP indicates example text by displaying it in fixed-width type. The required end tag restores the text to normal.

Syntax

<XMP
 CLASS=classname
ID=value
LANG=language
LANGUAGE=JAVASCRIPT | JSCRIPT | VBSCRIPT | VBS

STYLE=css1-properties
TITLE=text
event = script
>

Parameter | Description
CLASS=classname | Specifies the class of the tag being defined. This is used to associate a sub-classed style sheet with the tag.
ID=value | An SGML identifier used as the target for hypertext links or for naming particular elements in associated style sheets. Valid ID values must begin with a letter. The underbar character, "_", may be used in the ID name. The ID should be unique throughout the scope of the document. If more than one object with the same identifier exists in a document, a collection of those named items is created that can only be referenced by ordinal position.
LANG=language | Specifies which language to use in ISO standard language abbreviation form.
LANGUAGE=JAVASCRIPT | JSCRIPT | VBS | VBSCRIPT Specifies the language the current script is written in and invokes the proper scripting engine. The default value is JAVASCRIPT.
JAVASCRIPT, JSCRIPT | The scripting language is written in JavaScript.
VBS, VBSCRIPT | The scripting language is written in VBScript.
STYLE=css1-properties | Specifies an in-line style sheet for the tag.
TITLE=text | Used to provide advisory information. The contents of the title attribute will be displayed in a ToolTip during the onmouseover event.
event Can be one or more of these events:
onclick ondblclick
ondragstart onhelp
onkeydown onkeypress
onkeyup onmousedown
onmousemove onmouseout
onmouseover onmouseup
onselectstart

Remarks

This element is a block element.

Both the start and end tags are required.

Scripting Object

XMP

See Also

LISTING, PLAINTEXT, PRE, TT


add

Description

Adds an element to the collection.

Before you can add an element to a collection, you must create it first by using the createElement method.

Syntax

object.add(element [, index])

Parameter | Description
element | Element object to add.
index | Optional. Number specifying the position within the collection to place the element. If no value is given, the method places the element at the end of the collection.

Return Value

No return value.

Remarks

For the areas object, this method can only be used on the object after the page has been loaded. If the method is applied "inline," a run-time error will occur.

Applies To

areas, options

See Also

remove


addChannel

Description

Presents a dialog box allowing the user to add the channel specified or change its usage if it is already installed.

Syntax

object.addChannel(urlToCDF)

Parameter | Description
urlToCDF | Required. Specifies the URL of a Channel Definition Format (CDF) file to be installed.

Remarks

Important Note: This function is only intended for use by publishers shipping Active Channels that are pre-installed with Internet Explorer 4.0. It is included in this documentation for completeness.

Applies To

external


addImport

Description

Adds a style sheet to the imports collection for the given style sheet.

Syntax

integer = stylesheet.addImport(url [, index])

Parameter | Description
url | String specifying the location of the source file for the style sheet.
index | Optional. Integer specifying the requested position of the style sheet in the collection. If this value is not given, the style sheet is added to the end of the collection.

Return Value

Returns an integer index value specifying the position of the imported style sheet in the imports collection.

Remarks

The index is a zero-based index value.

Applies To

styleSheet


addReadRequest

Description

Adds an entry to the read-requests queue.

Syntax

navigator.userProfile.addReadRequest(attributeName [, isRequired], success)

Parameter | Description
attributeName | One of the standard vCard names; otherwise, the request is ignored and nothing is added to the read-requests queue.
isRequired | Optional. Currently, Internet Explorer ignores this parameter.
success | Returns TRUE if the request has been added to the queue successfully, or FALSE otherwise. This could mean that either the attribute name was not recognized or the attribute had already appeared in the request queue.

Applies To

userProfile


addRule

Description

Creates a new style rule for the styleSheet object and returns the index into the Rules collection. Rules can be added to a disabled styleSheet, but they will not apply to the document unless the styleSheet has been enabled.

Syntax

integer = object.addRule(selector, style [, index])

Parameter | Description
selector | String specifying the selector for the new rule. Single contextual selectors are valid. For example, "DIV P B" is a valid contextual selector.
style | String specifying the style assignments for this style rule. This style takes the same form as an inline style specification. For example, "color:blue" is a valid style parameter.
index | Integer that specifies where in the Rules collection to add the new style rule. This is an optional parameter. If an index is not provided, the rule will be added to the end of the Rules collection by default.

Return Value

The return value is reserved; do not use.

Remarks

The following example adds a rule to the beginning of the Rules collection for all text in BOLD that appears in a <DIV> <P> tag to be set to the color blue.

var new_rule;
new_rule = styleSheets[0].addRule("DIV P B", "color:blue", 0);

Remarks

NOTE: When manipulating stylesheets through the Object Model, you will not be able to addRule() where the style is "position" to an element which doesn't already have positioning set for it. You can, however, add a rule to the object to make it "position:absolute" if the object has already been set to "position:relative" (and vice versa).

Applies To

styleSheet


alert

Description

Displays an Alert dialog box with a message and an OK button.

Syntax

object.alert([message])

Parameter | Description
message | Optional. (String) String to display.

Return Value

No return value.

Remarks

The title bar of the Alert dialog box cannot be changed.

Applies To

window


assign

Description

Sets the current location to url. This method loads the given document specified by url if it exists.

Syntax

object.assign(url)

Parameter | Description
url | String specifying the URL of the document to assign.

Return Value

No return value.

Applies To

location


back

Description

Loads the previous URL in the History list.

Syntax

object.back( )

Return Value

No return value.

Remarks

This method performs the same action as a user choosing the Back button in the browser. The back method is the same as history.go(-1). Trying to go past the beginning of the history does not generate an error. Instead, you are left at the current page.

Applies To

history

See Also

forward, go


blur

Description

Causes an object to lose focus and fires the onblur event.

Syntax

object.blur( )

Return Value

No return value.

Applies To

A, APPLET, AREA, BODY, BUTTON, CAPTION, DIV, EMBED, FIELDSET, FRAME, FRAMESET, HR, IFRAME, IMG, INPUT, MARQUEE, OBJECT, SELECT, SPAN, TABLE, TD, TEXTAREA, TR, window


clear

Description

Clears the contents of the selection.

Syntax

object.clear( )

Return Value

No return value.

Applies To

selection


clear

Description

Clears the current document.

Syntax

object.clear( )

Return Value

No return value.

Applies To

document


clearInterval

Description

Cancels the interval previously started using the setInterval method.

Syntax

object.clearInterval(intervalID)

Parameter | Description
intervalID | Integer specifying which interval to cancel. This value must have been previously returned by the setInterval method.

Return Value

No return value.

Applies To

window


clearRequest

Description

Clears the compound request, cleaning the slate for building a new request for profile access.

Syntax

navigator.userProfile.clearRequest

Return Value

No return value.

Applies To

userProfile


clearTimeout

Description

Cancels a time-out that was set with the setTimeout method.

Syntax

object.clearTimeout(timeoutID)

Parameter | Description
timeoutID | (Long) Time-out setting that was returned by a previous call to the setTimeout method.

Return Value

No return value.

Applies To

window


click

Description

Simulates a click by causing the onclick event to fire.

Syntax

object.click( )

Return Value

No return value.

Applies To

A, ADDRESS, APPLET, AREA, B, BIG, BLOCKQUOTE, BODY, BR, BUTTON, CAPTION, CENTER, CITE, CODE, DD, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FONT, FORM, H1, H2, H3, H4, H5, H6, HR, I, IMG, INPUT, KBD, LABEL, LEGEND, LI, LISTING, MAP, MARQUEE, MENU, OBJECT, OL, OPTION, P, PLAINTEXT, PRE, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP


close

Description

Closes the current browser window.

Syntax

object.close( )

Return Value

No return value.

Applies To

window


close

Description

Closes an output stream and forces data sent to layout to display.

Syntax

object.close( )

Return Value

No return value.

Applies To

document


collapse

Description

Moves the insertion point to the beginning or the end of the current range.

Syntax

object.collapse([start])

Parameter | Description
start | Optional. (Boolean) False moves the insertion point to the end of the text range. True (default) moves the insertion point to the beginning of the text range.

Return Value

No return value.

Remarks

This feature might not be available on non-Win32® platforms. See article Q172976 in the Microsoft® Knowledge Base for the latest information on Internet Explorer cross-platform compatibility.

Applies To

TextRange

See Also

expand


compareEndPoints

Description

Compares the two end points and returns -1, 0, or 1 for less than, equal to, or greater than, respectively.

Syntax

object.compareEndPoints(type, range)

Parameter | Description
type String that describes the end point to compare. Can be one of these values:
StartToEnd
StartToStart
EndToStart
EndToEnd
range | Text range object specifying the range from which the source end point is to be taken.

Return Value

Returns the result of the comparison.

Remarks

This feature might not be available on non-Win32 platforms. See article Q172976 in the Microsoft Knowledge Base for the latest information on Internet Explorer cross-platform compatibility.

Applies To

TextRange


confirm

Description

Displays a Confirm dialog box with the specified message, and OK and Cancel buttons.

Syntax

object.confirm([message])

Parameter | Description
message | Optional. (String) String to display.

Return Value

Returns TRUE if the user chooses OK, or FALSE if the user chooses Cancel.

Remarks

You have no control over the dialog box title.

Applies To

window


contains

Description

Checks whether the given element is contained within the current element.

Syntax

Boolean = object.contains(element)

Parameter | Description
element | Element object specifying the element to check.

Return Value

Returns TRUE if the element is contained, or FALSE otherwise.

Applies To

A, ADDRESS, APPLET, AREA, B, BASE, BASEFONT, BGSOUND, BIG, BLOCKQUOTE, BODY, BR, BUTTON, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, COMMENT, DD, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FONT, FORM, FRAME, FRAMESET, H1, H2, H3, H4, H5, H6, HEAD, HR, HTML, I, IFRAME, IMG, INPUT, KBD, LABEL, LEGEND, LI, LINK, LISTING, MAP, MARQUEE, MENU, META, NEXTID, OBJECT, OL, OPTION, P, PLAINTEXT, PRE, S, SAMP, SCRIPT, SELECT, SMALL, SPAN, STRIKE, STRONG, STYLE, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TITLE, TR, TT, U, UL, VAR, WBR, XMP


createCaption

Description

Creates an empty CAPTION element in the TABLE. If a CAPTION already exists, createCaption() returns the existing element, otherwise, it returns a pointer to the element created.

Syntax

object.createCaption()

Return Value

Returns the CAPTION element object. If the method fails, it returns null.

Remarks

The following example creates a caption,

myCaption = document.all.myTable.createCaption()

Applies To

table

See Also

createTFoot, createTHead, deleteTHead, deleteTFoot, deleteCaption


createElement

Description

Creates an instance of the element object for the specified tag. Only new IMG and OPTION elements can be created. Before they can be used, new objects must be explicitly added to their respective collections.

Syntax

element = object.createElement(tag)

Parameter | Description
tag | (String) Tag specifier.

Return Value

Returns an element object.

Applies To

document

See Also

add


createRange

Description

Creates a text range object from the current selection.

Syntax

object.createRange( )

Applies To

selection


createStyleSheet

Description

Creates a style sheet for the document.

Syntax

object.createStyleSheet(url, index)

Parameter | Description
url | Optional string that indicates how the style sheet is to be added to the document. If a file name is specified for the URL, the style information will be added as a link object. If the URL contains style information, this information will be added to the style object.
index | Optional integer indicating where the new style sheet is inserted in the styleSheets collection. The default is to insert the new style at the end of the collection.

Return Value

Returns a styleSheet object.

Example

To create a link to a style sheet

document.createStyleSheet('styles.css');

To add style sheet to the style object

document.createStyleSheet(document.body.style.backgroundColor='blue');

Applies To

document


createTextRange

Description

Creates a text range object for the given object. You use a text range to examine and modify the text within an object.

Syntax

TextRange = object.createTextRange( )

Return Value

Returns a text range object if successful, or NULL otherwise.

Examples

The following JScript example creates a text range for the document, then uses the range to display all text and HTML tags in the document.

var rng = document.body.createTextRange( );
if (rng!=null) {
    alert(rng.htmlText);
}

The following JScript example creates a text range for the first BUTTON element in the document, then uses the text range to change the text in the button.

var coll = document.all.tags("BUTTON");
if (coll!=null && coll.length>0) {
    var rng = coll[0].createTextRange();
    rng.text = "Clicked";
}

Applies To

BODY, BUTTON, INPUT (text type only), TEXTAREA

See Also

TextRange


createTFoot

Description

Creates an empty TFOOT element in the TABLE. If a TFOOT already exists for the TABLE, createTFoot returns the existing element, otherwise, it returns a pointer to the element created.

Syntax

object.createTFoot()

Return Value

Returns the THead element object. If the method fails, it returns null.

Remarks

The following example creates a TFOOT,

myTFoot = document.all.myTable.createTFoot()

Applies To

table

See Also

createTHead, createCaption, deleteTHead, deleteTFoot, deleteCaption


createTHead

Description

Creates an empty THEAD element in the TABLE. If a THEAD already exists, createTHead returns the existing element, otherwise, it returns a pointer to the element created.

Syntax

object.createTHead()

Return Value

Returns the THead element object. If the method fails, it returns null.

Remarks

The following example creates a THEAD,

myTHead = document.all.myTable.createTHead()

Applies To

table

See Also

createTFoot, createCaption, deleteTHead, deleteTFoot, deleteCaption


deleteCaption

Description

Deletes the Caption element and its contents from the TABLE.

Syntax

object.deleteCaption()

Return Value

No return value.

Remarks

The following example deletes the caption,

document.all.myTable.deleteCaption()

Applies To

table

See Also

createTFoot, createTHead, createCaption, deleteTFoot, deleteTHead


deleteCell

Description

Deletes the specified cell (TD) in the table row and removes the cell from the cells collection. You can specify a cellIndex for the cell to be deleted from the TD, or without a cellIndex, the last cell in the cells collection will be deleted.

Syntax

object.deleteCell(index)

Return Value

No return value. Index specifies which element in the cells collection to remove.

Remarks

The following example deletes the last cell in the first row of the table

document.all.myTable.rows[0].deleteCell()

Applies To

TR

See Also

insertCell, deleteRow


deleteRow

Description

Deletes the specified row (TR) in the table and removes the row from the rows collection. Deleting a row from a TFOOT, TBODY, or THEAD also removes the row from the rows collection for the TABLE. Deleting a row in the TABLE, removes a row from the rows collection for the TBODY. However, when specifying the index for the row to be deleted, you must specify the sectionRowIndex if the row is being deleted from a TBODY, TFOOT or THEAD. You must specify the rowIndex if the row is being deleted from the TABLE.

Syntax

object.deleteRow(index)

Return Value

No return value Index specifies which element in the rows collection to remove.

Remarks

The following example deletes the specified row (TR) in the table,

myNewRow = document.all.myTable.deleteRow()

Applies To

table, TBODY, TFOOT, THEAD

See Also

rows, rowIndex, sectionRowIndex, insertRow


deleteTFoot

Description

Deletes the TFOOT element and its contents from the TABLE.

Syntax

object.deleteTFoot()

Return Value

No return value.

Remarks

The following example deletes the TFOOT element,

document.all.myTable.deleteTFoot()

Applies To

table

See Also

createTFoot, createTHead, createCaption, deleteTHead, deleteCaption


deleteTHead

Description

Deletes the THEAD element and its contents from the TABLE.

Syntax

object.deleteTHead()

Return Value

No return values.

Remarks

The following example deletes the THEAD element,

document.all.myTable.deleteTHead()

Applies To

table

See Also

createTFoot, createTHead, createCaption, deleteTFoot, deleteCaption


doReadRequest

Description

Performs the compound request accumulated in the read-requests queue. If the site does not already have read access, the user will be prompted with a list of attributes requested and can choose to allow or deny access.

Syntax

navigator.userProfile.doReadRequest(usageCode [, friendlyName [, domain [, path [, expiration]]]])

Parameter | Description
usageCode | Notification for the user of the type of access requested. This usage code should be one of the 13 codes (listed below) defined by the Internet Privacy Working Group (IPWG).
friendlyName | Optional. "Friendly name" of the party requesting access to private information. For security reasons, it is not enough for the user agent to display this friendly name to the end user. In addition to this friendly name, it is essential to display the URL that originates the script requesting profile access. If this script originates from a secure connection (for example, SSL), the SSL certificate can also be used to reliably identify the party requesting access.
domain and path | Optional. Which pages the user's choice will apply to in the future, in addition to the current one; the specification follows the cookie standard (RFC-2109 http://www.cis.ohio-state.edu/htbin/rfc/rfc2109.html).
expiration | Optional. How long the site is requesting access to these attributes. This is currently ignored by Internet Explorer.

Return Value

Returns TRUE if successful, or FALSE otherwise.

Remarks

The following table defines the usage codes.
Usage code values | Meaning
0 | Used for system administration.
1 | Used for research and/or product development.
2 | Used for completion and support of current transaction.
3 | Used to customize the content and design of a site.
4 | Used to improve the content of site including advertisements.
5 | Used for notifying visitors about updates to the site.
6 | Used for contacting visitors for marketing of services or products.
7 | Used for linking other collected information.
8 | Used by site for other purposes.
9 | Disclosed to others for customization or improvement of the content and design of the site.
10 | Disclosed to others, who may contact you, for marketing of services and/or products.
11 | Disclosed to others, who may contact you, for marketing of services and/or products, but you will have the opportunity to ask a site not to do this.
12 | Disclosed to others for any other purpose.

Applies To

userProfile


duplicate

Description

Returns a duplicate of the range.

Syntax

TextRange = object.duplicate( )

Return Value

Returns TextRange.

Remarks

This feature might not be available on non-Win32 platforms. See article Q172976 in the Microsoft Knowledge Base for the latest information on Internet Explorer cross-platform compatibility.

Applies To

TextRange


elementFromPoint

Description

Returns the element for the specified x and y coordinates.

Syntax

element = object.elementFromPoint(x, y)

Parameter | Description
x | (Integer) X-offset, in pixels.
y | (Integer) Y-offset, in pixels.

Return Value

Returns an element object.

Remarks

Coordinates are supplied in window coordinates (0,0 is the top-left corner of the window). For elementFromPoint to exhibit expected behavior, the object or element located at position (x, y) must support and respond to mouse events. MouseEventsEnabled must be 1.

Applies To

document


empty

Description

Deselects the current selection, sets the selection type to "none", and sets the item property to null.

Syntax

object.empty( )

Return Value

No return value.

Applies To

selection


execCommand

Description

Executes a command over the given selection or text range.

Syntax

Boolean = object.execCommand(sCommand [, bUserInterface [, vValue]])

Parameter | Description
sCommand | String specifying the command to execute. Can be any valid command identifier.
bUserInterface | Optional. Boolean value specifying whether to display a user interface if the command supports one. Can be TRUE or FALSE. If not given, defaults to FALSE.
vValue | Optional. Variant specifying a string, number, or other value to assign. Possible values depend on command.

Return Value

Returns TRUE if the command is successful, or FALSE otherwise.

Remarks

Wait to invoke the execCommand method until after the page has loaded.

Applies To

document, TextRange

See Also

queryCommandEnabled, queryCommandIndeterm, queryCommandState, queryCommandSupported, queryCommandValue


execScript

Description

Executes the script defined for the expression parameter in the language parameter. The language defaults to JScript.

Syntax

object.execScript(expression , language)

Parameter | Description
expression | String specifying the code to be executed.
language | String specifying the language in which the code is executed.

Return Value

No return value.

Applies To

window


expand

Description

Expands the range so that partial units are completely contained.

Syntax

Boolean = object.expand(unit)

Parameter Description
unit Units to move in the range. Can be one of the following:
character | Expands a character.
word | Expands a word. A word is a collection of characters terminated by a space or other white-space character.
sentence | Expands a sentence. A sentence is a collection of words terminated by a punctuation character, such as a period.
textedit | Expands to enclose the entire range.

Return Value

Returns TRUE if it successfully expands the range, or FALSE otherwise.

Remarks

This feature might not be available on non-Win32 platforms. See article Q172976 in the Microsoft Knowledge Base for the latest information on Internet Explorer cross-platform compatibility.

Example

The following example creates a range from the current selection, then uses expand to ensure that any word partially enclosed by the range becomes entirely enclosed in the range.

var rng = document.selection.createRange();
rng.expand("word");

Applies To

TextRange

See Also

collapse


findText

Description

Searches for text in the document. Positions the start and end points of the range to encompass the search string.

Syntax

bFound = object.findText(sText [, iSearchScope] [, iFlags])

Parameter | Description
sText | String specifying the text to find.
iSearchScope | Optional. An integer indicating the direction to search from the starting point of the range. A positive integer indicates a forward search; a negative integer indicates a backward search.
iFlags Optional. A combination of one or more of the following flags indicating the type of search:
2 | match whole words only.
4 | match case.

Return Value

Returns true if the search text is found, or false otherwise.

Remarks

A range has two distinct states: degenerate and non-degenerate. Analogous to a text editor, a degenerate range is like a text editor caret (insertion point); it does not actually select any characters. Instead it specifies a point between two characters. A degenerate range’s endpoints are effectively next to each other. On the other hand, a non-degenerate range is like a text editor selection. A certain amount of text is selected, and the end points of the range are not next to each other.

The degenerate state of the range has a significant impact on the behavior of the findText method. The value passed for the iSearchScope parameter controls the part of the document, relative to the range, that is searched. If the range is degenerate, either a large positive or a large negative number can be passed to indicate the direction of the search. If the range is non-degenerate, passing 0 will cause only the text selected by the range to be searched. Passing a large positive number will cause the text to the right of the start of the range to be searched. Passing a large negative number will cause the text to the left of the end of the range to be searched. For all intensive purposes, a large positive and a large negative number are 9999999 and -9999999, respectively. Passing anything else for iSearchScope may not be compatible with future versions of Internet Explorer.

This feature might not be available on non-Win32 platforms. See article Q172976 in the Microsoft Knowledge Base for the latest information on Internet Explorer cross-platform compatibility.

Example

The following example creates a Text Range over the body of the document and searches for text with various flag combinations. The results are indicated in the code comments.

<HTML>
<BODY>
Leonardo da Vinci was one of the great masters of the High Renaissance,
especially in painting, sculpture, architecture, engineering, and science.
</BODY>
</HTML>

<SCRIPT>
   var oRange = document.body.createTextRange();
   var sBookMark = oRange.getBookmark(); // record the current position in a bookmark
   oRange.findText('leo');               // true. case insensitive and partial word match.
   oRange.moveToBookmark(sBookMark);	 // reset the range using the bookmark
   oRange.findText('engineer', 0, 2);    // false. matches whole words only.
   oRange.moveToBookmark(sBookMark);
   oRange.findText('high', 0, 4);        // false. case sensitive.
   oRange.moveToBookmark(sBookMark);
   oRange.findText('Leonardo', 0, 6);    // true. case sensitive and matches whole words.

   // the degenerate case
   oRange.moveToBookmark(sBookMark);
   oRange.collapse();                    // make the range degenerate
   oRange.findText('Leonardo', 0, 6);    // false. must specify large character count in this case
   oRange.findText('Leonardo');          // true. no third parameter passed, so no count needed
   oRange.findText('Leonardo', 1000000000, 6);    // true. a large count covers the range.
</SCRIPT>

Applies To

TextRange


focus

Description

Causes a control to receive the focus and executes the code specified by onfocus.

Syntax

object.focus( )

Return Value

No return value.

Applies To

A, APPLET, AREA, BODY, BUTTON, CAPTION, DIV, EMBED, FIELDSET, FRAME, FRAMESET, HR, IFRAME, IMG, INPUT, MARQUEE, OBJECT, SELECT, SPAN, TABLE, TD, TEXTAREA, TR, window


forward

Description

Loads the next URL in the History list.

Syntax

object.forward( )

Return Value

No return value.

Remarks

This method performs the same action as a user choosing the Forward button in the browser. The forward method is the same as history.go(1). Trying to go past the end of the history does not generate an error. Instead, you are left at the current page.

Applies To

history

See Also

back, go


getAttribute

Description

Retrieves the value of the given attribute.

Syntax

variant = object.getAttribute(attrName [, iFlags])

Parameter | Description
attrName | String specifying the name of the attribute.
iFlags | Optional. A combination of the following flags: 1 indicates that a case-sensitive search should be used to locate the attribute. 2 indicates that the value should be returned as it was specified in the source. 0 (default) indicates that the search should be case-insensitive, and that the returned value may be interpolated.

Return Value

Returns a string, number, or Boolean value as defined by the attribute. If the attribute is not present, this method returns null.

Remarks

If two or more attributes have the same name (differing only in uppercase and lowercase letters) and caseSensitive is FALSE, this method retrieves values only for the last attribute (the last to be created with this name). All other attributes of the same name are ignored.

If iFlags is set to 1, the uppercase and lowercase letters in attrName must match exactly those in the attribute name. If the caseSensitive parameter for the setAttribute method is set to true and this option is set to false (default), a conflict will arise.

Applies To

A, ADDRESS, APPLET, AREA, B, BASE, BASEFONT, BGSOUND, BIG, BLOCKQUOTE, BODY, BR, BUTTON, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, COMMENT, DD, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FONT, FORM, FRAME, FRAMESET, H1, H2, H3, H4, H5, H6, HEAD, HR, HTML, I, IFRAME, IMG, INPUT, KBD, LABEL, LEGEND, LI, LINK, LISTING, MAP, MARQUEE, MENU, META, NEXTID, OBJECT, OL, OPTION, P, PLAINTEXT, PRE, S, SAMP, SCRIPT, SELECT, SMALL, SPAN, STRIKE, STRONG, STYLE, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TITLE, TR, TT, U, UL, VAR, WBR, XMP, style


getAttribute

Description

Returns the value of the named attribute. If read access for this attribute is not already available, this method simply returns the NULL string.

Syntax

navigator.userProfile.getAttribute(attributeName, attributeValue)

Parameter | Description
attributeName | One of the standard vCard names (listed below); otherwise the request is ignored and nothing is returned.
attributeValue | Value stored in the attributeName parameter.

Remarks

The following schema is used for the field names of the user data store. These names are specified when using the getAttribute method on the userProfile object. Please note that the format has changed from vCard_xxx to vCard.xxx and that the older format will no longer be supported.

vCard Names

vCard.Email | vCard.DisplayName | vCard.FirstName
vCard.LastName | vCard.MiddleName | vCard.Cellular
vCard.Gender* | vCard.JobTitle | vCard.Pager
vCard.Company | vCard.Department | vCard.Notes
vCard.Office | vCard.Homepage | vCard.Home.StreetAddress
vCard.Home.City | vCard.Home.State | vCard.Home.Zipcode
vCard.Home.Country | vCard.Home.Phone | vCard.Home.Fax
vCard.Business.StreetAddress | vCard.Business.City | vCard.Business.Phone
vCard.Business.Fax | vCard.Business.URL | vCard.Business.State
vCard.Business.Country | vCard.Business.Zipcode

Note (*) asterisk denotes extensions to the vCard schema, which will be referenced as X- elements as defined in the vCard schema.

Applies To

userProfile


getBookmark

Description

Retrieves a bookmark (opaque string) that can be used with moveToBookmark to return to the same range.

Syntax

string = object.getBookmark( )

Return Value

Returns a string if successful, or null otherwise.

Remarks

This feature might not be available on non-Win32 platforms. See article Q172976 in the Microsoft Knowledge Base for the latest information on Internet Explorer cross-platform compatibility.

Applies To

TextRange


go

Description

Loads a URL in the History list.

Syntax

object.go(delta | location)

Parameter | Description
delta | location | delta is an integer representing a relative position in the History list. location is a string representing all or part of a URL in the History list.

Return Value

No return value.

Remarks

Trying to go past the beginning or end of the history does not generate an error. Instead, you are left at the current page.

Applies To

history

See Also

back, forward


inRange

Description

Returns whether or not one range (the parameter) is contained within another.

Syntax

bContained = object.inRange(oRange)

Parameter | Description
oRange | Reference to a Text Range.

Return Value

Returns true if the range passed as the method parameter is contained within or is equal to the range upon which the method is called. Returns false otherwise.

Remarks

This feature might not be available on non-Win32 platforms. See article Q172976 in the Microsoft Knowledge Base for the latest information on Internet Explorer cross-platform compatibility.

Example

The following three examples show equal text ranges, a contained range, and a range outside the range upon which inRange is called.

   <HTML>
   <BODY>
   <DIV ID=div1>
   Content for division 1.
   </DIV>
   <DIV ID=div2>
   Content for division 2.
   </DIV>
   </BODY>
   </HTML>

   var oRng1 = document.body.createTextRange();
   var oRng2 = oRng1.duplicate();
   var bInside = oRng1.inRange(oRng2); // returns true; oRng2 is within or equal to oRng1

   oRng1.moveToElementText(div1);
   oRng2.moveToElementText(div2);
   bInside = oRng1.inRange(oRng2); // returns false; oRng2 is outside of oRng1

   var oRng3 = oRng1.duplicate();
   oRng3.findText('division 1');
   bInside = oRng1.inRange(oRng3); // returns false; oRng2 is outside of oRng1
Click the Show Me to see working code.

Applies To

TextRange

See Also

isEqual


insertAdjacentHTML

Description

Inserts the given HTML text into the element at the given place. If the text contains HTML tags, the method parses and formats the text as it inserts.

Syntax

object.insertAdjacentHTML(where, text)

Parameter | Description
where String specifying where to insert the HTML text. Can be one of the following:
BeforeBegin | Inserts the text immediately before the element.
AfterBegin | Inserts the text after the start of the element but before all other content in the element.
BeforeEnd | Inserts the text immediately before the end of the element but after all other content in the element.
AfterEnd | Inserts the text immediately after the end of the element.
text | String specifying the HTML text to insert. The string can be a combination of text and HTML tags. This must be well-formed, valid HTML or this method fails.

Return Value

No return value.

Remarks

You cannot insert text while the document is loading. Wait for the onload event before attempting to call this method.

Applies To

A, ADDRESS, AREA, B, BASEFONT, BIG, BLOCKQUOTE, BODY, BUTTON, CAPTION, CENTER, CITE, CODE, COMMENT, DD, DFN, DIR, DIV, DL, DT, EM, FIELDSET, FONT, FORM, FRAMESET, H1, H2, H3, H4, H5, H6, HR, I, IFRAME, IMG, INPUT, KBD, LABEL, LEGEND, LI, LISTING, MAP, MARQUEE, MENU, OL, OPTION, P, PLAINTEXT, PRE, S, SAMP, SCRIPT, SELECT, SMALL, SPAN, STRIKE, STRONG, STYLE, SUB, SUP, TD, TEXTAREA, TH, TR, TT, U, UL, VAR, XMP

See Also

insertAdjacentText,innerHTML, outerHTML


insertAdjacentText

Description

Inserts the given text into the element at the given place. The method inserts the text as plain text.

Syntax

object.insertAdjacentText(where, text)

Parameter | Description
where String specifying where to insert the text. Can be one of the following:
BeforeBegin | Inserts the text immediately before the element.
AfterBegin | Inserts the text after the start of the element but before all other content in the element.
BeforeEnd | Inserts the text immediately before the end of the element but after all other content in the element.
AfterEnd | Inserts the text immediately after the end of the element.
text | String specifying the text to insert.

Return Value

No return value.

Remarks

You cannot insert text while the document is loading. Wait for the onload event before attempting to call this method.

Applies To

A, ADDRESS, AREA, B, BASEFONT, BIG, BLOCKQUOTE, BODY, BUTTON, CAPTION, CENTER, CITE, CODE, COMMENT, DD, DFN, DIR, DIV, DL, DT, EM, FIELDSET, FONT, FORM, FRAMESET, H1, H2, H3, H4, H5, H6, HR, I, IFRAME, IMG, INPUT, KBD, LABEL, LEGEND, LI, LISTING, MAP, MARQUEE, MENU, OL, OPTION, P, PRE, S, SAMP, SCRIPT, SELECT, SMALL, SPAN, STRIKE, STRONG, STYLE, SUB, SUP, TD, TEXTAREA, TH, TR, TT, U, UL, VAR

See Also

insertAdjacentHTML,innerText,outerText


insertCell

Description

Creates a new cell in the table row and adds the cell to the cells collection.

Syntax

object.insertCell(index)

Return Value

Returns the TD element object. If the method fails, it returns null. Index is optional. Default value is "-1" which appends the TD to the end of the cells collection.

Remarks

The following example adds a cell to the end of the TR,

myNewCell = document.all.myTable.rows[0].insertCell()

Applies To

TR

See Also

deleteCell, InsertRow


insertRow

Description

Creates a new row (TR) in the table and adds the row to the rows collection. Inserting a row in a TFOOT, TBODY, or THEAD also adds a row to the rows collection for the TABLE. Inserting a row in the TABLE, adds a row to the rows collection for the TBODY. If specifying an index, the index should be relative to the rows collection for the element which first contains the TR. For example, insertRow for a TBODY would take an index value relative to the rows collection that is on the TBODY, not the TABLE.

Syntax

object.insertRow(index)

Return Value

Returns the TR element object. If the method fails, it returns null. Index is optional. Default value is "-1" which appends the TD to the end of the rows collection.

Remarks

The following example adds a row to the TABLE,

myNewRow = document.all.myTable.insertRow()

Applies To

table, TBODY, TFOOT, THEAD

See Also

rows, rowIndex, sectionRowIndex


isEqual

Description

Returns whether the specified range is equal to the current range.

Syntax

Boolean = object.isEqual(compareRange)

Parameter | Description
compareRange | (TextRange) Range object.

Return Value

Returns TRUE if equal, FALSE otherwise.

Applies To

TextRange

See Also

inRange


isSubscribed

Description

Returns whether the given channel is subscribed to by the client.

Syntax

Boolean = object.isSubscribed(urlToCDF)

Parameter | Description
urlToCDF | Required. Specifies the URL of a Channel Definition Format (CDF) file to be checked for a subscription.

Return Value

Returns true if the channel is subscribed to, or false if no subscription exists for that CDF file.

Remarks

For security purposes, if this method is used in an HTML page that is not in the same secondary domain specified in the urlToCDF, the method will return a scripting error.

Further information is available on Creating Active Channels.

Applies To

external


item

Description

Retrieves an element or a collection from the given collection. The index determines which action to take.

Syntax

element = object.item(index [, subindex])

Parameter | Description
index | Number or string specifying the element or collection to retrieve. If this parameter is a number, the method returns the element in the collection at the given position, where the first element has value 0, the second has 1, and so on. If this parameter is a string, the method returns a collection of elements, where the value of the name or id property for each element is equal to the string.
subindex | Optional. Number specifying the position of an element to retrieve. This parameter is used when index is a string. The method uses the string to construct a collection of all elements that have a name or id equal to the string, then retrieves from this collection the element at the position specified by subindex.

Return Value

Returns an element object or a collection of element objects if successful, or null otherwise.

Examples

The following JScript example uses the item method to retrieve each element from the document. In this case, the method parameter is a number, so the elements are retrieved in the order in which they appear in the document.

var coll = document.all;
if (coll!=null) {
    for (i=0; i<coll.length; i++)
        alert(coll.item(i).tagName);
}

The following JScript example uses the item method to retrieve a collection of all elements in the document having "Sample" as an id. It then uses item again to retrieve each element from the "Sample" collection.

var coll = document.all.item("Sample");
If (coll != null) {
    for (i=0; i<coll.length; i++) {
        alert(coll.item(i).tagName);
    }
}

The following JScript example is similar to the previous example, but uses the optional subindex parameter of item to retrieve individual elements.

var coll = document.all.item("Sample")
if (coll!=null) {
    for (i=0; i<coll.length; i++)
        alert(document.all.item("Sample",i).tagName);
}

Applies To

all, anchors, applets, areas, cells, elements, embeds, filters, forms, frames, images, imports, links, options, plugins, rows, scripts, styleSheets


javaEnabled

Description

Returns whether Java is enabled.

Syntax

Boolean = object.javaEnabled( )

Return Value

Returns TRUE if Java is enabled, or FALSE otherwise.

Applies To

navigator


Methods

add addChannel addImport
addReadRequest addRule alert
assign back blur
clear clear clearInterval
clearRequest clearTimeout click
close close collapse
compareEndPoints confirm contains
createCaption createElement createRange
createStyleSheet createTextRange createTHead
createTFoot deleteCaption deleteCell
deleteRow deleteTFoot deleteTHead
doReadRequest duplicate elementFromPoint
empty execCommand execScript
expand findText focus
forward getAttribute getAttribute
getBookmark go inRange
insertAdjacentHTML insertAdjacentText insertCell
insertRow isEqual isSubscribed
item javaEnabled move
moveBy moveEnd moveStart
moveTo moveToBookmark moveToElementText
moveToPoint navigate nextPage
open open parentElement
pasteHTML previousPage prompt
queryCommandEnabled queryCommandIndeterm queryCommandState
queryCommandSupported queryCommandValue refresh
reload remove removeAttribute
replace reset resizeBy
resizeTo scroll scrollBy
scrollTo scrollIntoView select
select setAttribute setEndPoint
setInterval setTimeout showHelp
showModalDialog start stop
submit tags taintEnabled
write writeln zOrder

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


move

Description

Collapses the given text range and moves the empty range by the given number of units.

Syntax

long = object.move(unit [, count])

Parameter | Description
unit String specifying the units to move. Can be one of the following:
character | Moves one or more characters.
word | Moves one or more words. A word is a collection of characters terminated by a space or other white-space character.
sentence | Moves one or more sentences. A sentence is a collection of words terminated by a punctuation character, such as a period.
textedit | Moves to the start or end of the original range.
count | Optional. Integer specifying the number of units to move. This can be positive or negative. When omitted, defaults to 1.

Return Value

Returns the actual number of units moved.

Remarks

This feature might not be available on non-Win32 platforms. See article Q172976 in the Microsoft Knowledge Base for the latest information on Internet Explorer cross-platform compatibility.

Applies To

TextRange

See Also

moveEnd, moveStart


moveBy

Description

Moves the screen position of the window by the specified x and y offsets relative to its current position.

Syntax

object.moveBy(x, y)

Parameter | Description
x | (Long) Horizontal scroll offset, in pixels.
y | (Long) Vertical scroll offset, in pixels.

Return Value

No return value.

Applies To

window


moveEnd

Description

Changes the scope of the range by moving the end position of the range.

Syntax

long = object.moveEnd(unit [, count])

Parameter | Description
unit String specifying the units to move. Can be one of the following strings:
character | Moves one or more characters.
word | Moves one or more words. A word is a collection of characters terminated by a space or other white-space character.
sentence | Moves one or more sentences. A sentence is a collection of words terminated by a punctuation character, such as a period.
textedit | Moves to the start or end of the original range.
count | Optional. Integer specifying the number of units to move. This can be positive or negative. When omitted, defaults to 1.

Return Value

Returns the actual number of units moved.

Remarks

This feature might not be available on non-Win32 platforms. See article Q172976 in the Microsoft Knowledge Base for the latest information on Internet Explorer cross-platform compatibility.

Applies To

TextRange

See Also

move, moveStart


moveStart

Description

Changes the scope of the range by moving the start position of the range.

Syntax

long = object.moveStart(unit [, count])

Parameter | Description
unit String specifying the units to move. Can be one of the following strings:
character | Moves one or more characters.
word | Moves one or more words. A word is a collection of characters terminated by a space or other white-space character.
sentence | Moves one or more sentences. A sentence is a collection of words terminated by a punctuation character, such as a period.
textedit | Moves to the start or end of the original range.
count | Optional. Integer specifying the number of units to move. This can be positive or negative. When omitted, defaults to 1.

Return Value

Returns the actual number of units moved.

Remarks

This feature might not be available on non-Win32 platforms. See article Q172976 in the Microsoft Knowledge Base for the latest information on Internet Explorer cross-platform compatibility.

Applies To

TextRange

See Also

move, moveEnd


moveTo

Description

Moves the screen position of the upper-left corner of the window to the specified x and y pixel position.

Syntax

object.moveTo(x, y)

Parameter | Description
x | (Long) Horizontal scroll offset, in pixels.
y | (Long) Vertical scroll offset, in pixels.

Return Value

No return value.

Applies To

window


moveToBookmark

Description

Moves to a bookmark. Bookmarks are opaque strings that are created with the getBookmark method.

Syntax

Boolean = object.moveToBookmark( )

Return Value

Returns TRUE if successful, or FALSE otherwise.

Remarks

This feature might not be available on non-Win32 platforms. See article Q172976 in the Microsoft Knowledge Base for the latest information on Internet Explorer cross-platform compatibility.

Applies To

TextRange


moveToElementText

Description

Moves the text range so that the start and end positions of the range encompass the text in the given element.

Syntax

object.moveToElementText(element)

Parameter | Description
element | Element object.

Return Value

No return value.

Remarks

This feature might not be available on non-Win32 platforms. See article Q172976 in the Microsoft Knowledge Base for the latest information on Internet Explorer cross-platform compatibility.

Applies To

TextRange


moveToPoint

Description

Moves the start and end positions of the text range to the given point. The coordinates of the point must be in pixels and be relative to the upper-left corner of the window. The resulting text range is empty, but can be expanded and moved using methods such as expand and moveEnd.

Syntax

object.moveToPoint(x, y)

Parameter | Description
x | Integer specifying the x-coordinate, in pixels.
y | Integer specifying the y-coordinate, in pixels.

Return Value

No return value.

Remarks

This feature might not be available on non-Win32 platforms. See article Q172976 in the Microsoft Knowledge Base for the latest information on Internet Explorer cross-platform compatibility.

Example

The following JScript example moves the text range to the same point as the user clicked the mouse, then expands the range and selects the text within the new range.

<SCRIPT FOR=document EVENT=onclick LANGUAGE="JScript">
var rng = document.body.createTextRange();
rng.moveToPoint(window.event.x, window.event.y);
rng.expand("word");
rng.select();
</SCRIPT>

Applies To

TextRange


navigate

Description

Equivalent to the window.location.href property.

Syntax

object.navigate(URL)

Parameter | Description
URL | (String) URL to be displayed.

Return Value

No return value.

Applies To

window

See Also

href property


nextPage

Description

Allows viewing the next page of records in the data set to which the table is bound.

Syntax

object.nextPage( )

Return Value

No return value.

Remarks

The number of records displayed in the table is determined by the dataPageSize property of the table. The Web author must set the DATAPAGESIZE attribute when designing the page or set the corresponding dataPageSize property at run time for this method to have any effect.

Note The page author does not need to check for boundary conditions.

Applies To

table

See Also

previousPage


open

Description

Opens a new window and loads the document given by URL, or a blank document if a URL is not provided.

Syntax

window = object.open([URL [, name [, features [, replace]]]])

Parameter | Description
URL | String specifying the URL of the document to display. If no URL is specified, a new window with about:blank will be displayed.
name | Optional. String specifying the name of the window. This name is used for TARGET on a FORM or an A.
features Optional. String specifying the window ornaments to display. The following table lists the supported features.
Syntax | Description
fullscreen={ yes | no | 1 | 0 } Specifies whether to display the browser in a full-screen or normal window. Default is no.

Use full-screen mode carefully. Because this mode hides the browser's title bar and menus, you should always provide a button or other visual clue to help the user close the window. ALT+F4 will also close the new window.

channelmode={ yes | no | 1 | 0 } | Specifies whether to display the window in theater mode and show the channel band.
toolbar={ yes | no | 1 | 0 } | Specifies whether to display the browser toolbar, making buttons such as Back, Forward, and Stop available.
location= { yes | no | 1 | 0 } | Specifies whether to display the input field for entering URLs directly into the browser.
directories = { yes | no | 1 | 0 } | Specifies whether to add directory buttons. Default is no.
status={ yes | no | 1 | 0 } | Specifies whether to add a status bar at the bottom of the window. Default is yes.
menubar={ yes | no | 1 | 0} | Specifies whether to display the menu bar. Default is yes.
scrollbars={ yes | no | 1 | 0} | Specifies whether to display horizontal and vertical scroll bars. Default is yes.
resizable={ yes | no | 1 | 0} | Specifies whether to display resize handles at the corners of the window.
width=number | Sets the width of the window, in pixels. Minimum value should be 100.
height=number | Specifies the height of the window, in pixels. Minimum value should be 100.
top=number | Specifies the top position, in pixels. This value is relative to the upper-left corner of the screen.
left=number | Specifies the left position, in pixels. This value is relative to the upper-left corner of the screen.
replace | Optional. A boolean value specifying whether the URL that is loaded into the new page should create a new entry in the window's browsing history or replace the current entry in the browsing history. If true, no new history entry is created.

Return Value

Returns a reference to the new window. Use this reference to script properties and methods on the new window.

Remarks

A name for the new window can be used as a target for a form or an A element. By default, the open() method creates a window that has a default width and height and the standard menu, toolbar, and other features of Internet Explorer. You can alter this set of features by using the features parameter. This parameter is a string consisting of one or more feature settings. The replace parameter controls whether the new window is put into the browser history list.

For example, the following creates a new window that contains Sample.htm. The new window is 200 by 400 pixels, has a status bar, but does not have a toolbar, menu bar, or address field.

window.open("sample.htm",null,
    "height=200,width=400,status=yes,toolbar=no,menubar=no,location=no");

Applies To

window


open

Description

Opens a stream to collect the output of write or writeln methods.

Syntax

document.open(mimeType, replace)

Parameter | Description
mimeType | Currently supports "text/html" only.
replace | Optional. String ("replace") indicating whether you want the new document you are writing to replace the current document in the History list. Otherwise, by default, the document you are creating will not replace the current document in the History list.

Return Value

No return value.

Remarks

The following example replaces the document with the new document.

document.open("text/html", "replace")

Applies To

document

Events

onbeforeunload


parentElement

Description

Retrieves the parent element for the given text range. The parent element is the element that completely encloses the text in the range.

Syntax

element = object.parentElement( )

Return Value

Returns an element object if successful, or null otherwise.

Remarks

If the text range spans text in more than one element, this method returns the smallest element that encloses all the elements. When you insert text into a range that spans multiple elements, the text is placed within the parent element rather than in any of the contained elements.

Remarks

This feature might not be available on non-Win32 platforms. See article Q172976 in the Microsoft Knowledge Base for the latest information on Internet Explorer cross-platform compatibility.

Example

The following JScript example retrieves the parent element for the text range created from the current selection and displays the tag name of the element.

var sel = document.selection;
var rng = sel.createRange();
var el = rng.parentElement();
alert(el.tagName);

Applies To

TextRange


pasteHTML

Description

Pastes HTML text into the given text range. The text completely replaces any previous text and HTML elements in the range.

Syntax

object.pasteHTML(htmlText)

Parameter | Description
htmlText | String specifying the HTML text to paste. The string can contain text and any combination of the HTML tags described in HTML Elements.

Return Value

No return value.

Remarks

Although this method never fails, it might alter the HTML text to make it fit the given text range. For example, attempting to paste a table cell into a text range that does not contain a table might cause the method to insert a TABLE element. For predictable results, you should paste only well-formed HTML text that is appropriate for the given text range.

Note You cannot use this method while the document is loading. Wait until the document is completely downloaded.

Remarks

This feature might not be available on non-Win32 platforms. See article Q172976 in the Microsoft Knowledge Base for the latest information on Internet Explorer cross-platform compatibility.

Example

The following JScript example replaces the current selection with a new paragraph.

var sel = document.selection;
if (sel!=null) {
    var rng = sel.createRange();
    if (rng!=null)
        rng.pasteHTML("<P><B>Selection has been replaced.</B>");
}

Applies To

TextRange


previousPage

Description

Allows viewing the previous page of records in the data set to which the table is bound.

Syntax

object.previousPage

Return Value

No return value.

Remarks

The number of records displayed in the table is determined by the dataPageSize property of the table. The Web author must set the DATAPAGESIZE attribute when designing the page or set the corresponding dataPageSize property at run time for this method to have any effect.

Note The page author does not need to check for boundary conditions.

Applies To

TABLE

See Also

nextPage


prompt

Description

Displays a Prompt dialog box with a message and an input field.

Syntax

object.prompt([message [, inputDefault]])

Parameter | Description
message | Optional. (String) String to display.
inputDefault | Optional. (String) String or integer that represents the default value of the input field.

Return Value

Returns the value that the user types in.

Remarks

If the inputDefault parameter is not supplied, the dialog box displays the value <undefined>. You have no control over the title of the prompt box.

Applies To

window


queryCommandEnabled

Description

Returns whether the command can be successfully executed using ExecCommand now, given the current state of the document.

Syntax

Boolean = object.queryCommandEnabled(command)

Parameter | Description
command | (String) String that specifies the command to query. Can be any valid command identifier.

Return Value

Returns TRUE if the command is enabled, or FALSE otherwise.

Remarks

Note: queryCommandEnabled("delete") on TextRange returns TRUE, while queryCommandEanbled("delete") on Document returns FALSE, but you can still use execCommand("Delete") to delete the selected text.

Applies To

document, TextRange

See Also

execCommand, queryCommandIndeterm, queryCommandState, queryCommandSupported, queryCommandValue


queryCommandIndeterm

Description

Returns whether the specified command is in the indeterminate state.

Syntax

Boolean = object.queryCommandIndeterm(command)

Parameter | Description
command | (String) String that specifies the command to query. Can be any valid command identifier.

Return Value

Returns TRUE if indeterminate, or FALSE otherwise.

Remarks

As an example, given a text range, if some of the characters are bold and others are not, queryCommandIndeterm for bold would return TRUE.

Applies To

document, TextRange

See Also

execCommand, queryCommandEnabled, queryCommandState, queryCommandSupported, queryCommandValue


queryCommandState

Description

Returns the current state of the command.

Syntax

Boolean = object.queryCommandState(command)

Parameter | Description
command | (String) String that specifies the command to query. Can be any valid command identifier.

Return Value

Returns TRUE if the given command has been carried out on the object, FALSE if it has not, and NULL if it is not possible to determine the command state.

Applies To

document, TextRange

See Also

execCommand, queryCommandEnabled, queryCommandIndeterm, queryCommandSupported, queryCommandValue


queryCommandSupported

Description

Returns whether the current command is supported on the current range.

Syntax

Boolean = object.queryCommandSupported(command)

Parameter | Description
command | (String) String that specifies the command to query. Can be any valid command identifier.

Return Value

Returns TRUE if the command is supported, or FALSE otherwise.

Applies To

document, TextRange

See Also

execCommand, queryCommandEnabled, queryCommandIndeterm, queryCommandState, queryCommandValue


queryCommandValue

Description

Returns the current value of the given command. If the command returns a value such as a color rather than a TRUE/FALSE state, this command is used to retrieve the current value of the document or range.

Syntax

string = object.queryCommandValue(command)

Parameter | Description
command | (String) String that specifies the command to query. Can be any valid command identifier.

Return Value

Returns a string representing the command value if the command is supported, or TRUE/FALSE.

Applies To

document, TextRange

See Also

execCommand, queryCommandEnabled, queryCommandIndeterm, queryCommandState, queryCommandSupported


refresh

Description

Refreshes the content of the table.

Syntax

object.refresh( )

Return Value

No return value.

Applies To

TABLE


reload

Description

Reloads the current page.

Syntax

object.reload([bReloadSource] )

Parameter | Description
bReloadSource | Optional. Boolean value specifying whether to reload the page from the cache or server. If TRUE, the page is reloaded from the server. By default, this parameter is FALSE.

Return Value

No return value.

Applies To

location


remove

Description

Removes an element from the collection.

Syntax

object.remove(index)

Parameter | Description
index | Number or string specifying the element to remove. If this parameter is a number, the method removes the element at the given position in the collection, where 0 is the first position, 1 the second, and so on. If this parameter is a string, the method removes all elements having a name or id property equal to the string.

Return Value

No return value.

Remarks

For the areas object, this method can only be used on the object after the page has been loaded. If the method is applied "inline," a run-time error will occur.

Applies To

areas, options

See Also

add


removeAttribute

Description

Removes the given attribute from the element.

Syntax

Boolean = object.removeAttribute(attrName [, caseSensitive])

Parameter | Description
attrName | String specifying the name of the attribute.
caseSensitive | Optional. Boolean value specifying whether to use a case-sensitive search to locate the attribute. If TRUE, the uppercase and lowercase letters in attrName must match exactly those in the attribute name. By default, this parameter is TRUE. If there are multiple attributes specified with different case sensitivity, the attribute returned might vary across platforms.

Return Value

Returns TRUE if successful, or FALSE otherwise.

Remarks

If two or more attributes have the same name (differing only in uppercase and lowercase letters) and caseSensitive is FALSE, this method removes only the last attribute (the last to be created with this name). All other attributes of the same name are ignored.

Applies To

A, ADDRESS, APPLET, AREA, B, BASE, BASEFONT, BGSOUND, BIG, BLOCKQUOTE, BODY, BR, BUTTON, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, COMMENT, DD, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FONT, FORM, FRAME, FRAMESET, H1, H2, H3, H4, H5, H6, HEAD, HR, HTML, I, IFRAME, IMG, INPUT, KBD, LABEL, LEGEND, LI, LINK, LISTING, MAP, MARQUEE, MENU, META, NEXTID, OBJECT, OL, OPTION, P, PLAINTEXT, PRE, S, SAMP, SCRIPT, SELECT, SMALL, SPAN, STRIKE, STRONG, STYLE, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TITLE, TR, TT, U, UL, VAR, WBR, XMP, style


replace

Description

Replaces the current document by loading the document at the given url. This method also removes the current document from the browser's session history.

Syntax

object.replace(url)

Parameter | Description
url | String specifying the URL to insert into the session history.

Remarks

Replacing a document causes it to no longer be accessible through the history object. Also, the URL is no longer accessible through the user interface navigation methods (Back, Forward, and so on).

Applies To

location


reset

Description

Simulates a mouse click on a reset button for the calling form.

Syntax

object.reset( )

Return Value

No return value.

Applies To

FORM

See Also

INPUT, button, submit


resizeBy

Description

Changes the size of the window outside dimensions by the specified x and y offset relative to its current size.

Syntax

object.resizeBy(x, y)

Parameter | Description
x | (Long) Horizontal scroll offset, in pixels.
y | (Long) Vertical scroll offset, in pixels.

Return Value

No return value.

Applies To

window


resizeTo

Description

Sets the size of the window outside dimensions to the specified x and y pixel sizes.

Syntax

object.resizeTo(x, y)

Parameter | Description
x | (Long) Horizontal scroll offset, in pixels.
y | (Long) Vertical scroll offset, in pixels.

Return Value

No return value.

Applies To

window


scroll

Description

Causes the window to scroll to the specified x and y offset at the upper-left corner of the window. The preferred method for this is scrollTo; the scroll method is provided for backward compatibility only.

Syntax

object.scroll(x, y)

Parameter | Description
x | (Long) Horizontal position, in pixels.
y | (Long) Vertical offset, in pixels.

Return Value

No return value.

Applies To

window


scrollBy

Description

Causes the window to scroll relative to the current scrolled position by the specified x and y pixel offsets.

Syntax

object.scrollBy(x, y)

Parameter | Description
x | (Long) Horizontal scroll offset, in pixels.
y | (Long) Vertical scroll offset, in pixels.

Return Value

No return value.

Remarks

Positive values of x/y scroll further right/down; negative values scroll further left/up. Setting the scroll position beyond the limits results in the extreme valid scroll position in the direction specified.

Applies To

window


scrollIntoView

Description

Causes the object to scroll into view, aligning it at either the top or bottom of the window.

Syntax

object.scrollIntoView([start])

Parameter | Description
start | Optional. Boolean value specifying whether to place the object at the top of the window or at the bottom. If TRUE, the method causes the object to scrolls so that its top is visible at the top of the window. If FALSE, the bottom of the object is visible at the bottom of the window. If no value is given, the object scrolls to the top by default.

Return Value

No return value.

Remarks

The following example causes the element to scroll into view within the window, placing it at either the top or bottom of the window. The method is useful for immediately showing the user the result of some action without requiring the user to manually scroll through the document to find the result. This example underlines the content of the fifth paragraph and scrolls it into view at the top of the window.

var coll = document.all.tags("P");
if (coll.length>=5) {
    coll(4).style.textDecoration = "underline";
    coll(4).scrollIntoView(true);
}

Depending on the size of the given object and the current window, this method might not be able to put the item at the very top or very bottom, but will always position the object as close to the requested position as possible.

Applies To

A, ADDRESS, APPLET, AREA, B, BIG, BLOCKQUOTE, BR, BUTTON, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, COMMENT, DD, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FONT, FORM, H1, H2, H3, H4, H5, H6, HR, I, IFRAME, IMG, INPUT, KBD, LABEL, LEGEND, LI, LISTING, MAP, MARQUEE, MENU, OBJECT, OL, P, PLAINTEXT, PRE, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, WBR, XMP, TextRange


scrollTo

Description

Scrolls the window to the specified x and y offsets at the upper-left corner of the window.

Syntax

object.scrollTo(x, y)

Parameter | Description
x | (Long) Horizontal scroll offset, in pixels.
y | (Long) Vertical scroll offset, in pixels.

Return Value

No return value.

Applies To

window


select

Description

Highlights the input area of a form element.

Syntax

object.select( )

Return Value

No return value.

Remarks

You can use the select method with the focus method to highlight a field and position the cursor for a user response.

Applies To

INPUT, TEXTAREA

See Also

onselect


select

Description

Makes the active selection equal to the current object.

Syntax

object.select( )

Return Value

No return value.

Remarks

This feature might not be available on non-Win32 platforms. See article Q172976 in the Microsoft Knowledge Base for the latest information on Internet Explorer cross-platform compatibility.

Applies To

TextRange


setAttribute

Description

Sets the value of the given attribute. If the attribute is not already present, the method adds the attribute to the element and sets the value.

Syntax

object.setAttribute(attrName , value [, caseSensitive])

Parameter | Description
attrName | String specifying the name of the attribute.
value | String, number, or Boolean value to assign to the attribute.
caseSensitive | Optional. Boolean value specifying whether to use a case-sensitive search to locate the attribute. If TRUE, the uppercase and lowercase letters in attrName must match exactly those in the attribute name. By default, this parameter is TRUE.

Return Value

No return value.

Remarks

Be careful when spelling attribute names. If caseSensitive is TRUE and attrName does not have the same uppercase and lowercase letters as the attribute, this method creates a new attribute.

If two or more attributes have the same name (differing only in uppercase and lowercase letters) and caseSensitive is FALSE, this method assigns a value only to the first attribute (the first to be created with this name). All other attributes of the same name are ignored.

Applies To

A, ADDRESS, APPLET, AREA, B, BASE, BASEFONT, BGSOUND, BIG, BLOCKQUOTE, BODY, BR, BUTTON, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, COMMENT, DD, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FONT, FORM, FRAME, FRAMESET, H1, H2, H3, H4, H5, H6, HEAD, HR, HTML, I, IFRAME, IMG, INPUT, KBD, LABEL, LEGEND, LI, LINK, LISTING, MAP, MARQUEE, MENU, META, NEXTID, OBJECT, OL, OPTION, P, PLAINTEXT, PRE, S, SAMP, SCRIPT, SELECT, SMALL, SPAN, STRIKE, STRONG, STYLE, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TITLE, TR, TT, U, UL, VAR, WBR, XMP, style


setEndPoint

Description

Sets the end point of one range based on the end point of another. This method takes two parameters: a string that describes the end points to transfer, and a range from which the source end point will be taken.

Syntax

object.setEndPoint(type, range)

Parameter | Description
type String that describes the end point to transfer. Can be one of these values:
StartToEnd
StartToStart
EndToStart
EndToEnd
range | Text range object specifying the range from which the source end point is to be taken.

Return Value

No return value.

Remarks

This feature might not be available on non-Win32 platforms. See article Q172976 in the Microsoft Knowledge Base for the latest information on Internet Explorer cross-platform compatibility.

Example

The following JScript example sets the start point of the current range (r1) to the end point of the second range (r2).

r1.setEndPoint("StartToEnd", r2);

Applies To

TextRange


setInterval

Description

Repeatedly evaluates an expression after a specified number of milliseconds has elapsed.

Syntax

intervalID = object.setInterval(expression, msec [, language])

Parameter | Description
expression | String containing the script code to execute each time the interval elapses.
msec | Integer value or numeric string specifying the length of the interval, in milliseconds.
language | Optional. String specifying the language in which the code is executed.

Return Value

Returns an integer identifier representing the interval. Use this identifier to clear (stop) the interval.

Example

The following example sets a 5-second interval. Each time the interval elapses, the background color of the document changes.

setInterval("changeColor()", 5000);
   .
   .
   .
function changeColor()
{
  if (document.body.bgColor == "#ff0000")   // Check if body bgColor is red by comparing to hexidecimal value
      document.body.bgColor = "blue";
  else
      document.body.bgColor = "red";
}

Applies To

window

See Also

clearInterval


setTimeout

Description

Evaluates an expression after a specified number of milliseconds has elapsed.

Syntax

timeoutID = object.setTimeout(expression, msec [, language])

Parameter | Description
expression | (String) Code to be executed at the specified interval.
msec | (Long) Numeric value or numeric string in millisecond units.
language | Optional. (String) String that specifies the language in which the code is executed.

Return Value

Returns an identifier that is used only to cancel the evaluation with the clearTimeout method.

Applies To

window


showHelp

Description

Displays a Help file. This method can be used with WinHelp or with HTMLHelp.

Syntax

object.showHelp(URL [, arguments])

Parameter | Description
URL | String specifying the URL of the document to display.
contextID | Optional. Identifier of a help context ID in a Help file. Required if displaying an .hlp file.

Return Value

No return value.

Remarks

When implementing this method, a second Help dialog box will appear if the user presses the F1 key or clicks Help from the menu bar. You can prevent the default Help dialog box from appearing by setting window.event.returnValue=false.

The contextID parameter is needed for calling Windows Help files. Without a valid contextID, Help does not load when the URL specifies a Windows Help file.

Applies To

window


showModalDialog

Description

Creates a dialog box and displays in it the HTML document given by URL. The dialog box is a special window that is modal, meaning it retains the input focus until the user closes it.

Syntax

variant = object.showModalDialog(sURL [, vArguments [, sFeatures]])

Parameter | Description
sURL | String specifying the URL of the document to load and display. While an empty string is accepted (""), it should be noted that this is useless since once a modal dialog has been opened, it cannot be accessed by the page that opened it.
vArguments | Optional. Variant specifying the arguments to use when displaying the document. This parameter can be used to pass a value of any type including an array of values. The dialog can extract the values passed by the caller from the dialogArguments property of the window object.
sFeatures Optional. String specifying the window ornaments for the dialog box. It can be a combination of the following values.
Syntax | Description
dialogWidth:number | Sets the width of the dialog window.
dialogHeight:number | Sets the height of the dialog window.
dialogTop:number | Sets the top position of the dialog window relative to the upper-left corner of the desktop.
dialogLeft:number | Sets the left position of the dialog window relative to the upper-left corner of the desktop.
center:{yes | no | 1 | 0 } | Specifies whether to center the dialog window within the desktop. Default is yes.

Return Value

Returns a number, string, or other value. This is equal to the value of the returnValue property as set by the document given by URL.

Remarks

The default font settings should be set in the same way CSS attributes are set; for example, "font:3;font-size:4". To define multiple font values, use multiple font attributes.

When dialogLeft and/or dialogTop is specified, the feature center is overridden, even though the default for center is yes.

Applies To

window


start

Description

Begins scrolling the marquee.

Syntax

object.start( )

Return Value

No return value.

Remarks

The onstart event must be implicitly set.

Applies To

MARQUEE


stop

Description

Stops the marquee scrolling.

Syntax

object.stop( )

Return Value

No return value.

Applies To

MARQUEE


submit

Description

Submits the form and fires the onsubmit event.

Syntax

object.submit( )

Return Value

No return value.

Applies To

FORM

See Also

INPUT, reset


tags

Description

Retrieves a collection of all elements in the given collection that have the given HTML tag name.

Syntax

elements = object.tags(tag)

Parameter | Description
tag | String specifying the name of an HTML tag. It can be the name of any one of the elements listed in Objects.

Return Value

Returns a collection of element objects if successful, or null otherwise.

Remarks

This method returns an empty collection if no elements having the given name are found. Use the length property on the collection to determine the number of elements it contains.

Example

The following JScript example retrieves a collection of all P elements in the document, then applies an underline to each.

var coll = document.all.tags("P");
if (coll!=null) {
    for (i=0; i<coll.length; i++)
    coll[i].style.textDecoration="underline";
}

Applies To

all, anchors, applets, areas, embeds, forms, images, links, plugins, scripts, styleSheets


taintEnabled

Description

Returns whether data tainting is enabled.

Syntax

object.taintEnabled( )

Return Value

Always returns FALSE for Internet Explorer 4.0. Data tainting is not supported.

Applies To

navigator


write

Description

Writes one or more HTML expressions to a document in the specified window.

Syntax

object.write(string)

Parameter | Description
string | String specifying the text and/or HTML tags to write.

Return Value

No return value.

Applies To

document


writeln

Description

Writes one or more HTML expressions to a document in the specified window, followed by a carriage return.

Syntax

object.writeln(string)

Parameter | Description
string | String specifying the text and/or HTML tags to write.

Return Value

No return value.

Remarks

In HTML, the carriage return is ignored unless within preformatted text.

Applies To

document


zOrder

Description

Sets the z-index for positions.

Syntax

object.zOrder([position])

Parameter Description
position (Variant) Can be an integer value specifying the z-order as an absolute value, or one of these string values:
Front | Sends the item to the front of the z-order.
Back | Sends the item to the back of the z-order.

Remarks

If no position is given, the default is Front. This method applies to all positioned elements.

Applies To

APPLET, BUTTON, CAPTION, DIV, EMBED, HR, IMG, INPUT (all types except hidden), MARQUEE, OBJECT, SPAN, TD, TEXTAREA


A

Description

Designates the start or destination of a hypertext link. The anchor element requires the href or the name property to be specified.

Remarks

Text and/or images can be within an anchor. To represent images that are anchors, a border in the visited or not-visited color is displayed.

Properties

accessKey, className, dataFld, dataSrc, document, hash, host, hostname, href, id, innerHTML, innerText, isTextEdit, lang, language, Methods, name, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, pathname, port, protocol, recordNumber, rel, rev, search, sourceIndex, style, tabIndex, tagName, target, title, urn

Methods

blur, click, contains, focus, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onblur, onclick, ondblclick, ondragstart, onerrorupdate, onfilterchange, onfocus, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

A


ACRONYM

Description

Indicates an acronym abbreviation.

Properties

className, document, id, innerHTML, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup,

HTML Element

ACRONYM

See Also

ADDRESS, CITE, DFN, EM, I


ADDRESS

Description

Specifies information such as address, signature, and authorship.

Remarks

This element is a block element.

Properties

className, document, id, innerHTML, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

ADDRESS

See Also

ACRONYM, CITE, DFN, EM, I


APPLET

Description

Places executable content on the page.

Remarks

This element is a block element.

Properties

accessKey, align, altHTML, className, code, codeBase, dataFld, dataSrc, document, height, hspace, id, isTextEdit, lang, language, name, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, src, style, tagName, title, vspace, width

Methods

blur, click, contains, focus, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children

Events

onafterupdate, onbeforeupdate, onblur, onclick, ondataavailable, ondatasetchanged, ondatasetcomplete, ondblclick, onerrorupdate, onfocus, onhelp, onkeydown, onkeypress, onkeyup, onload, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onreadystatechange, onresize, onrowenter, onrowexit,

HTML Element

APPLET


AREA

Description

Specifies the shape of a "hot spot" in a client-side image MAP.

Properties

alt, className, coords, document, hash, host, hostname, href, id, isTextEdit, lang, language, noHref, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, pathname, port, protocol, search shape, sourceIndex, style, tabIndex, tagName, target, title

Methods

blur, click, contains, focus, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onblur, onclick, ondblclick, ondragstart, onfilterchange, onfocus, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

AREA


B

Description

Specifies that the text should be rendered in bold, where available.

Properties

className, document, id, innerHTML, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

B

See Also

STRONG


BASE

Description

Specifies the document's base URL.

Remarks

This element is used to ensure that your document is not reviewed out of context.

This element can be used only within the HEAD tag.

Properties

className, document, href, id, isTextEdit, lang, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, tagName, target, title

Methods

contains, getAttribute, removeAttribute, setAttribute

Collections

all, children

HTML Element

BASE


BASEFONT

Description

Sets a base font value to be used as the default font when rendering text.

Remarks

This element can be used only within the BODY tag or the HEAD tag. BASEFONT should appear before any displayed text in the BODY of the document.

Properties

className, color, document, face, id, isTextEdit, outerHTML, outerText, parentElement, parentTextEdit, size, sourceIndex, tagName

Methods

contains, getAttribute, removeAttribute, setAttribute

Collections

all, children

HTML Element

BASEFONT


BGSOUND

Description

Allows you to create pages with background sounds or "sound tracks."

Remarks

This element can be used only within the HEAD tag.

Properties

balance, className, document, id, isTextEdit, loop, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, src, style, tagName, title, volume

Methods

contains, getAttribute, removeAttribute, setAttribute

Collections

all, children

HTML Element

BGSOUND


BIG

Description

Specifies that the enclosed text should be displayed in a relatively bigger font than the current font.

Properties

className, document, id, innerHTML, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

BIG


BLOCKQUOTE

Description

Sets apart a quotation in text.

Remarks

This element is a block element.

Properties

className, document, id, innerHTML, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

BLOCKQUOTE

See Also

Q


BODY

Description

Specifies the beginning and end of the document body.

Remarks

You can access the BODY element by using the body property on the document object.

Event handlers set using the onblur, onfocus, onload, or onunload property handle these events for the window object. These properties are of the window object but are hosted on the BODY element, since there is no "window" element available.

This element is a block element.

Properties

accessKey, aLink, background, bgColor, bgProperties, bottomMargin, className, clientHeight, clientLeft, clientTop, clientWidth, document, filter, id, innerHTML, innerText, isTextEdit, lang, language, leftMargin, link, noWrap, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, recordNumber, rightMargin, scroll, scrollHeight, scrollLeft, scrollTop, scrollWidth, sourceIndex, style, tabIndex, tagName, text, title, topMargin, vLink

Methods

click, contains, createTextRange, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, setAttribute

Collections

all, children, filters

Events

onafterupdate, onbeforeunload, onbeforeupdate, onchange, onclick, ondataavailable, ondatasetchanged, ondatasetcomplete, ondblclick, ondragstart, onerrorupdate, onfilterchange, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onrowenter, onrowexit, onselectstart

HTML Element

BODY

"


BR

Description

Inserts a line break.

Properties

className, clear, document, id, isTextEdit, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title

Methods

contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

HTML Element

BR


BUTTON

Description

Specifies a container for rich HTML that is rendered as a button.

Properties

accessKey, className, dataFld, dataFormatAs, dataSrc, disabled, document, form, id, innerHTML, innerText, isTextEdit, lang, language, name, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, status, style, tagName, title, type, value

Methods

blur, click, createTextRange, contains, focus, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onafterupdate, onbeforeupdate, onblur, onclick, ondblclick, ondragstart, onfilterchange, onfocus, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onresize, onrowenter, onrowexit, onselectstart

HTML Element

BUTTON


CAPTION

Description

Specifies a caption for a TABLE.

Remarks

This element is a block element.

Properties

align, className, clientHeight, clientLeft, clientTop, clientWidth, document, id, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title, vAlign

Methods

blur, click, contains, focus, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onafterupdate, onbeforeupdate, onblur, onchange, onclick, ondblclick, ondragstart, onfilterchange, onfocus, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onresize, onrowenter, onrowexit, onscroll, onselect, onselectstart

HTML Element

CAPTION


CENTER

Description

Causes subsequent text and images to be centered.

Remarks

This element is a block element.

Properties

className, document, id, innerHTML, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

CENTER


CITE

Description

Indicates a citation. Refers to a book, paper, or other published source material. Text is rendered in italic.

Properties

className, document, id, innerHTML, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

CITE

See Also

ACRONYM, ADDRESS, DFN, EM, I


CODE

Description

Specifies a code sample.

Properties

className, document, id, innerHTML, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

CODE

See Also

SAMP


COL

Description

Specifies column-based defaults for the table properties.

Properties

align, className, document, id, isTextEdit, parentElement, parentTextEdit, span, style, tagName, title, vAlign, width

Methods

contains, getAttribute, removeAttribute, setAttribute

Collections

all, children

HTML Element

COL

See Also

COLGROUP


COLGROUP

Description

Contains a group of columns.

Properties

align, className, document, id, isTextEdit, parentElement, parentTextEdit, span, style, tagName, title, vAlign, width

Methods

contains, getAttribute, removeAttribute, setAttribute

Collections

all, children

HTML Element

COLGROUP

See Also

COL


COMMENT

Description

Indicates a comment that will not be displayed.

Properties

className, document, id, isTextEdit, lang, parentElement, parentTextEdit, sourceIndex, tagName, title

Methods

contains, getAttribute, removeAttribute, setAttribute

Collections

all, children

HTML Element

COMMENT


DD

Description

Indicates the definition in a definition list. The definition is usually indented from the definition list.

Remarks

This element is a block element.

Properties

className, document, id, innerHTML, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, tagName, title

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

DD

See Also

DL, DT


DEL

Description

Indicates text that has been deleted from the document.

Properties

className, document, id, innerHTML, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup

HTML Element

DEL

See Also

INS


DFN

Description

Indicates the defining instance of a term.

Remarks

This element is a block element.

Properties

className, document, id, innerHTML, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

DFN

See Also

ACRONYM, ADDRESS, CITE, I


DIR

Description

Denotes a directory list.

Remarks

This element is a block element.

Properties

className, document, id, innerHTML, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

DIR


DIV

Description

Specifies a container that renders HTML.

Remarks

This element is a block element.

Properties

align, className, clientHeight, clientWidth, dataFld, dataFormatAs, dataSrc, document, id, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerText, parentElement, parentTextEdit, scrollHeight, scrollLeft, scrollTop, scrollWidth, sourceIndex, style, tagName, title

Methods

blur, click, contains, focus, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onafterupdate, onbeforeupdate, onblur, onclick, ondblclick, ondragstart, onfocus, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onresize, onrowenter, onrowexit, onscroll, onselectstart

HTML Element

DIV


DL

Description

Denotes a definition list.

Remarks

This element is a block element.

Properties

className, compact, document, id, innerHTML, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

DL

See Also

DD, DT


DT

Description

Indicates a definition term within a definition list.

Remarks

This element is a block element.

Properties

className, document, id, innerHTML, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup onselectstart

HTML Element

DT

See Also

DD, DL


EM

Description

Emphasizes text, usually by rendering it in italic.

Properties

className, document, id, innerHTML, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup onselectstart

HTML Element

EM

See Also

ACRONYM, ADDRESS, CITE, I


EMBED

Description

Allows you to embed documents of any type. The user needs to have an application that can view the data installed correctly on his or her computer. The EMBED object must appear inside the BODY of the document.

Remarks

This element is a block element.

Properties

accessKey, align, className, document, height, Hidden, id, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, palette, parentElement, parentTextEdit, pluginspage, sourceIndex, src, style, tagName, title, units, width

Methods

blur, contains, focus, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onblur, onfocus

HTML Element

EMBED


external

Description

Allows access to an additional object model provided by host applications of the Internet Explorer browser components. In a hosting scenario where it is available, the object model is defined by the application hosting the Internet Explorer components, and the hosting application should be referred to for documentation. For further details on how to implement extensions to the object model, see the SDK documentation on "Reusing the WebBrowser and MSHTML."

Methods

addChannel, isSubscribed

Applies To

window


FIELDSET

Description

Draws a box around the text and other elements it contains. This element is useful for grouping elements in a form and for distinctively marking text in a document.

Properties

accessKey, align, className, clientHeight, clientWidth, document, id, innerHTML, innerText, isTextEdit, lang, language, margin, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, padding, parentElement, parentTextEdit, recordNumber, scrollHeight, scrollLeft, scrollTop, scrollWidth, sourceIndex, style, tabIndex, tagName, title

Methods

blur, click, contains, focus, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onafterupdate, onbeforeupdate, onblur, onclick, onchange, ondblclick, ondragstart, onerrorupdate, onfilterchange, onfocus, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onresize, onrowenter, onrowexit, onscroll, onselect, onselectstart

HTML Element

FIELDSET


FONT

Description

Specifies a new font face, size, and color to be used for rendering the enclosed text.

Properties

className, color, document, face, id, innerHTML, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, size, sourceIndex, style, tagName, title

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

FONT


FORM

Description

Specifies that the contained controls take part in a form.

Remarks

When programming the form, all control-like elements are added to the form as named items.

When the focus is on a control in a form, pressing ESC once causes the value of the control to revert back to the last value, and pressing the key again resets the form. If the focus is on the but not on a particular control, pressing ESC once resets the form.

If one and only one text box is on a form, pressing ENTER fires the onsubmit event. If the form has a Submit button, the button appears with a dark border indicating that pressing ENTER submits the form.

This element is a block element.

Properties

action, className, document, encoding, id, innerHTML, innerText, isTextEdit, lang, language, method, name, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, target, title

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, reset, scrollIntoView, setAttribute, submit

Collections

all, children, elements, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onreset, onselectstart, onsubmit

HTML Element

FORM


FRAME

Description

Specifies an individual frame within a FRAMESET.

Remarks

This element is a block element.

Properties

borderColor, className, dataFld, dataSrc, document, frameBorder, height, id, isTextEdit, lang, language, marginHeight, marginWidth, name, noResize, parentElement, parentTextEdit, scrolling, sourceIndex, src, style, tagName, title

Methods

contains, getAttribute, removeAttribute, setAttribute

Collections

all, children

HTML Element

FRAME

See Also

FRAMESET


FRAMESET

Description

Specifies a frameset, which is used to organize multiple frames and nested framesets.

Remarks

This element is a block element.

Properties

border, borderColor, className, cols, document, frameBorder, frameSpacing, id, isTextEdit, lang, language, parentElement, parentTextEdit, rows, sourceIndex, style, tagName, title

Methods

contains, getAttribute, removeAttribute, setAttribute

Collections

all, children

Events

onbeforeunload, onload, onresize, onunload

HTML Element

FRAMESET

See Also

FRAME


H1

Description

Renders text as a heading style.

Remarks

This element is a block element.

Properties

align, className, document, id, innerHTML, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

H1


H2

Description

Renders text as a heading style.

Remarks

This element is a block element.

Properties

align, className, document, id, innerHTML, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

H2


H3

Description

Renders text as a heading style.

Remarks

This element is a block element.

Properties

align, className, document, id, innerHTML, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

H3


H4

Description

Renders text as a heading style.

Remarks

This element is a block element.

Properties

align, className, document, id, innerHTML, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

H4


H5

Description

Renders text as a heading style.

Remarks

This element is a block element.

Properties

align, className, document, id, innerHTML, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

H5


H6

Description

Renders text as a heading style.

Remarks

This element is a block element.

Properties

align, className, document, id, innerHTML, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

H6


HEAD

Description

Provides an unordered collection of information about the document.

Remarks

HEAD provides information that does not affect the rendering of the document, but might be of use to the browser. The following tags are valid in this element:

  • BASE
  • BASEFONT
  • BGSOUND
  • LINK
  • META
  • NEXTID
  • SCRIPT
  • STYLE
  • TITLE

Properties

className, document, id, isTextEdit, parentElement, sourceIndex, tagName, title

Methods

contains, getAttribute, removeAttribute, setAttribute

HTML Element

HEAD


HR

Description

Draws a horizontal rule.

Remarks

This element is a block element.

Properties

align, className, color, document, id, isTextEdit, lang, language, noShade, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, size, sourceIndex, style, tagName, title, width

Methods

blur, click, contains, focus, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onbeforeupdate, onblur, onclick, ondblclick, ondragstart, onfilterchange, onfocus, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onresize, onrowenter, onrowexit, onselectstart

HTML Element

HR


HTML

Description

Identifies the document as containing HTML elements.

Properties

className, document, id, isTextEdit, language, parentElement, sourceIndex, style, tagName, title

Methods

contains, getAttribute, removeAttribute, setAttribute

HTML Element

HTML


I

Description

Specifies that the text should be rendered in italic font, where available.

Properties

className, document, id, innerHTML, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

I

See Also

ADDRESS, CITE, DFN, EM


IFRAME

Description

Creates inline floating frames.

Remarks

This element is a block element.

The IFrame functions as a document within a document. Consequently, access to the IFrame object is provided through the frames collection. Use the frames collection to read or write to elements contained in an IFrame.

Properties

align, className, dataFld, dataSrc, document, frameBorder, frameSpacing, hspace, id, innerHTML, innerText, isTextEdit, lang, language, marginHeight, marginWidth, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, scrolling, sourceIndex, src, style, tagName, title, vspace

Methods

contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children

Example

The following code returns a reference to the all collection within the IFrame.

document.all.frames["MyIFrame"].document.all

HTML Element

IFRAME


IMG

Description

Embeds an image or a video clip in the document.

Remarks

This element does not fire the onfocus event when it receives the input focus unless it has been associated with a MAP element.

Properties

align, accesKey, alt, border, className, complete, dataFormatAs, dataFld, dataSrc, document, dynsrc, fileCreatedDate, fileModifiedDate, fileSize, fileUpdateDate, filter, href, height, hspace, id, innerHTML, innerText, isMap, isTextEdit, lang, language, loop, lowsrc, mimeTypes, name, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, protocol, readyState, scrollHeight, scrollLeft, scrollTop, scrollWidth, sourceIndex, src, start, style, tabIndex, tagName, title, useMap, vspace, width

Methods

blur, click, contains, focus, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onabort, onafterupdate, onbeforeupdate, onblur, onclick, ondataavailable, ondatasetchanged, ondatasetcomplete, ondblclick, ondragstart, onerror, onfilterchange, onfocus, onhelp, onkeydown, onkeypress, onkeyup, onload, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onresize, onrowenter, onrowexit, onscroll, onselectstart

HTML Element

IMG

See Also

INPUT


INPUT

Description

Specifies one of these form input controls:
button
checkbox
file
hidden
image
password
radio
reset
submit
text

Collections

all, children, filters

HTML Element

INPUT

See Also

BUTTON, SELECT, TEXTAREA

INPUT type=button

Description

Creates a button control.

Properties

accessKey, className, dataFld, dataFormatAs, dataSrc, disabled, document, form, id, isTextEdit, lang, language, name, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, readOnly, recordNumber, sourceIndex, style, tabIndex, tagName, title, type, value

Methods

blur, click, contains, createTextRange, focus, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, select, setAttribute

Collections

all, children, filters

Events

onblur, onclick, ondblclick, onfocus, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onresize, onselect

HTML Element

INPUT

See Also

BUTTON

INPUT type=checkbox

Description

Represents simple Boolean attributes or attributes that can take multiple values at the same time.

Remarks

This element is represented by a number of check box controls, each of which has the same name. Each selected check box generates a separate name/value pair in the submitted data, even if this results in duplicate names. The default value for check boxes is on.

Properties

accessKey, checked, className, dataFld, dataSrc, defaultChecked, disabled, document, form, id, indeterminate, isTextEdit, lang, language, name, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerText, parentElement, parentTextEdit, recordNumber, size, sourceIndex, status, style, tabIndex, tagName, title, type, value

Methods

blur, click, contains, focus, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, select, setAttribute

Collections

all, children, filters

Events

onafterupdate, onbeforeupdate, onblur, onchange, onclick, ondblclick, onerrorupdate, onfilterchange, onfocus, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onresize, onselect

HTML Element

INPUT

INPUT type=file

Description

Uploads files.

Properties

accessKey, className, defaultValue, disabled, document, form, id, isTextEdit, lang, language, name, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerText, parentElement, parentTextEdit, readOnly, recordNumber, sourceIndex, style, tabIndex, tagName, title, type, value

Methods

blur, click, contains, focus, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, select, setAttribute

Collections

all, children, filters

Events

onblur, onchange, onclick, ondblclick, onfilterchange, onfocus, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onresize, onselect

HTML Element

INPUT

INPUT type=hidden

Description

Transmits state information about client/server interaction.

Remarks

This value presents no control to the user, but sends the value of the value property with the submitted form.

Properties

className, dataFld, dataSrc, disabled, document, form, id, isTextEdit, language, name, parentElement, parentTextEdit, sourceIndex, style, tagName, type, value

Methods

contains, getAttribute, removeAttribute, setAttribute

Events

onafterupdate, onbeforeupdate, onerrorupdate

HTML Element

INPUT

INPUT type=image

Description

Represents an image control that you can click, causing the form to be immediately submitted.

Remarks

The x-coordinate is submitted under the name of the control with .x appended, and the y-coordinate is submitted under the name of the control with .y appended. Any value property is ignored. The image itself is specified by the src property, exactly as for the IMG element.

Properties

accessKey align, alt, className, complete, disabled, document, dynsrc, filter, form, height, id, innerHTML, isTextEdit, language, loop, lowsrc, name, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, readyState, recordNumber, sourceIndex, src, start, style, tabIndex, tagName, title, type width

Methods

blur, click, contains, focus, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, select, setAttribute

Collections

all, children, filters

Events

onabort, onafterupdate, onbeforeupdate, onblur, onchange, onclick, ondataavailable, ondatasetchanged, ondatasetcomplete, ondblclick, onerror, onerrorupdate, onfocus, onhelp, onkeydown, onkeypress, onkeyup, onload, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onresize, onrowenter, onrowexit, onselect

HTML Element

INPUT

See Also

IMG

INPUT type=password

Description

Similar to the text control, except that text is not displayed as the user enters it.

Properties

accessKey, align, className, dataFld, dataSrc, defaultValue, disabled, document, form, id, isTextEdit, lang, language, maxLength, name, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, readOnly, size, sourceIndex, style, tabIndex, tagName, title, type, value

Methods

blur, click, contains, focus, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, select, setAttribute

Collections

all, children, filters

Events

onblur, onchange, onclick, ondblclick, onfocus, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onresize, onselect

HTML Element

INPUT

INPUT type=radio

Description

Used for mutually exclusive sets of values.

Remarks

Each radio-button control in the group should be given the same name. Only the selected radio button in the group generates a name/value pair in the submitted data. Radio buttons require an explicit value property.

Properties

accessKey, checked, className, dataFld, dataSrc, defaultChecked, disabled, document, form, id, isTextEdit, lang, language, name, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerText, parentElement, parentTextEdit, recordNumber, size, sourceIndex, style, tabIndex, tagName, title, type, value

Methods

blur, click, contains, focus, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, select, setAttribute

Collections

all, children, filters

Events

onafterupdate, onbeforeupdate, onblur, onchange, onclick, ondblclick, onerrorupdate, onfocus, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onresize, onselect

HTML Element

INPUT

INPUT type=reset

Description

Represents a button that, when clicked, resets the form's controls to their specified initial values. The label to be displayed on the button can be specified just as for the submit button.

Properties

accessKey, className, disabled, document, form, id, isTextEdit, lang, language, name, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, recordNumber, sourceIndex, style, tabIndex, tagName, title, type, value

Methods

blur, click, contains, focus, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, select, setAttribute

Collections

all, children, filters

Events

onblur, onclick, ondblclick, onfilterchange, onfocus, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onresize, onselect

HTML Element

INPUT

See Also

BUTTON

INPUT type=submit

Description

Represents a button that, when clicked, submits the form.

Remarks

You can use the value attribute to provide a non-editable label to be displayed on the button. The default label is application-specific. If a SUBMIT button is clicked to submit the form, and that button has a name attribute specified, that button contributes a name/value pair to the submitted data.

Properties

accessKey, className, disabled, document, form, id, isTextEdit, lang, language, name, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, recordNumber, sourceIndex, style, tabIndex, tagName, title, type, value

Methods

blur, click, contains, focus, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, select, setAttribute

Collections

all, children, filters

Events

onblur, onclick, ondblclick, onfilterchange, onfocus, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onresize, onselect

HTML Element

INPUT

See Also

BUTTON

INPUT type=text

Description

Creates a single-line text-entry control. Use in conjunction with the size and maxLength properties.

Properties

accessKey, align, className, dataFld, dataSrc, defaultValue, disabled, document, form, id, innerHTML, isTextEdit, lang, language, maxLength, name, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, readOnly, recordNumber, size, sourceIndex, style, tabIndex, tagName, title, type, value

Methods

blur, click, contains, createTextRange, focus, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, select, setAttribute

Collections

all, children, filters

Events

onafterupdate, onbeforeupdate, onblur, onchange, onclick, ondblclick, onerrorupdate, onfilterchange, onfocus, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onresize, onselect

HTML Element

INPUT

See Also

TEXTAREA


INS

Description

Indicates text that has been inserted into the document.

Properties

className, document, id, innerHTML, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup,onselectstart

HTML Element

INS

See Also

DEL


KBD

Description

Renders text in fixed-width font.

Properties

className, document, id, innerHTML, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

KBD


LABEL

Description

Specifies a label for a control-like element.

Remarks

Labels cannot be nested.

If the user clicks the label with the mouse, the onclick event goes to the label, then bubbles to the control specified by the htmlFor property. Pressing the access key for the label is the same as clicking the mouse on the label.

Properties

accessKey, className, document, htmlFor, id, innerHTML, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

LABEL


LEGEND

Description

Inserts a caption into the box drawn by the FIELDSET element. This element must be the first element in FIELDSET.

Remarks

This element is a block element.

Properties

accessKey, align, className, clientHeight, clientWidth, document, id, innerHTML, innerText, isTextEdit, lang, language, margin offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, padding, parentElement, parentTextEdit, recordNumber, scrollHeight, scrollLeft, scrollTop, scrollWidth, sourceIndex, style, tabIndex, tagName, title

Methods

blur, click, contains, focus, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onafterupdate, onbeforeupdate, onblur, onclick, ondblclick, ondragstart, onerrorupdate, onfocus, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onresize, onrowenter, onrowexit, onscroll, onselectstart

HTML Element

LEGEND


LI

Description

Denotes one item of a list.

Remarks

This element is a block element.

Properties

className, document, id, innerHTML, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title, type, value

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

LI

See Also

OL, UL


LINK

Description

Specifies a typed relationship between the document and some other resource. For example, this element is used to link external style sheets to the document.

Remarks

This element can be used only within the HEAD tag.

Properties

className, disabled, document, href, id, parentElement, readyState, rel, sourceIndex, tagName, title

Methods

contains, getAttribute, removeAttribute, setAttribute

Collections

all, children

Events

onerror, onload, onreadystatechange

HTML Element

LINK


LISTING

Description

Renders text in fixed-width type.

Remarks

This element is a block element.

Properties

className, document, id, innerHTML, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

LISTING

See Also

XMP


MAP

Description

Specifies a collection of hot spots for a client-side image map.

Properties

className, document, filter, id, innerHTML, innerText, isTextEdit, lang, language, name offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, recordNumber, sourceIndex, style, tagName, title

Methods

click, contains, getAttribute, removeAttribute, scrollIntoView, setAttribute

Collections

all, areas, children

Events

onafterupdate, onbeforeupdate, onclick, ondataavailable, ondatasetchanged, ondatasetcomplete, ondblclick, ondragstart, onerrorupdate, onfilterchange,, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onrowenter, onrowexit, onselectstart

HTML Element

MAP


MARQUEE

Description

Enables you to create a scrolling text marquee.

Remarks

The width of MARQUEE defaults to 100%. When MARQUEE is in a TD that does not specify a width, you should explicitly set the width of MARQUEE. The marquee tries to size according to the TD, and the TD tries to size according to the marquee. Without a specific width, the marquee will collapse to a 1-pixel width, and the contents cannot be viewed.

Properties

accessKey, behavior, bgColor, className, clientHeight, clientWidth, dataFld, dataFormatAs, dataSrc, direction, document, height, hspace, id, innerHTML, innerText, isTextEdit, lang, language, loop, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, scrollAmount, scrollDelay, scrollHeight, scrollLeft, scrollTop, scrollWidth, sourceIndex, style, tagName, title, trueSpeed, vspace, width

Methods

blur, click, contains, focus, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute, start, stop

Collections

all, children, filters

Events

onafterupdate, onblur, onbounce, onclick, ondblclick, ondragstart, onfinish, onfocus, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onresize, onrowenter, onrowexit, onscroll, onselectstart, onstart

HTML Element

MARQUEE


MENU

Description

Specifies that the following block consists of individual items.

Remarks

This element is a block element.

Properties

className, document, id, innerHTML, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

MENU


META

Description

Provides support for client pull.

Remarks

This element can be used only within the HEAD tag.

Properties

charset, className, content, document, httpEquiv, id, isTextEdit, lang, name, parentElement, parentTextEdit, sourceIndex, tagName, title, url

Methods

contains, getAttribute, removeAttribute, setAttribute

Collections

all, children

HTML Element

META


NEXTID

Description

Serves as a parameter to be read and generated by text editing software to create unique identifiers.

Remarks

This element can be used only within the HEAD tag.

Properties

className, document, id, isTextEdit, language, parentElement, parentTextEdit, sourceIndex, tagName, title

Methods

contains, getAttribute, removeAttribute, setAttribute


document

Description

Represents the HTML document in a given browser window.

Remarks

You use the document object to retrieve information about the document, to examine and modify the HTML elements and text within the document, and to process events.

The document object is available at all times. You can retrieve the object by applying the document property to a window or an element object. If used by itself, document represents the document in the current window.

Examples

The following example checks for a document title and displays the title (if not null) in an alert (message) box.

if (document.title!="")
    alert("The title is " + document.title)

The following example shows an event handler function that displays the current position of the mouse (relative to the upper-left corner of the document) in the browser's status window.

<HTML>
<HEAD><TITLE>Report mouse moves</TITLE>
<SCRIPT LANGUAGE="JScript">
function reportMove() {
    window.status = "X=" + window.event.x + " Y=" + window.event.y;
}
</SCRIPT>
<BODY onmousemove="reportMove()">
<H1>Welcome!</H1>
</BODY>
</HTML>

Properties

activeElement, alinkColor, bgColor, body, charset, cookie, defaultCharset, domain, expando, fgColor, lastModified, linkColor, location, parentWindow, readyState, referrer, selection, title, URL, vlinkColor

Collections

all, anchors, applets, children, embeds, forms, frames, images, links, plugins, scripts, styleSheets

Methods

clear, close, createElement, createStyleSheet, elementFromPoint, execCommand, open, queryCommandEnabled, queryCommandIndeterm, queryCommandState, queryCommandSupported, queryCommandText, queryCommandValue, ShowHelp, write, writeln

Events

onafterupdate, onbeforeupdate, onclick, ondblclick, ondragstart, onerrorupdate, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onreadystatechange, onrowenter, onrowexit, onselectstart


event

Description

Represents the state of an event, such as the element in which the event occurred, the state of the keyboard keys, the location of the mouse, and the state of the mouse buttons.

The event object is available only during an event. That is, you can use it in event handlers but not in other code. You retrieve the event object by applying the event keyword to the window object.

Although all event properties are available to all event objects, some properties might not have meaningful values during some events. For example, the fromElement and toElement properties are meaningful only when processing the onmouseover and onmouseout events.

Examples

The following example checks whether a mouse click occurred within a link and prevents the link from being carried out if the SHIFT key is down.

<HTML>
<HEAD><TITLE>Cancels Links</TITLE>
<SCRIPT LANGUAGE="JScript">
function cancelLink() {
    if (window.event.srcElement.tagName == "A" && window.event.shiftKey)
        window.event.returnValue = false;
}
</SCRIPT>
<BODY onclick="cancelLink()">

The following example displays the current mouse position in the browser's status window.

<BODY onmousemove="window.status = 'X=' + window.event.x + ' Y=' + window.event.y">

Note that in VBScript you cannot use the event keyword without applying it to the window keyword or an expression that evaluates to a window.

Properties

altKey, button, cancelBubble, clientX, clientY, ctrlKey, fromElement, keyCode, offsetX, offsetY, reason, returnValue, screenX, screenY, shiftKey, srcElement, srcFilter, toElement, type, x, y

Applies To

window


history

Description

Contains information on the URLs that the client has previously visited.

Property

length

Methods

back, forward, go

Applies To

window


location

Description

Contains information on the current URL.

Remarks

The href property contains the entire URL, and the other properties contain portions of it. Location.href is the default property for the location object. For example, setting location='http://microsoft.com' is equivalent to setting location.href='http://microsoft.com'.

By setting any of the following properties, the browser will initiate an immediate navigation to the newly specified URL.

Properties

hash, host, hostname, href, pathname, port, protocol, search

Methods

assign, reload, replace


navigator

Description

Contains information about the Web browser.

Properties

appCodeName, appMinorVersion, appName, appVersion, browserLanguage, connectionSpeed, cookieEnabled, cpuClass, onLine, platform, systemLanguage, userAgent userLanguage, userProfile

Methods

javaEnabled, taintEnabled

Collections

mimeTypes, plugins

Applies To

window


screen

Description

Contains information about the client's screen and rendering abilities.

Properties

availHeight, availWidth, bufferDepth, colorDepth, height, updateInterval, width

Applies To

window


selection

Description

Represents the active selection, a highlighted block of text, and/or other elements in the document upon which a user or a script can carry out some action. You typically use the selection object as input from the user identifying what portion of the document to act on, or as output to the user showing the results of an action.

Remarks

Users and scripts can both create selections. Users create selections by dragging the mouse over a portion of the document. Scripts create them by calling the select method on a text range or similar object. You can retrieve the active selection by applying the selection keyword to the document object. To carry out work on a selection, you can create a text range object from the selection by using the createRange method.

A document can have only one selection at a time. The selection has a type that determines whether it is empty or contains a contiguous block of consecutive text and/or elements. Although an empty selection contains nothing, it is useful for marking a position in the document.

Properties

type

Methods

clear, createRange, empty

Applies To

document


style

Description

Represents the current settings of all possible inline styles for a given element.

Remarks

Inline styles are CSS style assignments that an author applies directly to individual HTML elements using the STYLE= attribute. You use the style object to examine these assignments and either make new assignments or change existing ones.

You can retrieve the style object by applying the style keyword to an element object. You retrieve the current setting for an inline style by applying the corresponding style property to the style object.

The style object does not give access to the style assignments in style sheets. To obtain information about styles in style sheets, you must use the styleSheets collection to gain access to the individual style sheets defined in the document.

Examples

The following example sets the typeface for text in the document body to "Verdana".

document.body.style.fontFamily = "Verdana"

The following example positions the given image at the top of the document.

var i = document.all.tags("IMG");
if (i.length>0) {
    if (i[0].style.position == "absolute")
        i[0].style.top = 0;
}

Properties

background, backgroundAttachment, backgroundColor, backgroundImage, backgroundPosition, backgroundPositionX, backgroundPositionY, backgroundRepeat, border, borderBottom, borderBottomColor, borderBottomStyle, borderBottomWidth, borderColor, borderLeft, borderLeftColor, borderLeftStyle, borderLeftWidth, borderRight, borderRightColor, borderRightStyle, borderRightWidth, borderStyle, borderTop, borderTopColor, borderTopStyle, borderTopWidth, borderWidth, clear, clip, color, cssText, cursor, display, filter, font, fontFamily, fontSize, fontStyle, fontVariant, fontWeight, height, left, letterSpacing, lineHeight, listStyle, listStyleImage, listStylePosition, listStyleType, margin, marginBottom, marginLeft, marginRight, marginTop, overflow, paddingBottom, paddingLeft, paddingRight, paddingTop, pageBreakAfter, pageBreakBefore, pixelHeight, pixelLeft, pixelTop, pixelWidth, posHeight, position, posLeft, posTop, posWidth, styleFloat, textAlign, textDecoration, textDecorationBlink, textDecorationLineThrough, textDecorationNone, textDecorationOverline, textDecorationUnderline, textIndent, textTransform, top, verticalAlign, visibility, width, zIndex

Methods

getAttribute, removeAttribute, setAttribute

Applies To

element object


styleSheet

Description

Represents a single style sheet in the document.

Remarks

You use the object to retrieve information about the style sheet, such as the URL of the source file for the style sheet and the element in the document that owns (defines) the style sheet, and also to modify the style sheet.

You retrieve a style sheet object from the styleSheets collection or from the imports collection. Each item in these collections is a style sheet. A style sheet object is available for a style sheet only if it is included in a document with a STYLE or LINK element, or with an @import statement in a STYLE element.

Properties

disabled, href, id, owningElement, parentStyleSheet, readOnly, type

Methods

addImport, addRule

Collections

imports, rules

Applies To

styleSheets


TextRange

Description

Represents text in an HTML element.

Remarks

You can use this object to retrieve and modify text in an element, to locate specific strings in the text, and to carry out commands that affect the appearance of the text.

You can retrieve a text range object by applying the createTextRange method to a BODY, BUTTON, or TEXTAREA element or an INPUT element having text type. You can modify the extent of the text range by moving its start and end positions with methods such as move, moveToElementText, and findText. Within the text range, you can retrieve and modify plain text or HTML text. These forms of text are identical except that HTML text includes HTML tags; plain text does not.

This feature might not be available on non-Win32® platforms. See article Q172976 in the Microsoft® Knowledge Base for the latest information on Internet Explorer cross-platform compatibility.

Example

The following JScript example changes the text of a BUTTON element to "Clicked".

var b = document.all.tags("BUTTON");
if (b!=null) {
    var r = b[0].createTextRange();
    if (r != null) {
        r.text = "Clicked";
    }
}

Properties

htmlText, text, boundingHeight, boundingLeft, boundingTop, boundingWidth, offsetLeft, offsetTop

Methods

collapse, compareEndPoints, duplicate, execCommand, expand, findText, getBookmark, inRange, isEqual, move, moveEnd, moveStart, moveToBookmark, moveToElementText, moveToPoint, parentElement, pasteHTML, queryCommandEnabled, queryCommandIndeterm, queryCommandState, queryCommandSupported, queryCommandValue, scrollIntoView, select, setEndPoint

See Also

createTextRange


window

Description

Represents an open window in the browser.

Remarks

You use the window object to retrieve information about the state of the window and to gain access to the document in the window, to the events that occur in the window, and to features of the browser that affect the window.

Typically, the browser creates one window object when it opens an HTML document. However, if a document defines one or more frames (that is, contains one or more FRAME or IFRAME tags), the browser creates one window object for the original document and one additional window object for each frame. These additional objects are child windows of the original window and can be affected by actions that occur in the original. For example, closing the original window causes all child windows to close. You can also create new windows (and corresponding window objects) by using methods such as open and showModalDialog.

You can apply any window property, method, or collection to any variable or expression that evaluates to a window object, regardless of how that window was created. Additionally, you can access all window properties, methods, and collections in the current window by using the property, method, or collection name directly—that is, without prefixing it with an expression that evaluates to the current window object. However, to help make more readable code and to avoid potential ambiguities, many developers use the window keyword when accessing window properties, methods, and collections for the current window. This keyword always refers to the current window.

Note Window property, method, and collection names are reserved keywords and cannot be used as the names of variables and routines.

The dialogArguments, dialogHeight, dialogLeft, dialogTop, dialogWidth, and returnValue properties are available only for windows created using the showModalDialog method.

Examples

The following example displays an alert (message) box for the current window.

alert("A simple message.")

The following example checks whether the current window contains child windows and, if it does, displays the names of those child windows.

if (window.frames!=null) {
    for (i=0; i<window.frames.length; i++)
        window.alert("Child window "+i+" is named "+window.frames(i).name);
}

The following example shows a simple event handler function for the window's onload event. Note that in the absence of a "window" element, the BODY element hosts the following window object events: onblur, onfocus, onload, and onunload.

<BODY onload="window.status='Page is loaded!'">

Properties

clientInformation, closed, defaultStatus, dialogArguments, dialogHeight, dialogLeft, dialogTop, dialogWidth, document, event, history, length*, location, name, navigator, offscreenBuffering, opener, parent*, returnValue, screen, self, status, top*

*An asterisk indicates properties not applicable to modal dialogs.

Collections

frames*

Methods

alert, blur, clearInterval, clearTimeout, close, confirm, execScript, focus, moveBy, moveTo, navigate, open*, prompt, resizeBy, resizeTo, scroll, scrollBy, scrollTo, setInterval, setTimeout, showHelp, showModalDialog*

*An asterisk indicates properties not applicable to modal dialogs.

Events

onbeforeunload, onblur, onerror, onfocus, onhelp, onload, onresize, onscroll, onunload


OBJECT

Description

Inserts an object onto the HTML page. An object can appear in the HEAD or the BODY of a document.

Possible return values (those generated by Object Model properties) on the OBJECT tag will depend on the implementation of the OBJECT. For example, the readyState property will return null or error if the OBJECT does not implement a readyState property. Object Model properties available for an OBJECT depend on the contents of the OBJECT. See the documentation for the individual object for supported Object Model properties.

Note: the object property for the OBJECT element is a way of reconciling Object Model members that are duplicated by the OBJECT element's implementation and DHTML. For instance, if the OBJECT implements an item method, and DHTML implements an item method, to use the one defined for the OBJECT, document.all.objectID.object.item() would differentiate these methods.

Remarks

This element is a block element.

Properties

accessKey, align, altHTML, classid, className, code, codeBase, codeType, data, dataFld, dataSrc, dataFormatAs, document, height, hspace, id, isTextEdit, lang, language, name, object, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, readyState, sourceIndex, style, tabIndex, tagName, title, type, vspace, width

Methods

blur, click, contains, focus, getAttribute, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onafterupdate, onbeforeupdate, onblur, onclick, ondataavailable, ondatasetchanged, ondatasetcomplete, ondblclick, ondragstart, onerror, onerrorupdate, onfilterchange, onfocus, onreadystatechange, onrowenter, onrowexit, onselectstart

HTML Element

OBJECT


Objects

The following topics list the set of objects defined by Dynamic HTML. The links take you to the object definitions, which contain the set of members for the object.

Objects
A ACRONYM ADDRESS
all APPLET applets
anchors AREA areas
B BASE BASEFONT
BGSOUND BIG BLOCKQUOTE
BODY BR BUTTON
CAPTION cells CENTER
children CITE CODE
COL COLGROUP COMMENT
DD DEL DFN
DIR DIV DL
document DT elements
EM EMBED embeds
event external FIELDSET
filters FONT FORM
forms FRAME frames
FRAMESET H1 H2
H3 H4 H5
H6 HEAD history
HR HTML I
IFRAME images IMG
INPUT INS KBD
LABEL LEGEND LI
LINK links LISTING
location MAP MARQUEE
MENU META navigator
NEXTID OBJECT OL
OPTION options P
PLAINTEXT plugins PRE
Q rows rules
S SAMP screen
SCRIPT scripts SELECT
selection SMALL SPAN
STRIKE STRONG STYLE
style styleSheet styleSheets
SUB SUP TABLE
TBODY TD TEXTAREA
TextRange TFOOT TH
THEAD TITLE TR
TT U UL
userProfile VAR window
XMP

Input Types
button checkbox file
hidden image password
radio reset submit text

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


OL

Description

Draws lines of text as an ordered list.

Remarks

This element is a block element.

Properties

className, document, id, innerHTML, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, start, style, tagName, title, type

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

OL

See Also

LI


OPTION

Description

Denotes one choice in a select list.

Remarks

Although OPTION elements do not appear in the all collection, you can gain access to these elements by applying the options collection to the SELECT element.

Style settings that you apply to the style object for this element are ignored. But style settings that you apply to the containing SELECT element are also applied to this element.

This element is a block element.

Example

The following JScript example displays the text for all options in the first SELECT list in the document.

var el = document.all.tags("SELECT").item(0);
if (el != null) {
    for (i=0; i<el.options.length; i++) {
        alert("Option " + i + " is " + el.options(i).text);
    }
}

Properties

className, document, id, isTextEdit, language, offsetHeight, offsetParent, offsetWidth, parentElement, parentTextEdit, selected, sourceIndex, style, tagName, text, value

Methods

contains, getAttribute, removeAttribute, scrollIntoView, setAttribute

HTML Element

OPTION

See Also

SELECT


P

Description

Denotes a paragraph.

Remarks

This element is a block element.

Properties

className, document, id, innerHTML, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

P


PLAINTEXT

Description

Renders text in fixed-width type without processing tags.

Remarks

This element is a block element.

Properties

className, document, id, innerHTML, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title

Methods

click, contains, getAttribute, insertAdjacentHTML, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

PLAINTEXT

See Also

XMP


PRE

Description

Renders text in fixed-width type.

Remarks

This element is a block element.

Properties

className, document, id, innerHTML, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

PRE

See Also

XMP


Q

Description

Sets apart a quotation in text.

Remarks

This element is a block element.

Properties

className, document, id, innerHTML, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

Q

See Also

BLOCKQUOTE


S

Description

Renders text in strike-through type.

Properties

className, document, id, innerHTML, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

S

See Also

STRIKE


SAMP

Description

Specifies a code sample.

Properties

className, document, id, innerHTML, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

SAMP

See Also

CODE


SCRIPT

Description

Specifies a script for the page that will be interpreted by a script engine.

Remarks

Code within the SCRIPT block that is not contained within a function is executed immediately as the page is loaded. To keep scripts from being displayed on down-level browsers, the SCRIPT block should be nested within a comment block.

This element is a block element.

Properties

className, defer, document, event, htmlFor, id, innerHTML, innerText, isTextEdit, language, parentElement, parentTextEdit, readyState, sourceIndex, src, style, tagName, text, title, type

Methods

contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, setAttribute

Events

onerror, onload, onreadystatechange

HTML Element

SCRIPT


SELECT

Description

Denotes a list box or drop-down list.

Examples

The following JScript example adds a new option to the end of an existing SELECT list.

var oOption = document.createElement("OPTION");
oOption.text="Apples";
oOption.value="5";
document.all.MyList.add(oOption);

Properties

accessKey, className, dataFld, dataSrc, disabled, document, form, id, isTextEdit, lang, language, length, multiple, name, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, recordNumber, selectedIndex, size, sourceIndex, style, tabIndex, tagName, type, value

Methods

add, blur, click, contains, focus, getAttribute, insertAdjacentHTML, insertAdjacentText, item, remove, removeAttribute, scrollIntoView, setAttribute, tags

Collections

all, children, filters, options

Events

onafterupdate, onbeforeupdate, onblur, onchange, onclick, ondblclick, ondragstart, onerrorupdate, onfilterchange, onfocus, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onresize, onrowenter, onrowexit, onselectstart

HTML Element

SELECT

See Also

OPTION


SMALL

Description

Specifies that the enclosed text should be displayed with a relatively smaller font than the current font.

Properties

className, document, id, innerHTML, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

SMALL


SPAN

Description

Specifies an inline text container. This element is especially useful for applying CSS styles.

Properties

className, dataFld, dataFormatAs, dataSrc, document, id, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerText, parentElement, parentTextEdit, scrollHeight, scrollLeft, scrollTop, scrollWidth, sourceIndex, style, tagName, title

Methods

blur, click, contains, focus, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onblur, onclick, ondblclick, ondragstart, onfilterchange, onfocus, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onscroll, onselectstart

HTML Element

SPAN


STRIKE

Description

Renders text in strike-through type.

Properties

className, document, id, innerHTML, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

STRIKE

See Also

S


STRONG

Description

Renders text in bold.

Properties

className, document, id, innerHTML, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

STRONG

See Also

ACRONYM, ADDRESS, B, CITE


STYLE

Description

Specifies a style sheet for the page.

Remarks

This element should appear in the HEAD section of an HTML document. Internet Explorer 4.0 permits multiple style blocks.

Properties

className, disabled, document, id, isTextEdit, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, parentElement, parentTextEdit, readyState, sourceIndex, style, tagName, type

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, scrollIntoView, setAttribute

Events

onerror, onload, onreadystatechange

HTML Element

STYLE


SUB

Description

Specifies that the enclosed text should be displayed in subscript, using a smaller font than the current font.

Properties

className, document, id, innerHTML, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

SUB

See Also

SUP


SUP

Description

Specifies that the enclosed text should be displayed in superscript and in a smaller font relative to the current font.

Properties

className, document, id, innerHTML, innerText, isTextEdit, lang, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

SUP

See Also

SUB


TABLE

Description

Specifies that the contained content is organized into a table with rows and columns.

Remarks

Valid tags within a table include:

  • CAPTION
  • COL
  • COLGROUP
  • TBODY
  • TFOOT
  • THEAD
  • TR

This element is a block element. When a document is loading, modifications to a table are restricted until the window.onload event occurs. Read-only access is allowed at any time.

Properties

align, background, bgColor, border, borderColor, borderColorDark, borderColorLight, cellPadding, cellSpacing, className, clientHeight, clientWidth, cols, dataFld, dataPageSize, dataSrc, document, frame, height, id, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerText, parentElement, parentTextEdit, rules, scrollHeight, scrollLeft, scrollTop, scrollWidth, sourceIndex, style, tagName, title, width

Methods

blur, click, contains, deleteRow, focus, getAttribute, insertAdjacentHTML, insertAdjacentText, insertRow, nextPage, previousPage, refresh, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters, rows

Events

onafterupdate, onbeforeupdate, onblur, onclick, ondblclick, ondragstart, onfocus, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onresize, onrowenter, onrowexit, onscroll, onselectstart

HTML Element

TABLE

See Also

TD, TR


TBODY

Description

Designates rows as the body of the table.

Remarks

This element is exposed for all tables, even if the table did not explicitly define a TBODY element.

This element is a block element.

Properties

align, bgColor, className, document, id, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, parentElement, parentTextEdit, sourceIndex, style, tagName, title, vAlign

Methods

click, contains, deleteRow, getAttribute, insertRow, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

TBODY


TD

Description

Specifies a cell in a table.

Remarks

This element is a block element.

Properties

align, background, bgColor, borderColor, borderColorDark, borderColorLight, className, clientHeight, clientWidth, colSpan, document, height, id, isTextEdit, lang, language, noWrap, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, parentElement, parentTextEdit, rowSpan, sourceIndex, style, tagName, title, vAlign, width

Methods

blur, click, contains, focus, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onafterupdate, onbeforeupdate, onblur, onclick, ondblclick, ondragstart, onfilterchange, onfocus, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onresize, onrowenter, onrowexit, onselectstart

HTML Element

TD

See Also

TABLE, TH, TR


TEXTAREA

Description

Specifies a multiline text input control.

Remarks

The default font is fixed pitch. You can also set the overflow CSS attribute to "hidden" to remove the scroll bars from the TEXTAREA.

<TEXTAREA STYLE="overflow:hidden" ID=txtComments>
   The patient is in stable condition after suffering an attack of
   the insatiable munchies.
</TEXTAREA>

Properties

accessKey, className, clientHeight, clientWidth, cols, dataFld, dataSrc, disabled, document, form, id, innerText, isTextEdit, lang, language, name, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerText, parentElement, parentTextEdit, readOnly, rows, scrollHeight, scrollLeft, scrollTop, scrollWidth, sourceIndex, status, style, tabIndex, tagName, title, type, value, wrap

Methods

blur, click, contains, createTextRange, focus, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, select, setAttribute

Collections

all, children, filters

Events

onafterupdate, onbeforeupdate, onblur, onchange, onclick, ondblclick, ondragstart, onerrorupdate, onfilterchange, onfocus, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onresize, onrowenter, onrowexit, onscroll, onselect, onselectstart

HTML Element

TEXTAREA

See Also

INPUT


TFOOT

Description

Designates rows as the table's footer.

Remarks

This element is a block element.

Properties

align, bgColor, className, document, id, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, parentElement, parentTextEdit, sourceIndex, style, tagName, title, vAlign

Methods

click, contains, deleteRow, getAttribute, insertRow, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup , onselectstart

HTML Element

TFOOT


TH

Description

Specifies a header column. Header columns are centered within the cell and are bold.

Remarks

This element is a block element.

Properties

align, background, bgColor, borderColor, borderColorDark, borderColorLight, className, colSpan, document, id, isTextEdit, lang, language, noWrap, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, parentElement, parentTextEdit, rowSpan, sourceIndex, style, tagName, title, vAlign

Methods

click, contains, getAttribute, removeAttribute, scrollIntoView, setAttribute

Collections

all, children

Events

onclick, ondblclick, ondragstart, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

TH

See Also

TD, TR


THEAD

Description

Designates rows as the table's header.

Remarks

This element is a block element.

Properties

align, bgColor, className, document, id, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, parentElement, parentTextEdit, sourceIndex, style, tagName, title, vAlign

Methods

click, contains, deleteRow, getAttribute, insertRow, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

THEAD


TITLE

Description

Identifies the contents of the document in a global context.

Remarks

This element can be used only within the HEAD tag.

This element is a block element.

Properties

className, document, id, isTextEdit, lang parentElement, parentTextEdit, sourceIndex, tagName, text, title

Methods

contains, getAttribute, removeAttribute, setAttribute

Collections

all, children, filters

HTML Element

TITLE


TR

Description

Specifies a row in a table.

Remarks

Within a row, the following tags are valid:

  • TD
  • TH

This element is a block element.

Properties

align, bgColor, borderColor, borderColorDark, borderColorLight, className, document, id, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, parentElement, parentTextEdit, rowIndex, sectionRowIndex, sourceIndex, style, tagName, title, vAlign

Methods

blur, click, contains, deleteCell, focus, getAttribute, insertCell, removeAttribute, scrollIntoView, setAttribute

Collections

all, cells, children, filters

Events

onafterupdate, onbeforeupdate, onblur, onclick, ondblclick, ondragstart, onfilterchange, onfocus, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onresize, onrowenter, onrowexit, onselectstart

HTML Element

TR

See Also

TABLE, TD, TH


TT

Description

Renders text in fixed-width type.

Properties

className, document, id, innerHTML, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

TT

See Also

XMP


U

Description

Renders text underlined.

Properties

className, document, id, innerHTML, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

U


UL

Description

Draws lines of text as a bulleted list.

Remarks

This element is a block element.

Properties

className, document, id, innerHTML, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title, type

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

UL

See Also

LI


userProfile

Description

Provides methods that allow a script to request read access to a user's profile information, and to perform read actions. Note that the request is queued up before the reading or writing action is performed, which simplifies the user's experience because he or she is only prompted for profile release permissions once for a batch of requests.

Example

The following is an example of a script that can be run on the client to read various values from the profile information.

// queue up a request for read access to multiple profile attributes
navigator.userProfile.addReadRequest("vcard.displayname");
navigator.userProfile.addReadRequest("vcard.gender");

// request access to this information
navigator.userProfile.doReadRequest(usage-code, "Acme Corporation");

// now perform read operations to access the information
name = navigator.userProfile.getAttribute("vcard.displayname");
gender = navigator.userProfile.getAttribute("vcard.gender");

// the script can now use the 'name' and 'gender' variables
// to personalize content or to send information back to the server

// this is to support getting back to a clean slate by clearing the
// request queue.
navigator.userProfile.clearRequest();

Methods

addReadRequest, clearRequest, doReadRequest, getAttribute


VAR

Description

Renders text as a small fixed-width font.

Properties

className, document, id, innerHTML, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title

Methods

click, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

VAR


XMP

Description

Renders text in fixed-width type used for example text.

Remarks

This tag is no longer recommended. Instead, the PRE or SAMP tag should be used.

This element is a block element.

Properties

className, document, id, innerText, isTextEdit, lang, language, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML, outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title

Methods

click, contains, getAttribute, insertAdjacentHTML, removeAttribute, scrollIntoView, setAttribute

Collections

all, children, filters

Events

onclick, ondblclick, ondragstart, onfilterchange, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselectstart

HTML Element

XMP

See Also

LISTING, PLAINTEXT, PRE, TT


accessKey

Description

Specifies an accelerator key that can be applied to several elements, listed below. The ALT key plus a specified access key allows you to set the focus on a particular page.

Syntax

object.accessKey[ = "sAccessKey"]

Parameter | Description
accessKey | Any alphanumeric keyboard key.

Remarks

By default, the accessKey property sets focus to an element. In addition, some controls perform an action after receiving focus. For example, using accessKey on a button fires the onclick event. Whereas using accessKey on a radio button fires the onclick event and toggles the checked property, visibly selecting or deselecting the control.

The following example uses a combination of the LABEL element and the accessKey property to set focus on a text box. The rich text support in the LABEL element makes it possible to underline the designated accessKey.

<LABEL FOR="fp1" ACCESSKEY="1">#<u>1</u>: Press Alt+1 to set focus to textbox</label>
<INPUT TYPE="text" NAME="T1" VALUE=text1 SIZE="20" TABINDEX="1" ID="fp1">

This property has read/write permission and takes a string.

Applies To

A, APPLET, BUTTON, EMBED, FIELDSET, IFRAME, IMG, INPUT, LABEL, OBJECT, SELECT, TABLE, TEXTAREA


action

Description

Specifies the address to be used to carry out the action of the form. If none is specified, the base URL of the document is used.

Syntax

object.action[ = action]

Remarks

The way the data is submitted depends upon the value of the method and encoding properties.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

FORM


activeElement

Description

Identifies the element that has the focus.

This read-only property is set when you select a control in the interface or use the focus method.

Syntax

object.activeElement

Applies To

document


align

Description

Specifies how the element is aligned with adjacent text.

Syntax

object.align[ = "string"]

Settings

The value of this read-write property can be one of these strings:

absbottom | Aligns the bottom of the element with the absolute bottom of the surrounding text. The absolute bottom is equal to the baseline of the text minus the height of the largest descender in the text.
absmiddle | Aligns the middle of the element with the middle of the surrounding text. The absolute middle is the midpoint between the absolute bottom and texttop of the surrounding text.
baseline | Aligns the bottom of the element with the baseline of the surrounding text.
bottom | Aligns the bottom of the element with the bottom of the surrounding text. The bottom is equal to the baseline minus the standard height of a descender in the text.
left | Aligns the element to the left of the surrounding text. All preceding and subsequent text flows to the right of the element. This is the default value.
middle | Aligns the middle of the element with the surrounding text.
right | Aligns the element to the right of the surrounding text. All subsequent text flows to the left of the element.
texttop | Aligns the top of the element with the absolute top of the surrounding text. The absolute top is the baseline plus the height of the largest ascender in the text.
top | Aligns the top of the element with the top of the text. The top of the text is the baseline plus the standard height of an ascender in the text.

For the INPUT element, this attribute applies only to the image type. It is undefined for all other types.

Applies To

APPLET, EMBED, IFRAME, IMG, INPUT type=image, OBJECT


align

Description

Specifies the alignment of the caption or legend.

Syntax

object.align[ = align]

Settings

This read-write property can be set to one of these string values:

bottom | Align bottom-center.
center | Center the caption.
left | Left align.
right | Right align.
top | Align top-center.

Remarks

Difference between a LEGEND tag and a CAPTION tag:

The LEGEND tag is used only within a FIELDSET tag. The contents of the LEGEND tag are displayed by cutting a hole in the top border of the FIELDSET and placing the LEGEND text in that hole.

The CAPTION tag is used only within a TABLE tag. Its contents are displayed centered above the table and do not interact at all with the table border.

Applies To

CAPTION, LEGEND


align

Description

Specifies how the table should be aligned.

Syntax

object.align[ = align]

Settings

This read-write property can be set to one of these string values:

center | Align to the center.
left | Align to the left edge. This is the default value.
right | Align to the right edge.

Applies To

TABLE


align

Description

Displays the element left flush, right flush, or centered relative to the display or table.

Syntax

object.align[ = align]

Settings

This read-write property can be set to one of these string values:

center | Align to the center.
left | Align to the left edge.
right | Align to the right edge.

The default is left-aligned for TR and TD. The default is center-aligned for TH.

Applies To

COL, COLGROUP, DIV, H1, H2, H3, H4, H5, H6, HR, P, TBODY, TD, TFOOT, TH, THEAD, TR


aLink

Description

Sets the color for the active link. The color can be one of the color names or values given in Color Table.

Syntax

object.aLink[ = color]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

body

See Also

link, vLink


alinkColor

Description

Sets the color for the active link. The color can be one of the color names or values given in Color Table.

Syntax

object.alinkColor[ = color]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

document

See Also

linkColor, vlinkColor


alt

Description

Indicates optional text as an alternative to the graphic for rendering in nongraphical environments. Alternate text should be provided whenever the graphic is not rendered.

Syntax

object.alt[ = alt]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

AREA, IMG


altHTML

Description

Indicates an optional HTML script to execute if the OBJECT fails to load.

Syntax

object.altHTML

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

APPLET, OBJECT


altKey

Description

Specifies the state of the ALT key.

Syntax

object.altKey

Settings

This read-only property is TRUE if the key is down, or FALSE otherwise.

Applies To

event


appCodeName

Description

Indicates a string that returns the code name of the browser.

Syntax

object.appCodeName

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

navigator


appMinorVersion

Description

Returns the application's minor version value. Internet Explorer 4.0 returns zero.

Syntax

object.appMinorVersion

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

navigator


appName

Description

Indicates a string that specifies the name of the browser.

Syntax

object.appName

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

navigator


appVersion

Description

Indicates a string that returns the version of the browser.

Syntax

object.appVersion

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

navigator


availHeight

Description

Returns the height of the working area of the system's screen, in pixels, excluding the toolbar.

Syntax

object.availHeight

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

screen

See Also

height


availWidth

Description

Returns the width of the working area of the system's screen, in pixels, excluding the toolbar.

Syntax

object.availWidth

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

screen

See Also

width


background

Description

Sets or retrieves the separate background attributes (backgroundColor, backgroundImage, backgroundRepeat, backgroundAttachment, and backgroundPosition) at once.

Syntax

object.style.background[ = background]

Remarks

The property is a shorthand ("composite") property. Separate properties can be used to specify each of the individual properties, but in many cases it is more convenient to set them in one place using this composite property. Possible values here include all of the possible values for each of the individual properties.

For more information on supported colors, see Color Table.

All individual background properties not set by the composite background property will be set to their initial values.

The property has read/write permission.

Applies To

HTML Tags | A, ADDRESS, B, BIG, BLOCKQUOTE, BODY, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, DD, DFN, DIR, DIV, DL, DT, EM, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HTML, I, IMG, INPUT, INPUT type=button, INPUT type=checkbox, INPUT type=file, INPUT type=image, INPUT type=password, INPUT type=radio, INPUT type=reset, INPUT type=submit, INPUT type=text, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, S, SAMP, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP
Scripting | style

CSS Attribute

background


background

Description

Specifies a background picture. The picture is tiled behind the text and graphics on the page.

Syntax

object.background[ = background]

Remarks

This property has read/write permission.

Applies To

BODY


background

Description

Specifies a background picture for a table.

Syntax

object.background[ = background]

Remarks

The picture is tiled behind the text and graphics in the table, table head, or table cell.

This property has read/write permission.

Applies To

TABLE, TD, TH


backgroundAttachment

Description

Sets or retrieves whether the background image scrolls with the content or is fixed.

Syntax

object.style.backgroundAttachment[ = scroll]

Remarks

Possible values include:
fixed | Background image does not scroll with the content.
scroll | Background image scrolls with the content.

The property has read/write permission.

Applies To

HTML Tags | BODY, HTML
Scripting | style

CSS Attribute

background-attachment


backgroundColor

Description

Sets or retrieves the background color of an element.

Syntax

object.style.backgroundColor[ = backgroundColor]

Remarks

For more information on supported colors, see Color Table.

The property has read/write permission.

Applies To

HTML Tags | A, ADDRESS, B, BIG, BLOCKQUOTE, BODY, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, DD, DFN, DIR, DIV, DL, DT, EM, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HTML, I, IMG, INPUT, INPUT type=button, INPUT type=checkbox, INPUT type=file, INPUT type=image, INPUT type=password, INPUT type=radio, INPUT type=reset, INPUT type=submit, INPUT type=text, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP
Scripting | style

CSS Attribute

background-color


backgroundImage

Description

Sets or retrieves the background image of an element.

Syntax

object.style.backgroundImage[ = URL]

Remarks

The URL identifies the image file. When setting a background image, it's a good idea to also set a background color to be used when the image is unavailable. When the image is available, it is overlaid on top of the background color.

The property has read/write permission.

Applies To

HTML Tags | A, ADDRESS, B, BIG, BLOCKQUOTE, BODY, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, DD, DFN, DIR, DIV, DL, DT, EM, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HTML, I, IMG, INPUT, INPUT type=button, INPUT type=checkbox, INPUT type=file, INPUT type=image, INPUT type=password, INPUT type=radio, INPUT type=reset, INPUT type=submit, INPUT type=text, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, S, SAMP, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP
Scripting | style

CSS Attribute

background-image


backgroundPosition

Description

Sets or retrieves the initial position of the background image.

Syntax

object.style.backgroundPosition[ = backgroundPosition]

Remarks

The property has read/write permission.

Applies To

HTML Tags | A, ADDRESS, B, BIG, BLOCKQUOTE, BODY, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, DD, DFN, DIR, DIV, DL, DT, EM, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HTML, I, IMG, INPUT, INPUT type=button, INPUT type=checkbox, INPUT type=file, INPUT type=image, INPUT type=password, INPUT type=radio, INPUT type=reset, INPUT type=submit, INPUT type=text, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, S, SAMP, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP
Scripting | style

CSS Attribute

background-position


backgroundPositionX

Description

Returns the x-coordinate of the CSS background-position attribute.

Syntax

object.backgroundPositionX[ = backgroundPositionX]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

style

CSS Attribute

background-position

See Also

backgroundPositionY


backgroundPositionY

Description

Returns the y-coordinate of the CSS background-position attribute.

Syntax

object.backgroundPositionY[ = backgroundPositionY]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

style

CSS Attribute

background-position

See Also

backgroundPositionX


backgroundRepeat

Description

Sets or retrieves whether the image is repeated, if a background image is specified.

Syntax

object.style.backgroundRepeat[ = repeat]

Remarks

Possible values include:
no-repeat | The image is not repeated.
repeat-y | The image is repeated vertically.
repeat-x | The image is repeated horizontally.
repeat | The image is repeated horizontally and vertically.

The property has read/write permission.

Applies To

HTML Tags | A, ADDRESS, B, BIG, BLOCKQUOTE, BODY, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, DD, DFN, DIR, DIV, DL, DT, EM, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HTML, I, IMG, INPUT, INPUT type=button, INPUT type=checkbox, INPUT type=file, INPUT type=image, INPUT type=password, INPUT type=radio, INPUT type=reset, INPUT type=submit, INPUT type=text, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, S, SAMP, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP
Scripting | style

CSS Attribute

background-repeat


balance

Description

Returns the balance value of the background sound. The value determines how the available volume is divided between the left and right speakers.

Syntax

object.balance

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

BGSOUND


behavior

Description

Specifies how the text scrolls in the marquee.

Syntax

object.behavior[ = behavior]

Settings

Possible values include:
alternate | The marquee alternates left and right.
scroll | The marquee is a scrolling marquee in the direction specified by the direction property. The text scrolls off the end and starts over.
slide | The marquee is a scrolling marquee in the direction specified by the direction attribute. The text scrolls to the end and stops.

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

MARQUEE


bgColor

Description

Sets the background color behind the element. The color can be one of the color names or values given in Color Table.

Syntax

object.bgColor[ = color]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

MARQUEE, TABLE, TBODY, TD, TFOOT, TH, THEAD, TR

See Also

background


bgColor

Description

Sets the background color of the page. The color can be one of the color names or values given in Color Table.

Syntax

object.bgColor[ = color]

Remarks

JScript supports the entire set of valid property colors both as strings and their numerical equivalents as a string. JScript always returns the property as the numerical equivalent as a string regardless of the format the value was set to.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

BODY, document

See Also

background


bgProperties

Description

Sets or retrieves the properties for the background picture. For example, specifies whether the picture is a fixed watermark or scrolls with the page.

Syntax

object.bgProperties[ = bgProperties]

Settings

This read-write property is a string. If set to "fixed", the background picture is fixed and does not scroll with the page. If set to an empty string (""), the background picture scrolls.

Applies To

BODY

See Also

background


border

Description

Sets or retrieves the width, color, and style of a border to be drawn around the element.

Syntax

object.style.border[ = border]

Remarks

The border property is a shorthand (composite) property for setting border width, color, and style for all four sides of an object. If a borderColor is not specified, the text color is used.

All individual border properties not set by the composite border property will be set to their default values. For example, the default value for borderWidth is medium.

Setting border=thin is identical to saying border=thin none; the default value for color picks up the text color if one isn't initially set. So, in addition to setting the border width to thin, it will clear any borderStyle or borderColor that has been previously set.

For more information on supported colors, see Color Table.

Setting a border to zero or omitting the attribute causes no border to be displayed. Supplying the border attribute without a value defaults to a single border.

The property has read/write permission. It is supported on block and replaced elements only.

Applies To

HTML Tags | BLOCKQUOTE, BODY, CAPTION, CENTER, DD, DIR, DIV, DL, DT, EMBED, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, IFRAME, IMG, INPUT, LI, LISTING, MARQUEE, MENU, OBJECT, OL, P, PLAINTEXT, PRE, SPAN, TABLE, TD, TEXTAREA, TH, TR, UL, XMP
Scripting | style

CSS Attribute

border


border

Description

Defines the space between the frames, including the 3-D border.

Syntax

object.border[ = border]

Remarks

The border can be set only on an outermost FRAMESET tag. Setting a border for an inner FRAMESET is ignored, even if a border is not defined on the outermost FRAMESET.

This property has read/write permission.

Applies To

FRAMESET


border

Description

Sets or retrieves the width of the border to be drawn around the element.

Syntax

object.border[ = border]

Remarks

Setting a border to zero or omitting the attribute causes no border to be displayed. Supplying the border attribute without a value defaults to a single border.

This property has read/write permission, meaning you can change as well as retrieve its current value.

Applies To

IMG, TABLE

See Also

borderColor, borderColorDark, borderColorLight, hspace, vspace


borderBottom

Description

Sets or retrieves the color, style, and width of the element's bottom border.

Syntax

object.style.borderBottom[ = borderBottom]

Remarks

The color can be one of the color names or values given in Color Table.

This property has read/write permission.

Applies To

HTML Tags | BLOCKQUOTE, BODY, CAPTION, CENTER, DD, DIR, DIV, DL, DT, EMBED, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, IFRAME, IMG, INPUT, LI, LISTING, MARQUEE, MENU, OBJECT, OL, P, PLAINTEXT, PRE, SPAN, TABLE, TD, TEXTAREA, TH, TR, UL, XMP
Scripting | style

CSS Attribute

border-bottom


borderBottomColor

Description

Sets or retrieves the color of the element's bottom border.

Syntax

object.style.borderBottomColor[ = color]

Remarks

The color can be one of the color names or values given in Color Table.

The property has read/write permission.

Applies To

HTML Tags | BLOCKQUOTE, BODY, CAPTION, CENTER, DD, DIR, DIV, DL, DT, EMBED, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, IFRAME, IMG, INPUT, LI, LISTING, MARQUEE, MENU, OBJECT, OL, P, PLAINTEXT, PRE, SPAN, TABLE, TD, TEXTAREA, TH, TR, UL, XMP
Scripting | style

CSS Attribute

border-bottom-color


borderBottomStyle

Description

Sets or retrieves the style of the element's bottom border.

Syntax

object.style.borderBottomStyle[ = borderBottomStyle]

Remarks

Dotted and dashed are treated as solid.

The border styles are defined as follows:
none | No border is drawn (regardless of any border-width).
solid | Border is a solid line.
double | Border is a double line drawn on top of the background of the element. The sum of the two single lines and the space between equals the border-width value. The border width must be at least 3 pixels wide to draw a double border.
groove | 3-D groove is drawn in colors based on the value.
ridge | 3-D ridge is drawn in colors based on the value.
inset | 3-D inset is drawn in colors based on the value.
outset | 3-D outset is drawn in colors based on the value.

The property has read/write permission.

Applies To

HTML Tags | BLOCKQUOTE, BODY, CAPTION, CENTER, DD, DIR, DIV, DL, DT, EMBED, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, IFRAME, IMG, INPUT, LI, LISTING, MARQUEE, MENU, OBJECT, OL, P, PLAINTEXT, PRE, SPAN, TABLE, TD, TEXTAREA, TH, TR, UL, XMP
Scripting | style

CSS Attribute

border-bottom-style


borderBottomWidth

Description

Sets or retrieves the width of the element's bottom border.

Syntax

object.style.borderBottomWidth[ = borderBottomWidth]

Remarks

The property has read/write permission. It is supported on block and replaced elements only.

Applies To

HTML Tags | BLOCKQUOTE, BODY, CAPTION, CENTER, DD, DIR, DIV, DL, DT, EMBED, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, IFRAME, IMG, INPUT, LI, LISTING, MARQUEE, MENU, OBJECT, OL, P, PLAINTEXT, PRE, SPAN, TABLE, TD, TEXTAREA, TH, TR, UL, XMP
Scripting | style

CSS Attribute

border-bottom-width


borderColor

Description

Sets or retrieves the element's border color.

Syntax

object.style.borderColor[ = color]

Remarks

Up to four different colors can be specified. If one color is supplied, it is used for all four sides. If two colors are supplied, the first is used for the top and bottom, and the second is used for left and right. If three colors are supplied, they are used for top, right and left, and bottom, respectively. For a list of supported color values, see Color Table.

The property has read/write permission. It is supported on block and replaced elements only.

Applies To

HTML Tags | BLOCKQUOTE, BODY, CAPTION, CENTER, DD, DIR, DIV, DL, DT, EMBED, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, IMG, IFRAME, INPUT, LI, LISTING, MARQUEE, MENU, OBJECT, OL, P, PLAINTEXT, PRE, SPAN, TABLE, TD, TEXTAREA, TH, TR, UL, XMP
Scripting | style

CSS Attribute

border-color


borderColor

Description

Sets or retrieves the border color and must be used with the borderWidth and borderStyleproperties, except for frames.

Syntax

object.borderColor[ = color]

Remarks

The property has read/write permission.

Applies To

FRAME, FRAMESET, TABLE, TD, TH, TR

See Also

border, borderColorDark, borderColorLight


borderColorDark

Description

Sets independent border color control over one of the two colors used to draw a 3-D border, opposite of borderColorLight, and must be used with the border property. The color can be one of the color names or values given in Color Table.

Syntax

object.borderColorDark[ = color]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

TABLE, TD, TH, TR

See Also

border, borderColor, borderColorLight


borderColorLight

Description

Sets independent border color control over one of the two colors used to draw a 3-D border, opposite of borderColorDark, and must be used with the border property. The color can be one of the color names or values given in Color Table.

Syntax

object.borderColorLight[ = borderColorLight]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

TABLE, TD, TH, TR

See Also

border, borderColor, borderColorDark


borderLeft

Description

Sets or retrieves the color, style, and width of the left border.

Syntax

object.style.borderLeft[ = color]

Remarks

The color can be one of the color names or values given in Color Table.

This property has read/write permission. It is supported on block and replaced elements only.

Applies To

HTML Tags | BLOCKQUOTE, BODY, CAPTION, CENTER, DD, DIR, DIV, DL, DT, EMBED, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, IFRAME, IMG, INPUT, LI, LISTING, MARQUEE, MENU, OBJECT, OL, P, PLAINTEXT, PRE, SPAN, TABLE, TD, TEXTAREA, TH, TR, UL, XMP
Scripting | style

CSS Attribute

border-left


borderLeftColor

Description

Sets or retrieves the color of the element's left border.

Syntax

object.style.borderLeftColor[ = color]

Remarks

The color can be one of the color names or values given in Color Table.

The property has read/write permission.

Applies To

HTML Tags | BLOCKQUOTE, BODY, CAPTION, CENTER, DD, DIR, DIV, DL, DT, EMBED, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, IFRAME, IMG, INPUT, LI, LISTING, MARQUEE, MENU, OBJECT, OL, P, PLAINTEXT, PRE, SPAN, TABLE, TD, TEXTAREA, TH, TR, UL, XMP
Scripting | style

CSS Attribute

border-left-color


borderLeftStyle

Description

Sets or retrieves the style of the element's left border.

Syntax

object.style.borderLeftStyle[ = borderLeftStyle]

Remarks

Dotted and dashed are treated as solid.

The border styles are defined as follows:
none | No border is drawn (regardless of any border-width).
solid | Border is a solid line.
double | Border is a double line drawn on top of the background of the element. The sum of the two single lines and the space between equals the border-width value. The border width must be at least 3 pixels wide to draw a double border.
groove | 3-D groove is drawn in colors based on the value.
ridge | 3-D ridge is drawn in colors based on the value.
inset | 3-D inset is drawn in colors based on the value.
outset | 3-D outset is drawn in colors based on the value.

The property has read/write permission.

Applies To

HTML Tags | BLOCKQUOTE, BODY, CAPTION, CENTER, DD, DIR, DIV, DL, DT, EMBED, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, IFRAME, IMG, INPUT, LI, LISTING, MARQUEE, MENU, OBJECT, OL, P, PLAINTEXT, PRE, SPAN, TABLE, TD, TEXTAREA, TH, TR, UL, XMP
Scripting | style

CSS Attribute

border-left-style


borderLeftWidth

Description

Sets or retrieves the width of the element's left border.

Syntax

object.style.borderLeftWidth[ = borderLeftWidth]

Remarks

The property has read/write permission. It is supported on block and replaced elements only.

Applies To

HTML Tags | BLOCKQUOTE, BODY, CAPTION, CENTER, DD, DIR, DIV, DL, DT, EMBED, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, IFRAME, IMG, INPUT, LI, LISTING, MARQUEE, MENU, OBJECT, OL, P, PLAINTEXT, PRE, SPAN, TABLE, TD, TEXTAREA, TH, TR, UL, XMP
Scripting | style

CSS Attribute

border-left-width


borderRight

Description

Sets or retrieves the color, style, and width of the element's right border.

Syntax

object.style.borderRight[ = borderRight]

Remarks

For more information on supported colors, see Color Table.

This property has read/write permission.

Applies To

HTML Tags | BLOCKQUOTE, BODY, CAPTION, CENTER, DD, DIR, DIV, DL, DT, EMBED, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, IFRAME, IMG, INPUT, LI, LISTING, MARQUEE, MENU, OBJECT, OL, P, PLAINTEXT, PRE, SPAN, TABLE, TD, TEXTAREA, TH, TR, UL, XMP
Scripting | style

CSS Attribute

border-right


borderRightColor

Description

Sets or retrieves the color of the element's right border.

Syntax

object.style.borderRightColor[ = color]

Remarks

The color can be one of the color names or values given in Color Table.

The property has read/write permission.

Applies To

HTML Tags | BLOCKQUOTE, BODY, CAPTION, CENTER, DD, DIR, DIV, DL, DT, EMBED, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, IFRAME, IMG, INPUT, LI, LISTING, MARQUEE, MENU, OBJECT, OL, P, PLAINTEXT, PRE, SPAN, TABLE, TD, TEXTAREA, TH, TR, UL, XMP
Scripting | style

CSS Attribute

border-right-color


borderRightStyle

Description

Sets or retrieves the style of the element's right border.

Syntax

object.style.borderRightStyle[ = borderRightStyle]

Remarks

Dotted and dashed are treated as solid.

The border styles are defined as follows:
none | No border is drawn (regardless of any border-width).
solid | Border is a solid line.
double | Border is a double line drawn on top of the background of the element. The sum of the two single lines and the space between equals the border-width value. The border width must be at least 3 pixels wide to draw a double border.
groove | 3-D groove is drawn in colors based on the value.
ridge | 3-D ridge is drawn in colors based on the value.
inset | 3-D inset is drawn in colors based on the value.
outset | 3-D outset is drawn in colors based on the value.

The property has read/write permission.

Applies To

HTML Tags | BLOCKQUOTE, BODY, CAPTION, CENTER, DD, DIR, DIV, DL, DT, EMBED, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, IFRAME, IMG, INPUT, LI, LISTING, MARQUEE, MENU, OBJECT, OL, P, PLAINTEXT, PRE, SPAN, TABLE, TD, TEXTAREA, TH, TR, UL, XMP
Scripting | style

CSS Attribute

border-right-style


borderRightWidth

Description

Sets or retrieves the width of the element's right border.

Syntax

object.style.borderRightWidth[ = borderRightWidth]

Remarks

The property has read/write permission. It is supported on block and replaced elements only.

Applies To

HTML Tags | BLOCKQUOTE, BODY, CAPTION, CENTER, DD, DIR, DIV, DL, DT, EMBED, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, IFRAME, IMG, INPUT, LI, LISTING, MARQUEE, MENU, OBJECT, OL, P, PLAINTEXT, PRE, SPAN, TABLE, TD, TEXTAREA, TH, TR, UL, XMP
Scripting | style

CSS Attribute

border-right-width


borderStyle

Description

Sets or retrieves the style of the element's left, right, top, and bottom borders.

Syntax

object.style.borderStyle[ = borderStyle]

Remarks

Dotted and dashed are treated as solid.

The border styles are defined as follows:
none | No border is drawn (regardless of any border-width).
solid | Border is a solid line.
double | Border is a double line drawn on top of the background of the element. The sum of the two single lines and the space between equals the border-width value. The border width must be at least 3 pixels wide to draw a double border.
groove | 3-D groove is drawn in colors based on the value.
ridge | 3-D ridge is drawn in colors based on the value.
inset | 3-D inset is drawn in colors based on the value.
outset | 3-D outset is drawn in colors based on the value.

The property has read/write permission.

Applies To

HTML Tags | BLOCKQUOTE, BODY, CAPTION, CENTER, DD, DIR, DIV, DL, DT, EMBED, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, IFRAME, IMG, INPUT, LI, LISTING, MARQUEE, MENU, OBJECT, OL, P, PLAINTEXT, PRE, SPAN, TABLE, TD, TEXTAREA, TH, TR, UL, XMP
Scripting | style

CSS Attribute

border-style


borderTop

Description

Sets or retrieves the color, style, and width of the element's top border.

Syntax

object.style.borderTop[ = borderTop]

Remarks

For more information on supported colors, see Color Table.

This property has read/write permission.

Applies To

HTML Tags | BLOCKQUOTE, BODY, CAPTION, CENTER, DD, DIR, DIV, DL, DT, EMBED, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, IFRAME, IMG, INPUT, LI, LISTING, MARQUEE, MENU, OBJECT, OL, P, PLAINTEXT, PRE, SPAN, TABLE, TD, TEXTAREA, TH, TR, UL, XMP
Scripting | style

CSS Attribute

border-top


borderTopColor

Description

Sets or retrieves the color of the element's top border.

Syntax

object.style.borderTopColor[ = color]

Remarks

The color can be one of the color names or values given in Color Table.

The property has read/write permission.

Applies To

HTML Tags | BLOCKQUOTE, BODY, CAPTION, CENTER, DD, DIR, DIV, DL, DT, EMBED, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, IFRAME, IMG, INPUT, LI, LISTING, MARQUEE, MENU, OBJECT, OL, P, PLAINTEXT, PRE, SPAN, TABLE, TD, TEXTAREA, TH, TR, UL, XMP
Scripting | style

CSS Attribute

border-top-color


borderTopStyle

Description

Sets or retrieves the style of the element's top border.

Syntax

object.style.borderTopStyle[ = borderTopStyle]

Remarks

Dotted and dashed are treated as solid.

The border styles are defined as follows:
none | No border is drawn (regardless of any border-width).
solid | Border is a solid line.
double | Border is a double line drawn on top of the background of the element. The sum of the two single lines and the space between equals the border-width value. The border width must be at least 3 pixels wide to draw a double border.
groove | 3-D groove is drawn in colors based on the value.
ridge | 3-D ridge is drawn in colors based on the value.
inset | 3-D inset is drawn in colors based on the value.
outset | 3-D outset is drawn in colors based on the value.

The property has read/write permission.

Applies To

HTML Tags | BLOCKQUOTE, BODY, CAPTION, CENTER, DD, DIR, DIV, DL, DT, EMBED, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, IFRAME, IMG, INPUT, LI, LISTING, MARQUEE, MENU, OBJECT, OL, P, PLAINTEXT, PRE, SPAN, TABLE, TD, TEXTAREA, TH, TR, UL, XMP
Scripting | style

CSS Attribute

border-top-style


borderTopWidth

Description

Sets or retrieves the width of the element's top border.

Syntax

object.style.borderTopWidth[ = borderTopWidth]

Remarks

The property has read/write permission. It is supported on block and replaced elements only.

Applies To

HTML Tags | BLOCKQUOTE, BODY, CAPTION, CENTER, DD, DIR, DIV, DL, DT, EMBED, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, IFRAME, IMG, INPUT, LI, LISTING, MARQUEE, MENU, OBJECT, OL, P, PLAINTEXT, PRE, SPAN, TABLE, TD, TEXTAREA, TH, TR, UL, XMP
Scripting | style

CSS Attribute

border-top-width


borderWidth

Description

Sets or retrieves the width of the left, right, top, and bottom border.

Syntax

object.style.borderWidth[ = borderWidth]

Remarks

Up to four different widths can be specified. If one width is supplied, it is used for all four sides. If two widths are supplied, the first is used for the top and bottom, and the second is used for left and right. If three widths are supplied, they are used for top, right and left, and bottom, respectively.

The property has read/write permission. It is supported on block and replaced elements only.

Applies To

HTML Tags | BLOCKQUOTE, BODY, CAPTION, CENTER, DD, DIR, DIV, DL, DT, EMBED, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, IFRAME, IMG, INPUT, LI, LISTING, MARQUEE, MENU, OBJECT, OL, P, PLAINTEXT, PRE, SPAN, TABLE, TD, TEXTAREA, TH, TR, UL, XMP
Scripting | style

CSS Attribute

border-width


bottomMargin

Description

Specifies the bottom margin for the entire body of the page and overrides the default margin.

Syntax

object.bottomMargin[ = bottomMargin]

Settings

This read-write property takes a string representation of a decimal number. If set to "", the bottom margin will be exactly on the bottom edge.

Applies To

BODY


boundingHeight

Retrieves the height of the rectangle that bounds the TextRange.

Syntax

HTML | n/a
Scripting | iHeight = TextRange.boundingHeight

Remarks

Default Value | Data Type | Access | Inherited
n/a | numeric | n/a

Applies To

HTML Tags | n/a
Scripting | TextRange

Availability

HTML | n/a
Scripting | Internet Explorer 4.0

See Also

boundingLeft, boundingTop, boundingWidth


boundingLeft

Retrieves the left coordinate of the rectangle that bounds the TextRange.

Syntax

HTML | n/a
Scripting | iLeft = TextRange.boundingLeft

Remarks

Default Value | Data Type | Access | Inherited
n/a | numeric | n/a

Applies To

HTML Tags | n/a
Scripting | TextRange

Availability

HTML | n/a
Scripting | Internet Explorer 4.0

See Also

boundingHeight, boundingTop, boundingWidth


boundingTop

Retrieves the top coordinate of the rectangle that bounds the TextRange.

Syntax

HTML | n/a
Scripting | iTop = TextRange.boundingTop

Remarks

Default Value | Data Type | Access | Inherited
n/a | numeric | n/a

Applies To

HTML Tags | n/a
Scripting | TextRange

Availability

HTML | n/a
Scripting | Internet Explorer 4.0

See Also

boundingHeight, boundingLeft, boundingWidth


boundingWidth

Retrieves the width of the rectangle that bounds the TextRange.

Syntax

HTML | n/a
Scripting | iWidth = TextRange.boundingWidth

Remarks

Default Value | Data Type | Access | Inherited
n/a | numeric | n/a

Applies To

HTML Tags | n/a
Scripting | TextRange

Availability

HTML | n/a
Scripting | Internet Explorer 4.0

See Also

boundingHeight, boundingLeft, boundingTop


browserLanguage

Description

Indicates the current browser language. For possible return values, see Language Codes.

Syntax

object.browserLanguage

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

navigator


bufferDepth

Description

Specifies an offscreen bitmap buffer.

Syntax

object.bufferDepth[ = bufferDepth]

Settings

This read-write property can have these values:

0
No explicit buffering. The colorDepth property is set to the screen depth.
-1
Perform buffering at the screen depth. colorDepth is set to the screen depth.
1, 4, 8, 15, 16, 24, or 32
Perform buffering using the given bits-per-pixel. colorDepth is also set to this value. The value 15 specifies 16 bits-per-pixel, in which only 15 bits are used in a 5-5-5 layout of RGB values.

Nonsupported values cause bufferDepth to be set to -1.

When bufferDepth is -1 and the user changes system settings that affect the screen depth, the buffer depth is automatically updated to the new depth. This is not the case if you set bufferDepth to a specific value.

Applies To

screen


button

Description

Specifies which mouse button, if any, is pressed.

Syntax

object.button

Settings

This read-only property has one of these values:

0 | No button.
1 | Left button is pressed.
2 | Right button is pressed.
4 | Middle button is pressed.

This property is intended to be used with the onmousedown, onmouseup, and onmousemove events. For other events, it typically is zero regardless of the state of the mouse buttons.

Applies To

event


cancelBubble

Description

Specifies whether the current event should bubble up the hierarchy of event handlers.

Syntax

object.cancelBubble[ = cancelBubble]

Settings

This read-write property takes a Boolean value:

TRUE | Cancels bubbling for this event, preventing the next event handler in the hierarchy from receiving the event.
FALSE | Enables bubbling. This is the default value.

Using this property to cancel bubbling for an event does not affect subsequent events.

Example

The following document fragment cancels bubbling of the onclick event if it occurs in the IMG element when the SHIFT key is down. This prevents the event from bubbling up to the onclick event handler for the document.

<SCRIPT LANGUAGE="JScript">
function checkCancel() {
if (window.event.shiftKey)
    window.event.cancelBubble = true;
}
function showSrc() {
    if (window.event.srcElement.tagName == "IMG")
        alert(window.event.srcElement.src);
}
</SCRIPT>
<BODY onclick="showSrc()">
<IMG onclick="checkCancel()" SRC="sample.gif">

Applies To

event


caption

Description

Points to the CAPTION element in the TABLE. If none exist, it is null.

Syntax

object.caption[ = element]

Return Value

This property has read-only permission.

Remarks

The following example sets the inline style for the CAPTION.

document.all.myTable.caption.style.color = "blue"

Applies To

table


cellIndex

Description

Indicates the element's position in the cells collection of a given row. Collection indexes are in the source order of the HTML document. Note that when a cell spans multiple rows, that cell only appears in the cells collection for the first of the rows that the cell spans.

Syntax

object.cellIndex[ = element]

Return Value

This property has read-only permission.

Applies To

TD

See Also

sectionRowIndex, sourceIndex, rowIndex


cellPadding

Description

Specifies the amount of space between the border of the cell and the content of the cell.

Syntax

object.cellPadding[ = cellPadding]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

TABLE

See Also

cellSpacing


cellSpacing

Description

Specifies the amount of space between cells in a table.

Syntax

object.cellSpacing[ = cellSpacing]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

TABLE

See Also

cellPadding


charset

Description

Sets or returns the character set of the document.

Syntax

object.charset[ = charset]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

document, META


checked

Description

Specifies whether the given check box or radio button is selected.

Syntax

object.checked[ = checked]

Settings

This read-write property takes a Boolean value. It is TRUE if the control is selected, or FALSE otherwise. The default value for this property is FALSE.

Check boxes that are not selected do not return their values when the form is submitted.

Applies To

INPUT

See Also

defaultChecked


classid

Description

Specifies the class identifier for the object.

Syntax

object.classid

Remarks

The format is: classid="clsid:controlspecificclsid "

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

OBJECT


className

Description

Specifies the class of the given element. The class is typically used to associate a particular style rule in a style sheet with the element.

Syntax

object.className[ = className]

Settings

This read-write property takes any valid string. By default, the property is equal to the string assigned to the CLASS= attribute of the given element, or is an empty string if the attribute is not explicitly assigned.

Applies To

A, ACRONYM, ADDRESS, APPLET, AREA, B, BIG, BLOCKQUOTE, BODY, BR, BUTTON, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, DD, DEL, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FONT, FORM, FRAME, FRAMESET, H1, H2, H3, H4, H5, H6, HEAD, HR, I, IFRAME, IMG, INPUT, INS, KBD, LABEL, LEGEND, LI, LISTING, MAP, MARQUEE, MENU, OBJECT, OL, OPTION, P, PLAINTEXT, PRE, Q, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP


clear

Description

Sets or retrieves whether the element allows floating elements on its left and/or right sides so that the next text will display past the floating elements.

Syntax

object.style.clear[ = clear]

Remarks

Possible values include:
all | Element is moved below any floating element.
left | Element is moved below any floating element on the left side.
right | Element is moved below any floating element on the right side.
none | Floating elements are allowed on all sides.

The value of this property lists the sides where floating elements are not accepted.

The property has read/write permission.

Applies To

HTML Tags | A, ADDRESS, APPLET, B, BIG, BLOCKQUOTE, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, DD, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FORM, FRAME, FRAMESET, H1, H2, H3, H4, H5, H6, HR, I, IFRAME, IMG, INPUT, INPUT type=button, INPUT type=checkbox, INPUT type=file, INPUT type=image, INPUT type=radio, INPUT type=reset, INPUT type=submit, INPUT type=text, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OBJECT, OL, OPTION, P, PLAINTEXT, PRE, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP
Scripting | style

CSS Attribute

clear


clear

Description

Inserts vertical space so that the next text displayed will be below left-aligned or right-aligned floating images.

Syntax

object.clear[ = clear]

Remarks

Possible values include:
all | Element is moved below any floating element.
left | Element is moved below any floating element on the left side.
right | Element is moved below any floating element on the right side.
none | Floating elements are allowed on all sides.

The value of this property lists the sides where floating elements are not accepted.

The property has read/write permission.

Applies To

BR


clientHeight

Description

Returns the height of the element, in pixels. This height does not take into account any margin, border, scroll bar, or padding that might have been applied to the element.

Syntax

object.clientHeight

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

For more information on how to access the dimension and location of elements on the page through the document object model, see Measuring Element Dimension and Location.

Applies To

APPLET, BODY, BUTTON, CAPTION, DIV, EMBED, FIELDSET, IMG, INPUT, LEGEND, MARQUEE, OBJECT, SPAN, TABLE, TD, TEXTAREA, TR


clientInformation

Description

Returns the navigator object. You use this to retrieve information about the version and name of the browser, as well as whether certain features are enabled.

Syntax

object.clientInformation

Examples

The following JScript example checks whether the user agent name of the browser contains "MSIE". If it does, the browser is Microsoft® Internet Explorer.

if (window.clientInformation.userAgent.indexOf( "MSIE " ) > 0)
    // is Microsoft Internet Explorer

The following JScript example checks whether Java™ applets can be run.

if (window.clientInformation.javaEnabled() == true )
    // Java is enabled, applets can run

Applies To

window


clientLeft

Description

Returns the distance between the offsetLeft and the true left side of the client area, in pixels. The difference between the offsetLeft and clientLeft is the border of the element.

Syntax

object.clientLeft

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

For more information on how to access the dimension and location of elements on the page through the document object model, see Measuring Element Dimension and Location.

Applies To

APPLET, BODY, BUTTON, CAPTION, DIV, EMBED, FIELDSET, IMG, INPUT, LEGEND, MARQUEE, OBJECT, SPAN, TABLE, TD, TEXTAREA, TR


clientTop

Description

Returns the distance between the offsetTop and the true top of the client area, in pixels. The difference between the offsetTop and the clientTop is the border area of the element.

Syntax

object.clientTop

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

For more information on how to access the dimension and location of elements on the page through the document object model, see Measuring Element Dimension and Location.

Applies To

APPLET, BODY, BUTTON, CAPTION, DIV, EMBED, FIELDSET, IMG, INPUT, LEGEND, MARQUEE, OBJECT, SPAN, TABLE, TD, TEXTAREA, TR


clientWidth

Description

Returns the width of the element, in pixels. This width does not take into account any margin, border, scroll bar, or padding that might have been applied to the element.

Syntax

object.clientWidth

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

For more information on how to access the dimension and location of elements on the page through the document object model, see Measuring Element Dimension and Location.

Applies To

APPLET, BODY, BUTTON, CAPTION, DIV, EMBED, FIELDSET, IMG, INPUT, LEGEND, MARQUEE, OBJECT, SPAN, TABLE, TD, TEXTAREA, TR


clientX

Description

Returns the position of the mouse hit relative to the size of the client area of the window. This does not include window decorations or scroll bars.

Syntax

object.clientX

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

event


clientY

Description

Returns the position of the mouse hit relative to the size of the client area of the window. This does not include window decorations or scroll bars.

Syntax

object.clientY

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

event


clip

Description

Sets or retrieves which part of the element is visible.

Syntax

object.style.clip[ = clip]

Remarks

This property defines a clipping region shape and size for a positioned element. The clipping region defines the part of the element that is visible. Any part of the element that is outside the clipping region is transparent. Any coordinate can be replaced by the value auto, which causes the clipping rectangle to match the element's opposite side. The default value is to clip to expose the entire element.

Note that the order of the values clip:rect(0 0 50 50) would render the element invisible, as it would set both the top and the right positions of the clipping region to 0. To achieve a 50-by-50 view port, the syntax should be clip:rect(0 50 50 0).

The property has read/write permission.

Applies To

HTML Tags | DIV, FIELDSET, IMG, INPUT, INPUT type=button, MARQUEE, SPAN, TABLE, TEXTAREA
Scripting | style

CSS Attribute

clip


closed

Description

Returns whether the referenced window is closed.

Syntax

object.closed

Settings

This read-only property is TRUE if the window is closed, or FALSE otherwise.

Applies To

window


code

Description

Specifies the name of the file containing the compiled Java class.

Syntax

object.code

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

OBJECT


codeBase

Description

Specifies a URL referencing where to find the implementation of the object.

Syntax

object.codeBase

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

OBJECT


codeBase

Description

Specifies the base URL for the application. This is an optional parameter.

Syntax

object.codeBase

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

APPLET, EMBED


codeType

Description

Specifies the Internet media type for the code associated with the object.

Syntax

object.codeType[ = codeType]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

OBJECT


color

Description

Sets or retrieves the color to be used by the font or horizontal rule.

Syntax

object.color[ = color]

Remarks

The color can be one of the color names or values given in Color Table.

The property has read/write permission.

Applies To

BASEFONT, FONT, HR


color

Description

Sets or retrieves the color to be used by the text.

Syntax

object.style.color[ = color]

Remarks

The color can be one of the color names or values given in Color Table.

The property has read/write permission.

Applies To

HTML Tags | A, ADDRESS, APPLET, B, BIG, BLOCKQUOTE, BODY, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, DD, DFN, DIR, DIV, DL, DT, EM, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HTML, I, INPUT, INPUT type=button, INPUT type=file, INPUT type=reset, INPUT type=submit, INPUT type=text, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP
Scripting | style

CSS Attribute

color


colorDepth

Description

Returns the bits-per-pixel value used for colors on the destination device or buffer. Script programmers use this value when deciding how best to use colors.

Syntax

object.colorDepth

Settings

The value of this read-only property depends on the bufferDepth property. If bufferDepth is 0 or -1, colorDepth is equal to the bits-per-pixel value for the screen or printer. If bufferDepth is nonzero, colorDepth is equal to bufferDepth.

Example

The following JScript example picks foreground and background colors based on the color depth of the screen.

if (screen.colorDepth > 2) {
    document.body.bgColor = "white";
    document.body.color = "blue";
} else {
    document.body.bgColor = "black";
    document.body.color = "white";
}

Applies To

screen


cols

Description

Specifies how many characters wide the text area is.

Syntax

object.cols[ = cols]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

TEXTAREA


cols

Description

Specifies the number of columns in the table.

Syntax

object.cols[ = cols]

Remarks

Providing this number can speed up the processing of the table.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

TABLE


cols

Description

Specifies a comma-delimited list of frames to create. Each item in the list contains the initial size of the column.

Syntax

object.cols[ = cols]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

FRAMESET


colSpan

Description

Specifies how many columns in the TABLE this cell should span.

Syntax

object.colSpan[ = colSpan]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Remarks

This property can only be changed after the page has been loaded.

Applies To

TD, TH


compact

Description

Specifies that the list should be compacted to remove extra space between list elements.

Syntax

object.compact[ = compact]

Remarks

The default value for this property is FALSE.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

DL


complete

Description

Returns whether the specified element is fully loaded.

Syntax

object.complete

Settings

This read-only property is TRUE if the element is loaded, or FALSE otherwise.

Applies To

IMG


connectionSpeed

Description

Indicates the current connection speed of your session.

Syntax

object.connectionSpeed

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

navigator


content

Description

Specifies meta-information to be associated with the given name or HTTP response header.

Syntax

object.content[ = content]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

META

See Also

httpEquiv


cookie

Description

Specifies a string value of a cookie, which is a small piece of information stored by the browser.

Cookies are made from the following. (All are optional with the exception of the name=value pair.) Arguments are separated by semicolons.

name=value; | Each cookie is stored in a name=value pair, that is, if the cookie is "foo" and you want to save foo's value as "bar", the cookie would be saved as foo=bar. You can save as many name=value pairs in the cookie as you want, but the cookie is always returned as a string of all the cookies that apply to the page, so the string that is returned has to be parsed to find the values of individual cookies.
Expires=date; | If no expiration is set on a cookie, it will expire when the browser is closed. Setting an expiration date in the future causes the cookie to be saved across browser sessions. Setting an expiration date in the past will delete a cookie. The date should be specified using GMT format.
domain=domainname; | The domain of the cookie can be set, which allows pages on a domain made up of more than one server to share cookie information.
path=path; | Setting a path for the cookie will allow the current document to share cookie information with other pages within the same domain, that is, if the path is set to /foobar, all pages in /foobar and all pages in subfolders of /foobar will be able to access the same cookie information.
secure; | Specifying a cookie as "secure" means that the stored cookie information can be accessed only from a secure environment.

Syntax

object.cookie[ = cookie]

Remarks

Use string methods such as substring, charAt, indexOf, and lastIndexOf to determine the value stored in the cookie.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

document


cookieEnabled

Description

Returns whether client-side cookies are enabled in the browser.

Syntax

object.cookieEnabled

Settings

This read-only property is TRUE if cookies are enabled, or FALSE otherwise.

Applies To

navigator


coords

Description

Specifies coordinates that define the hot spot's shape.

Syntax

object.coords[ = coords]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

AREA

See Also

shape


cpuClass

Description

Returns a string of the CPU class (for example, x86, Alpha, Other).

Syntax

object.cpuClass

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

navigator


cssText

Description

Sets or returns the persisted representation of the style rule. If a string is returned, it will break out the composite properties into individual attributes.

Syntax

object.cssText[ = cssText]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

style


ctrlKey

Description

Returns the state of the CTRL key, a Boolean value.

Syntax

object.ctrlKey

Settings

This read-only property is TRUE if the key is down, or FALSE otherwise.

Applies To

event


cursor

Description

Sets or retrieves the the type of cursor to display for the mouse pointer.

Syntax

object.style.cursor[ = cursor]

Remarks

The following types are defined:

auto | Browser determines the cursor to display based on the current context.
crosshair | Simple cross hair.
default | Platform-dependent default cursor (usually an arrow).
hand | Hand.
help | Arrow with question mark indicating help.
move | Crossed arrows indicating something is to be moved.
*-resize | Arrow indicating edge is to be moved (* may be n, ne, nw, s, se, sw, e, or w).
text | Editable text (usually an I-bar).
wait | Hourglass or watch indicating that the program is busy and the user should wait.

This property has read/write permission.

Applies To

HTML Tags | A, ADDRESS, APPLET, B, BIG, BLOCKQUOTE, BODY, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, DD, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, HTML, I, IFRAME, IMG, INPUT, INPUT type=button, INPUT type=checkbox, INPUT type=file, INPUT type=image, INPUT type=radio, INPUT type=reset, INPUT type=submit, INPUT type=text, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OBJECT, OL, P, PLAINTEXT, PRE, S, SAMP, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP
Scripting | style

CSS Attribute

cursor


data

Description

Specifies a URL that references the object's data.

Syntax

object.data

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

OBJECT

See Also

type


dataFld

Description

Specifies which field of a given data source (as specified by the dataSrc property) to bind to the given element.

Syntax

object.dataFld

Remarks

The property can be set at run time. At design time it can be set through the DATAFLD attribute.

Examples

In the following example, the <OBJECT> with ID="sundae" has its Color property bound to the color column of the data source control. Similarly, the text box displays the flavor.

<TABLE DATASRC="#ice_cream">
    <TR>
        <TD><INPUT TYPE=TEXTBOX DATAFLD=flavor>

<TD><OBJECT ID="sundae" WIDTH=100 HEIGHT=51
            CLASSID="CLSID:FFFFFFF-EEEE-DDDD-CCCC-BBBBBBBBBBBB">
            <PARAM NAME="Color" DATAFLD="color">
            <PARAM NAME="Appearance" VALUE="1">
        </OBJECT>
</TABLE>

In the following example the <SELECT> control is bound to the "card_type" column of the data source control "#order". The value of the field will result in the appropriate option being selected.

<SELECT DATASRC="#order" DATAFLD="card_type">
    <OPTION>Visa
    <OPTION>Mastercard
    <OPTION>American Express
    <OPTION>Diners Club
    <OPTION>Discover
</SELECT>

Applies To

A, APPLET, BODY, BUTTON, DIV, FRAME, IFRAME, IMG, INPUT, LABEL, MARQUEE, OBJECT, SELECT, SPAN, TEXTAREA


dataFormatAs

Description

Specifies how the data supplied to the element should be rendered.

Syntax

object.dataFormatAs

Remarks

The property can be set at run time. At design time it can be set through the dataFormatAs attribute. In Internet Explorer 4.0, the possible values for both the property and the corresponding HTML attribute are TEXT and HTML. TEXT is the default.

Examples

In the following DIV and SPAN examples, the data will be supplied in HTML format. In the TEXTAREA example, the data will be supplied in text format.

<DIV DATAFLD="Column2" DATAFORMATAS="html"></DIV>

<TEXTAREA DATASRC="#customer" DATAFLD="address" DATAFORMATAS="text"
    ROWS=6 COLS=60>
</TEXTAREA>

<SPAN DATASRC="#bank_acct" DATAFLD="balance" DATAFORMATAS="none"></SPAN>

Applies To

BODY, BUTTON, DIV, INPUT type=button, LABEL, MARQUEE, SPAN


dataPageSize

Description

Sets the number of records displayed in a table bound to a data source.

Syntax

object.dataPageSize

Remarks

Use the nextPage and previousPage methods to display the subsequent and previous page of records in the table.

The property can be set at run time. At design time it can be set through the dataPageSize attribute.

Example

In the following example, the intrinsic text box is bound to the customer name of the current row of the data source control with the ID "#customer_source". The row in the table will be repeated 10 times, the value specified by DATAPAGESIZE.

<TABLE DATASRC="#customer_source" DATAPAGESIZE=10>
    <TR>
        <TD><INPUT TYPE=TEXTBOX DATAFLD="customer_name">
</TABLE>

Applies To

TABLE


dataSrc

Description

Specifies the source of the data for databinding.

Syntax

object.dataSrc

Remarks

Both tabular and single-valued data consumers use the dataSrc property to specify a binding. The property takes a string that corresponds to the unique ID of a data source object (DSO) on the page.

When the dataSrc property is used for tabular data binding, it specifies that the entire contents of the table be repeated once for each record from the data set.

The dataSrc property can be inherited by the elements contained in a repeated TABLE. This behavior occurs when an element within a TABLE when that element only specifies a dataFld attribute. To complete the binding, the binding agent interrogates the enclosing TABLE for its data source. This inheritance behavior holds only for single-valued consumers. Tabular data consumers (TABLE) must specify an explicit dataSrc.

The property can be set at run time. At design time it can be set through the corresponding DATASRC attribute.

Example

In the following example, the intrinsic text box is bound to the customer name of the current row of the data source control with the ID "#customer_source", and the contents of the table, in this case <TR>, will be repeated once for each record in the set of tabular data.

<TABLE DATASRC="#customer_source">
    <TR>
        <TD><INPUT TYPE=TEXTBOX DATAFLD="customer_name">
</TABLE>

Applies To

A, APPLET, BODY BUTTON, DIV, FRAME, IFRAME, IMG, INPUT, LABEL, MARQUEE, OBJECT, SELECT, SPAN, TABLE, TEXTAREA


defaultCharset

Description

Sets or returns the default character set of the document.

Syntax

object.defaultCharset[ = defaultCharset]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

META, document


defaultChecked

Description

Determines whether the check box or radio button is selected by default.

Syntax

object.defaultChecked[ = defaultChecked]

Settings

This read-write property is TRUE if the check box or radio button is selected by default, or FALSE otherwise. The default value for this property is TRUE.

The property can be changed programmatically but has no affect on the appearance nor on how forms are submitted.

Applies To

INPUT

See Also

checked


defaultSelected

Description

Determines whether the option is selected by default.

Syntax

object.defaultSelected[ = defaultSelected]

Settings

This read-write property is TRUE if the option is selected by default, or FALSE otherwise. The default value for this property is TRUE.

The property can be changed programmatically but has no affect on the appearance nor on how forms are submitted. It does change the appearance of the selected option if the form is reset.

Applies To

OPTION

See Also

selected


defaultStatus

Description

For a window, reflects the default message displayed in the status bar at the bottom of the window.

Syntax

object.defaultStatus[ = defaultStatus]

Remarks

Do not confuse defaultStatus with status. The status property reflects a priority or transient message in the status bar, such as the message that appears when an onmouseover event occurs over an anchor.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

window


defaultValue

Description

Specifies the initial contents of a password or text control or the TEXTAREA element.

Syntax

object.defaultValue[ = defaultValue]

Settings

This read-write property takes a string value.

This value can be changed programmatically but has no affect on the appearance nor on how forms are submitted. It does change the initial value of the control when the form is reset.

Applies To

INPUT, TEXTAREA


defer

Description

Indicates to the browser that there is no code in the script that needs to be executed when the page is initially loaded.

Syntax

bDeferred = object.defer

Remarks

Using the attribute at design time can improve the download performance of a page because the browser does not need to parse and execute the script and can continue downloading and parsing the page instead.

Applies To

SCRIPT


defer

Description

Indicates whether the script contains an inline executable function.

Syntax

object.defer

Applies To

SCRIPT


dialogArguments

Description

Returns the variable or array of variables passed into the modal dialog window.

Syntax

object.dialogArguments

Remarks

This property applies only to windows created using the showModalDialog method.

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

window


dialogHeight

Description

Returns the height of the dialog window.

Syntax

object.dialogHeight[ = dialogHeight]

Remarks

This property applies only to windows created using the showModalDialog method.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

window


dialogLeft

Description

Returns the left coordinate of the dialog window.

Syntax

object.dialogLeft[ = dialogLeft]

Remarks

This property applies only to windows created using the showModalDialog method.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

window


dialogTop

Description

Returns the top coordinate of the dialog window.

Syntax

object.dialogTop[ = dialogTop]

Remarks

This property applies only to windows created using the showModalDialog method.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

window


dialogWidth

Description

Returns the width of the dialog window.

Syntax

object.dialogWidth[ = dialogWidth]

Remarks

This property applies only to windows created using the showModalDialog method.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

window


direction

Description

Specifies which direction the text should scroll.

Syntax

object.direction[ = direction]

Settings

This read-write property can be one of these strings:

down | The marquee scrolls down.
left | The marquee scrolls left.
right | The marquee scrolls right.
up | The marquee scrolls up.

The default value is left, which means scrolling to the left from the right.

Applies To

MARQUEE


disabled

Description

Disables a control. The control appears greyed and does not respond to user input.

Syntax

object.disabled[ = disabled]

Remarks

The default value for this property is FALSE.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

APPLET, BUTTON, INPUT, LINK, SELECT, STYLE, TEXTAREA


disabled

Description

Returns FALSE for a style sheet that does not specify a title and that is not currently selected.

Syntax

object.disabled

Remarks

The value of this property can also change per media-dependent style sheets. The application of individual style sheets can be turned on and off dynamically. Note that the value of this property is also controlled by whether titled style sheets are applied.

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

styleSheet


display

Sets or retrieves whether an element is rendered.

Syntax

object.style.display[ = display]

Remarks

If this property is set to none, the element is not rendered. If it is set to block, inline, or list-item, the element is rendered. The default is to render the element.

Values for block, inline, and list-item are not supported explicitly but are useful in setting the display property to be on. In contrast to the visibility property, display=none reserves no space for the element on the screen.

Although you can apply the display property to parts of a table (such as a TR or TD element), changing the property has no effect on those parts. However, you can dynamically control the rendering of the entire table by applying the property to the TABLE element.

This property has read/write permission.

Applies To

HTML Tags | BODY, DIV, IFRAME, IMG, INPUT, INPUT type=button, MARQUEE, SELECT, SPAN, TABLE, TEXTAREA
Scripting | style

CSS Attribute

display


domain

Description

Sets or returns the security domain of the document.

Syntax

object.domain[ = domain]

Settings

This read-write property initially returns the host name of the server the page is from. It can be assigned the domain suffix to allow sharing of pages across frames. For example, a page in one frame from home.microsoft.com and a page from www.microsoft.com would initially not be able to communicate with each other. However, by setting the domain property of both pages to the suffix, microsoft.com, both pages would be considered secure and now access is available between the pages.

Applies To

document


dynsrc

Description

Specifies the address of a video clip or VRML world to be displayed in the window. Stands for Dynamic Source.

Syntax

object.dynsrc[ = dynsrc]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

IMG


encoding

Description

Specifies the mime encoding for the form. This property corresponds to the HTML ENCTYPE= attribute.

Syntax

object.encoding[ = encoding]

Remarks

The default is "application/x-www-form-urlencoded". Internet Explorer 4.0 also recognizes "multipart/form-data", which with a POST method is required to submit a file upload to the server.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

FORM

See Also

action


event

Description

Specifies the event the script is being written for.

Syntax

object.event

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

SCRIPT


expando

Description

Specifies whether arbitrary variables can be created within an object. Default is set to TRUE.

Syntax

object.expando[ = boolean]

Remarks

You can extend the properties on an object by creating arbitrary properties with values. For example, an author scripting in a case-sensitive language such as JScript can easily make the mistake when setting a property value. For instance, if the property value is "borderColor" and the author types the value "bordercolor = 'blue'", they author has just, in fact, created another property on the style object called "bordercolor" with the value 'blue'. If the author queries the value of the property, the value "blue" will be returned. However, the borders for the element will not turn blue.

Setting this property to FALSE on the document object will disallow the creation of arbitrary variables.

Applies To

document


face

Description

Sets the current font's typeface.

Syntax

object.face[ = face]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

BASEFONT, FONT

See Also

font


fgColor

Description

Sets or retrieves the foreground (text) color of the document.

Syntax

object.fgColor[ = color]

Settings

This read-write property can be set to any one of the color names or values given in Color Table. The default value for this property is typically black, but depends on the browser.

Applies To

document

See Also

color, text


fileCreatedDate

Description

Returns the date the file was created.

Syntax

object.fileCreatedDate

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

IMG


fileModifiedDate

Description

Returns the date the file was last modified.

Syntax

object.fileModifiedDate

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

IMG


fileSize

Description

Returns the file size.

Syntax

object.fileSize

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

IMG


fileUpdatedDate

Description

Returns the date the file was last updated.

Syntax

object.fileUpdatedDate

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

IMG


filter

Description

Sets or retrieves the filter or collection of filters applied to the element.

Syntax

object.style.filter[ = filter]

Remarks

Internet Explorer 4 supports the following built-in filter types: Visual Filter, Reveal Transition Filter, or Blend Transition Filter. For detailed information, see Creating Multimedia Effects with Visual Filters and Transitions. The filter mechanism is extensible and allows additional filters to be developed and added later.

This read/write property takes a string specifying a filter and its parameters.

Applies To

HTML Tags | BODY, BUTTON, DIV*, IMG, INPUT, MARQUEE, SPAN*, TABLE, TD, TEXTAREA, TFOOT, TH, THEAD, TR
Scripting | style

*An asterisk in the list indicates that a defined height, width, or absolute position is required.

CSS Attribute

filter


font

Description

Sets or retrieves the separate font attributes (fontWeight, fontVariant, fontSize, and fontFamily) for text in the element.

Syntax

object.style.font[ = font]

Remarks

Setting this property also sets the component properties. In this case, the string must be a combination of valid values for the component properties, with no more than one value per property. If the string does not contain a value for a component property, that property remains unchanged.

Example

The following JScript example sets the font to a 12-point, serif typeface with a normal weight and with all letters in small capital letters.

var sVar = document.all.MyParagraph;
sVar.style.font = "normal small-caps 12pt serif";
    .
    .
    .
alert(sVar.font.style);

Applies To

HTML Tags | A, ADDRESS, APPLET, B, BIG, BLOCKQUOTE, BODY, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, DD, DFN, DIR, DIV, DL, DT, EM, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HTML, I, INPUT, INPUT type=button, INPUT type=file, INPUT type=reset, INPUT type=submit, INPUT type=text, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, S, SAMP, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP
Scripting | style

CSS Attribute

font


fontFamily

Description

Sets or retrieves the name of the font used for text in the element.

Syntax

object.style.fontFamily[ = fontFamily]

Remarks

The value is a prioritized list of font family names and/or generic family names. List items are separated by commas to minimize confusion between multiple-word font family names. If the font family name contains white space, it should be quoted with single or double quotation marks.

This property has read/write permission.

Applies To

HTML Tags | A, ADDRESS, APPLET, B, BIG, BLOCKQUOTE, BODY, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, DD, DFN, DIR, DIV, DL, DT, EM, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HTML, I, INPUT, INPUT type=button, INPUT type=file, INPUT type=reset, INPUT type=submit, INPUT type=text, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP
Scripting | style

CSS Attribute

font-family


fontSize

Description

Sets or retrieves the size of the font used for text in the element.

Syntax

object.style.fontSize[ = fontSize]

Remarks

The default value is medium. Negative values are not allowed. Font sizes are computed based on the font size of the parent element. Therefore, a font size of "10em" means that the size of the "em" is based on the font used by the parent element.

The values for font size are shown below:
absolute-size | A set of keywords that indicate predefined font sizes. Possible keywords include [xx-small | x-small | small | medium | large | x-large | xx-large]. Named font sizes scale according to the user's font setting preferences.
relative-size | A set of keywords that are interpreted as relative to the font size of the parent element. Possible values include [ larger | smaller].
length | An absolute value for the font size.
percentage | A percentage value of the parent element's font size.

This property has read/write permission.

Applies To

HTML Tags | A, ADDRESS, APPLET, B, BIG, BLOCKQUOTE, BODY, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, DD, DFN, DIR, DIV, DL, DT, EM, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HTML, I, INPUT, INPUT type=button, INPUT type=file, INPUT type=reset, INPUT type=submit, INPUT type=text, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP
Scripting | style

CSS Attribute

font-size


fontSmoothingEnabled

Description

Indicates whether the user has selected the corresponding option through the browser options.

Syntax

object.fontSmoothingEnabled

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

screen


fontStyle

Description

Sets or retrieves whether the font style is italic, normal, or oblique.

Syntax

object.style.fontStyle[ = fontStyle]

Remarks

The settings for the property are italic, normal, or oblique. Internet Explorer 4 displays italic and oblique identically.

This property has read/write permission.

Applies To

HTML Tags | A, ADDRESS, APPLET, B, BIG, BLOCKQUOTE, BODY, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, DD, DFN, DIR, DIV, DL, DT, EM, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HTML, I, INPUT, INPUT type=button, INPUT type=file, INPUT type=reset, INPUT type=submit, INPUT type=text, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, S, SAMP, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP
Scripting | style

CSS Attribute

font-style


fontVariant

Description

Sets or retrieves the font variation as small-caps for text in the element.

Syntax

object.style.fontVariant[ = fontVariant]

Remarks

This read/write property can be set to either normal or small-caps. The default value is normal. Internet Explorer 4.0 renders small-caps as uppercase letters in a smaller size.

Applies To

HTML Tags | A, ADDRESS, APPLET, B, BIG, BLOCKQUOTE, BODY, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, DD, DFN, DIR, DIV, DL, DT, EM, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HTML, I, INPUT, INPUT type=button, INPUT type=file, INPUT type=reset, INPUT type=submit, INPUT type=text, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, S, SAMP, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP
Scripting | style

CSS Attribute

font-variant


fontWeight

Description

Sets or retrieves the weight (boldness) of the text.

Syntax

object.style.fontWeight[ = fontWeight]

Remarks

The key words for fontWeight values are mapped to specific font variations depending on the fonts that are installed on the user's computer. In many cases, the user will not see the difference between different font-weight settings because the system will choose the closest match, which may be the same as the font-weight setting that was previously set on the element.

Setting the font-weight to 400 is equivalent to normal. Setting the font-weight to 700 is equivalent to bold. A font-weight of bolder or lighter is interpreted relative to the parent element's weight. A value of bolder for text whose parent is normal would set the text to bold.

This property has read/write permission.

Applies To

HTML Tags | A, ADDRESS, APPLET, B, BIG, BLOCKQUOTE, BODY, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, DD, DFN, DIR, DIV, DL, DT, EM, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HTML, I, INPUT, INPUT type=button, INPUT type=file, INPUT type=reset, INPUT type=submit, INPUT type=text, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP
Scripting | style

CSS Attribute

font-weight


form

Description

Returns a reference to the form the element is embedded on.

Syntax

object.form

Remarks

Returns null if the element is not on a form.

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

APPLET, BUTTON, EMBED, FORM, INPUT, OBJECT, OPTION, SELECT, TEXTAREA


frame

Description

Controls the appearance of the border frame around the table.

Syntax

object.frame[ = frame]

Settings

Possible values include;
above | Displays a border on the top side of the border frame.
below | Displays a border on the bottom side of the table frame.
border | Displays a border on all sides of the table frame.
box | Displays a border on all sides of the table frame.
hsides | Displays a border on the top and bottom sides of the table frame.
lhs | Displays a border on the left side of the table frame.
rhs | Displays a border on the right side of the table frame.
void | Removes all outside table borders.
vsides | Displays a border on the left and right sides of the table frame.

Remarks

The default value for this property is void, that is, display no borders.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

TABLE

See Also

rules


frameBorder

Description

Specifies whether or not to display a border for the frame.

Syntax

object.frameBorder[ = frameBorder]

Remarks

Valid values are 0 and 1, with 0 specifying no border and 1 specifying an inset border. In addition, "Yes" and "No" are supported corresponding to 1 and 0, respectively. Invalid settings default to turning on borders.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

FRAME, FRAMESET, IFRAME


frameSpacing

Description

Creates additional space between the frames, in pixels.

Syntax

object.frameSpacing[ = frameSpacing]

Remarks

The amount defined for frameSpacing does not include the width of the frame border. Frame spacing can be set on one or more FRAMESET elements and applies to the contained FRAMESET elements unless the contained FRAMESET defines a different frame spacing.

The default spacing is 2 pixels.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

FRAMESET, IFRAME


fromElement

Description

Specifies the element being moved from the onmouseover and onmouseout events.

Syntax

object.fromElement

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

event


hash

Description

Sets or returns the subsection of the href property that follows the # symbol.

Syntax

object.hash[ = hash]

Remarks

If there is no hash, this property returns an empty string.

This property is useful for moving to a bookmark within a document. Assigning an invalid value does not cause an error.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

A, AREA, location


height

Description

Returns the vertical resolution of the screen, in pixels.

Syntax

object.height

Remarks

This property has read-only permission.

Applies To

screen


height

Description

Sets or retrieves the height of the element.

Syntax

object.style.height[ = height]

Remarks

The value of this read/write property is a string consisting of a floating-point number and a units designator, as described for cascading style sheets.

To carry out operations on the numeric value of this property, use pixelHeight or posHeight.

Percentage values are based on the width of the parent element. When scripting the height property, use either the pixelHeight or posHeight property for numeric manipulation of a height value.

For more information on how to access the dimension and location of elements on the page through the document object model, see Measuring Element Dimension and Location.

Applies To

HTML Tags | APPLET, DIV, EMBED, FIELDSET, HR, IFRAME, IMG, INPUT, INPUT type=button, MARQUEE, OBJECT, SPAN, TABLE, TEXTAREA
Scripting | style

CSS Attribute

height


height

Description

Sets or retrieves the height of the element.

Syntax

object.height

Remarks

Percentage values are based on the width of the parent element. When scripting the height property, use either the pixelHeight or posHeight property for numeric manipulation of a height value.

This property specifies the calculated height of the element, in pixels. For table rows and table cells, this property has a range of 0 to 32750 pixels.

If the value of the corresponding HTML attribute was set using a percentage, this property specifies the height in pixels represented by that percentage.

The scripting property is read/write for the IMG element, but read-only for other elements.

For more information on how to access the dimension and location of elements on the page through the document object model, see Measuring Element Dimension and Location.

Applies To

EMBED, FRAME, IMG, MARQUEE, OBJECT, TABLE

See Also

width


hidden

Description

Forces the embedded element to be invisible.

Syntax

object.Hidden[ = Hidden]

Remarks

This property has read-write permissions.

Applies To

EMBED


host

Description

Sets or retrieves the hostname:port part of the location or URL.

Syntax

object.host[ = host]

Settings

This read-write property is the concatenation of the hostname and port properties, separated by a colon. When the port property is null, the host property is the same as the hostname property.

You can set the host property at any time, although it is safer to set the href property to change a location. If the host that you specify cannot be found, you will get an error.

Applies To

A, AREA, location


hostname

Description

Specifies the host name part of the location or URL.

Syntax

object.hostname[ = hostname]

Remarks

If no host name is available, this property returns an empty string.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

A, AREA, location


href

Description

Returns a string specifying the URL of the linked style sheet, if the style sheet is a LINK. If the style sheet is a STYLE, the property returns NULL.

Syntax

object.href[ = href]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

styleSheet


href

Description

Specifies the destination URL or anchor point.

Syntax

object.href[ = href]

Remarks

The HREF attribute on the anchor is a scriptable attribute. HREFs on anchors can jump to bookmarks or any element's identification attribute.

When specifying an anchor, everything between the <A HREF..> and the A becomes a clickable link to that address.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

A, AREA, IMG LINK


href

Description

Specifies the baseline URL that relative links will be based on.

Syntax

object.href[ = href]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

BASE


href

Description

Returns the entire URL as a string.

Syntax

object.HREF[ = href]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

location

See Also

navigate method


hspace

Description

Specifies the horizontal margin for the element.

Syntax

object.hspace[ = hspace]

Remarks

This property is similar to border, except the margins are not painted with color when the element is a link.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

IFRAME, IMG, MARQUEE

See Also

border, vspace


htmlFor

Description

Specifies which element is being bound to the event script. This property corresponds to the HTML FOR= attribute.

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Syntax

object.htmlFor

Applies To

SCRIPT


htmlFor

Description

Specifies which control-like element to assign the given label element to. This property corresponds to the HTML FOR= attribute.

Syntax

object.htmlFor[ = htmlFor]

Remarks

This property references the identifier of another element.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

LABEL


htmlText

Description

Returns the HTML source as a valid HTML fragment.

Syntax

object.htmlText

Remarks

This property corresponds to the fragment portion of the CF_HTML clipboard format.

This property has read-only permission, meaning you can retrieve its current value, but not change it.

This feature may not be available on non-Win32® platforms. See article Q172976 in the Microsoft Knowledge Base for the latest information on Internet Explorer cross-platform compatibility.

Applies To

TextRange


httpEquiv

Description

Binds the content of the element to an HTTP response header.

Syntax

object.http-Equiv[ = http-Equiv]

Remarks

If omitted, the name property should be used to identify the meta-information. The httpEquiv property is not case sensitive.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

META

See Also

content


id

Description

Returns a string identifying the object.

Syntax

object.id

Remarks

To be used in scripts, the identifier can be any alphanumeric string that begins with a letter. Valid special characters include the underbar, "_".

The id should be unique throughout the scope of the current document. If a document contains more than one object with the same identifier, the objects are exposed as a collection that can only be referenced by ordinal position.

This property has read-only permission.

Applies To

A, ACRONYM, ADDRESS, APPLET, AREA, B, BASE, BASEFONT, BGSOUND, BIG, BLOCKQUOTE, BODY, BR, BUTTON, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, COMMENT, DD, DEL, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FONT, FORM, FRAME, FRAMESET, H1, H2, H3, H4, H5, H6, HEAD, HR, HTML, I, IFRAME, IMG, INPUT, INS, KBD, LABEL, LEGEND, LI, LINK, LISTING, MAP, MARQUEE, MENU, OBJECT, OL, OPTION, P, PLAINTEXT, PRE, Q, S, SAMP, SCRIPT, SELECT, SMALL, SPAN, STRIKE, STRONG, STYLE, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TITLE, TR, TT, U, UL, VAR, XMP, styleSheet


indeterminate

Description

Changes the user interface of a check box to have a dimmed background to represent an indeterminate state. When indeterminate is set, the check box will appear checked, but dimmed. The value of indeterminate is independent of the values for the checked and the status properties.

Syntax

object.indeterminate[ = indeterminate]

Settings

This read-write property is TRUE if the check box is dimmed, or FALSE otherwise. The default value for this property is FALSE.

This property does not remove whether the element is checked and is different than disabling the control. A check box in the indeterminate state can still receive the focus. When the user clicks an indeterminate button, the indeterminate state is turned off and the check box is appropriately checked or unchecked.

Applies To

INPUT


index

Description

Returns the ordinal position of the option in the list box.

Syntax

object.index

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

OPTION


innerHTML

Description

Sets or retrieves the HTML between the start and end tags of the current element.

Syntax

object.innerHTML[ = innerHTML]

Settings

This read-write property takes a string containing a valid combination of text and HTML tags, except for <html>, <head>, and <title> tags.

When setting this property, the given string completely replaces the existing content of the element. If the string contains HTML tags, the string is parsed and formatted as it is placed into the document.

Note You cannot set this property while the document is loading. Wait for the onload event before attempting to set it. If a tag is dynamically created using TextRange, innerHTML, or outerHTML, you can only use JScript to create new events to handle the newly formed tags. VBScript is not supported.

Applies To

A, ACRONYM, ADDRESS, B, BIG, BLOCKQUOTE, BODY, BUTTON, CAPTION, CENTER, CITE, CODE, DD, DEL, DFN, DIR, DIV, DL, DT, EM, FIELDSET, FONT, FORM, H1, H2, H3, H4, H5, H6, I, IFRAME, IMG, INS, KBD, LABEL, LEGEND, LI, LISTING, MAP, MARQUEE, MENU, OL, P, PRE, Q, S, SAMP, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TH, TT, U, UL, VAR

See Also

insertAdjacentHTML method


innerText

Description

Sets or retrieves the text between the start and end tags of the current element.

Syntax

object.innerText[ = innerText]

Settings

This read-write property can be any valid string. When setting this property, the given string completely replaces the existing content of the element, except for <html>, <head>, and <title> tags.

Note You cannot set this property while the document is loading. Wait for the onload event before attempting to set it. If a tag is dynamically created using TextRange, innerHTML, or outerHTML, you can only use JScript to create new events to handle the newly formed tags. VBScript is not supported.

Applies To

A, ACRONYM, ADDRESS, B, BIG, BLOCKQUOTE, BODY, BR, BUTTON, CAPTION, CENTER, CITE, CODE, COMMENT, DD, DEL, DFN, DIR, DIV, DL, DT, EM, FIELDSET, FONT, FORM, H1, H2, H3, H4, H5, H6, I, IFRAME, IMG, INS, KBD, LABEL, LEGEND, LI, LISTING, MAP, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, Q, S, SAMP, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TD, TEXTAREA, TH, TITLE, TT, U, UL, VAR, XMP

See Also

insertAdjacentText method


isMap

Description

Identifies the picture as a server-side image map.

Syntax

object.isMap[ = isMap]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

IMG


isTextEdit

Description

Specifies whether a text range object can be created using the given element.

Syntax

object.isTextEdit

Settings

The value of this read-only property is TRUE if a text range can be created, or FALSE otherwise.

Only the BODY, BUTTON, and TEXTAREA elements and an INPUT element having text type can be used to create a text range object.

Applies To

A, ACRONYM, ADDRESS, APPLET, AREA, B, BASE, BASEFONT, BGSOUND, BIG, BLOCKQUOTE, BODY, BR, BUTTON, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, COMMENT, DD, DEL, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FONT, FORM, FRAME, FRAMESET, H1, H2, H3, H4, H5, H6, HEAD, HR, HTML, I, IFRAME, IMG, INPUT, INS, KBD, LABEL, LEGEND, LI, LINK, LISTING, MAP, MARQUEE, MENU, META, NEXTID, OBJECT, OL, OPTION, P, PLAINTEXT, PRE, Q, S, SAMP, SCRIPT, SELECT, SMALL, SPAN, STRIKE, STRONG, STYLE, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TITLE, TR, TT, U, UL, VAR, XMP


keyCode

Description

Specifies the Unicode key code associated with the key that caused the event. This property is intended to be used with the onkeydown, onkeyup, and onkeypress events.

Syntax

object.keyCode[ = keyCode]

Settings

This read-write property can be set to a Unicode key code. It is zero if no key caused the event.

Applies To

event


lang

Description

Specifies the language to use. The specifier is an ISO standard language abbreviation.

Syntax

object.lang[ = lang]

Remarks

The parser can use this property to determine how to display language-specific choices for quotations, numbers, and so on.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

A, ACRONYM, ADDRESS, APPLET, AREA, B, BIG, BLOCKQUOTE, BODY, BUTTON, CAPTION, CENTER, CITE, CODE, DD, DEL, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FONT, FORM, FRAME, FRAMESET, H1, H2, H3, H4, H5, H6, I, IFRAME, IMG, INPUT, INS, KBD, LABEL, LEGEND, LI, LISTING, MAP, MARQUEE, MENU, OBJECT, OL, OPTION, P, PLAINTEXT, PRE, Q, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TITLE, TR, TT, U, UL, VAR, XMP


language

Description

Specifies the language that the current script is written in. JScript is the default for this attribute.

Syntax

object.language

Settings

This read-only property can refer to any scripting language. Internet Explorer 4.0 ships with a JScript (JavaScript-compatible) and VBScript scripting engine. Keywords for accessing these scripting languages include the following:

javascript | Specifies that the script is written in JavaScript.
Jscript | Specifies the language as JavaScript.
vbs | Specifies the language as VBScript.
vbscript | Specifies that the script is written in VBScript.

Applies To

A, ACRONYM, ADDRESS, APPLET, AREA, B, BIG, BLOCKQUOTE, BODY, BR, BUTTON, CAPTION, CENTER, CITE, CODE, DD, DEL, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FONT, FORM, FRAME, FRAMESET, H1, H2, H3, H4, H5, H6, HR, I, IFRAME, IMG, INPUT, INS, KBD, LABEL, LEGEND, LI, LISTING, MAP, MARQUEE, OBJECT, OL, OPTION, P, PLAINTEXT, PRE, Q, S, SAMP, SCRIPT, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP


Language Codes

Description

The following table lists all the possible language codes used to specify various system settings.
af Afrikaans | sq Albanian
ar-sa Arabic(Saudi Arabia) | ar-iq Arabic(Iraq)
ar-eg Arabic(Egypt) | ar-ly Arabic(Libya)
ar-dz Arabic(Algeria) | ar-ma Arabic(Morocco)
ar-tn Arabic(Tunisia) | ar-om Arabic(Oman)
ar-ye Arabic(Yemen) | ar-sy Arabic(Syria)
ar-jo Arabic(Jordan) | ar-lb Arabic(Lebanon)
ar-kw Arabic(Kuwait) | ar-ae Arabic(U.A.E.)
ar-bh Arabic(Bahrain) | ar-qa Arabic(Qatar)
eu Basque | bg Bulgarian
be Belarusian | ca Catalan
zh-tw Chinese(Taiwan Region) | zh-cn Chinese(PRC)
zh-hk Chinese(Hong Kong SAR, PRC) | zh-sg Chinese(Singapore)
hr Croatian | cs Czech
da Danish | nl Dutch(Standard)
nl-be Dutch(Belgian) | en English
en-us English(United States) | en-gb English(British)
en-au English(Australian) | en-ca English(Canadian)
en-nz English(New Zealand) | en-ie English(Ireland)
en-za English(South Africa) | en-jm English(Jamaica)
en English(Caribbean) | en-bz English(Belize)
en-tt English(Trinidad) | et Estonian
fo Faeroese | fa Farsi
fi Finnish | fr French(Standard)
fr-be French(Belgian) | fr-ca French(Canadian)
fr-ch French(Swiss) | fr-lu French(Luxembourg)
gd Gaelic(Scots) | gd-ie Gaelic(Irish)
de German(Standard) | de-ch German(Swiss)
de-at German(Austrian) | de-lu German(Luxembourg)
de-li German(Liechtenstein) | el Greek
he Hebrew | hi Hindi
hu Hungarian | is Icelandic
in Indonesian | it Italian(Standard)
it-ch Italian(Swiss) | ja Japanese
ko Korean | ko Korean(Johab)
lv Latvian | lt Lithuanian
mk Macedonian | ms Malaysian
mt Maltese | no Norwegian(Bokmal)
no Norwegian(Nynorsk) | pl Polish
pt-br Portuguese(Brazilian) | pt Portuguese(Standard)
rm Rhaeto-Romanic | ro Romanian
ro-mo Romanian(Moldavia) | ru Russian
ru-mo Russian(Moldavia) | sz Sami(Lappish)
sr Serbian(Cyrillic) | sr Serbian(Latin)
sk Slovak | sl Slovenian
sb Sorbian | es Spanish(Spain - Traditional Sort)
es-mx Spanish(Mexican) | es Spanish(Spain - Modern Sort)
es-gt Spanish(Guatemala) | es-cr Spanish(Costa Rica)
es-pa Spanish(Panama) | es-do Spanish(Dominican Republic)
es-ve Spanish(Venezuela) | es-co Spanish(Colombia)
es-pe Spanish(Peru) | es-ar Spanish(Argentina)
es-ec Spanish(Ecuador) | es-cl Spanish(Chile)
es-uy Spanish(Uruguay) | es-py Spanish(Paraguay)
es-bo Spanish(Bolivia) | es-sv Spanish(El Salvador)
es-hn Spanish(Honduras) | es-ni Spanish(Nicaragua)
es-pr Spanish(Puerto Rico) | sx Sutu
sv Swedish | sv-fi Swedish(Finland)
th Thai | ts Tsonga
tn Tswana | tr Turkish
uk Ukrainian | ur Urdu
ve Venda | vi Vietnamese
xh Xhosa | ji Yiddish
zu Zulu


lastModified

Description

Contains the last-modified date of the page (if the page supplies one).

Syntax

object.lastModified

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

document


left

Description

Sets or retrieves the position of the element relative to the left edge of the document.

Syntax

object.style.left[ = left]

Remarks

The value of this read/write property is a string consisting of a floating-point number and a units designator, as described for cascading style sheets.

For more information about how to access the dimension and location of elements on the page through the document object model, see Measuring Element Dimension and Location.

Applies To

HTML Tags | A, ADDRESS, APPLET, B, BIG, BLOCKQUOTE, CENTER, CITE, CODE, DD, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, I, IFRAME, IMG, INPUT, INPUT type=button, INPUT type=checkbox, INPUT type=file, INPUT type=image, INPUT type=radio, INPUT type=reset, INPUT type=submit, INPUT type=text, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OBJECT, OL, P, PRE, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TEXTAREA, TT, U, UL, VAR, XMP
Scripting | style

CSS Attribute

left

See Also

pixelLeft, posLeft


leftMargin

Description

Specifies the left margin for the entire body of the page and overrides the default margin.

Syntax

object.leftMargin[ = leftMargin]

Settings

This read-write property is a string. If set to "", the left margin will be exactly on the left edge.

Applies To

BODY

See Also

topMargin


length

Description

Returns the number of elements in a collection. The window.length property returns the number of frames contained in a window.

Syntax

object.length

Remarks

This property is read-write on the areas and options collections and <SELECT> object, specifically for image maps and select boxes, respectively. This allows you to change the length of the collection as necessary.

In all other cases, this property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

all, anchors, applets, areas, embeds, forms, frames, history, images, imports, links, plugins, scripts, SELECT, styleSheets, window

See Also

options collection


letterSpacing

Description

Sets or retrieves the amount of additional space between letters in the element.

Syntax

object.letterSpacing[ = letterSpacing]

Remarks

The attribute will add the appropriate letter spacing after each character. If you do not want the end of a word to be affected by the spacing, you need to place the last character outside the closing element tag. Letter spacing can be influenced by justification. Negative values are permitted.

This property has read/write permission.

Applies To

HTML Tags | A, ADDRESS, B, BIG, BLOCKQUOTE, BODY, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, DD, DFN, DIR, DIV, DL, DT, EM, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HTML, I, INPUT, INPUT type=button, INPUT type=file, INPUT type=reset, INPUT type=submit, INPUT type=text, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, S, SAMP, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP
Scripting | style

CSS Attribute

letter-spacing


lineHeight

Description

Sets or retrieves the distance between lines in a paragraph.

Syntax

object.style.lineHeight[ = lineHeight]

Remarks

Line height is the distance between the descender of the font to the top of the internal leading of the font. A negative line height is allowed to achieve various shadowing effects.

If there is more than one element on a formatted line, the maximum line height applies. Negative values are not allowed.

The property has read/write permission.

Applies To

HTML Tags | A, ADDRESS, B, BIG, BLOCKQUOTE, BODY, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, DD, DFN, DIR, DIV, DL, DT, EM, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HTML, I, INPUT, INPUT type=button, INPUT type=file, INPUT type=reset, INPUT type=submit, INPUT type=text, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, S, SAMP, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP
Scripting | style

CSS Attribute

line-height


link

Description

Sets or retrieves the color of the document links.

Syntax

object.style.link[ = color]

Remarks

The color can be one of the color names or values given in Color Table.

This is the color used when the link has not been visited, is not actively being navigated, and does not have a mouse positioned over it. Setting the hover pseudo-class is often used in conjunction with setting specific styles for the other states of a link: active, visited, and hover.

The property has read/write permission.

Applies To

body

See Also

aLink, vLink


linkColor

Description

Returns the color of the document links. The color can be one of the color names or values given in Color Table.

Syntax

object.linkColor[ = color]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

document

See Also

alinkColor, vlinkColor


listStyle

Description

Sets or retrieves these three properties at once: listStyleType, listStyleImage, and listStylePosition.

Syntax

object.style.listStyle[ = listStyle]

Remarks

This shorthand property can specify both a URL and a list-style-type, which will be used if the URL is not found.

The property has read/write permission.

Applies To

HTML Tags | LI, OL, UL
Scripting | style

CSS Attribute

list-style


listStyleImage

Description

Sets or retrieves which image to use as a list-item marker.

Syntax

object.style.listStyleImage[ = listStyleImage]

Remarks

When the image is available, it will replace the marker set with the listStyleType marker. The default value for this property is none.

The property has read/write permission.

Applies To

HTML Tags | LI, OL, UL
Scripting | style

CSS Attribute

list-style-image


listStylePosition

Description

Sets or retrieves how the list-item marker is drawn with regard to the element's content.

Syntax

object.style.listStylePosition[ = listStylePosition]

Remarks

This property is applicable only on elements with a display value of list-item.

The property has read/write permission.

Applies To

HTML Tags | LI, OL, UL
Scripting | style

CSS Attribute

list-style-position


listStyleType

Description

Sets or returns the type of predefined line-item marker.

Syntax

object.style.listStyleType[ = listStyleType]

Remarks

This property determines the appearance of the list-item marker if listStyleImage is none or if the image pointed to by the URL cannot be displayed. The default value is disc.

The property has read/write permission.

Applies To

HTML Tags | LI, OL, UL
Scripting | style

CSS Attribute

list-style-type


location

Description

Returns information on the current URL. The href property contains the entire URL, and the other properties contain portions of it. The full list of properties includes hash, host, hostname, href, pathname, port, protocol, and search.

Syntax

object.location[ = location]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

document


loop

Description

Specifies how many times a sound or video will loop when activated. If applied to a marquee, it specifies how many times the content of the marquee should loop. If n=-1 or infinite, it will loop continuously.

Syntax

object.loop[ = loop]

Remarks

Following are descriptions on how loop works for some boundary cases.

<BGSOUND src="file:///c:\win95\system\msremind.wav"> | once
<BGSOUND src="file:///c:\win95\system\msremind.wav" LOOP> | once
<BGSOUND src="file:///c:\win95\system\msremind.wav" LOOP=> | zero times
<BGSOUND src="file:///c:\win95\system\msremind.wav" LOOP=-1> | infinitely
<BGSOUND src="file:///c:\win95\system\msremind.wav" LOOP=0> | once

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

BGSOUND, IMG, MARQUEE


lowsrc

Description

Specifies a lower resolution image to display.

Syntax

object.lowsrc[ = lowsrc]

Remarks

Setting the src attribute in code has the side effect of actually starting to load the new URL into the image area (and aborting the transfer of any image data that is already loading into the same area). Therefore, if you're going to alter the lowsrc property, you need to do so before setting the src property. If the URL in the src property references an image that is not the same size as the image cell it is loaded into, the source image is scaled to fit.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

IMG


map

Description

Sets or returns the element representing the image map.

Syntax

object.map[ = map]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

IMG


margin

Description

Retrieves the width of the left and right margins and the height of the top and bottom margins.

Syntax

object.style.margin

Remarks

The property has read-only permission.

Applies To

HTML Tags | BLOCKQUOTE, BODY, CAPTION, CENTER, DD, DIR, DIV, DL, DT, EMBED, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, IFRAME, IMG, INPUT, LI, LISTING, MARQUEE, MENU, OBJECT, OL, P, PLAINTEXT, PRE, SPAN, TABLE, TD, TEXTAREA, TH, TR, UL, XMP
Scripting | style

CSS Attribute

margin


marginBottom

Description

Retrieves the height of the bottom margin for the element.

Syntax

object.style.marginBottom

Remarks

Negative margins are supported except for top and bottom margins on inline elements.

The property has read-only permission.

Applies To

HTML Tags | BLOCKQUOTE, BODY, CAPTION, CENTER, DD, DIR, DIV, DL, DT, EMBED, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, IFRAME, IMG, INPUT, LI, LISTING, MARQUEE, MENU, OBJECT, OL, P, PLAINTEXT, PRE, SPAN, TABLE, TD, TEXTAREA, TH, TR, UL, XMP
Scripting | style

CSS Attribute

margin-bottom


marginHeight

Description

Sets the top and bottom margins to the appropriate height before displaying the text in a frame.

Syntax

object.marginHeight[ = marginHeight]

Remarks

The value for the margin height is in pixels. Margins cannot be less than 1 nor so large that the text cannot be displayed.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

FRAME, IFRAME

See Also

marginWidth


marginLeft

Description

Retrieves the width of the left margin for the element.

Syntax

object.style.marginLeft

Remarks

Negative margins are supported except for top and bottom margins on inline elements.

This property has read-only permission.

Applies To

HTML Tags | BLOCKQUOTE, BODY, CAPTION, CENTER, DD, DIR, DIV, DL, DT, EMBED, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, IFRAME, IMG, INPUT, LI, LISTING, MARQUEE, MENU, OBJECT, OL, P, PLAINTEXT, PRE, SPAN, TABLE, TD, TEXTAREA, TH, TR, UL, XMP
Scripting | style

CSS Attribute

margin-left


marginRight

Description

Retrieves the width of the right margin for the element.

Syntax

object.style.marginRight

Remarks

The property has read-only permission.

Applies To

HTML Tags | BLOCKQUOTE, BODY, CAPTION, CENTER, DD, DIR, DIV, DL, DT, EMBED, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, IFRAME, IMG, INPUT, LI, LISTING, MARQUEE, MENU, OBJECT, OL, P, PLAINTEXT, PRE, SPAN, TABLE, TEXTAREA, TD, TH, TR, UL, XMP
Scripting | style

CSS Attribute

margin-right


marginTop

Description

Retrieves the height of the top margin for the element.

Syntax

object.style.marginTop

Remarks

Negative margins are supported except for top and bottom margins on inline elements.

The property has read-only permission.

Applies To

HTML Tags | BLOCKQUOTE, BODY, CAPTION, CENTER, DD, DIR, DIV, DL, DT, EMBED, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, IFRAME, IMG, INPUT, LI, LISTING, MARQUEE, MENU, OBJECT, OL, P, PLAINTEXT, PRE, SPAN, TABLE, TD, TEXTAREA, TH, TR, UL, XMP
Scripting | style

CSS Attribute

margin-top


marginWidth

Description

Sets or retrieves the amount the left and right margin should be set to before displaying the text in a frame.

Syntax

object.marginWidth[ = marginWidth]

Remarks

The value for margin width is in pixels. Margins cannot be less than 1 nor so large that the text cannot be displayed.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

FRAME, IFRAME

See Also

marginHeight


maxLength

Description

Indicates the maximum number of characters that can be entered into a text control. This limits the user entry, not programmatic assignments to the value property.

Syntax

object.maxLength[ = maxLength]

Remarks

This value can be larger than the size of the text box. When this occurs, the text box should scroll accordingly as the user types. The default is no limit.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

INPUT

See Also

size


media

Description

Sets the media type through the STYLE and LINK elements.

Syntax

object.media[ = media]

Parameter | Description
MEDIA | Designed for rendering on these media. Default value is ALL.
SCREEN - Output is intended for nonpaged computer screens.
PRINT - Output is intended for paged, opaque material and for documents on screen viewed in print preview mode.
ALL - Applies to all devices.

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

LINK, STYLE


method

Description

Indicates how the form data should be sent to the server—either as GET or POST, which are the only legal values.

Syntax

object.method[ = method]

Settings

Possible values include;
get | Append the arguments to the action URL and open it as if it were an anchor.
post | Send the data through an HTTP post transaction.

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

FORM

See Also

action


Methods

Description

Specifies information about the functions that the user can perform on an object.

Syntax

object.Methods[ = Methods]

Remarks

These methods are more accurately given by the HTTP protocol when it is used, but it might, for reasons similar as for the title property, be useful to include the information in advance in the link. The HTML user agent can chose a different rendering as a function of the methods allowed; for example, something that is searchable might get a different icon.

The value of the property is a comma-separated list of HTTP methods supported by the object for public use.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

A


mimeTypes

Description

Returns an empty collection for Internet Explorer 4.0. This property exists for compatibility with other browsers.

Syntax

object.mimeTypes

Remarks

This property has read-only permission.

Applies To

navigator


multiple

Description

Indicates that multiple items in the list can be selected.

Syntax

object.multiple[ = multiple]

Remarks

The default value for this property is FALSE.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

SELECT


name

Description

Specifies the name of a window or the frame so it can be targeted from links in other documents.

Syntax

object.name[ = sName]

Settings

This read/write property takes either a window name or frame name, or one of these special values:

window_name | A string that specifies a frame.
_blank | Loads the link into a new, unnamed window.
_parent | Loads the link over the parent. If the frame has no parent, this refers to _self.
_self | Replaces the page with the specified link.
_top | Loads the link at the topmost level.

Remarks

An exception to the rule, the window keyword must be used to access the name property.

Examples

The following code shows the name property being assigned to the window object.

window.name="MyWindow";

The name property on the window frequently comes from the FRAME definition.

parent.frames[0].name="Left";

The NAME attribute for a window can only be persisted in HTML when defined in a frame within a frameset.

<FRAMESET>
   <FRAME NAME="Left" SRC="blank.htm">
</FRAMESET>

The name property can be assigned using the window open method.

window.open("file.htm","Frame1");

Applies To

FRAME, IFRAME, window


name

Description

Specifies the name of the control, bookmark, or application.

Syntax

object.name[ = name]

Remarks

The name is used to bind the value of the control when submitting a form. The name is not the value that is displayed for the button, reset, and submit objects. Submitting the form submits the internally stored value, not the one displayed.

JScript allows the name to be changed at run time. This does not cause the name in the programming model to change in the collection of elements, but does change the name used for submitting elements.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

A, APPLET, BUTTON, FORM, IMG, INPUT, LINK, MAP, META, OBJECT, SELECT, TEXTAREA


noHref

Description

Indicates that clicks in this region should cause no action.

Syntax

object.noHref[ = noHref]

Remarks

The default value for this property is FALSE.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

AREA


noResize

Description

Specifies whether the user can resize the frame.

Syntax

object.noResize[ = noResize]

Settings

This read-write property takes a Boolean value:

TRUE | Frame size is fixed. User cannot resize it.
FALSE | Frame is resizable. This is the default value for the property.

By default, all frames are resizable.

Applies To

FRAME, IFRAME


noShade

Description

Draws the horizontal rule without 3-D shading.

Syntax

object.noShade[ = noShade]

Remarks

The default value for this property is FALSE.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

HR


noWrap

Description

Prevents the browser from automatically performing word wrap.

Syntax

object.noWrap[ = noWrap]

Remarks

The default value for this property is FALSE.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

BODY, DD, DIV, DT, TD, TH


object

Description

References the contained object. For instance, if the control's object model uses a conflicting name space, preceding the control's property with object resolves the conflict.

Syntax

object.object

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

OBJECT


offscreenBuffering

Description

Specifies whether to use offscreen buffering. When the document is first loaded the value is a string, "auto", which allows Internet Explorer 4.0 to decide when offscreen buffering is used.

Syntax

object.offscreenBuffering[ = Boolean]

Settings

This read-write property can be set to TRUE to enable offscreen buffering, and FALSE to disable it. The return type of the property, once it has been set, is a Boolean value.

Applies To

window


offsetHeight

Description

Returns the height of the element, in pixels, relative to the parent coordinate system.

Syntax

object.offsetHeight

Remarks

Using a combination of offset* properties, you can determine the location, width, and height of an element by using the offsetLeft, offsetTop, offsetHeight, and offsetWidth properties. These numeric properties specify the physical coordinates and dimensions of the element relative to the element's offset parent. For example, the following document is a simple clock that adjusts the size of its readout to fit the current width and height of the document body.

<HTML>
<HEAD><TITLE>A Simple Clock</TITLE>
<SCRIPT LANGUAGE="JScript">
function startClock() {
    window.setInterval("Clock_Tick()", 1000);
    Clock_Tick();
}

var ratio = 4;
function Clock_Tick()
{
    var s = Date();
    var t = s.substring(11,19);
    var doc_height = document.body.offsetHeight;
    var doc_width = document.body.offsetWidth;

    if ((doc_height*ratio)>doc_width)
        doc_height = doc_width / ratio;
    document.all.MyTime.innerText = t;
    document.all.MyTime.style.fontSize = doc_height;
}
</SCRIPT>
<BODY onload="startClock()">
<P ID="MyTime">&nbsp;</P>
</BODY>
</HTML>

This property has read-only permission, meaning you can retrieve its current value, but not change it.

For more information on how to access the dimension and location of elements on the page through the document object model, see Measuring Element Dimension and Location.

Applies To

A, ACRONYM, ADDRESS, APPLET, AREA, B, BIG, BLOCKQUOTE, BODY, BR, BUTTON, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, COMMENT, DD, DEL, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FONT, FORM, FRAME, H1, H2, H3, H4, H5, H6, HR, I, IFRAME, IMG, INPUT, INS, KBD, LABEL, LEGEND, LI, LISTING, MAP, MARQUEE, MENU, OBJECT, OL, OPTION, P, PLAINTEXT, PRE, Q, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP


offsetLeft

Description

Returns the calculated left position, in pixels, based on the window.

Syntax

object.offsetLeft

Remarks

Using a combination of offset* properties, you can determine the location, width, and height of an element by using the offsetLeft, offsetTop, offsetHeight, and offsetWidth properties. These numeric properties specify the physical coordinates and dimensions of the element relative to the element's offset parent. For example, the following document is a simple clock that adjusts the size of its readout to fit the current width and height of the document body.

<HTML>
<HEAD><TITLE>A Simple Clock</TITLE>
<SCRIPT LANGUAGE="JScript">
function startClock() {
    window.setInterval("Clock_Tick()", 1000);
    Clock_Tick();
}

var ratio = 4;
function Clock_Tick()
{
    var s = Date();
    var t = s.substring(11,19);
    var doc_height = document.body.offsetHeight;
    var doc_width = document.body.offsetWidth;

    if ((doc_height*ratio)>doc_width)
        doc_height = doc_width / ratio;
    document.all.MyTime.innerText = t;
    document.all.MyTime.style.fontSize = doc_height;
}
</SCRIPT>
<BODY onload="startClock()">
<P ID="MyTime">&nbsp;</P>
</BODY>
</HTML>

This property has read-only permission.

For more information on how to access the dimension and location of elements on the page through the document object model, see Measuring Element Dimension and Location.

Applies To

A, ACRONYM, ADDRESS, APPLET, AREA, B, BIG, BLOCKQUOTE, BODY, BR, BUTTON, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, COMMENT, DD, DEL, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FONT, FORM, FRAME, H1, H2, H3, H4, H5, H6, HR, I, IFRAME, IMG, INPUT, INS, KBD, LABEL, LEGEND, LI, LISTING, MAP, MARQUEE, MENU, OBJECT, OL, OPTION, P, PLAINTEXT, PRE, Q, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TextRange, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP


offsetParent

Description

Returns a reference to the container element that defines the top and left offsets for the object.

Syntax

object.offsetParent

Remarks

The offsetLeft and offsetTop property values are relative to the element specified by the offsetParent property for the element. Most of the time the property returns BODY. For example, in the following document, even though the TD element appears to the far right in the document, its position is (0,0) because its offset parent is TR, not the document body.

<HTML>
<HEAD><TITLE>Elements: Positions</TITLE></HEAD>
<SCRIPT LANGUAGE="JScript">
function showPosition() {
    var el = document.all.MyID;
    alert("The TD element is at (" + el.offsetLeft + "," + el.offsetTop + ")\n" +
     "The offset parent is " + el.offsetParent.tagName );
}
</SCRIPT>
<BODY onload="showPosition()">
<P>This document contains a right-aligned table.
<TABLE BORDER=1 ALIGN=right>
<TR><TD ID=MyID>This is a small table
</TABLE>
</BODY>
</HTML>

This property has read-only permission.

Applies To

A, ACRONYM, ADDRESS, APPLET, AREA, B, BIG, BLOCKQUOTE, BODY, BR, BUTTON, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, COMMENT, DD, DEL, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FONT, FORM, FRAME, H1, H2, H3, H4, H5, H6, HR, I, IFRAME, IMG, INPUT, INS, KBD, LABEL, LEGEND, LI, LISTING, MAP, MARQUEE, MENU, OBJECT, OL, OPTION, P, PLAINTEXT, PRE, Q, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP


offsetTop

Description

Returns the calculated top position of the element in the element's parent coordinates.

Syntax

object.offsetTop

Remarks

Using a combination of offset* properties, you can determine the location, width, and height of an element by using the offsetLeft, offsetTop, offsetHeight, and offsetWidth properties. These numeric properties specify the physical coordinates and dimensions of the element relative to the element's offset parent. For example, the following document is a simple clock that adjusts the size of its readout to fit the current width and height of the document body.

<HTML>
<HEAD><TITLE>A Simple Clock</TITLE>
<SCRIPT LANGUAGE="JScript">
function startClock() {
    window.setInterval("Clock_Tick()", 1000);
    Clock_Tick();
}

var ratio = 4;
function Clock_Tick()
{
    var s = Date();
    var t = s.substring(11,19);
    var doc_height = document.body.offsetHeight;
    var doc_width = document.body.offsetWidth;

    if ((doc_height*ratio)>doc_width)
        doc_height = doc_width / ratio;
    document.all.MyTime.innerText = t;
    document.all.MyTime.style.fontSize = doc_height;
}
</SCRIPT>
<BODY onload="startClock()">
<P ID="MyTime">&nbsp;</P>
</BODY>
</HTML>

This property has read-only permission.

For more information on how to access the dimension and location of elements on the page through the document object model, see Measuring Element Dimension and Location.

Applies To

A, ACRONYM, ADDRESS, APPLET, AREA, B, BIG, BLOCKQUOTE, BODY, BR, BUTTON, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, COMMENT, DD, DEL, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FONT, FORM, FRAME, H1, H2, H3, H4, H5, H6, HR, I, IFRAME, IMG, INPUT, INS, KBD, LABEL, LEGEND, LI, LISTING, MAP, MARQUEE, MENU, OBJECT, OL, OPTION, P, PLAINTEXT, PRE, Q, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TextRange, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP


offsetWidth

Description

Returns the width of the element relative to the document's top-left corner.

Syntax

object.offsetWidth

Remarks

Using a combination of offset* properties, you can determine the location, width, and height of an element by using the offsetLeft, offsetTop, offsetHeight, and offsetWidth properties. These numeric properties specify the physical coordinates and dimensions of the element relative to the element's offset parent. For example, the following document is a simple clock that adjusts the size of its readout to fit the current width and height of the document body.

<HTML>
<HEAD><TITLE>A Simple Clock</TITLE>
<SCRIPT LANGUAGE="JScript">
function startClock() {
    window.setInterval("Clock_Tick()", 1000);
    Clock_Tick();
}

var ratio = 4;
function Clock_Tick()
{
    var s = Date();
    var t = s.substring(11,19);
    var doc_height = document.body.offsetHeight;
    var doc_width = document.body.offsetWidth;

    if ((doc_height*ratio)>doc_width)
        doc_height = doc_width / ratio;
    document.all.MyTime.innerText = t;
    document.all.MyTime.style.fontSize = doc_height;
}
</SCRIPT>
<BODY onload="startClock()">
<P ID="MyTime">&nbsp;</P>
</BODY>
</HTML>

This property has read-only permission, meaning you can retrieve its current value, but not change it.

For more information on how to access the dimension and location of elements on the page through the document object model, see Measuring Element Dimension and Location.

Applies To

A, ACRONYM, ADDRESS, APPLET, AREA, B, BIG, BLOCKQUOTE, BODY, BR, BUTTON, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, COMMENT, DD, DEL, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FONT, FORM, FRAME, H1, H2, H3, H4, H5, H6, HR, I, IFRAME, IMG, INPUT, INS, KBD, LABEL, LEGEND, LI, LISTING, MAP, MARQUEE, MENU, OBJECT, OL, OPTION, P, PLAINTEXT, PRE, Q, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP


offsetX

Description

Returns container relative positions. These match the offsetLeft and offsetTop properties of the element. Use offsetParent to find the container element that defines this coordinate system.

Syntax

object.offsetX

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

event


offsetY

Description

Returns container relative positions. These match the offsetLeft and offsetTop properties of the element. Use offsetParent to find the container element that defines this coordinate system.

Syntax

object.offsetY

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

event


onLine

Description

Indicates whether or not the system is in global offline mode.

Syntax

object.onLine

Remarks

True indicates the system is in global online mode. False indicates the system is in global offline mode. This property has read-only permission, meaning you can retrieve its current value, but not change it.

The user can modify the global offline state by selecting the Work Offline item from the Internet Explorer 4.0 File menu. This property does not indicate whether or not the system is physically connected to the network.

Applies To

navigator


opener

Description

Returns a reference to the window that created the current window.

Syntax

object.opener[ = opener]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

window


outerHTML

Description

Sets or retrieves the current element and its content in HTML.

Syntax

object.outerHTML[ = outerHTML]

Settings

This read-write property can be any valid string containing a combination of text and HTML tags, except for <html>, <head>, and <title> tags.

When setting this property, the given string completely replaces the element, including its start and end tags. If the string contains HTML tags, the string is parsed and formatted as it is placed into the document.

Note You cannot set this property while the document is loading. Wait for the onload event before attempting to set it. If a tag is dynamically created using TextRange, innerHTML, or outerHTML, you can only use JScript to create new events to handle the newly formed tags. VBScript is not supported.

Applies To

A, ACRONYM, ADDRESS, APPLET, AREA, B, BGSOUND, BIG, BLOCKQUOTE, BR, BUTTON, CENTER, CITE, CODE, COMMENT, DD, DEL, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FONT, FORM, H1, H2, H3, H4, H5, H6, HR, I, IFRAME, IMG, INPUT, INS, KBD, LABEL, LEGEND, LI, LISTING, MAP, MARQUEE, MENU, OBJECT, OL, P, PLAINTEXT, PRE, Q, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TEXTAREA, TT, U, UL, VAR, XMP

See Also

insertAdjacentHTML method


outerText

Description

Sets or retrieves the text of the current element.

Syntax

object.outerText[ = outerText]

Settings

This read-write property can be any valid string. When setting this property, the given string completely replaces the original text in the element, except for <html>, <head>, and <title> tags.

Note You cannot set this property while the document is loading. Wait for the onload event before attempting to set it. If a tag is dynamically created using TextRange, innerHTML, or outerHTML, you can only use JScript to create new events to handle the newly formed tags. VBScript is not supported.

Applies To

A, ACRONYM, ADDRESS, APPLET, AREA, B, BGSOUND, BIG, BLOCKQUOTE, BR, BUTTON, CENTER, CITE, CODE, COMMENT, DD, DEL, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FONT, FORM, H1, H2, H3, H4, H5, H6, HR, I, IFRAME, IMG, INPUT, INS, KBD, LABEL, LEGEND, LI, LISTING, MAP, MARQUEE, MENU, OBJECT, OL, P, PLAINTEXT, PRE, Q, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TEXTAREA, TT, U, UL, VAR, XMP

See Also

insertAdjacentText method


overflow

Description

Sets or retrieves what should be done when the element's content exceeds the height and/or width of the element.

Syntax

object.style.overflow[ = overflow]

Remarks

This property applies to positioned elements. By default, overflowing content is visible. This means the element does not observe its specified height and width. If the attribute is set to scroll, the content is clipped to the height and width specified on the element, and the overflowing content is accessible through scroll bars. If the attribute is set to hidden, the content of the element is clipped to the height and width of the element, and no scroll bars appear to access the hidden content.

For the TEXTAREA element, only the hidden value is valid. Setting the overflow to hidden on a TEXTAREA element hides its scroll bars.

The scripting property has read/write permission.

Applies To

HTML Tags | DIV, FIELDSET, SPAN, TEXTAREA
Scripting | style

CSS Attribute

overflow


owningElement

Description

Returns the element that is next in the HTML hierarchy. This will usually contain the STYLE or LINK element that defined the style sheet.

Syntax

object.owningElement

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

styleSheet


padding

Description

Sets or retrieves paddingTop, paddingBottom, paddingLeft, and paddingRight in one style sheet rule.

Syntax

object.style.padding[ = padding]

Remarks

Padding describes how much space to insert between the element and its margin, or if there is a border, between the element and its border.

This is a composite property. Up to four values can be specified. The order is top, right, bottom, left. If there is only one value, it applies to all sides; if there are two or three, the missing values are taken from the opposite side. Negative values are not allowed.

The property has read/write permission.

Applies To

HTML Tags | BODY, CAPTION, DIV, IFRAME, MARQUEE, TABLE, TD, TEXTAREA, TR
Scripting | style

CSS Attribute

padding


paddingBottom

Description

Sets or retrieves the height of the padding at the bottom of the element.

Syntax

object.style.paddingBottom[ = paddingBottom]

Remarks

The property has read/write permission.

Applies To

HTML Tags | BODY, CAPTION, DIV, IFRAME, MARQUEE, TABLE, TD, TEXTAREA, TR
Scripting | style

CSS Attribute

padding-bottom


paddingLeft

Description

Sets or retrieves the width of the padding at the left edge of the element.

Syntax

object.style.paddingLeft[ = paddingLeft]

Remarks

This property has read/write permission.

Applies To

HTML Tags | BODY, CAPTION, DIV, IFRAME, MARQUEE, TABLE, TD, TEXTAREA, TR
Scripting | style

CSS Attribute

padding-left


paddingRight

Description

Sets or retrieves the width of the padding at the right edge of the element.

Syntax

object.style.paddingRight[ = paddingRight]

Remarks

This property has read/write permission.

Applies To

HTML Tags | BODY, CAPTION, DIV, IFRAME, MARQUEE, TABLE, TD, TEXTAREA, TR
Scripting | style

CSS Attribute

padding-right


paddingTop

Description

Sets or retrieves the height of the padding at the top of the element.

Syntax

object.style.paddingTop[ = paddingTop]

Remarks

This property has read/write permission.

Applies To

HTML Tags | BODY, CAPTION, DIV, IFRAME, MARQUEE, TABLE, TD, TEXTAREA, TR
Scripting | style

CSS Attribute

padding-top


pageBreakAfter

Description

Sets or retrieves whether a page break occurs after the element and on which page (left or right) the subsequent content should resume.

Syntax

object.style.pageBreakAfter[ = pageBreakAfter]

Remarks

This property applies when printing the document.

The values are defined as follows:
auto | Insert a page break after the element only if necessary.
always | Always insert a page break after the element.
left | Insert one or two page breaks after the element until a blank left page is reached.
right | Insert one or two page breaks after the element until a blank right page is reached.

If there are conflicts between this property and the page-break-before value on the previous element (as formatted on the canvas), the value that results in the largest number of page breaks will be used.

The property has read/write permission.

Applies To

HTML Tags | BLOCKQUOTE, BODY, CENTER, DD, DIR, DIV, DL, DT, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, UL, XMP
Scripting | style

CSS Attribute

page-break-after


pageBreakBefore

Description

Sets or retrieves whether a page break occurs before the element and on which page (left or right) the subsequent content should resume.

Syntax

object.style.pageBreakBefore[ = pageBreakBefore]

Remarks

This property applies when printing the document.

The values are defined as follows:
auto | Insert a page break before the element only if necessary.
always | Always insert a page break before the element.
left | Insert one or two page breaks before the element until a blank left page is reached.
right | Insert one or two page breaks before the element until a blank right page is reached.

If there are conflicts between this property and the page-break-after value on the next element (as formatted on the canvas), the value that results in the largest number of page breaks will be used.

The property has read/write permission.

Applies To

HTML Tags | BLOCKQUOTE, BODY, CENTER, DD, DIR, DIV, DL, DT, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, UL, XMP
Scripting | style

CSS Attribute

page-break-before


palette

Description

Specifies the palette used for the embedded document.

Syntax

object.palette

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

EMBED


parent

Description

Returns the parent object in the object hierarchy.

Syntax

object.parent

Remarks

For a document, the parent is the containing window. For a window defined using FRAME, the parent is the window that contains the corresponding FRAMESET definition.

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

window


parentElement

Description

Returns the parent element in the element hierarchy.

Syntax

object.parentElement

Remarks

The topmost element returns NULL as its parent.

This is a read-only property.

Applies To

A, ACRONYM, ADDRESS, APPLET, AREA, B, BASE, BASEFONT, BGSOUND, BIG, BLOCKQUOTE, BODY, BR, BUTTON, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, COMMENT, DD, DEL, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FONT, FORM, FRAME, FRAMESET, H1, H2, H3, H4, H5, H6, HEAD, HR, HTML, I, IFRAME, IMG, INPUT, INS, KBD, LABEL, LEGEND, LI, LINK, LISTING, MAP, MARQUEE, MENU, META, NEXTID, OBJECT, OL, OPTION, P, PLAINTEXT, PRE, Q, S, SAMP, SCRIPT, SELECT, SMALL, SPAN, STRIKE, STRONG, STYLE, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TITLE, TR, TT, U, UL, VAR, XMP


parentStyleSheet

Description

Returns the style sheet that was used for importing style sheets. If a style sheet is at the top level (that is, it's a LINK or STYLE), parentStyleSheet returns NULL.

Syntax

object.parentStyleSheet

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

styleSheet


parentTextEdit

Description

Returns the next element in the hierarchy that can be used to create a text range that contains the original element.

Syntax

object.parentTextEdit

Settings

This read-only property is an element object if the parent exists. Otherwise, it is null.

Example

The following example retrieves the parent element (if needed), creates the text range, moves to the original element, and selects the first word in the element.

<SCRIPT LANGUAGE="JScript">
function selectWord() {
    var el = window.event.srcElement ;
    if (!el.isTextEdit)
        el = window.event.srcElement.parentTextEdit;
    if (el != null) {
        var rng = el.createTextRange();
        rng.moveToElementText(window.event.srcElement);
        rng.collapse();
        rng.expand("word");
        rng.select();
    }
}
</SCRIPT>

Applies To

A, ACRONYM, ADDRESS, APPLET, AREA, B, BASE, BASEFONT, BGSOUND, BIG, BLOCKQUOTE, BODY, BR, BUTTON, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, COMMENT, DD, DEL, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FONT, FORM, FRAME, FRAMESET, H1, H2, H3, H4, H5, H6, HEAD, HR, HTML, I, IFRAME, IMG, INPUT, INS, KBD, LABEL, LEGEND, LI, LINK, LISTING, MAP, MARQUEE, MENU, META, NEXTID, OBJECT, OL, OPTION, P, PLAINTEXT, PRE, Q, S, SAMP, SCRIPT, SELECT, SMALL, SPAN, STRIKE, STRONG, STYLE, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TITLE, TR, TT, U, UL, VAR, XMP


parentWindow

Description

Returns the window object for the document.

Syntax

object.parentWindow

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

document


pathname

Description

Specifies the file or object path.

Syntax

object.pathname[ = pathname]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

A, AREA, location


pixelHeight

Description

Sets or retrieves the height of the element, in pixels. Unlike the height property, this property's value is an integer, not a string, and is always interpreted in pixels.

Syntax

object.pixelHeight[ = pixelHeight]

Settings

This read-write property can be any integer value. Setting this property changes the value of the height without changing the units designator.

Remarks

For more information on how to access the dimension and location of elements on the page through the document object model, see Measuring Element Dimension and Location.

Applies To

style

CSS Attribute

height

See Also

posHeight


pixelLeft

Description

Sets or retrieves the left position of the element, in pixels. Unlike the left property, this property's value is an integer, not a string, and is always interpreted in pixels.

Syntax

object.pixelLeft[ = pixelLeft]

Settings

This read-write property can be any integer value. Setting this property changes the value of the left position without changing the units designator.

Remarks

This property reflects the value of the CSS left attribute for positioned items. This property always returns zero for nonpositioned items since left does not mean anything unless the object is positioned. Use the offsetLeft property to calculate actual positions within the document area.

For more information on how to access the dimension and location of elements on the page through the document object model, see Measuring Element Dimension and Location.

Applies To

style

CSS Attribute

left

See Also

posLeft


pixelTop

Description

Sets or retrieves the top position of the element, in pixels. Unlike the top property, this property's value is an integer, not a string, and is always interpreted in pixels.

Syntax

object.pixelTop[ = pixelTop]

Settings

This read-write property can be any integer value. Setting this property changes the value of the top position without changing the units designator.

Remarks

This property reflects the value of the CSS top attribute for positioned items. This property always returns zero for nonpositioned items since top does not mean anything unless the object is positioned. Use the offsetTop property to calculate actual positions within the document area.

For more information on how to access the dimension and location of elements on the page through the document object model, see Measuring Element Dimension and Location.

Applies To

style

CSS Attribute

top

See Also

posTop


pixelWidth

Description

Sets or retrieves the width of the element, in pixels. Unlike the width property, this property's value is an integer, not a string, and is always interpreted in pixels.

Syntax

object.pixelWidth[ = pixelWidth]

Settings

This read-write property can be any integer value. Setting this property changes the value of the height without changing the units designator.

Remarks

For more information on how to access the dimension and location of elements on the page through the document object model, see Measuring Element Dimension and Location.

Applies To

style

CSS Attribute

width

See Also

posWidth


platform

Description

Indicates the platform that the browser is running on (for example, Win32®, Win16, WinCE, and so on).

Syntax

object.platform

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

navigator


plugins

Description

Returns an empty collection for Internet Explorer 4.0. This property exists for compatibility with other browsers.

Syntax

object.plugins

Remarks

This property has read-only permission.

Applies To

navigator


pluginspage

Description

Specifies the plug-ins supporting this embedded document.

Syntax

object.pluginspage

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

EMBED


port

Description

Specifies the port number in a URL.

Syntax

object.port[ = port]

Remarks

If no port is specified, an empty string is returned.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

A, AREA, location


posHeight

Description

Sets and retrieves the height of the element in the units specified by the CSS height attribute. Unlike the height property, this property's value is a floating-point number, not a string.

Syntax

object.posHeight[ = posHeight]

Settings

This read-write property takes any valid floating-point number. Setting this property changes the value of the height but leaves the units designator for the property unchanged.

Remarks

For more information on how to access the dimension and location of elements on the page through the document object model, see Measuring Element Dimension and Location.

Example

The following JScript example increases the height of the first IMG element by 10 units.

document.all.tags("IMG").item(0).style.posHeight += 10;

Applies To

style

CSS Attribute

height

See Also

pixelHeight


position

Description

Retrieves the type of positioning used for the element.

Syntax

object.style.position

Remarks

The default is static, which means there is no special positioning, and the element obeys the layout rules of HTML.

An absolutely positioned element is always relative to either the next positioned parent or, if there isn't one, the BODY by default. Values for left and top are relative to the upper-left corner of the next positioned element in the hierarchy. Be sure to note the Applies To listings for elements that can be relatively and absolutely positioned.

See Positioning for an overview on how to use dynamic positioning.

The property has read-only permission.

Applies To

HTML Tags

For position:absolute

APPLET, DIV, EMBED, FIELDSET, HR, IFRAME, IMG, INPUT, INPUT type=button, OBJECT, MARQUEE, SELECT, SPAN, TABLE, TEXTAREA

For position:relative

A, ADDRESS, APPLET, B, BIG, BLOCKQUOTE, CENTER, CITE, CODE, DD, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, I, IFRAME, IMG, INPUT, INPUT type=button, INPUT type=checkbox, INPUT type=file, INPUT type=image, INPUT type=radio, INPUT type=reset, INPUT type=submit, INPUT type=text, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OBJECT, OL, P, PRE, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TEXTAREA, TT, U, UL, VAR, XMP

Scripting style

CSS Attribute

position


posLeft

Description

Sets and retrieves the left position of the element in the units specified by the CSS left attribute. Unlike the left property, this property's value is a floating-point number, not a string.

Syntax

object.posLeft[ = posLeft]

Settings

This read-write property takes any valid floating-point number. Setting this property changes the value of the left position but leaves the units designator for the property unchanged.

Remarks

This property reflects the value of the CSS left attribute for positioned items. This property always returns zero for nonpositioned items since left does not mean anything unless the object is positioned. Use the offsetLeft property to calculate actual positions within the document area.

For more information on how to access the dimension and location of elements on the page through the document object model, see Measuring Element Dimension and Location.

Example

The following JScript example moves the first IMG element to the left by 10 units.

document.all.tags("IMG").item(0).style.posLeft -= 10;

Applies To

style

CSS Attribute

left

See Also

pixelLeft


posTop

Description

Sets and retrieves the top position of the element in the units specified by the CSS top attribute. Unlike the top property, this property's value is a floating-point number, not a string.

Syntax

object.posTop[ = posTop]

Settings

This read-write property takes any valid floating-point number. Setting this property changes the value of the top position but leaves the units designator for the property unchanged.

Remarks

This property reflects the value of the CSS top attribute for positioned items. This property always returns zero for nonpositioned items since top does not mean anything unless the object is positioned. Use the offsetTop property to calculate actual positions within the document area.

For more information on how to access the dimension and location of elements on the page through the document object model, see Measuring Element Dimension and Location.

Example

The following JScript example moves the first IMG element up by 10 units.

document.all.tags("IMG").item(0).style.posTop -= 10;

Applies To

style

CSS Attribute

top

See Also

pixelTop


posWidth

Description

Sets and retrieves the width of the element in the units specified by the CSS width attribute. Unlike the width property, this property's value is a floating-point number, not a string.

Syntax

object.posWidth[ = posWidth]

Settings

This read-write property takes any valid floating-point number. Setting this property changes the value of the width but leaves the units designator for the property unchanged.

Remarks

For more information on how to access the dimension and location of elements on the page through the document object model, see Measuring Element Dimension and Location.

Example

The following JScript example increases the width of the first IMG element by 10 units.

document.all.tags("IMG").item(0).style.posWidth -= 10;

Applies To

style

CSS Attribute

width

See Also

pixelWidth


Properties

The following table lists the properties in the DHTML object model. For properties that appear in multiple table cells, roll the mouse over the text to view a ToolTip indicating the objects to which the property applies. Click the text to jump to a full description of that property.

accessKey action activeElement
align align align
align aLink alinkColor
alt altHTML altKey
appCodeName appMinorVersion appName
appVersion availHeight availWidth
background background background
backgroundAttachment backgroundColor backgroundImage
backgroundPosition backgroundPositionX backgroundPositionY
backgroundRepeat balance behavior
bgColor bgColor bgProperties
border border border
borderBottom borderBottomColor borderBottomStyle
borderBottomWidth borderColor borderColor
borderColorDark borderColorLight borderLeft
borderLeftColor borderLeftStyle borderLeftWidth
borderRight borderRightColor borderRightStyle
borderRightWidth borderStyle borderTop
borderTopColor borderTopStyle borderTopWidth
borderWidth bottomMargin boundingHeight
boundingLeft boundingTop boundingWidth
browserLanguage bufferDepth button
cancelBubble caption cellIndex
cellPadding cellSpacing charset
checked classid className
clear clear clientHeight
clientInformation clientLeft clientTop
clientWidth clientX clientY
clip closed code
codeBase codeBase codeType
color color colorDepth
cols cols cols
colSpan compact complete
connectionSpeed content cookie
cookieEnabled coords cpuClass
cssText ctrlKey cursor
data dataFld dataFormatAs
dataPageSize dataSrc defaultCharset
defaultChecked defaultSelected defaultStatus
defaultValue defer defer
dialogArguments dialogHeight dialogLeft
dialogTop dialogWidth direction
disabled disabled display
domain dynsrc encoding
event expando face
fgColor fileCreatedDate fileModifiedDate
fileSize fileUpdatedDate filter
font fontFamily fontSize
fontSmoothingEnabled fontStyle fontVariant
fontWeight form frame
frameBorder frameSpacing fromElement
hash height height
height hidden host
hostname href href
href href hspace
htmlFor htmlFor htmlText
httpEquiv id indeterminate
index innerHTML innerText
isMap isTextEdit keyCode
lang language lastModified
left leftMargin length
letterSpacing lineHeight link
linkColor listStyle listStyleImage
listStylePosition listStyleType location
loop lowsrc map
margin marginBottom marginHeight
marginLeft marginRight marginTop
marginWidth maxLength media
method Methods mimeTypes
multiple name name
noHref noResize noShade
noWrap object offscreenBuffering
offsetHeight offsetLeft offsetParent
offsetTop offsetWidth offsetX
offsetY onLine opener
outerHTML outerText overflow
owningElement padding paddingBottom
paddingLeft paddingRight paddingTop
pageBreakAfter pageBreakBefore palette
parent parentElement parentStyleSheet
parentTextEdit parentWindow pathname
pixelHeight pixelLeft pixelTop
pixelWidth platform plugins
pluginspage port posHeight
position posLeft posTop
posWidth protocol readOnly
readOnly readyState reason
recordNumber recordset referrer
rel returnValue returnValue
rev rightMargin rowIndex
rows rows rowSpan
rules screenX screenY
scroll scrollAmount scrollDelay
scrollHeight scrolling scrollLeft
scrollTop scrollWidth search
sectionRowIndex selected selectedIndex
self shape shiftKey
size size size
sourceIndex span src
src src srcElement
srcFilter start start
status status style
styleFloat systemLanguage tabIndex
tagName target text
text text text
textAlign textDecoration textDecorationBlink
textDecorationLineThrough textDecorationNone textDecorationOverline
textDecorationUnderline textIndent textTransform
tfoot thead title
title toElement top
top topMargin trueSpeed
type type type
type type type
type type type
units updateInterval url
url urn useMap
userAgent userLanguage vAlign
vAlign value value
value verticalAlign visibility
vLink vlinkColor volume
vspace width width
width wrap x
y zIndex

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


protocol

Description

Specifies the initial substring up to and including the first colon, which indicates the URL's access method.

Syntax

object.protocol[ = protocol]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

A, AREA, IMG, location


readOnly

Description

Indicates whether the style sheet can be modified. If a style sheet is obtained through a LINK or an Import tag, the style sheet cannot be modified. The default value is FALSE (cannot be modified).

Syntax

object.readOnly

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

styleSheet


readOnly

Description

Causes the element's contents to be read-only, meaning that the user cannot enter or edit text in the control.

Syntax

object.readOnly[ = readOnly]

Remarks

This is different than disabled. Read-only still allows the element to receive the focus, while disabled does not.

The default value for this property is FALSE.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

INPUT (text and password types only), TEXTAREA


readyState

Description

Specifies the current state of an object being downloaded.

Syntax

object.readyState

Settings

Possible values include:
uninitialized | The object is not initialized with data.
loading | The object is currently loading its data.
interactive | The object can be interacted with even though it is not fully loaded.
complete | The control is completely loaded.

Remarks

Each object can independently determine which of the four states it exposes.

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

IMG, LINK, OBJECT, SCRIPT, STYLE, document

See Also

onreadystatechange


reason

Description

Indicates the disposition of data transfer for a data source object.

Syntax

object.reason

Settings

This read-only property is an integer value specifying the reason for completion. It can be one of these values:

0 | Data transmitted successfully.
1 | Data transfer aborted.
2 | Data transfer in error.

Applies To

event


recordNumber

Description

Specifies the ordinal record from the data set that generated the element. Applies to a bound, repeated table.

Syntax

object.recordNumber

Remarks

This property can be used in conjunction with the ADO recordset available from every data source object through the object's recordset property.

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

A, ACRONYM, ADDRESS, APPLET, AREA, B, BGSOUND, BIG, BLOCKQUOTE, BR, BUTTON, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, COMMENT, DD, DEL, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FONT, FORM, H1, H2, H3, H4, H5, H6, HR, I, IFRAME, IMG, INPUT, INS, KBD, LABEL, LI, LISTING, MAP, MARQUEE, MENU, OBJECT, OL, OPTION, P, PLAINTEXT, PRE, Q, S, SAMP, SCRIPT, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP, Hidden


recordset

Description

Returns the recordset if the object is a data provider.

Syntax

object.recordset

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

OBJECT


referrer

Description

Specifies the URL of the previous location.

Syntax

object.referrer

Remarks

This is only true when the current page has been reached through a link from the previous page. Otherwise, document.referrer will return empty; it will also return empty when the link is from a secure site.

For example, if PageA.htm has a link to PageB.htm, and the user clicks the link on PageA.htm to go to PageB.htm, the document.referrer on PageB.htm will return "PageA.htm". However, if the user is on PageA.htm and types PageB.htm into the address line, or uses Open in the File menu to get to PageB.htm, the document.referrer will return empty.

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

document


rel

Description

Specifies the relationship(s) described by the hypertext link from the anchor to the target.

Syntax

object.rel[ = rel]

Remarks

The value is a comma-separated list of relationship values. Values and their semantics will be registered by the HTML registration authority. The default relationship, if none other is given, is void. The rel property is used only when the href property is present.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

A, LINK


returnValue

Description

Specifies the return value from the modal dialog window.

This property applies only to windows created using the showModalDialog method.

Syntax

object.returnValue[ = Variant]

Applies To

window


returnValue

Description

Specifies the return value from the event.

Syntax

object.returnValue[ = Boolean]

Settings

This read-write property can be either TRUE or FALSE. Setting it to FALSE cancels the default action of the source element of the event.

The value of this property takes precedence over values returned by the function, such as through a return statement.

Applies To

event


rev

Description

Same as the rel property, but the semantics of the link type are in the reverse direction. A link from A to B with REL="X" expresses the same relationship as a link from B to A with REV="X". An anchor can have both rel and rev properties.

Syntax

object.rev[ = rev]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

A, LINK


rightMargin

Description

Specifies the right margin for the entire body of the page, and overrides the default margin.

Syntax

object.rightMargin[ = rightMargin]

Settings

This read-write property takes a string value. If set to an empty string (""), the right margin will be exactly on the right edge.

Applies To

BODY


rowIndex

Description

Indicates the element's position in the rows collection that is for the TABLE. This is different from sectionRowIndex, which indicates the element's position in the TBODY, THEAD, or TFOOT rows collection. These sections are mutually exclusive, so the TR is always contained in one of these sections, as well as the TABLE. Collection indexes are in source order of the HTML document.

Syntax

object.rowIndex[ = element]

Return Value

This property has read-only permission.

Applies To

TR

See Also

sectionRowIndex, sourceIndex, cellIndex


rows

Description

Specifies the number of rows tall the text area control should be.

Syntax

object.rows[ = rows]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

TEXTAREA


rows

Description

Specifies a comma-delimited list of frames to create. Each item in the list contains the initial size of the row.

Syntax

object.rows[ = rows]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

FRAMESET


rowSpan

Description

Specifies how many rows in a TABLE this cell should span. This property can only be changed after the page has been loaded.

Syntax

object.rowSpan[ = rowSpan]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

TD, TH


rules

Description

Specifies which dividing lines are displayed (inner borders).

Syntax

object.rules[ = rules]

Settings

This read-write property takes one of these string values:

all | Displays a border on all rows and columns.
cols | Displays borders between all table columns.
groups | Displays horizontal borders between all table groups. Groups are specified by the THEAD, TBODY, TFOOT, and COLGROUP elements.
none | Removes all interior table borders.
rows | Displays horizontal borders between all table rows.

The property is not set by default.

Applies To

TABLE, stylesheet

See Also

frame


screenX

Description

Returns coordinates relative to the physical screen size.

Syntax

object.screenX

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

event


screenY

Description

Returns coordinates relative to the physical screen size.

Syntax

object.screenY

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

event


scroll

Description

Turns the scroll bars on or off.

Syntax

object.scroll[ = scroll]

Settings

This read-write property can be one of the following strings:

yes | Turns on the scroll bars. This is the default value.
no | Turns off the scroll bars.

Applies To

BODY


scrollAmount

Description

Specifies the number of pixels the text scrolls between each subsequent drawing of the MARQUEE.

Syntax

object.scrollAmount[ = scrollAmount]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

MARQUEE


scrollDelay

Description

Specifies the speed of the MARQUEE scroll, in milliseconds.

Syntax

object.scrollDelay[ = scrollDelay]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

MARQUEE


scrollHeight

Description

Returns the element's scrolling height, in pixels. This is the distance between the top and bottom edges of the element's visible content. The physical height of the content, including the nonvisible content, can be obtained with the offsetHeight property.

Syntax

object.scrollHeight

Remarks

For more information on how to access the dimension and location of elements on the page through the document object model, see Measuring Element Dimension and Location.

Setting

This read-only property is always a nonnegative integer.

Applies To

BODY, BUTTON, DIV, FIELDSET, FRAME, IFRAME, IMG, MARQUEE, SPAN, TEXTAREA

See Also

scrollLeft, scrollTop, scrollWidth


scrolling

Description

Specifies that the frame can be scrolled.

Syntax

object.scrolling[ = scrolling]

Settings

Possible values include;
auto | The browser determines if the scroll bars are necessary.
no | The frame cannot be scrolled.
yes | The frame can be scrolled.

Remarks

The scroll bars default to "auto" if this attribute is omitted.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

FRAME, IFRAME


scrollLeft

Description

Sets or retrieves the distance, in pixels, between the left edge of the element and the leftmost portion of the element that is currently visible in the window. This is equal to the horizontal distance that the content of the element has been scrolled.

Syntax

object.scrollLeft[ = scrollLeft]

Settings

This read-write property is always a nonnegative integer. Although it can be set to any positive or negative value, the property is set to zero if the assigned value is less than zero, and is set to the value of scrollWidth if the assigned value is greater than this. The default value is zero.

This property is always zero for elements that do not support scroll bars. For these elements, setting the property has no effect.

Remarks

For more information on how to access the dimension and location of elements on the page through the document object model, see Measuring Element Dimension and Location.

Applies To

BODY, BUTTON, DIV, FIELDSET, FRAME, IFRAME, IMG, MARQUEE, SPAN, TEXTAREA

See Also

scrollHeight, scrollTop, scrollWidth


scrollTop

Description

Sets or retrieves the distance, in pixels, between the top of the element and the topmost portion of the content that is currently visible in the window. This is equal to the vertical distance that the content of the element has been scrolled.

Syntax

object.scrollTop[ = scrollTop]

Settings

This read-write property is always a nonnegative integer. Although it can be set to any positive or negative value, the property is set to zero if the assigned value is less than zero, and is set to the value of scrollHeight if the assigned value is greater than this. The default value is zero.

This property is always zero for elements that do not have scroll bars. For these elements, setting the property has no effect.

Remarks

For more information on how to access the dimension and location of elements on the page through the document object model, see Measuring Element Dimension and Location.

Applies To

BODY, BUTTON, DIV, FIELDSET, FRAME, IFRAME, IMG, MARQUEE, SPAN, TEXTAREA

See Also

scrollHeight, scrollLeft, scrollWidth


scrollWidth

Description

Returns the element's scrolling width, in pixels. This is the distance between the left and right edges of the element's visible content.

Syntax

object.scrollWidth

Settings

This read-only property is always a nonnegative integer.

Remarks

For more information on how to access the dimension and location of elements on the page through the document object model, see Measuring Element Dimension and Location.

Applies To

BODY, BUTTON, DIV, FIELDSET, FRAME, IFRAME, IMG, MARQUEE, SPAN, TEXTAREA

See Also

scrollHeight, scrollLeft, scrollTop, width


search

Description

Indicates the substring of the href property that follows the ? symbol. This is the query string or form data.

Syntax

object.search[ = search]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

A, AREA, location


sectionRowIndex

Description

Indicates the element's position in the TBODY, THEAD, or TFOOT rows collection. These sections are mutually exclusive, so the TR is always contained in one of these sections, as well as the TABLE. The rowIndex property indicates the element's position in the rows collection for the TABLE. Collection indexes are in source order of the HTML document.

Syntax

object.sectionRowIndex[ = element]

Return Value

This property has read-only permission.

Applies To

TR

See Also

sectionRowIndex, sourceIndex, cellIndex


selected

Description

Indicates that this item is the default. If not present, the first item is selected by default.

Syntax

object.selected[ = selected]

Remarks

This property is used to determine whether a value is submitted with the form. If the value of the control matches the default value, the control's value is not submitted. The value is only submitted when the control's value does not match the default value. Therefore, changing this value changes the rule for whether the value is submitted with the form.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

OPTION

See Also

defaultSelected


selectedIndex

Description

Sets or retrieves an integer specifying the index of the selected option in a select object.

Syntax

object.selectedIndex[ = selectedIndex]

Remarks

Options in a select object are indexed in the order in which they are defined, starting with an index of zero. You can set the selectedIndex property at any time. The display of the select object updates immediately when you set the selectedIndex property. Both forms of the syntax specify the same value.

In general, this property is more useful for select objects that are created without the multiple attribute. If you evaluate selectedIndex when multiple options are selected, the selectedIndex property specifies the index of the first option only. Setting selectedIndex clears any other options that are selected in the select object.

The selected property of the select object's options array is more useful for select objects that are created with the MULTIPLE attribute. With the selected property, you can evaluate every option in the options array to determine multiple selections, and you can select individual options without clearing the selection of other options.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

SELECT


self

Description

Refers to the current window. The property provides a way to explicitly refer to the current window or frame.

Syntax

object.self

Remarks

Use the self property to disambiguate a window property from a form of the same name. You can also use the self property to make your code more readable.

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

window


shape

Description

Specifies the type of shape used in the image map.

Syntax

object.shape[ = shape]

Settings

This read-write property takes a string specifying a shape. Each shape causes the coords attribute to take a different set of values.

circ | Circle. Takes three coordinates: centerx, centery, and radius.
circle | Circle. Takes three coordinates: centerx, centery, and radius.
poly | Polygon. Takes three or more pairs of coordinates denoting a polygonal region.
polygon | Polygon. Takes three or more pairs of coordinates denoting a polygonal region.
rect | Rectangle. Takes four coordinates: x1, y1, x2, and y2.
rectangle | Rectangle. Takes four coordinates: x1, y1, x2, and y2.

Applies To

AREA

See Also

coords


shiftKey

Description

Specifies the state of the SHIFT key, a Boolean value.

Syntax

object.shiftKey

Settings

This read-only property is TRUE if the SHIFT key is down, and FALSE if the key is up.

Applies To

event


size

Description

Specifies font size.

Syntax

object.size[ = size]

Settings

This read-write property takes an integer value in the range 1 through 7, with 7 representing the largest font.

Applies To

BASEFONT, FONT


size

Description

Sets the height of the HR element, in pixels.

Syntax

object.size[ = size]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

HR


size

Description

Specifies the size of the control.

Syntax

object.size[ = size]

Remarks

For the INPUT element, the size is in characters and represents the width of the text box. For the SELECT element, when the size is specified, it represents a list box with the specified number of rows.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

INPUT, SELECT

See Also

maxLength


sourceIndex

Description

Returns the ordinal position of the element in the source order as it appears in the all collection.

Syntax

object.sourceIndex

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

A, ACRONYM, ADDRESS, APPLET, AREA, B, BASE, BASEFONT, BGSOUND, BIG, BLOCKQUOTE, BODY, BR, BUTTON, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, COMMENT, DD, DEL, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FONT, FORM, FRAME, FRAMESET, H1, H2, H3, H4, H5, H6, HEAD, HR, HTML, I, IFRAME, IMG, INPUT, INS, KBD, LABEL, LI, LINK, LISTING, MAP, MARQUEE, MENU, META, NEXTID, OBJECT, OL, OPTION, P, PLAINTEXT, PRE, Q, S, SAMP, SCRIPT, SELECT, SMALL, SPAN, STRIKE, STRONG, STYLE, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TITLE, TR, TT, U, UL, VAR, XMP


span

Description

Specifies how many columns are in the group.

Syntax

object.span[ = span]

Remarks

This property should be ignored if the COLGROUP element contains one or more COL elements. The span property provides a more convenient way of grouping columns without the need to specify COL elements.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

COL, COLGROUP


src

Description

Specifies the URL of a sound to be played.

Syntax

object.src[ = src]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

BGSOUND


src

Description

Specifies an external file that contains the source code.

Syntax

object.src

Remarks

A script can contain an external reference as well as code within the block. The code specified by src precedes the code contained within the document.

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

SCRIPT


src

Description

Specifies a URL to be loaded by the object.

Syntax

object.src[ = src]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

APPLET, EMBED, FRAME, IFRAME, IMG, INPUT type=img


srcElement

Description

Specifies the element that fired the event.

Syntax

object.srcElement

Settings

This read-only property is an element object.

Applies To

event


srcFilter

Description

Specifies the filter object that caused the onfilterchange event to fire.

Syntax

object.srcFilter

Remarks

This is a read-only property.

Applies To

event


start

Description

Specifies the starting number for a list.

Syntax

object.start[ = start]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

OL


start

Description

Specifies when a video clip file should start playing.

Syntax

object.start[ = start]

Settings

This read-write property can be one of the following strings:

fileopen | The video starts as soon as it is finished loading.
mouseover | The video starts when the mouse goes over the animation.

Applies To

IMG


status

Description

Sets or retrieves the message in the status bar at the bottom of the window.

Syntax

object.status[ = status]

Settings

The value of this read-write property can be any valid string.

Do not confuse status with defaultStatus. The defaultStatus property reflects the default message displayed in the status bar.

Applies To

window


status

Description

Sets or retrieves the current value of a check box or radio button. This property is an alias for the value property for check boxes and radio buttons.

Syntax

object.status[ = status]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

INPUT


style

Description

Specifies an inline style sheet for the tag.

Syntax

object.style[ = style]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

A, ACRONYM, ADDRESS, APPLET, AREA, B, BIG, BLOCKQUOTE, BODY, BR, BUTTON, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, DD, DEL, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FONT, FORM, H1, H2, H3, H4, H5, H6, HR, I, IFRAME, IMG, INPUT, INS, KBD, LABEL, LEGEND, LI, LISTING, MAP, MARQUEE, MENU, OBJECT, OL, P, PLAINTEXT, PRE, Q, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP


styleFloat

Description

Sets or retrieves the CSS float attribute, which specifies whether the element floats, causing text to flow around it.

Syntax

object.styleFloat[ = styleFloat]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

style

CSS Attribute

float


systemLanguage

Description

Indicates the default language that the system is running. For possible return values, see Language Codes.

Syntax

object.systemLanguage

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

navigator


tabIndex

Description

Sets the tab index for the object.

Syntax

object.tabIndex[ = tabIndex]

Remarks

Tab selection order is determined by the value of tabIndex as follows:

  • All elements with tabIndex > 0 are selected in increasing tab index order, or in source order for duplicate tab index values.
  • All elements with tabIndex = 0, or without tabIndex set, are selected next, in source order if more than one.
  • Elements with tabIndex = -1 are omitted from tabbing order.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

A, APPLET, AREA, BODY, BUTTON, DIV, EMBED, HR, IFRAME, IMG, INPUT, MARQUEE, OBJECT, SELECT, TABLE, TEXTAREA


tagName

Description

Returns the tag for the current element.

Syntax

object.tagName

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

A, ACRONYM, ADDRESS, APPLET, AREA, B, BASE, BASEFONT, BGSOUND, BIG, BLOCKQUOTE, BODY, BR, BUTTON, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, COMMENT, DD, DEL, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FONT, FORM, FRAME, FRAMESET, H1, H2, H3, H4, H5, H6, HEAD, HR, HTML, I, IFRAME, IMG, INPUT, INS, KBD, LABEL, LEGEND, LI, LINK, LISTING, MAP, MARQUEE, MENU, META, NEXTID, OBJECT, OL, OPTION, P, PLAINTEXT, PRE, Q, S, SAMP, SCRIPT, SELECT, SMALL, SPAN, STRIKE, STRONG, STYLE, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TITLE, TR, TT, U, UL, VAR, XMP


target

Description

Specifies the window or frame at which to target the contents.

Syntax

object.target[ = target]

Remarks

If there is no frame or window that matches the specified target, a new window is opened for the link.

The default value for target depends upon the URL and site. If the user does not leave the site, the default is _self, but if the user exits to a new site, the default is _top.

Special Target Values
_blank | Specifies to load the link into a new blank window. This window is not named.
_parent | Specifies to load the link into the immediate parent of the document the link is in.
_self | Specifies to load the link into the same window the link was clicked in.
_top | Specifies to load the link into the full body of the window.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

A, AREA, BASE, FORM


text

Description

Sets or retrieves the text contained within the range.

Syntax

object.text[ = text]

Remarks

The text is formatted within the current context of the document. This property cannot be set while the document is loading. Wait for the onload event before attempting to setting this property.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

This feature might not be available on non-Win32 platforms. See article Q172976 in the Microsoft Knowledge Base for the latest information on Internet Explorer cross-platform compatibility.

Applies To

TextRange


text

Description

Sets or retrieves the text (foreground) color for the document body.

Syntax

object.text[ = color]

Settings

This read-write property can be set to any one of the color names or values given in Color Table.

Applies To

BODY


text

Description

Retrieves the textual content of the block element as a string.

Syntax

object.text

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

SCRIPT, TITLE


text

Description

Sets or retrieves the text string specified by the OPTION tag.

Syntax

object.text[ = text]

Remarks

Assigning a value to the text property changes the text property internally but does not cause the listed value to change. Submitting the form submits the internally stored value, not the one displayed.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

OPTION


textAlign

Description

Sets or retrieves whether text is left-aligned, right-aligned, centered, or justified.

Syntax

object.style.textAlign[ = textAlign]

Remarks

Values are left, right, center, or justify. Full justification is new to Internet Explorer 4.0 and sets contents aligned at both right and left margins.

The property has read/write permission.

Applies To

HTML Tags | BLOCKQUOTE, BODY, CENTER, DD, DIR, DIV, DL, DT, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, TABLE, TD, TH, TR, UL, XMP
Scripting | style

CSS Attribute

text-align


textDecoration

Description

Sets or retrieves whether the text in the element has blink, line-through, overline, or underline decorations.

Syntax

object.style.textDecoration[ = textDecoration]

Remarks

Internet Explorer 4.0 supports the keyword blink but does not render the blink effect.

If the element has no text (for example, the IMG element in HTML) or is an empty element (for example, "<EM> </EM>"), this property has no effect.

The property has read/write permission.

Applies To

HTML Tags | A, ADDRESS, B, BIG, BLOCKQUOTE, BODY, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, DD, DFN, DIR, DIV, DL, DT, EM, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HTML, I, INPUT, INPUT type=button, INPUT type=file, INPUT type=reset, INPUT type=submit, INPUT type=text, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP
Scripting | style

CSS Attribute

text-decoration


textDecorationBlink

Description

Specifies whether the text in the element has the blink decoration.

Syntax

object.textDecorationBlink[ = textDecorationBlink]

Remarks

Although you can set this style property, it has no effect on the text in the element. Blinking text is not implemented.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

style

CSS Attribute

text-decoration


textDecorationLineThrough

Description

Specifies whether the text in the element has the line-through decoration.

Syntax

object.textDecorationLineThrough[ = textDecorationLineThrough]

Settings

This read-write property can be set to TRUE to apply the line-through decoration, or FALSE to prevent it.

Applies To

style

CSS Attribute

text-decoration


textDecorationNone

Description

Specifies whether the text in the element has any decoration.

Syntax

object.textDecorationNone[ = textDecorationNone]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

style

CSS Attribute

text-decoration


textDecorationOverline

Description

Specifies whether the text has the overline decoration.

Syntax

object.textDecorationOverline[ = textDecorationOverline]

Settings

This read-write property can be set to TRUE to apply the overline, or FALSE to prevent it.

Applies To

style

CSS Attribute

text-decoration


textDecorationUnderline

Description

Specifies whether the text has the underline decoration.

Syntax

object.textDecorationUnderline[ = textDecorationUnderline]

Settings

This read-write property can be set to TRUE to apply the underline, or FALSE to prevent it.

Applies To

style

CSS Attribute

text-decoration


textIndent

Description

Retrieves the indentation of the text in the element.

Syntax

object.style.textIndent

Remarks

The property can be negative. An indent is not inserted in the middle of an element that was broken by another element (such as BR in HTML).

The property has read-only permission.

Applies To

HTML Tags | BLOCKQUOTE, BODY, CENTER, DD, DIR, DIV, DL, DT, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, TABLE, TD, TH, TR, UL, XMP
Scripting | style

CSS Attribute

text-indent


textTransform

Description

Retrieves the rendering of the text.

Syntax

object.style.textTransform

Remarks

This read-only property can have one of these string values:
capitalize | Transforms the first character of each word to uppercase.
uppercase | Transforms all the characters to uppercase characters.
lowercase | Transforms all the characters to lowercase characters.

Applies To

HTML Tags | A, ADDRESS, B, BIG, BLOCKQUOTE, BODY, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, DD, DFN, DIR, DIV, DL, DT, EM, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HTML, I, INPUT, INPUT type=button, INPUT type=file, INPUT type=reset, INPUT type=submit, INPUT type=text, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP
Scripting | style

CSS Attribute

text-transform


tfoot

Description

Points to the TFOOT element in the TABLE. If none exist, it is null.

Syntax

object.tfoot[ = element]

Return Value

This property has read-only permission.

Remarks

The following example sets the inline style for the TFOOT.

document.all.myTable.tfoot.style.color = "blue"

Applies To

table


thead

Description

Points to the THEAD element in the TABLE. If none exist, it is null.

Syntax

object.thead[ = element]

Return Value

This property has read-only permission.

Remarks

The following example sets the inline style for the THEAD.

document.all.myTable.thead.style.color = "blue"

Applies To

table


title

Description

Sets or retrieves the title of the style sheet. The title is a string that is a grouping mechanism for style sheets.

Syntax

object.title[ = title]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

LINK


title

Description

Specifies advisory information for the element.

Remarks

Internet Explorer 4.0 renders the title as a ToolTip when the user hovers the mouse over the element.

This property has read-write permissions and takes a string.

Syntax

object.title[ = "sMyString"]

Applies To

A, ACRONYM, ADDRESS, APPLET, AREA, B, BASE, BASEFONT, BGSOUND, BIG, BLOCKQUOTE, BODY, BR, BUTTON, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, COMMENT, DD, DEL, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FONT, FORM, FRAME, FRAMESET, H1, H2, H3, H4, H5, H6, HEAD, HR, I, IFRAME, IMG, INPUT, INS, KBD, LABEL, LEGEND, LI, LISTING, MAP, MARQUEE, MENU, META, NEXTID, OBJECT, OL, OPTION, P, PLAINTEXT, PRE, Q, S, SAMP, SCRIPT, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TITLE, TR, TT, U, UL, VAR, XMP


toElement

Description

Specifies the element being moved to for the onmouseover and onmouseout events.

Syntax

object.toElement

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

event


top

Description

Sets or retrieves the position of the element relative to the top of the document.

Syntax

object.style.top[ = top]

Remarks

This read/write property is a string consisting of a number and a units designator, as described for cascading style sheets.

For more information on how to access the dimension and location of elements on the page through the document object model, see Measuring Element Dimension and Location.

Applies To

HTML Tags | A, ADDRESS, APPLET, B, BIG, BLOCKQUOTE, CENTER, CITE, CODE, DD, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, I, IFRAME, IMG, INPUT type=button, INPUT type=checkbox, INPUT type=file, INPUT type=image, INPUT type=radio, INPUT type=reset, INPUT type=submit, INPUT type=text, INPUT, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OBJECT, OL, P, PRE, S, SAMP, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TEXTAREA, TT, U, UL, VAR, XMP
Scripting | style

CSS Attribute

top

See Also

pixelTop, posTop


top

Description

Specifies the topmost ancestor window, which is its own parent.

Syntax

object.top

Remarks

This property has read-only permission.

Applies To

window


topMargin

Description

Specifies the margin for the top of the page, and overrides the default margin.

Syntax

object.topMargin[ = topMargin]

Settings

This read-write property is a string. If set to "", the margin will be exactly on the top edge.

Applies To

BODY

See Also

leftMargin


trueSpeed

Description

Specifies whether the position of the marquee is calculated using the scrollDelay, scrollAmount, and the actual time elapsed from the last clock tick.

Syntax

object.trueSpeed

Settings

This read-only property is a Boolean value:

TRUE | The marquee advances the pixel value of scrollAmount per the number of milliseconds set for scrollDelay. For example, the marquee advances 10 pixels for every 6 milliseconds (ms) if scrollDelay is 6 and scrollAmount is 10.
FALSE | The marquee computes movement based on 60ms ticks of the clock. This means every scrollDelay value under 60 is essentially ignored, and the marquee advances the amount of scrollAmount each 60ms. For example, if scrollDelay is 6 and scrollAmount is 10, the marquee advances 10 pixels every 60ms.

By default, this property is FALSE for compatibility with Internet Explorer 3.0.

Applies To

MARQUEE


type

Description

Changes the style of the list.

Syntax

object.type[ = type]

Settings

This read-write property can be one of these string values:

1 | Use numbers. This is the default value.
a | Use small letters.
A | Use large letters.
i | Use small roman numerals.
I | Use large roman numerals.

Applies To

LI, OL, UL


type

Description

Returns the type of selection.

Syntax

object.type

Settings

This read-only property can be one of these string values:

None | No selection/insertion point.
Text | The selection is a text selection.
Control | The selection type is a control selection.

Applies To

selection


type

Description

Specifies the CSS language in which the style sheet is written.

Syntax

object.type

Settings

This read-only property can be any string, including an empty string. Valid style sheets for Internet Explorer 4.0 are set to "text/css".

Applies To

STYLE


type

Description

Specifies the visual appearance and default behavior of the button.

Syntax

object.type

Settings

This read-only property can be one of these strings:

button | Creates a Command button. This is the default value for this property.
reset | Creates a Reset button. If in a form, this button resets the fields in the form to their initial values.
submit | Creates a Submit button. If in a form, this button submits the form.

A Submit button has the same default behavior as the button created using the submit type with the INPUT element. When the input focus is in a control in the form (other than another button), the Submit button receives a bold border, and the user can "click" the button by pressing the ENTER key. If the Submit button has a name property, the button contributes a name/value pair to the submitted data.

When the Submit and Reset buttons are in the document (rather than in a form), the Submit button receives a bold border if the focus is in the document but not in another button, and the user can press ENTER to click the Submit button.

Applies To

BUTTON


type

Description

Returns the event name or scripting language as a string for the event object and script object, respectively.

Syntax

object.type

Remarks

Events are returned without the "on" prefix. For example, the "onclick" event is returned as "click".

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

event


type

Description

Specifies the mime type of the object. This is used to retrieve a class identifier for the object when no CLASSID= attribute is given.

Syntax

object.type[ = type]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

OBJECT

See Also

data


type

Description

Specifies the CSS language the style sheet is written in.

Syntax

object.type

Settings

This read-only property can be any string, including an empty string. Style sheets having any type other than "text/css" are not supported for Internet Explorer 4.0.

Applies To

styleSheet


type

Description

Specifies the type of intrinsic control represented by the given element object.

Syntax

object.type

Settings

This read-only property is a string specifying the control type. The possible values depend on the element as listed in the following table.
Element | Possible Value | Description
INPUT | button | Used to create a button control.
checkbox | Used for simple Boolean attributes or for attributes that can take multiple values at the same time. It is represented by a number of check box controls, each of which has the same name. Each selected check box generates a separate name/value pair in the submitted data, even if this results in duplicate names. The default value for check boxes is on.
file | A file upload element.
hidden | No control is presented to the user, but the value of the value property is sent with the submitted form.
image | An image control that you can click, causing the form to be immediately submitted. The coordinates of the selected point are measured in pixel units from the upper-left corner of the image, and are submitted with the form as two name/value pairs. The x-coordinate is submitted under the name of the control with .x appended, and the y-coordinate is submitted under the name of the control with .y appended. Any value property is ignored. The image itself is specified by the src property, exactly as for the IMG element.
password | Similar to the text control, except that text is not displayed as the user enters it.
radio | Used for mutually exclusive sets of values. Each radio-button control in the group should be given the same name. Only the selected radio button in the group generates a name/value pair in the submitted data. Radio buttons require an explicit value property.
reset | Reset is a button that when clicked resets the form's controls to their specified initial values. The label to be displayed on the button can be specified just as for the Submit button.
submit | Submit is a button that when clicked submits the form. You can use the value attribute to provide a non-editable label to be displayed on the button. The default label is application specific. If a Submit button is clicked in order to submit the form, and that button has a name attribute specified, that button contributes a name/value pair to the submitted data.
text | Used for a single-line text-entry control. Use in conjunction with the size and maxLength properties.
SELECT | select-multiple | Used to specify a multiple-select list box.
select-one | Used to specify a single-select list box.
TEXTAREA | textarea | Used for multiple-line text-entry controls. Use in conjunction with the size and maxLength properties.

Applies To

INPUT, SELECT, TEXTAREA


type

Description

Specifies the language that the current script is written in.

Syntax

object.type

Settings

This read-only property can be any string, including an empty string.

Remarks

This read-only property can refer to any scripting language. Internet Explorer 4.0 ships with a JScript (JavaScript-compatible) and VBScript scripting engine. Keywords for accessing these scripting languages include the following:

javascript | Specifies that the script is written in JavaScript.
Jscript | Specifies the language as JScript.
vbs | Specifies the language as VBScript.
vbscript | Specifies that the script is written in VBScript.

Remarks

To avoid conflict, the type should match the language type specified in the language property.

Applies To

SCRIPT


units

Description

Defines the units for the height and width of the EMBED element. Possible units include pixels and ems.

Syntax

object.units[ = units ]

Settings

This read-write property can be set to an integer value specifying the number of milliseconds between updates to the screen. A value of zero (0) disables the update interval.

Applies To

EMBED


updateInterval

Description

Sets or retrieves the update interval for the screen.

Syntax

object.updateInterval[ = msec ]

Settings

This read-write property can be set to an integer value specifying the number of milliseconds between updates to the screen. A value of zero (0) disables the update interval.

Use this property judiciously—a value too small or too large will adversely affect the page rendering response.

Remarks

The interval causes invalidations to the window to be buffered and then drawn in msec milliseconds intervals. The purpose is to limit excessive invalidations that reduce the overall painting performance, which can happen if there is an overabundance of flipbook-style animations occurring at once.

Applies To

screen


url

Description

Indicates the URL for the current document.

Syntax

object.url[ = URL]

Remarks

This property is an alias for the location.href property on the window.

This property has read-write permissions.

Applies To

document


url

Description

If a URL is specified, reloads the URL after the time specified by the CONTENT= attribute of the META element has elapsed.

Syntax

object.url[ = url]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

META


urn

Description

Specifies a uniform resource name (URN) for a target document.

Syntax

object.urn[ = urn]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

A


useMap

Description

Identifies a URL, often with a bookmark extension (#name), to use as a client-side image map.

Syntax

object.useMap[ = useMap]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

IMG


userAgent

Description

Specifies a string that represents the user-agent header sent in the HTTP protocol from the client to the server.

Syntax

object.userAgent

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

navigator


userLanguage

Description

Indicates the current user language. For possible return values, see Language Codes.

Syntax

object.browserLanguage

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

navigator


vAlign

Description

Specifies whether the caption appears at the top or bottom.

Syntax

object.vAlign[ = vAlign]

Settings

This read-write property can be set to one of these strings:

bottom | Places the caption at the bottom of the table.
top | Places the caption at the top of the table. This is the default value for this property.

Applies To

CAPTION


vAlign

Description

Specifies how the text and other content of an element is vertically aligned within the element.

Syntax

object.vAlign[ = vAlign]

Settings

This read-write property can be set to one of these strings:

baseline | Aligns the baseline of the first line of text with the baselines in adjacent elements.
bottom | Aligns the text at the bottom of the element.
middle | Aligns the text in the middle of the element. This is the default value for this property.
top | Aligns the text at the top of the element.

Applies To

COL, COLGROUP, TBODY, TD, TFOOT, TH, THEAD, TR

See Also

vertical-align


value

Description

Sets or retrieves the value of the object.

Syntax

object.value[ = value]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

SELECT, TEXTAREA


value

Description

Specifies the value of the given control to be submitted to the server as a name/value pair.

Syntax

object.value[ = value]

Settings

This read-write property can be any valid string. The purpose of the string depends on the type of control.

Applies To

INPUT, OPTION


value

Description

Changes the count of ordered lists as they progress.

Syntax

object.value[ = value]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

LI


verticalAlign

Description

Sets or retrieves the vertical positioning of the element.

Syntax

object.style.verticalAlign[ = verticalAlign]

Remarks

The values for verticalAlign are shown below:
sub | Vertically aligns text to subscript.
super | Vertically aligns text to superscript.
top | Vertically aligns contents of element supporting VALIGN to top of element.
middle | Vertically aligns contents of element supporting VALIGN to middle of element.
bottom | Vertically aligns contents of element supporting VALIGN to bottom of element.
baseline | Aligns contents of element supporting VALIGN to baseline.
text-top | Vertically aligns text of element supporting VALIGN to top of element.
text-bottom | Vertically aligns text of element supporting VALIGN to bottom of element.

The property has read/write permission.

Applies To

HTML Tags | CAPTION, COL, IMG, SPAN, TABLE, TBODY, TD, TH, THEAD, TFOOT, TR
Scripting | style

CSS Attribute

vertical-align


visibility

Description

Sets or retrieves whether the content of the element is displayed.

Syntax

object.style.visibility[ = visibility]

Remarks

Unlike display:none, elements that are not visible still reserve the same physical space in the content layout as they would if they were visible. Changing the visibility through scripting is useful for showing and hiding content based on user interaction. Note that for a child element to be visible, the parent element must also be visible. See Dynamic Styles for document style scripting information.

The property has read/write permission.

Applies To

HTML Tags | A, ADDRESS, APPLET, B, BIG, BLOCKQUOTE, BODY, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, DD, DFN, DIR, DIV, DL, DT, EM, EMBED, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HR, HTML, I, IFRAME, IMG, INPUT, INPUT type=button, INPUT type=checkbox, INPUT type=file, INPUT type=image, INPUT type=radio, INPUT type=reset, INPUT type=submit, INPUT type=text, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OBJECT, OL, P, PRE, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP
Scripting | style

CSS Attribute

visibility


vLink

Description

Sets or returns the color of links that have already been visited. The color can be one of the color names or values given in Color Table.

Syntax

object.vLink[ = color]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

body

See Also

aLink, link


vlinkColor

Description

Sets or returns the color of links that have already been visited. The color can be one of the color names or values given in Color Table.

Syntax

object.vlinkColor[ = color]

Remarks

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

document

See Also

alinkColor, linkColor


volume

Description

Specifies the volume setting for the sound. The higher the setting, the louder the sound.

Syntax

object.volume

Remarks

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

BGSOUND


vspace

Description

Specifies vertical margins for the element.

Syntax

object.vspace[ = vspace]

Remarks

This property is similar to border, except the margins are not painted with color when the element is a link.

This property has read-write permissions, meaning you can change as well as retrieve its current value.

Applies To

APPLET, IFRAME, IMG, MARQUEE

See Also

border, hspace


width

Description

Specifies the horizontal resolution of the screen, in pixels.

Syntax

object.width

Remarks

This property has read-only permission.

Applies To

screen


width

Description

Specifies the calculated width of the element, in pixels.

Syntax

object.width

Remarks

This property is an integer value. Although an HTML author can specify the width as a percentage, this property always retrieves the width in pixels.

This property is read/write for the IMG element, but it is read-only for the other elements.

Applies To

EMBED, FRAME, IMG, MARQUEE, OBJECT, TABLE

See Also

height


width

Description

Sets or retrieves the width of the element.

Syntax

object.style.width[ = width]

Remarks

This read/write property is a string consisting of a floating-point number and a units designator, as described for cascading style sheets.

DIV and SPAN cannot be positioned unless a width is provided. Percentage values are based on the width of the parent element.

When scripting the width property, use either the pixelWidth or posWidth property for numeric manipulation of a width value.

For more information on how to access the dimension and location of elements on the page through the document object model, see Measuring Element Dimension and Location.

Applies To

HTML Tags | APPLET, DIV, EMBED, FIELDSET, HR, IFRAME, IMG, INPUT, INPUT type=button, MARQUEE, OBJECT, SELECT, SPAN, TABLE, TEXTAREA
Scripting | style

CSS Attribute

width


wrap

Description

Specifies how to handle word-wrapping in the element.

Syntax

object.wrap[ = wrap]

Settings

This read-write property can be one of these strings:

off | Word-wrapping is disabled. The lines appear exactly as the user types them. This is the default value for this property.
physical | The text is displayed and submitted word-wrapped.
virtual | The text is displayed and submitted using word-wrapping.

Applies To

TEXTAREA


x

Description

Returns the position of the mouse hit relative to the element in the parent hierarchy that is positioned using the CSS positioning attribute. If no element in the hierarchy has been positioned, the BODY element is the default.

Syntax

object.x

Remarks

If the mouse is outside the window when the event is called, this property returns -1.

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

event


y

Description

Returns the position of the mouse hit relative to the element in the parent hierarchy that is positioned using the CSS positioning attribute. If no element in the hierarchy has been positioned, the BODY element is the default.

Syntax

object.y

Remarks

If the mouse is outside the window at the time the event fires, this property returns -1.

This property has read-only permission, meaning you can retrieve its current value, but not change it.

Applies To

event


zIndex

Description

Sets or retrieves the stacking order of positioned elements.

Syntax

object.style.zIndex[ = zIndex]

Remarks

By default (auto), the stacking order is bottom-to-top in the order that the z-indexed elements appear in the HTML source. Positive z-index values are positioned above a negative (or lesser value) z-index. Two elements with the same z-index are stacked according to source order.

The property has read/write permission.

Applies To

HTML Tags | A, ADDRESS, APPLET, B, BIG, BLOCKQUOTE, BODY, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, DD, DFN, DIR, DIV, DL, DT, EM, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HTML, I, INPUT, INPUT type=button, INPUT type=file, INPUT type=reset, INPUT type=submit, INPUT type=text, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, OL, P, PLAINTEXT, PRE, S, SAMP, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP
Scripting | style

CSS Attribute

z-index


Tips and Tricks

As with any type of programming, writing bug-free, efficient scripts that meet your expectations takes a bit of work. The following sections provide some tips and hints to make that work take less time and go more smoothly.

Checking the Internet Explorer Version Number

Canceling a Button Click

Preventing a Document From Being Cached

Using Objects

Replacing Custom Controls with Dynamic HTML

Checking the Internet Explorer Version Number

Your scripts should always check the version of the client browser so as to degrade gracefully if the browser does not support the new features of Internet Explorer version 4. The easiest way to identify whether the browser is Internet Explorer and determine its version number is to use the following JScript function:

function msieversion()
// return Microsoft Internet Explorer (major) version number, or 0 for others.
// This function works by finding the "MSIE " string and extracting the version number
// following the space, up to the decimal point for the minor version, which is ignored.
{
    var ua = window.navigator.userAgent
    var msie = ua.indexOf ( "MSIE " )
    if ( msie > 0 )        // is Microsoft Internet Explorer; return version number
        return parseInt ( ua.substring ( msie+5, ua.indexOf ( ".", msie ) ) )
    else
        return 0    // is other browser
}

This function runs on the large majority of browsers and returns the major version number for any Microsoft Internet Explorer browser, or zero for all other browsers. Use of this function assures that the script will be compatible with future versions of Internet Explorer.

Scripts should always check version numbers greater than or equal so as to be compatible with future versions. Existing scripts that check for userAgent equal to "MSIE 3" should be changed to check the version correctly so that these scripts will recognize Internet Explorer 4.0 which supports all of the functionality of the previous version.

The following example shows how to correctly check the client browser version.

if ( msieversion() >= 4 )
    document.alert( "This is IE4 or later - safe to use all IE4 features" )
else if ( msieversion() >= 3 )
    document.alert( "This is IE3 - safe to use ActiveX" )
else
    document.alert( "This is not IE" )

Canceling a Button Click

The following HTML example shows a common scripting mistake related to event handling and canceling the default action.

<HTML>
<HEAD><TITLE>Canceling the Default Action</TITLE>
<SCRIPT LANGUAGE="JScript">
function askConfirm() {
    return window.confirm ("Choose OK to follow hyperlink, Cancel to not.")
}
</SCRIPT>

<BODY onload="b3.onclick=askConfirm">
<!-- Try links with different hookups - should be canceled by "Cancel" to confirm dialog. -->

<BR><A NAME=b1 HREF="http://www.microsoft.com" onclick="askConfirm()">1 Without return (won't work)</A>

<BR><A NAME=b2 HREF="http://www.microsoft.com" onclick="return askConfirm()">2 With return (works)</A>

<BR><A NAME=b3 HREF="http://www.microsoft.com">3 Function pointer (works)</A>

</BODY>
</HTML>

The first A element in this example does not work properly. Without the return in the onclick JScript expression, the browser interprets the function expression, throws away the resulting value (this is just a statement consisting of an expression, no assignment, an so on), and leaves the default action unaffected.

The other A elements correctly bind the return value to the event, hence the default action can be canceled when false is returned.

Preventing a Document From Being Cached

You can prevent a document from being cached by adding the following META tag to the document.

<META HTTP-EQUIV="Expires" CONTENT="0">

Preventing the document from being cached ensures that a fresh copy of the document will always be retrieved from the site, even during the user's current session, regardless of how the user has set his browser's caching options. This is useful if the content of the document changes frequently.

Using Objects

Objects are ActiveX controls or other similar components that provide custom capabilities and services for HTML documents. You can add a control to your document by using the OBJECT element, and gain access to the capabilities and services of the control by using its properties and methods from script.

When using objects, be aware that Dynamic HTML extends every object by providing these additional properties:
align BaseHref
classid code
codeBase codeType
data form
height name
object recordset
type width

If a control has properties with these same names, you will not be able to access the properties unless you preface the name with the object property. For example, assume that an ActiveX control is added to the document by using the following.

<OBJECT ID="MyControl" HEIGHT=100 WIDTH=200 CLASSID="clsid: ... ">
</PARAM NAME="width" VALUE="400">
</OBJECT>

In this example, there are two widths: an extended property set within the OBJECT element, and a property belonging to the control that is set using the PARAM element. To access these from script, you use the following code.

alert(MyControl.width);   // this is Dynamic HTML's property; displays "200"
alert(MyControl.object.width);  // this is the object's property; displays "400"

Replacing Custom Controls with Dynamic HTML

Dynamic HTML provides everything you need to generate animated effects without resorting to custom controls. For example, consider the following script, which is a replacement for the Path control.

var tickDuration;
tickDuration = 50;

var activeObjectCount;
var activeObjects;
var itemDeactivated;

var tickGeneration;

activeObjects = new Array();
activeObjectCount = 0;
timerRefcount = 0;
itemDeactivated = false;

tickGeneration = 0;

function initializePath(e) {
 e.waypointX = new Array();
 e.waypointY = new Array();
 e.duration = new Array();

}

function addWaypoint(e, number, x, y, duration) {
 e.waypointX[number] = x;
 e.waypointY[number] = y;
 e.duration[number] = duration;
}

function compact() {
  var i, n, c;

  n = new Array();
  c = 0;
  itemDeactivated = false;
  for (i=0; i<activeObjectCount; i++)  {
     if (activeObjects[i].active == true) {
        n[c] = activeObjects[i];
        c++;
     }
  }

  activeObjects = n;
  activeObjectCount = c;
}

function tick(generation) {

  if (generation < tickGeneration) {
    // alert("Error "+generation);
     return;
  }

  //alert("tick: "+generation);

  if (itemDeactivated)
     compact();

  if (activeObjectCount == 0) {
     return;
  }
  else {
    for (i=0; i<activeObjectCount; i++) {
      moveElement(activeObjects[i]);
    }

    window.setTimeout("tick("+generation+");", tickDuration);
  }
}

function start(e) {
  if (itemDeactivated)
     compact();

  activeObjects[activeObjectCount] = e;
  activeObjectCount++;

  if (activeObjectCount == 1) {
    tickGeneration++;
    tick(tickGeneration);
  }
}

function runWaypoint(e, startPoint, endPoint) {

  var startX, startY, endX, endY, duration;

  if (e.waypointX == null)
    return;

  startX = e.waypointX[startPoint];
  startY = e.waypointY[startPoint];
  endX = e.waypointX[endPoint];
  endY = e.waypointY[endPoint];

  duration = e.duration[endPoint];
  e.ticks = duration / tickDuration;

  e.endPoint = endPoint;
  e.active = true;
  e.currTick = 0;

  e.dx = (endX - startX) / e.ticks;
  e.dy = (endY - startY) / e.ticks;

  e.style.posLeft = startX;
  e.style.posTop = startY;

  start(e);
}

function moveElement(e) {
  e.style.posLeft += e.dx;
  e.style.posTop += e.dy;

  e.currTick++;

  if (e.currTick > e.ticks) {
    e.active = false;
    itemDeactivated = true;
    if (e.onpathcomplete != null) {
       window.pathElement = e;
       e.onpathcomplete()
    }
  }
}

To use this script in your document, do the following:

  1. Load the script by using the src attribute of the SCRIPT element.
  2. Initialize the paths by using the initializePath function.
  3. Set the way points by using the addWaypoint function.
  4. Set the path-complete handlers, using the runWaypoint function.

The following sample document show how this works.

<html>

<body>

<div id=Item1 style="position: absolute; left: 0; top: 0;">Item1</div>
<div id=Item2 style="position: absolute; left: 0; top: 0;">Item2</div>
<div id=Item3 style="position: absolute; left: 0; top: 0;">Item3</div>
<div id=Item4 style="position: absolute; left: 0; top: 0;">Item4</div>
<div id=Item5 style="position: absolute; left: 0; top: 0;">Item5</div>
<div id=Item6 style="position: absolute; left: 0; top: 0;">Item6</div>

<input type=button value="Start" onclick="runWaypoint(Item1, 0, 1); runWaypoint(Item2, 0, 1);">
<div id=Debug>Generation</div>

<script src="htmlpath.js">
</script>

<script>

// need to call initializePath on all objects that will be moved with this mechanism
initializePath(Item1);
initializePath(Item2);
initializePath(Item3);
initializePath(Item4);
initializePath(Item5);
initializePath(Item6);

// the 0th waypoint is the intial position for waypoint #1
// syntax is item, waypoint, endx, endy, duration in msecs
addWaypoint(Item1, 0, 0, 0, 0);
addWaypoint(Item1, 1, 200, 200, 2000);

addWaypoint(Item2, 0, 100, 100, 0);
addWaypoint(Item2, 1, 400, 100, 4000);

addWaypoint(Item3, 0, 400, 400, 0);
addWaypoint(Item3, 1, 200, 100, 1000);

addWaypoint(Item4, 0, 0, 0, 0);
addWaypoint(Item4, 1, 200, 200, 2000);

addWaypoint(Item5, 0, 100, 100, 0);
addWaypoint(Item5, 1, 400, 100, 4000);

addWaypoint(Item6, 0, 400, 400, 0);
addWaypoint(Item6, 1, 200, 100, 1000);

function endfunction() {
  // syntax for runWaypoint is Item, start point, end point
  runWaypoint(Item3, 0, 1);
  runWaypoint(Item4, 0, 1);
  runWaypoint(Item5, 0, 1);
  runWaypoint(Item6, 0, 1);

}

function endfunction2() {
  runWaypoint(Item1, 0, 1);
}

Item1.onpathcomplete = endfunction;
Item6.onpathcomplete = endfunction2;

</script>
</body>
</html>


Samples and Tools

Samples

The following samples demonstrate various features of Dynamic HTML.

Dynamic Styles Demonstrates an example of Dynamic Styles. Change text colors, font styles, visibility, and even cursors without refreshing the page!

Dynamic Content Demonstrates an example of Dynamic Content. Stay up-to-the-minute with a DHTML clock. Change the text on the page with the click of a mouse.

Positioning

  • Position Demonstrates 2-D layering of moving images with a mouse.
  • Asteroids You want interactivity? You've got it with a fully functional Dynamic HTML version of Asteroids! This demonstration takes advantage of positioning and JScript to deliver shoot-em-up action.

Centering Demonstrates centering an object within a division on the page.

Resizing

  • Sample1 Demonstrates various samples of resizing capabilities.
  • Sample2 Demonstrates the resizing of div, image, and text.

Image Switches images using preloaded images.

Domain Illustrates accessing a second-tier domain in an IFRAME.

Replacing Custom Controls with Dynamic HTML

  • Path Demonstrates how to replace the path control through the use of scripting.
  • Pop-up Menu Demonstrates how to create a pop-up menu through the use of Dynamic HTML.

DirectAnimation Controls

  • MMAudio Illustrates mixing several .wav files.
  • Structured Graphics Control
    • MMSGX Demonstrates how to use a structured graphic control.
    • Surface Shows how the DirectAnimation DrawingSurface API is used to create a single vector shape with independent internal and external rotations.
  • Path Control
    • Tricycle Shows a sprite control on a path, and allows you to control its behavior.
  • Sprite Control
    • Sprite Demonstrates the ability to add still and animated images on your Web page, with control over frames per second, forward or reverse playback, or dynamic reading of source files.
    • Banner Demonstrates the ability to use the sprite control as a clickless control for a banner-type advertisement.
    • Concentrate Demonstrates the ability to use the sprite control to contain images for this match game.
    • Swapgame Demonstrates the ability to use the sprite control to contain images for puzzle-type games.
  • Sequencer Control
    • Sequencer-JScript Demonstrates how to use the sequence control through JScripting.
    • Sequencer-VBScript Demonstrates how to use the sequence control through VBScripting.

Filters and Transitions

  • Filters
    • Filters Demonstrates the different filters.
  • Transitions
    • Transitions Demonstrates the different transitions.
    • Blend Transition Demonstrates the blend transition.

Tools

Tools for Debugging Scripts

  • Microsoft Script Debugger for Internet Explorer

Wizards for Generating Simple Filters and Transitions Pages

  • Filter Wizards
    • Filters Wizard HTML-based wizard that generates working code for the different filters, based on the parameters entered by the user.
    • Wave Filter Wizard HTML-based wizard that generates working code for the wave filter, based on the parameters entered by the user.
    • Light Filter Wizard HTML-based wizard that generates working code for the light filter, based on the parameters entered by the user.
  • Transitions Wizard
    • Transitions Wizard HTML-based wizard that generates basic code for the different transitions, based on the parameters entered by the user.

CSS Syntax Validation Tool

  • StyleT 2.0 Guide Provides information on the StyleT 2.0 Test Tool. This test tool performs a series of tests to ensure that the syntax of the files matches the CSS Specification. StyleT.htm is available in the \bin directory of the Internet Client SDK installation.

Wizards for Generating Simple DirectAnimation Control Pages

  • Path Wizard HTML-based wizard that generates working code for moving an object around, based on the parameters entered by the user.
  • Graphics HTML-based wizard that generates working code (for the Structured Graphics and Sequencer controls) that produces a rotating text logo, based on the parameters entered by the user.


Changing Element Styles

Dynamic HTML allows you to write script that can change the HTML attributes that modify a given element. These attributes can be things such as the SRC attribute on an IMG or IFRAME element, or the STYLE attribute for a DIV element. This document shows you how to change the SRC= attribute on an IFRAME element so that the contents of IFRAME change on the fly. The same example also shows you how to change the background color of the body for the SRC= document of the IFRAME. The next set of examples shows how to change the class name of the element so that it is associated with a different style sheet.

Dynamic HTML gives you scriptable access to all HTML elements, attributes, and CSS styles. You as the author can use these techniques to design some pretty cool DHTML Web pages.

Changing the Style of an IFRAME

Changing Element Classes

Scripting CSS Attributes

Changing the Style of an IFRAME

The following example shows how to change the contents of IFRAME as well as change the style attribute of the BODY element of the contained IFRAME. Click the Show Me button to show the page, and then look at the code.

<HTML>
<HEAD><TITLE>Changing Element Attributes</TITLE>
<SCRIPT LANGUAGE="JavaScript">
 function change_image() {
   document.all.myiframe.src="frame_content2.htm";
   //use the all collection to access attributes of the IFRAME element
}
function change_background() {
     document.frames.myiframe.document.body.style.backgroundColor="green";
     // use the frames collection to access the document contained in the IFRAME.
}
</SCRIPT>
</HEAD>
<BODY>
    <IFRAME id=myiframe src="frame_content.htm">
    </IFRAME>
    <BUTTON onclick=change_image()>Change contents of the IFRAME</BUTTON>
    <BUTTON onclick=change_background()>Change the background color of the IFRAME</BUTTON>
</BODY>
</HTML>

Changing Element Classes

There are two primary ways to change the inline style for an element—either change the element's STYLE attribute, or change the className of the element to match a defined class in a global style sheet. The following example shows how straightforward it is to change the inline STYLE attribute with an event.

<H1 id=myStyle onclick="this.style.color=blue">This text will change to blue when clicked </H1>

This changes the property "color" of the style sub-object for the H1 element.

However, to change the style for more than one element, use global style sheets, which let you define styles based on a "contextual selector"—styles can apply to tag names, element identifiers, or all elements in a class. The DHTML class attribute on every element lets you associate any element with any class name. This way, multiple elements can belong to a single class, and setting a global style for a class means that the style sheet applies to every element with that class name.

Because the class attribute can be scripted, you can dynamically change class associations with elements in a document, as in the following example.

<HTML>
<HEAD><TITLE>Changing Element Attributes</TITLE>
<STYLE>
.textRed {color:red}
.textBlue {color:blue}
</STYLE>
</HEAD>
<BODY>
<H1 class=textBlue onmouseover="this.className='textRed'" onmouseout="this.className='textBlue'">Mouse over this text to see
the color change from blue to red and back to blue</H1>
</BODY>
</HTML>

In the example, global rules are defined for two classes, "textRed" and "textBlue". The H1 initially is a part of the textBlue class and therefore is displayed in blue. Moving the mouse over the text fires the onmouseover event, and the inline event handler changes the association of the H1 element to the textRed class, which renders the text red. Note that the class attribute is referenced through the className property.

Note The scriptable properties for CSS styles are all read/write except position. You cannot dynamically set a nonpositioned element to be positioned. If you want to absolutely position an element using an event handler script, be sure that the element has its initial position set to relative using either a global style sheet or an inline style.

Scripting CSS Attributes

All style attributes are strings. Several properties have been added to the style object to help manipulate values as nonstrings. For example, pixelHeight is an integer so that the height of an object can be mathematically manipulated in base pixel units regardless of how the height attribute was set. The posHeight property is an integer that describes the height attribute in the units to which the author originally set the CSS height attribute.

If a style property represents some number of units, you can include a units designator when assigning the value. The "pt" (points) and "px" (pixels) designators are used in the following examples.

document.all.MyElement.style.fontSize = "24pt";
document.all.MyElement.style.fontSize = "120px";

If you don't supply a units designator, the default unit of measure for the property is used. One benefit of this is that you can assign a number or the result of an expression (rather than a string) and it will be converted automatically. For example, the assignments below are the same—they both set the font size to 72 pixels.

document.all.MyElement.style.fontSize = "72";
document.all.MyElement.style.fontSize = 72;


Style Sheets and Printing

The STYLE and LINK elements support the MEDIA attribute, which defines the output device for the style sheet. Values for MEDIA are SCREEN, PRINT and ALL. The default is SCREEN, so not setting the MEDIA attribute causes the style sheet to always be applied to the page for the screen as well as printing. The PRINT value specifies that the style sheet is used when the page is printed; this value does not affect how the document will be displayed onscreen. The ALL value determines that the document is formatted for both the screen and print.

Note that all filter: styles, including visual effects filters, are ignored when printing. Internet Explorer renders this content for printing with any applicable text style properties.

Setting Page Breaks For Printing

You can control the placement of page breaks in your documents by using the page-break-before and page-break-after attributes. These attributes indicate when to break to a new page when printing the document and on what page (left or right) to resume printing. These attributes are useful when you want to print long documents into logical sections.

For example, the following document defines a class "page" in a style sheet and uses it to set page breaks in the document.

<HTML>
<HEAD><TITLE>Dynamic Styles: Page Breaking</TITLE>
<STYLE>
    BR.page { page-break-after: always }
</STYLE>
</HEAD>
<BODY>
    .
    content on page 1
    .
<BR CLASS=page>
    .
    content on page 2
    .
</BODY>
</HTML>

You can set page breaks from within a script by setting the pageBreakBefore and pageBreakAfter properties on the style object. The following example sets a page break immediately before each H1 element in the document. The heading is subsequently printed on a right-hand page.

var coll = document.all.tags("H1");
for (i=0; i<coll.length; i++) {
    coll(i).style.pageBreakBefore = "always right";
}


Managing Style Sheets

Dynamically changing cascading style sheet (CSS) styles that are applied to documents is not limited to the inline styles (styles defined with the STYLE= attribute). Global style sheets defined with a LINK or STYLE tag in the HEAD section of the document can be manipulated through script. Manipulating the global style sheet is a powerful way to dynamically change the styles that apply to Web pages.

styleSheets Collection

Global style sheets are made accessible to script through the styleSheets collection on the document object. This collection represents instances of STYLE and LINK elements in the HEAD section of the document with a type (or type attribute) of "text/css". Style sheets of other types are not supported. Imported style sheets are contained within a STYLE element, and are surfaced by the containing STYLE element as type styleSheet. STYLE and LINK elements can be added to the document through the createElement method on the window object. This method adds a new style sheet object to the styleSheets collection on the document. Style rules and imported style sheets can then be added to this style sheet with the addImport and addRule methods.

You can use identifiers to access style sheets in the document. You set an identifier for a style sheet by setting the ID attribute of the LINK or STYLE element.

Disabling Style Sheets

A powerful feature of the styleSheet object is that you can turn a style sheet off and on dynamically. The disabled property defaults to false, but can be set to "true" to remove the style sheet from being applied to the document. Toggling the application of style sheets is another technique for dynamically changing the style of a Web page.

Replacing Style Sheets

You can replace one style sheet with another by setting the href property of the style sheet to the URL of the replacement, as in the following example:

if (document.styleSheets(0).href != null)
    document.styleSheets(0).href = "newstyle.css";

When you replace a style sheet, the styleSheets collection is immediately updated to reflect the change. Replacing a style sheet in this way is available only for style sheets that have been included using the LINK element or the @import statement. The href property is null for style sheets defined using the STYLE element.

Dynamically Changing Style Sheet Rules

Each style sheet is a collection of rules. The rules collection of the styleSheet object enumerates these rules. This collection can be accessed even if the style sheet is disabled. Rules are added and removed from the rules collection with add and remove methods on the individual style sheet. A rule that is added to a disabled style sheet will not apply to the document unless the style sheet's disabled property is changed to "false".

The rules in the rules collection are in the source order of the document. Style rules linked in using the "@import" syntax of CSS are expanded in-place in the rules collection per the CSS1 specification.

As rules are added or deleted, a rule's absolute position in the rule collection may change, but its position relative to other rules will remain the same. The default location to add a new rule (without specifying an index) is at the end of the collection, which is the highest precedence (not accounting for selector specificity, as per the CSS specification) and is applied to the document last. If an index is supplied, the rule should be inserted before the rule currently in that ordinal position in the collection, or, if the index is larger than the number of rules in the collection, it should be added to the end .

The following is an example of using the addRule method.

<HTML>
<HEAD>
<SCRIPT LANGUAGE="JScript">
function newRule() {
    document.styleSheets.MyStyles.addRule("P","color:blue");
}
</SCRIPT>
<STYLE ID="MyStyles">
H1 {color:red}
H2 {color:red;font-style:italic}
</STYLE>
</HEAD>
<BODY onclick="newRule()">
<H1>Welcome!</H1>
<P>This document uses style sheets.</P>
<H2>Ways to Include Style Sheets</H2>
<UL>
<LI>LINK
<LI>STYLE
<LI>@import
</UL>
</BODY>
</HTML>

Each rule has a selector, identifying the elements to apply the rule to, and a list of style assignments, identifying the style attributes to apply to these elements. The selector is typically the name of an element, class, or identifier, but can also be a combination of names, such as a comma-separated list of element names. Each style assignment consists of a style attribute name and a value separated by a colon. If there is more than one assignment, the assignments are separated by semicolons. The rule object has a readOnly property that indicates whether the particular rule is from an editable source. Imported and linked styles cannot be edited, so the readOnly property for the contained rule would return "true".

As an example of manipulating style rules, consider the following simple style sheet:

<STYLE
ID="MyStyles">
H1 {color:red}
H2 {color:red;font-style:italic}
</STYLE>

The rules collection would contain two rules. Each rule has two parts (and corresponding properties): the selector and the style. The selector in the first rule in the above style sheet is "H1".

alert(document.styleSheets[0].rules[0].selectorText); // this returns "H1"

To change the style of the first rule in the first style sheet, use the following:

document.styleSheets[0].rules[0].style.color = "blue";

User-Defined Style Sheets

Through the Options dialog box of the browser, users can specify a style sheet that they want to have applied to all pages that they view. This style sheet will be applied to the document first, meaning the author has the final say of how a CSS attribute is defined. Style sheets defined in the document override the user-defined style sheet. The user-defined style sheet is simply a "preference" that will affect the page if the author has not defined a rule for that CSS attribute. User-defined style sheets specified by the user in the Options box dialog of the browser are not listed in the styleSheets collection.


Dynamic Styles

You can dynamically change the style of any HTML element in a document. You can change colors, typefaces, spacing, indentation, position, and even the visibility of text. Because the Dynamic HTML object model makes every HTML element and attribute accessible, it is easy to use scripts to dynamically read and change styles. The following section describes dynamic styles and provides a general explanation of how to use the object model to examine and modify styles.

Making Styles Dynamic

Web authors gained unprecedented control over the look of documents with the introduction of cascading style sheets (CSS) in Internet Explorer 3.0. CSS allows authors and readers to attach a style to Web pages that defines the presentation of content by modifying style attributes of corresponding HTML elements.

Microsoft® Internet Explorer 4.0 takes CSS technology a step further, providing the ability to dynamically change any HTML attribute, at any time, on any element. Using simple JavaScript, JScript, or VBScript (Visual Basic® Scripting Edition), the attributes for any HTML element can be modified in response to any document or user event, and the page will automatically reflow without reloading the page from the server. This means that, for example, the STYLE element can be changed to change an element's inline CSS style, or any other HTML attribute (such as the SRC attribute on an IMG element).

Dynamic Styles Are Easy

You might expect that this new functionality will require that you learn a new set of HTML tags. However, dynamic styles have been designed to require no new HTML. CSS attributes can be set from the style sub-object for each element, while regular HTML attributes are accessed as properties on each element. For instance, to change the color of text within an H1 heading to red when the user moves the mouse over the heading, all you need to add is a simple piece of code known as an event handler.

<H1 onmouseover="this.style.color = 'red';">Make me red</H1>

The event handler, onmouseover="this.style.color = 'red';" takes a predefined action (onmouseover) and assigns an action for it to carry out when it fires (this.style.color = 'red'). It is just as easy to change not only the style but the content of a SRC attribute in the same manner.

<IMG src="before.gif" onmouseover="this.src = 'after.gif';">

In this example, as the mouse moves over the image, its source changes from "before.gif" to "after.gif". For more information on using event handlers, see Understanding the Event Model.

Documents Are Dynamic

When the color of an element is changed dynamically, it still fits into the same physical space in the document as it did before the color change. This is a relatively simple task for the browser to carry out. However, there are other styles, such as fontSize or fontFamily, that, when changed, actually change the size of the element and the amount of space required to display that element in the document. Internet Explorer 4.0 handles each such change automatically by reflowing a document to ensure that all the elements fit perfectly without reloading the document from the server.

<html>
<body>
This is some text.
<span style="color:blue" onclick="this.style.fontSize = '30'">

This is more text.</span>
This is even more text.
</body>
</html>

Initially, the document has two lines of text, identical in font size and color. After clicking "This is more text," the text changes, increasing in size and changing to blue. The browser automatically adjusts the line spacing to accommodate the new text size.

Powerful Attributes

Because Internet Explorer 4.0 automatically reflows the document when attribute values change, some very powerful functionality can be built with very small amounts of code. For example, using the CSS display attribute, you can make elements on the page disappear, and treat them as if they were never on the page in the first place.

<html>
<body>
<div style="cursor: hand" onclick="toggle(document.all.HideShow);">
Click Here</div>
<span style="color: blue" id=HideShow>This will go away</span><br>
This is some text
<script>
function toggle(e) {
  if (e.style.display == "none") {
     e.style.display = "";
  } else {
     e.style.display = "none";
  }
}
</script>
</body>
</html>

This HTML displays three lines. When the user clicks the line that says "Click Here", the browser changes the display attribute of the SPAN element with the text "This will go away" to display: none, and the text beneath shifts up to occupy its space. When clicked again, the display attribute is reset so that the "Click Here" text is visible again.

Notice that by simply setting display: none on an element, it disappears and the browser automatically reclaims the space it occupied. This mechanism can be used to create pages that display new information, such as an expandable table of contents, as the user interacts with individual entries. The two supported values for the display property are none and "" (or null).

The sample above also makes use of the CSS cursor attribute. The cursor attribute allows a Web author to specify what the cursor will look like when it is over an element. In this case, the hand cursor was chosen to indicate that the text titled "Click Here" would perform an action when clicked, just like a text link on a Web page. Using the cursor attribute eliminates the need to use an anchor tag to have the cursor change to a hand, indicating the contents are "clickable".

The set of valid values for the cursor attribute are crosshair, default, hand, move, e-resize, ne-resize, nw-resize, n-resize, se-resize, sw-resize, s-resize, w-resize, text, wait, and help.

While the display property makes an element invisible and allows the browser to reclaim the space that it occupied, the visibility property can be used to simply make an element disappear, but still reserve its space in the document.

The following example is identical to the previous demonstration, except it uses the visibility property instead of the display property.

<html>
<body>
<div style="cursor: hand" onclick="toggle(document.all.HideShow);">

Click Here</div>
<span style="color: blue" id=HideShow>This will go away</span><br>
This is some text
<script>
function toggle(e) {
  if (e.style.visibility == "hidden") {
     e.style.visibility = "visible";
  } else {
     e.style.visibility = "hidden";
  }
}
</script>
</body>
</html>

Notice how in this example the line of text will become invisible, but the content below does not shift up to reclaim its space.

Special Considerations

You might have noticed that many CSS properties have a dash in their name (such as background-color). The dash, as you may know, isn't a valid character for identifiers in most scripting languages. To get around this little problem, continue to use the dashed name when specifying the CSS attribute in HTML or in a style sheet, but when accessing the attribute as a script property, remove the dash, and capitalize the next letter. For example:

background-color becomes backgroundColor

border-left becomes borderLeft

margin-bottom becomes marginBottom

The CSS attribute names specified in the HTML or style sheet are listed in the CSS Attributes section of the SDK. The corresponding scriptable properties are listed as properties of the style object in the Objects section of the SDK.

Also notice that while any CSS property can be set at any time, the current settings on the STYLE element will only reflect its inline styles, and not any inherited styles that are defined in a global style sheet with a STYLE or LINK tag. The following example shows what happens when a style is defined both globally and inline.

<html>
<head>
<style>
.class1 {font-family: arial}
</style>
</head>
<body>
<div id=SetByClass class=Class1>Set By Class</div>
<div style="font-family: arial">
      <div id=Inherited>Inherited</div>
</div>
<div id=DirectlySet style="font-family: arial">Directly Set</div>
<div id=SetWithScript>Set with Script</div>
<script>
      alert(SetByClass.style.fontFamily);
      alert(Inherited.style.fontFamily);
      alert(DirectlySet.style.fontFamily);
      SetWithScript.style.fontFamily = "arial";
      alert(SetWithScript.style.fontFamily);
</script>
</body>
</html>

When this document loads, four alert dialog boxes pop up successively. The first two are blank, while the next two contain the text "arial." While all the text on the document is Arial, referencing style.fontFamily will show "arial" only on the DIV that had the font-family property set with an inline style or was previously set with script.

Additional Topics

With Internet Explorer 4.0, authors have total control over all attributes of all elements, at any time. Changes made to attributes that cause the page to change shape are handled automatically, with no additional script intervention by the author. Changing attributes through script can be done simply with inline script, or by pointing to a function where the element is accessed through a collection on the document. For more information about accessing elements through collections, see Scripting with Elements and Collections, or simply dive into the reference for details on the document collections and details on each HTML attribute that can be changed. You might also want to check out the event bubbling information for how to bind event handlers to one of the many events that the document can fire. The following topics describe some specific topics of dynamic styles:

  • Changing Element Styles
  • Managing Style Sheets
  • Style Sheets and Printing

Related SDK sections:

  • Scripting with Elements and Collections
  • Understanding the Event Model
  • CSS Attributes
  • HTML Elements
  • Objects


Cross-Platform Functionality

With Internet Explorer 4.0, content authors can easily create pages that run on all platforms—the 32-bit Windows® platforms, Windows 3.1, Macintosh®, and Unix. In particular, core Dynamic HTML (DHTML) and Active Channel functionality are cross-platform.

The following DHTML features are supported across platforms:

  • Full CSS 1 Core
  • CSS—Positioning
  • DHTML—Dynamic Styles
  • DHTML—Stylesheet Object Model
  • DHTML—Element Collection
  • DHTML—Event Model
  • DHTML—Core Dynamic Content: innerHTML, outerHTML, and associated methods
  • Data Binding
  • HTML 4 support
  • HTML dialogs

The following Active Channel functionality is supported across platforms:

  • General CDF support
  • Subscriptions, notification, offline reading

In addition, several features are available on some platforms, but will degrade gracefully on other platforms:

  • CSS Filters and Transitions. On some platforms, the filters and transitions may degrade to a basic filter or transition effect.
  • Font Download. If a platform does not support font download, the specified font will be substituted by another font already on the computer.
  • User Profile—Object Model. If a platform does not support this feature, it will appear as though the user has disabled it.

Win32 Premium Platforms

In addition to the cross-platform functionality, the versions of Internet Explorer 4.0 for the 32-bit Windows platforms (Windows 95, Windows 98, Windows NT®) support additional premium functionality, including:

  • Multimedia controls
  • DHTML—Extended Dynamic Content: the TextRange, Table object model, and associated methods
  • Data Binding—Remote Data Service
  • XML parser ActiveX control
  • Active Channels: page hit logging
  • Active Channels: display as screen saver
  • Active Channels: display as desktop component

In the future, support for the above features might be added to additional platforms based on customer demand.


HTMLHelp API Reference

The HtmlHelp API currently resides in the file HTMLHELP.DLL, however this is very likely to be moved to a different DLL before HTML Help ships. If you are not using GetProcAddress to get a pointer to the HtmlHelp function, then you must plan on changing the library you link to.

The functionality provided by the HtmlHelp API resides in the file HHCTRL.OCX. Because this functionality requires loading various other DLLs such as ole32.dll, the API itself resides in a DLL that requires no additional DLLs to be loaded. Only when the API is actually called will ole32 and other DLLs be loaded.

The HtmlHelp API is modeled after the WinHelp API function to make it easy to convert existing programs to use HTML Help instead of WinHelp to display their help. By the time HTML Help ships, there will also be an IHHWindow interface that can be used in place of the HtmlHelp API. This can be used by programs that already load OLE32.DLL or by programs like Visual Basic.

In its simplest form, the HtmlHelp API creates a child window which in turn hosts SHDOCVW and displays the HTML file you specify. The window is a child of whatever parent window you specify, and will automatically stay on top of that parent window, and close when the parent window is closed. You can also take complete control of the window-creation process by defining the window styles, coordinates, caption, and display state. This means you can embed SHDOCVW even in a non-OLE activated program.

SYNTAX

HWND HtmlHelp(HWND hwndCaller, LPCSTR pszFile, UINT uCommand, DWORD dwData);

hwndCaller
Specifies the handle of the window calling the HtmlHelp API. If the HtmlHelp API call results in messages being sent from the HTML Help window, they will be sent to this window handle.
pszFile
Specifies an HTML file, a URL, a compiled HTML file, or a window definition (preceeded with a ‘>’ character). If the command being used does not require a file or URL, this value may be NULL.
uCommand
Specifies the action to perform. See the Comments section for details.
dwData
Specifies any data that may be required based on the value of the uCommand parameter.

Comments

The uCommand parameter determines what action to take, and what needs to be supplied for the pszFile and dwData parameters. The following table lists the commands, actions, and required parameters:
Command | Description | pszFile | dwData
HH_DISPLAY_TOPIC | Displays an HTML file. If a window type is not specified, a default window type is used. If the window type or default window type is already being displayed, the HTML file will replace what is currently being displayed. | File, URL, or compiled HTML file. If the greater then character (>) is used, it must be followed by the name of the window type to display the topic in. | May be zero or a pointer to a File, URL, or compiled HTML file. This parameter may be a pointer to a filename within a compiled HTML file if the pszFile parameter points to that compiled HTML file.
HH_DISPLAY_TEXT_POPUP | Displays text from a string resource, text string, or text file in a popup window. | Text filename if text resides in a file. Use NULL if the text is in a string resource id or specified in the HH_POPUP structure. | Points to a HH_POPUP structure.
HH_SET_WIN_TYPE | Creates a new window type, or modifies an existing window type. | Ignored. | Points to a HH_WINTYPE structure.
HH_GET_WIN_TYPE | Retrieves the HH_WINTYPE structure associated with a window type. If the window type has not been specified, the return value is -1. If the window type has been specified, the return value is the handle of the window (NULL if the window hasn’t been created). | Specifies the name of the window. The window name must begin with a ‘>’ character, and may optionally be preceded by the name of the compiled HTML file. | Points to the address of a PHH_WINTYPE pointer. Do not modify the structure this pointer points to.
HH_GET_WIN_HANDLE | Retrieves the handle of the window associated with the specified window type. If the window type has not been created, the return value is NULL. | Ignored | Pointer to the name of the window type.
HH_SET_INFO_TYPES | Sets all the information types to be used in a window. In a tri-pane window, this will cause the navigation pane to redraw (if currently displayed) to reflect any changes in the Information Types being used. | Ignored. | Points to a HH_WINTYPE structure. The cbStruct and ainfoTypes members must be filled in.
HH_SET_INFO_TYPES | Sets all the hidden information types to be used in a window. This command will not affect any Information Types chosen by the user. In a tri-pane window, this will cause the navigation pane to redraw (if currently displayed) to reflect any changes in the Information Types being used. | Ignored. | Points to a HH_WINTYPE structure. The cbStruct and ainfoTypes members must be filled in.
HH_SYNC | Synchronizes the Table of Contents of a tri-pane window with the specified URL. This should only be used with windows thatwhich are not auto-syncnchronized. | Specifies the name of the window to sychronizesynchronize. | Specifies the URL to synchronize with. This URL does not need to be currently displayed...
HH_ADD_NAV_UI | Adds a navigational window to use in the navigational pane of a tri-pane window. | Address of an HhWinCallBack function to support the new UI. | Unique numeric value representing the UI. The UI may be switched to by specifying this value in the curNavType member of the HH_WINTYPE structure.
HH_ADD_BUTTON | Adds a button to the toolbar of a tri-pane window. | Address of an HhWinCallBack function to support the button. | Unique numeric value representing the button.
HH_KEYWORD_LOOKUP | Attempts to find the given keyword in a .HHK file. If found, the topic is displayed in the specified (or current, if not specified) window. | If NULL, the .HHK file associated with the current window is used. If a string containing a window definition is used, but not a .HHK file, then the .HHK from the specified window is used, and if the topic is found, it will be displayed in that window. If a .HHK file is specified, that file will be used. | Points to a string containing one or more keywords,keywords separated by a semi-colon.

HH_WINTYPE structure

Window types may be defined by an author and stored in a compiled HTML file, or they may be defined by a program by using the HtmlHelp API. Each window type should have a unique name. If a call to the HtmlHelp API is made specifying a window type that does not exist, then a type will be created using the indicated type name, but with default properties. When creating, modifying, or retrieving a window type, the HH_WINTYPE structure is used. The following describes this structure:

typedef struct tagHH_WINTYPE {

int cbStruct; // IN: size of this structure including all Information Types

BOOL fUniCodeStrings; // IN/OUT: TRUE if all strings are in UNICODE

LPCTSTR pszType; // IN/OUT: Name of a type of window

DWORD fsValidMembers; // IN: Bit flag of valid members (HHWIN_PARAM_)

DWORD fsWinProperties; // IN/OUT: Properties/attributes of the window (HHWIN_)

LPCTSTR pszCaption; // IN/OUT: Window title

DWORD dwStyles; // IN/OUT: Window styles

DWORD dwExStyles; // IN/OUT: Extended Window styles

RECT rcWindowPos; // IN: Starting position, OUT: current position

int nShowState; // IN: show state (e.g., SW_SHOW)

HWND hwndHelp; // OUT: window handle

HWND hwndCaller; // OUT: who called this window

HH_INFOTYPE* paInfoTypes; // IN: Pointer to an array of Information Types

// The following members are only valid if HHWIN_PROP_TRI_PANE is set

HWND hwndToolBar; // OUT: toolbar window in tri-pane window

HWND hwndNavigation; // OUT: navigation window in tri-pane window

HWND hwndHTML; // OUT: window displaying HTML in tri-pane window

int iNavWidth; // IN/OUT: width of navigation window

RECT rcHTML; // OUT: HTML window coordinates

LPCTSTR pszToc; // IN: Location of the table of contents file

LPCTSTR pszIndex; // IN: Location of the index file

LPCTSTR pszFile; // IN: Location of the html file

LPCTSTR pszHome; // IN/OUT: html file to display when Home button is clicked

DWORD fsToolBarFlags; // IN: flags controlingcontrolling the appearance of the toolbar

BOOL fExpanded; // IN: TRUE/FALSE to expand or contract, OUT: current state

int curNavType; // IN/OUT: UI to display in the navigational pane

int tabpos; // IN/OUT: NAVTAB_TOP, NAVTAB_LEFT, or NAVTAB_BOTTOM

int idNotify; // IN: ID to use for WM_NOTIFY messages

BYTE tabOrder[HH_MAX_TABS + 1]; // IN/OUT: tab order: Contents, Index, Search, History, Favorites, Reserved 1-5, Custom tabs

} HH_WINTYPE;
Member | Description
cbStruct | Specifies the size of the structure. This value must always be filled in before passing the structure to the HtmlHelp API.
fUniCodeStrings | Specifies whether the strings used in this structure are UNICODE or not.
pszType | Specifies a null-terminated string containing the name of the window type.
fsValidMembers | Specifies which members in the structure are valid. See the following Comments section for a description of this member.
fsWinProperties | Specifies the properties of the window. See the following Comments section for a description of this member.
pszCaption | Specifies a null-terminated string contain the caption to display in the title bar of the window.
dwStyles | Specifies the styles used to create the window. These styles may be ignored, combined with default styles, or used exclusively depending on the value of fsValidMembers and fsWinProperties.
dwExStyles | Specifies the extended styles used to create the window. These styles may be ignored, combined with default styles, or used exclusively depending on the value of fsValidMembers and fsWinProperties.
rcWindowPos | Specifies the coordinates of the window. When setting this value, any negative member will be ignored. For example, to change the position, but not the width and height, the left and top positions would be set and the right and bottom RECT members would be set to -1.
nShowState | Specifies the initial display state of the window.
hwndHelp | Specifies the handle of the window if the window has been created.
hwndCaller | Specifies the window to send messages to.
paInfoTypes | This specifies the Information Types to display. Each Information Type is a bit flag, with bit zero indicating whether or not all Information Types should be shown. If bit zero is not set, then all HTML Help commands that use Information Types will this information to determine what navigational UI should be displayed, and where hyperlinks should jump to.
hwndToolBar | Specifies the handle of the window containing the toolbar in a tri-pane window.
hwndNavigation | Specifies the handle of the window containing the current navigation UI in a tri-pane window.
hwndHTML | Specifies the handle of the window that displays HTML files in a tri-pane window. This window is a host for SHDOCVW.
iNavWidth | Specifies the width of the navigation pane in a tri-pane window when the tri-pane window is expanded.
rcHTML | Specifies the coordinates of the HTML pane in a tri-pane window.
pszToc | In a tri-pane window, this specifies the file or URL to use for the Table of Contents.
pszIndex | In a tri-pane window, this specifies the file or URL to use for the Index.
pszFile | In a tri-pane window, this specifies the file or URL to display in the right pane. This file will be displayed if the user clicks the Home button in the toolbar.
pszHome | In a tri-pane window, this specifies the file or URL to display in the right pane when the Home button is clicked.
fsToolBarFlags | In a tri-pane window, this determines which buttons will be displayed in the toolbar pane. See the section below describing HHWIN_BUTTON constants.
fExpanded | In a tri-pane window, this determines whether or not the navigational pane is to be shown.
curNavType | Specifies which navigational UI is displayed in the navigational pane of a tri-pane window.
tabpos | Specifies where the tabs are to be placed in the navigational pane of a tri-pane window. The tabs may be set on the top, left or bottom.
idNotify | Specifies the ID to use as the WPARAM member of WM_NOTIFY messages.
tabOrder | Specifies the order that tabs appear in the navigation pane of a Tri-pane window. Set the HHWIN_PARAM_TABORDER flag if you use this member. The first ten positions are reserved for default HTML Help tabs: Contents, Index, Search, History, Favorites, and Reserved 1-5 (for future expansion). Each byte represents the numeric position, starting with zero. For example, to put the Index tab first and the Contents tab second, you would specify tabOrder[HH_TAB_CONTENTS] = 1, and tabOrder[HH_TAB_INDEX] = 0.
cHistory | Specifies the number of history items to keep. This member is currently ignored, but will be used in the future.
pszJump1 | Specifies the URL to jump to when the Jump1 button is clicked.
pszJump1 | Specifies the URL to jump to when the Jump2 button is clicked.

The fsValidMembers member is used when modifying an existing window type, and determines which of the other members should be updated. This parameter may be a combination of one or more of the following values:
HHWIN_PARAM_PROPERTIES | The fsWinProperties member is valid.
HHWIN_PARAM_STYLES | The dwStyles member is valid.
HHWIN_PARAM_EXSTYLES | The dwExStyles member is valid.
HHWIN_PARAM_RECT | The rcWindowPos member is valid.
HHWIN_PARAM_NAV_WIDTH | The rcNavigation member is valid.
HHWIN_PARAM_SHOWSTATE | The nShowState member is valid.
HHWIN_PARAM_INFOTYPES | The ainfoTypes member is valid.
HHWIN_PARAM_TB_FLAGS | The fsToolBarFlags member is valid.
HHWIN_PARAM_EXPANSION | The fExpanded member is valid.
HHWIN_PARAM_TABPOS | The tabpos member is valid
HHWIN_PARAM_TABORDER | The tabOrder member is valid.
HHWIN_PARAM_HISTORY_COUNT | The cHistory member is valid.

The fsWinProperties member is used to define various properties for the window, and is also used to control how the window is created. This member may be a combination of one or more of the following values:
HHWIN_PROP_ONTOP | Specifies that the window is to be kept on top of every window on the desktop instead of just being on top of the caller’s window.
HHWIN_PROP_NOTITLEBAR | Specifies that the window should not contain a title bar.
HHWIN_PROP_NODEF_STYLES Specifies that no default styles should be used when creating the window. If this flag is not specified, a window will be created with the following default styles:

WS_THICKFRAME | WS_OVERLAPPED | WS_VISIBLE

HHWIN_PROP_NODEF_EXSTYLES | Specifies that no default extended styles should be used when creating the window. If this flag is used with the HHWIN_PROP_ONTOP flag, then the HHWIN_PROP_ONTOP flag will be ignored.
HHWIN_PROP_TRI_PANE | Specifies that a tri-pane window is to be created. Once a window has already been created, this flag cannot be used to change the existing window.
HHWIN_PROP_NOTB_TEXT | Specifies that the toolbar of a tri-pane window should not contain text underneath the buttons.
HHWIN_PROP_POST_QUIT | Specifies that when the help window is closed, a WM_QUIT message is posted to the calling programs message queue. This will normally cause the calling program to terminate.
HHWIN_PROP_AUTO_SYNC | Specifies that if the Contents or Index navigational pane is currently displayed, then if the user jumps to a different HTML file, the Contents or Index will scroll to the entry or keyword that points to the current URL. If the URL cannot be located in the current navigational pane, no action will be taken.
HHWIN_PROP_TRACKING | Specifies that tracking notification messages should be sent to the caller.
HHWIN_PROP_TAB_SEARCH | Specifies that a full-text search tab is to be included as one of the navigation panes in a tri-pane window.
HHWIN_PROP_TAB_HISTORY | Specified that a history tab is to be included as one of the navigation panes in a tri-pane window. This property is not supported in version 1.
HHWIN_PROP_TAB_FAVORITES | Specifies that a favorites tab is to be included as one of the navigation panes in a tri-pane windowsin a tri-pane window. This property is not supported in version 1.
HHWIN_PROP_CHANGE_TITLE | Specifies that the title bar of the HTML Help window should reflect the title of any HTML file displayed in the HTML pane.
HHWIN_PROP_TAB_ADVANCED | Specifies that an advanced search tab is to be included as one of the navigation panes of a tri-pane window.

The fsToolBarFlags member is used to specify which buttons to display in the toolbar. This member may be a combination of one or more of the following values:
HHWIN_BUTTON_EXPAND | Expand/contract button (for the navigational pane)
HHWIN_BUTTON_BACK | Back button.
HHWIN_BUTTON_FORWARD | Forward button.
HHWIN_BUTTON_STOP | Stop button.
HHWIN_BUTTON_REFRESH | Refresh button.
HHWIN_BUTTON_HOME | Home button (to the HTML file defined for the window).
HHWIN_BUTTON_HISTORY | History button.
HHWIN_BUTTON_FAVORITES | Favorites button.
HHWIN_BUTTON_TOC | Table of Contents button.
HHWIN_BUTTON_INDEX | Index button.
HHWIN_BUTTON_SEARCH | Simple search button.
HHWIN_BUTTON_HISTORY | History button.
HHWIN_BUTTON_FAVORITES | Favorites button.
HHWIN_BUTTON_JUMP1 | Jump1 button.
HHWIN_BUTTON_JUMP2 | Jump2 button

The curNavType membmermember is used to specify which navigational UI tab should be activated. This member may be one of the following values:
HHWIN_NAVTYPE_TOC | Displays the Contents tab.
HHWIN_NAVTYPE_INDEX | Displays the Index tab.

The tabpos member is used to specify where the tabs are to be placed on the navigational pane of a tri-pane window. This member may be one of the following values:
HHWIN_NAVTAB_TOP | Places the tabs at the top.
HHWIN_NAVTAB_LEFT | Places the tabs at the left.
HHWIN_NAVTAB_BOTTOM | Places the tabs at the bottom.

HH_POPUP structure

The HH_POPUP structure is used when displaying a text-only popup. Because of the speed in which they display, text-only popups should be used when no formatting is needed. The text to display may reside in a resource file, in a text string, or in a text file.

typedef struct tagHH_POPUP

{

int cbStruct; // sizeof this structure

HINSTANCE hinst; // instance handle for string resource

UINT idString; // string resource id, or text id if pszFile is specified in HtmlHelp call

LPCTSTR pszText; // used if idString is zero

POINT pt; // top center of popup window

COLORREF clrForeground; // use -1 for default

COLORREF clrBackground; // use -1 for default

RECT rcMargins; // amount of space between edges of window and text, -1 for each member to ignore

LPCTSTR pszFont; // facename, point size, char set, BOLD ITALIC UNDERLINE

} HH_POPUP;
Member Description

cbStruct

Specifies the size of the structure. This value must always be filled in before passing the structure to the HtmlHelp API.

hinst

Instance handle of the program or dll to retrieve the string resource from. Ignored if idString is zero, or a filename was passed to the HtmlHelp API.

idString

Specifies either a resource id, or a thethe topic number in a text file.

pszText

Specifies the text to display if idString is zero.

pt

Specifies where the top center of the popup should be located.

clrForeground

Specifies the RGB value to use for the foreground color. If this value is -1, the system color for window text will be used.

clrBackground

Specifies the RGB value to use for the background color. If this value is -1, the system color for window background will be used.

rcMargins

Specifies the margins to use on the left, top, right, and bottom sides of the popup. A -1 for any of the rectangle members will use the default.

pszFont

Specifies an optional text string containing: facename[,point size[,charset[,color[, BOLD ITALIC UNDERLINE]]]]. This string specifies a font, its point size, its character set, its color, and various attributes. Options may be omitted by simply specifying the next comma. For example, to create a bold, 10-pt MS Sans Serif font, the parameter value would be: MS Sans Serif, 10, , , BOLD

TRI-PANE Windows

A tri-pane window consists of three panes (child windows) consisting of a toolbar pane at the top, a navigation pane on the left, and an HTML pane that hosts SHDOCVW on the right. The navigation pane may be expanded or contracted by the user or programmatically. Expansion always enlarges the window by a fixed amount – that amount is 250 pixels by default, but may be set by the author or programmer as part of the window description.

If more then one navigational UI is specified, then a tabbed control will be used to switch between the navigational UI. By default, the tabs for this control will run vertically – but a window may be defined to have the tabs on top or the bottom.

An embedded window can take advantage of the toolbar pane without having a navigational pane by simply not including the Expand button. For example, the Help tab of the Index editor in HTML Help Workshop (displayed when editing a keyword) uses a tri-pane window without the navigation pane.

Notification Messages

If the idNotify member of the HH_WINTYPE structure is non-zero, then WM_NOTIFY messages will be sent to the last caller of the HTML Help window.
Notification | lParam | Description
HHN_NAVCOMPLETE | HHNNAVCOMPLETE* | Sent when the user successfully navigates to a URL.
HHN_TRACK | HHNTRACK* | Sent if the window has tracking properties and the user uses a toolbar button or switches navigational tabs. The message is sent before the action is taken. If the action changes to a different URL, a HHN_NAVCOMPLETE notification will be sent after this notification.

HHNNAVCOMPLETE structure

typedef struct tagHHNNAVCOMPLETE {

NMHDR hdr;

PCSTR pszUrl;

} HHNNAVCOMPLETE;
Member | Description
hdr | Standard WM_NOTIFY header
pszUrl | Multi-byte, zero terminated string specifying the URL that has been navigated to.

HHNTRACK structure

typedef struct tagHHNTRACK

{

NMHDR hdr;

PCSTR pszCurUrl; // Multi-byte, null-terminated string

int idAction; // HHACT_ value

} HHNTRACK;

Member | Description
hdr | Standard WM_NOTIFY header
pszCurUrl | Multi-byte, zero terminated string specifying the current URL before the action is taken.
idAction | Specifies the action the user is about to take. This is one of the HHACT_ constants described below.

The idAction parameter may be one of the following values:
Value | Description
HHACT_EXPAND | The user is about to expand the navigation pane.
HHACT_CONTRACT | The user is about to contract the navigation pane.
HHACT_BACK | The user clicked the Back button.
HHACT_FORWARD | The user clicked the Forward button.
HHACT_STOP | The user clicked the Stop button.
HHACT_REFRESH | The user clicked the Refresh button.
HHACT_HOME | The user clicked the Home button.
HHACT_SYNC | The user clicked the Sync button.
HHACT_OPTIONS | The user clicked the Options button.
HHACT_PRINT | The user clicked the Print button.
HHACT_TAB_CONTENTS | The user switched to the Contents tab.
HHACT_TAB_INDEX | The user switched to the Index tab.
HHACT_TAB_FIND | The user switched to the Find tab.
HHACT_TAB_HISTORY | The user switched to the History tab.
HHACT_TAB_FAVORITES | The user switched to the Favorites tab.

Keyword Lookup

A caller may use the HtmlHelp API to lookup a keyword in a .HHK file, whether or not that file is the current keyword index or not. The .HHK file to be searched can exist on its own, or it can be in a compiled HTML file. The path to the file may be preceded with %SystemRoot% to make the path relative to the Windows directory. If the file is not found, it will be searched for in the following locations (and in the following order):

  • The registry (HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\HTML Help\base filename). The filename without the path is used as the key, and the value contains the path where the file is located.
  • The Windows\help folder.
  • The [FILES] section of HH.INI. The keyword is the filename without the path, and the value is aan optionally quoted path optionally followed by a message to prompt the user if the file still cannot be found. For example: myfile.hhk="d:\myapp" Please insert the MyDisk CD into your CDROM drive.

If the filename portion of the HtmlHelp API call contains both a filename and a window type, then the window type will be used to determine what window to display the result in. This window type will overrrideoverride any window type specified in the .HHK file.

If the window type is not specified, the current window will be used (if there is one) unless the .HHK file specifies a window type. If no window type is specified either in the filename or the .HHK file, a default window type called "Keyword Lookup" will be created and used.

If the filename portion is not specified, but the window type is (for example, ">MyWindow") then the .HHK file associated with that window type will be searched.


Internet Tools & Technologies

This section describes the services and technologies provided with Internet Explorer 4.0 and explains how to exploit them in your own components and applications.

Active Desktop Interface

Asynchronous and URL Monikers

Cache Container Tool

Common Controls

Microsoft CryptoAPI 2.0

Microsoft DirectX Media SDK

Hit Logging API

HTML Clipboard Format

HTMLHelp API Reference

Hyperlinks

IE4/MSHTML Data Binding Interfaces

Information Delivery API

Microsoft Internet Component Download

Internet Explorer Address Book

Internet Mail and News Registry Layout

Internet Ratings

Internet Shortcuts API Reference

Offline Browsing

Open Software Description (OSD)

Pluggable Protocols

Predefined Protocols

Programming the Document Object Model from C/C++

Reusing the WebBrowser and MSHTML

Microsoft Script Debugger for Internet Explorer

Task Scheduler API

URL Security Zones

Microsoft Web Publishing SDK

Windows Scripting Host

Windows Shell API

WinInet API

XML Object Model


Active Desktop Interface

This article contains information on the IActiveDesktop interface that is part of the Microsoft® Windows® Shell API. This interface and its methods allow you to add, remove, and change items on the desktop.

Overview of the Active Desktop Interface

ActiveDesktop Object

IActiveDesktop Interface

Methods

Structures

Flags

Overview of the Active Desktop Interface

The Active Desktop is a feature of Microsoft Internet Explorer 4.0 that allows you to include HTML documents and items (such as ActiveX™ Controls and Java applets) directly to your desktop. The IActiveDesktop interface, which is part of the Windows Shell API, is used to programmatically add, remove, and modify the items on the desktop. Active Desktop items can also be added using a Channel Definition Format (CDF) file. For information about creating Active Desktop items and adding them with a CDF file, see Creating Active Desktop Items. For more information on CDF files, see Creating Active Channels for Internet Explorer 4.0.

Accessing the Active Desktop

To access the Active Desktop, a client application would need to create an instance of the Active Desktop object with the CoCreateInstance function and get a pointer to its IActiveDesktop interface.

The following sample shows how to get a pointer to the IActiveDesktop interface.

HRESULT hr;
IActiveDesktop *pActiveDesktop;

//Create an instance of the Active Desktop
hr = CoCreateInstance(CLSID_ActiveDesktop, NULL, CLSCTX_INPROC_SERVER,
            IID_IActiveDesktop, (void**)&pActiveDesktop);

//Insert code to call the IActiveDesktop methods

// Call the Release method
pActiveDesktop->Release();

Adding a Desktop Item

There are three methods that can be used to add a desktop item: IActiveDesktop::AddDesktopItem, IActiveDesktop::AddDesktopItemWithUI, and IActiveDesktop::AddUrl. Each desktop item added to the Active Desktop must have a different source URL.

The IActiveDesktop::AddDesktopItemWithUI and IActiveDesktop::AddUrl both provide the option to display the various user interfaces that can be displayed before adding a desktop item to the Active Desktop. The interfaces will verify if the user really wants to add the desktop item to their Active Desktop, notify the user of any security risks that are warranted by the URL security zone settings, and ask the user if the user would like to create a subscription for this desktop item. Both methods also provide a way of suppressing the user interfaces. The IActiveDesktop::AddDesktopItem method requires a call to IActiveDesktop::ApplyChanges in order to update the registry. For the IActiveDesktop::AddDesktopItemWithUI, the client application must immediately release the IActiveDesktop interface and then use the CoCreateInstance function to get an interface to an instance of the Active Desktop object that includes the newly added desktop item.

The IActiveDesktop::AddDesktopItem method will add the specified desktop item to the Active Desktop without any user interface, unless the URL security zone settings prevent it. If the URL security zone settings do not allow the desktop item to be added without prompting the user, the method will fail. IActiveDesktop::AddDesktopItem also requires a call to IActiveDesktop::ApplyChanges in order to update the registry.

The following sample demonstrates how to add a desktop item with the IActiveDesktop::AddDesktopItem method.

HRESULT hr;
IActiveDesktop *pActiveDesktop;
COMPONENT compDesktopItem;

//Create an instance of the Active Desktop
hr = CoCreateInstance(CLSID_ActiveDesktop, NULL, CLSCTX_INPROC_SERVER,
            IID_IActiveDesktop, (void**)&pActiveDesktop);

// Initialize the COMPONENT structure
compDesktopItem.dwSize = sizeof(COMPONENT);

// Insert code that adds the information about the desktop item to the COMPONENT structure

// Add the desktop item
pActiveDesktop->AddDesktopItem(&compDesktopItem,0);

// Save the changes to the registry
pActiveDesktop->ApplyChanges(AD_APPLY_ALL);

Enumerating the Desktop Items

To enumerate the desktop items currently installed on the Active Desktop, the client application needs to get the total number of desktop items installed using the IActiveDesktop::GetDesktopItemCount method and then creating a loop that retrieves the COMPONENT structure for each desktop item by calling the IActiveDesktop::GetDesktopItem method using the desktop item index.

The following sample demonstrates one way to enumerate the desktop items.

HRESULT hr;
IActiveDesktop *pActiveDesktop;
COMPONENT compDesktopItem;
int intCount;
int intIndex = 0;

//Create an instance of the Active Desktop
hr = CoCreateInstance(CLSID_ActiveDesktop, NULL, CLSCTX_INPROC_SERVER,
            IID_IActiveDesktop, (void**)&pActiveDesktop);

pActiveDesktop->GetDesktopItemCount(&intCount,0);

compDesktopItem.dwSize = sizeof(COMPONENT);

while(intIndex<=(intCount-1))
{
    //get the COMPONENT structure for the current desktop item
    pActiveDesktop->GetDesktopItem(intIndex, &compDesktopItem,0);

    //Insert code that processes the structure

    //Increment the index
    intIndex++;

    //Insert code to clean-up structure for next component
}

// Call the Release method
pActiveDesktop->Release();


Flags

This section contains the flags used by the methods of the IActiveDesktop interface.

AD_APPLY_ALL
Aggregate of the AD_APPLY_SAVE, AD_APPLY_HTMLGEN, and AD_APPLY_REFRESH values.
AD_APPLY_BUFFERED_REFRESH
AD_APPLY_FORCE
Force an Active Desktop change.
AD_APPLY_HTMLGEN
Regenerate the desktop HTML file.
AD_APPLY_REFRESH
Refresh the desktop item.
AD_APPLY_SAVE
Save the desktop item.
COMP_ELEM_ALL
Aggregate of the COMP_ELEM_* values.
COMP_ELEM_CHECKED
The item has been checked.
COMP_ELEM_DIRTY
The item has been changed, but the changes have not been saved.
COMP_ELEM_FRIENDLYNAME
The friendly name of the item.
COMP_ELEM_NOSCROLL
The item is not scrollable.
COMP_ELEM_POS_LEFT
The horizontal position of the item.
COMP_ELEM_POS_TOP
The vertical position of the item.
COMP_ELEM_POS_ZINDEX
The z-index of the item.
COMP_ELEM_SIZE_HEIGHT
The height of the item.
COMP_ELEM_SIZE_WIDTH
The width of the item.
COMP_ELEM_SOURCE
The original source of the item.
COMP_ELEM_TYPE
The item type.
COMP_TYPE_CFHTML
Compressed format HTML.
COMP_TYPE_CONTROL
The item is a control.
COMP_TYPE_HTMLDOC
The item is an HTML document.
COMP_TYPE_MAX
The maximum value of a COMP_TYPE_* flag.
COMP_TYPE_PICTURE
The item is a picture.
COMP_TYPE_WEBSITE
The item is a Web site.
COMPONENT_TOP
An izOrder value meaning the item is at the top.
WPSTYLE_CENTER
The wallpaper is centered.
WPSTYLE_MAX
The maximum value of a WPSTYLE_* flag.
WPSTYLE_STRETCH
The wallpaper is stretched to fit the entire screen.
WPSTYLE_TILE
The wallpaper is tiled.


IActiveDesktop Interface

This section contains the reference information for the IActiveDesktop interface and its methods.

IActiveDesktop


Methods

This section describes the methods exposed by the IActiveDesktop interface.

IActiveDesktop::AddDesktopItem
IActiveDesktop::AddDesktopItemWithUI
IActiveDesktop::AddUrl
IActiveDesktop::ApplyChanges
IActiveDesktop::GenerateDesktopItemHtml
IActiveDesktop::GetDesktopItem
IActiveDesktop::GetDesktopItemByID
IActiveDesktop::GetDesktopItemBySource
IActiveDesktop::GetDesktopItemCount
IActiveDesktop::GetDesktopItemOptions
IActiveDesktop::GetPattern
IActiveDesktop::GetWallpaper
IActiveDesktop::GetWallpaperOptions
IActiveDesktop::ModifyDesktopItem
IActiveDesktop::RemoveDesktopItem
IActiveDesktop::SetDesktopItemOptions
IActiveDesktop::SetPattern
IActiveDesktop::SetWallpaper
IActiveDesktop::SetWallpaperOptions


IActiveDesktop::AddDesktopItem

HRESULT AddDesktopItem(
    LPCOMPONENT pcomp,
    DWORD dwReserved
);

Adds a desktop item.

pcomp
Address of the COMPONENT structure associated with the item to be added.
dwReserved
Reserved. Must be set to zero.

If the source URL of the desktop item being added matches a desktop item already installed on the Active Desktop, this method will fail.

The desktop item is added to the desktop, but it does not save it to the registry. The client application must call IActiveDesktop::ApplyChanges separately to update the registry.


IActiveDesktop::AddDesktopItemWithUI

HRESULT AddDesktopItemWithUI(
    HWND hwnd,
    LPCOMPONENT pcomp,
    DWORD dwReserved
);

Adds a desktop item to the Active Desktop after displaying user interfaces that confirm the addition of the desktop item, verify security zone permissions, and ask if the user wants to create a subscription.

hwnd
Handle of the parent window. If NULL, the desktop item will be added without displaying any user interface.
pcomp
Address of the COMPONENT structure containing the details of the desktop item to be added.
dwReserved
Reserved. Must be set to zero.

If the source URL of the desktop item being added matches a desktop item already installed on the Active Desktop, this method will fail.

This method creates a second instance of the Active Desktop to add the desktop item, so the desktop item will not appear in the current instance. The application must call the IUnknown::Release method on this IActiveDesktop interface and the use the CoCreateInstance function to get the Active Desktop object with the newly added component.


IActiveDesktop::AddUrl

HRESULT AddUrl(
    HWND hwnd,
    LPCWSTR pszSource,
    LPCOMPONENT pcomp,
    DWORD dwFlags
);

Adds the desktop item associated with the specified URL.

hwnd
Handle to the parent window for the user interface.
pszSource
String containing the URL of the desktop item.
pcomp
Address of the COMPONENT structure containing the details of the desktop item to be added.
dwFlags
Unsigned long integer value that controls this method. Can be set to ADDURL_SILENT to add a desktop item without displaying any user interfaces.

If the source URL of the desktop item being added matches a desktop item already installed on the Active Desktop, this method will fail.

By default, this method will display some user interface and then add the desktop item to the Active Desktop. Like IActiveDesktop::AddDesktopItem, the client application must call IActiveDesktop::ApplyChanges to have the changes saved to the registry.


IActiveDesktop::ApplyChanges

HRESULT ApplyChanges(
    DWORD dwFlags
);

Applies changes to the Active Desktop and saves them in the registry.

dwFlags
Unsigned long integer value that contains the changes to be applied. Can be one of the following values:
AD_APPLY_SAVE
AD_APPLY_HTMLGEN
AD_APPLY_REFRESH
AD_APPLY_ALL
AD_APPLY_FORCE


IActiveDesktop::GenerateDesktopItemHtml

HRESULT GenerateDesktopItemHtml(
    LPCWSTR pwszFileName,
    LPCOMPONENT pcomp,
    DWORD dwReserved
);

Generates a generic HTML page containing the given desktop item.

pwszFileName
String value containing the name to store the HTML file under.
pcomp
Address of the COMPONENT structure of the desktop item to insert in the HTML page.
dwReserved
Reserved. Must be set to zero.


IActiveDesktop::GetDesktopItem

HRESULT GetDesktopItem(
    int nComponent,
    LPCOMPONENT pcomp,
    DWORD dwReserved
);

Retrieves the specified desktop item.

nComponent
Unsigned long integer value that contains the desktop item's index. The index values start at zero. Use IActiveDesktop::GetDesktopItemCount to get a count on the total number of desktop items.
pcomp
Address of the COMPONENT structure of the retrieved desktop item.
dwReserved
Reserved. Must be set to zero.

The index values will change as desktop items are added and removed from the Active Desktop. Applications cannot assume that an index value will always be associated with a particular desktop item.


IActiveDesktop::GetDesktopItemByID

HRESULT GetComponentByID(
    DWORD dwID,
    LPCOMPONENT pcomp,
    DWORD dwReserved
);

Retrieves the desktop item that matches the given identification.

dwID
Unsigned long integer value that contains the desktop item's identification.
pcomp
Address of the COMPONENT structure of the retrieved desktop item.
dwReserved
Reserved. Must be set to zero.

The desktop item's identification is returned in the dwID member of the COMPONENT structure returned from the IActiveDesktop::GetDesktopItem method. This identification is only valid until the IActiveDesktop::ApplyChanges method is called. Applications that need to get the same desktop item consistently should enumerate the desktop items using the IActiveDesktop::GetDesktopItem and IActiveDesktop::GetDesktopItemCount methods.


IActiveDesktop::GetDesktopItemBySource

HRESULT GetDesktopItemBySource (
    LPCWSTR pszSource,
    LPCOMPONENT pcomp,
    DWORD dwReserved
);

Retrieves a desktop item using its source URL.

pszSource
String value containing the source URL of the desktop item.
pcomp
Address of the COMPONENT structure that will be used to store the details about the desktop item. The size of the structure must be initialized in order for it to work properly.
dwReserved
Reserved. Must be set to zero.


IActiveDesktop::GetDesktopItemCount

HRESULT GetDesktopItemCount(
    LPINT lpiCount,
    DWORD dwReserved
);

Retrieves a count of the desktop items.

lpiCount
Address of an integer value that contains the count.
dwReserved
Reserved. Must be set to zero.

The lpiCount value can be used to enumerate all desktop items. The index values start at zero and go to lpiCount minus one.


IActiveDesktop::GetDesktopItemOptions

HRESULT GetDesktopItemOptions(
    LPCOMPONENTSOPT pco
    DWORD dwReserved
);

Retrieves the desktop item's options.

pco
Address of the COMPONENTSOPT structure containing the options that are currently set.
dwReserved
Reserved. Must be set to zero.


IActiveDesktop::GetPattern

HRESULT GetPattern(
    LPWSTR pwszPattern,
    UINT cchPattern,
    DWORD dwReserved
);

Retrieves the pattern currently being used.

pwszPattern
String value that contains a string of decimals whose bit pattern represents a picture.
cchPattern
Unsigned long integer value that contains the size of the string.
dwReserved
Reserved. Must be set to zero.


IActiveDesktop::GetWallpaper

HRESULT GetWallpaper(
    LPWSTR pwszWallpaper,
    UINT cchWallpaper,
    DWORD dwReserved
);

Retrieves the wallpaper currently being used.

pwszWallpaper
String value that contains the file name of the wallpaper.
cchWallpaper
Unsigned integer value that contains size of the string.
dwReserved
Reserved. Must be set to zero.


IActiveDesktop::GetWallpaperOptions

HRESULT GetWallpaperOptions(
    LPWALLPAPEROPT pwpo,
    DWORD dwReserved
);

Retrieves the wallpaper options.

pwpo
Address of a WALLPAPEROPT structure containing the options currently set.
dwReserved
Reserved. Must be set to zero.


IActiveDesktop

Allows a client program to manage the desktop items and wallpaper on a local computer.
Methods | Description
AddDesktopItem | Adds a desktop item.
AddDesktopItemWithUI | Adds a desktop item to the Active Desktop using a user interface.
AddUrl | Adds the desktop item associated with the specified URL.
ApplyChanges | Applies changes to the Active Desktop.
GenerateDesktopItemHtml | Generates a generic HTML page containing the given desktop item.
GetDesktopItem | Retrieves the specified desktop item.
GetDesktopItemByID | Retrieves the desktop item that matches the given identification.
GetDesktopItemBySource | Retrieves a desktop item using its source URL.
GetDesktopItemCount | Retrieves a count of the desktop items.
GetDesktopItemOptions | Retrieves the desktop item's options.
GetPattern | Retrieves the pattern currently being used.
GetWallpaper | Retrieves the wallpaper currently being used.
GetWallpaperOptions | Retrieves the wallpaper options.
ModifyDesktopItem | Modifies the desktop item.
RemoveDesktopItem | Removes the specified desktop item from the desktop.
SetDesktopItemOptions | Sets the item's options.
SetPattern | Sets the ActiveDesktop pattern.
SetWallpaper | Sets the wallpaper for the Active Desktop.
SetWallpaperOptions | Sets the wallpaper options.


IActiveDesktop::ModifyDesktopItem

HRESULT ModifyDesktopItem(
    LPCCOMPONENT pcomp,
    DWORD dwFlags
);

Modifies the desktop item.

pcomp
Address of the COMPONENT structure containing the modifications. The desktop item associated with the wszSource member of the structure will be modified.
dwFlags
Unsigned long integer value containing the flags used for the modification. Can be one of the following values:
AD_APPLY_SAVE
AD_APPLY_HTMLGEN
AD_APPLY_REFRESH
AD_APPLY_ALL
AD_APPLY_FORCE


IActiveDesktop::RemoveDesktopItem

HRESULT RemoveDesktopItem(
    LPCCOMPONENT pcomp,
    DWORD dwReserved
);

Removes the specified desktop item from the desktop.

pcomp
Address of the COMPONENT structure that specifies the item to be removed. The desktop item associated with the wszSource member of the structure will be removed.
dwReserved
Reserved. Must be set to zero.


IActiveDesktop::SetDesktopItemOptions

HRESULT SetDesktopItemOptions(
    LPCCOMPONENTSOPT pcomp,
    DWORD dwReserved
);

Sets the item's options.

pcomp
Address of the COMPONENTSOPT structure that contains the options to set.
dwReserved
Reserved. Must be set to zero.


IActiveDesktop::SetPattern

HRESULT SetPattern(
    LPCWSTR pwszPattern,
    DWORD dwReserved
);

Sets the Active Desktop pattern.

pwszPattern
String value that contains a string of decimals whose bit pattern represents a picture.
dwReserved
Reserved. Must be set to zero.


IActiveDesktop::SetWallpaper

HRESULT SetWallpaper(
    LPCWSTR pwszWallpaper,
    DWORD dwReserved
);

Sets the wallpaper for the Active Desktop.

pwszWallpaper
String value containing the file name of the wallpaper to be set.
dwReserved
Reserved. Must be set to zero.


IActiveDesktop::SetWallpaperOptions

HRESULT SetWallpaperOptions(
    LPCWALLPAPEROPT pwpo,
    DWORD dwReserved
);

Sets the wallpaper options.

pwpo
Address of the WALLPAPEROPT structure containing the options to be set.
dwReserved
Reserved. Must be set to zero.


Active Desktop Active Desktop *
  * Previous Topic: ActiveDesktop Object
  * Next Topic: IActiveDesktop Interface

Active Desktop

CLSID_ActiveDesktop

Manages the Active Desktop. Has one interface, IActiveDesktop.


ActiveDesktop Object ActiveDesktop Object *
  * Previous Topic: Active Desktop Interface
  * Next Topic: Active Desktop

ActiveDesktop Object

This section contains the reference information for the ActiveDesktop object.

Active Desktop


COMPONENT

typedef struct _tagCOMPONENT {
    DWORD dwSize;
    DWORD dwID;
    int iComponentType;
    BOOL fChecked;
    BOOL fDirty;
    BOOL fNoScroll;
    COMPPOS cpPos;
    WCHAR wszFriendlyName[MAX_PATH];
    WCHAR wszSource[INTERNET_MAX_URL_LENGTH];
} COMPONENT;

Contains the information related to a desktop item.

dwSize
Unsigned long integer value that contains the size of the structure.
dwID
Reserved. Must be set to zero. Will contain the desktop item's identification number when returned from IActiveDesktop::GetDesktopItem.
iComponentType
Integer value that indicates the item type. Can be one of the following values:
COMP_TYPE_CFHTML
COMP_TYPE_CONTROL
COMP_TYPE_HTMLDOC
COMP_TYPE_MAX
COMP_TYPE_PICTURE
COMP_TYPE_WEBSITE
fChecked
Boolean value that indicates whether the component is enabled.
fDirty
Boolean value that indicates whether the component has been modified, but has not been saved yet.
fNoScroll
Boolean value that indicates whether the component is scrollable.
cpPos
COMPPOS structure that contains the position information of the item.
wszFriendlyName
Wide character string that contains the friendly name of the item.
wszSource
Wide character string that contains the URL of the item.


COMPONENTSOPT

typedef struct _tagCOMPONENTSOPT {
    DWORD dwSize;
    BOOL fEnableComponents;
    BOOL fActiveDesktop;
} COMPONENTSOPT;

Contains the desktop item options.

dwSize
Unsigned long integer value that contains the size of the structure.
fEnableComponents
Boolean value that determines if desktop items are enabled.
fActiveDesktop
Boolean value that determines if the Active Desktop is enabled.


COMPPOS

typedef _tagCOMPPOS {
    DWORD dwSize;
    int iLeft;
    int iTop;
    DWORD dwWidth;
    DWORD dwHeight;
    int izIndex;
    BOOL fCanResize;
    BOOL fCanResizeX;
    BOOL fCanResizeY;
    int iPreferredLeftPercent;
    int iPreferredTopPercent;
} COMPPOS;

Contains the position information for a desktop item.

dwSize
Unsigned long integer value that contains the size of the structure.
iLeft
Integer value that contains the horizontal location of the top-left corner of the item, in pixels.
iTop
Integer value that contains the vertical location of the top-left corner of the item, in pixels.
dwWidth
Unsigned long integer value that contains the width of the item, in pixels.
dwHeight
Unsigned long integer value that contains the height of the item, in pixels.
izIndex
Integer value that indicates the z-order of the item.
fCanResize
Boolean value that determines if the item can be resized.
fCanResizeX
Boolean value that determines if the width of the item is adjustable.
fCanResizeY
Boolean value that determines if the height of the item is adjustable.
iPreferredLeftPercent
Integer value that indicates the preferred horizontal distance between the top-left corner of the screen and the top-left corner of the item as a percentage of the screen.
iPreferredTopPercent
Integer value that indicates the preferred vertical distance between the top-left corner of the screen and the top-left corner of the item as a percentage of the screen.


Structures

This section describes the structures used by the methods of the IActiveDesktop interface.
COMPONENT
COMPONENTSOPT
COMPPOS
WALLPAPEROPT


WALLPAPEROPT

typedef struct _tagWALLPAPEROPT {
    DWORD dwSize;
    DWORD dwStyle;
} WALLPAPEROPT;

Contains the wallpaper options.

dwSize
Unsigned long integer value that contains the size of the WALLPAPEROPT structure.
dwStyle
Unsigned long integer value that contains the wallpaper style. Can be one of the following values:
WPSTYLE_CENTER
WPSTYLE_TILE
WPSTYLE_STRETCH
WPSTYLE_MAX


Internet Explorer Address Book

Microsoft® Internet Explorer Address Book is an application and service that helps users keep track of people. It has a local database and a user interface for finding and editing information about people, and it can perform queries against network directory servers using the Internet-standard (LDAP) protocol. There are two ways users can access the Address Book from the Start Menu. They can select Programs, select Internet Explorer, and then select Address Book, or they can select Find and then select People. Other applications can also use Internet Explorer Address Book. For example, Microsoft Outlook Express uses Internet Explorer Address Book as its e-mail address book. Internet Explorer Address Book offers interfaces that enable other applications to directly use its database and its user interface services.

For more information on Internet Explorer Address Book, please see:

Internet Explorer Address Book File Location

Interfaces

Functions

Structures

Internet Explorer Address Book Files and Locations

The collection of interfaces available to the developer from Internet Explorer Address Book represents the programmatic techniques necessary to implement the functionality of Internet Explorer Address Book.

  • Registering Internet Explorer Address Book
  • Creating an Instance of Internet Explorer Address Book
  • Loading Wab32.dll at Run Time
  • Using Internet Explorer Address Book Files Under Internet Explorer 3.0x

Registering Internet Explorer Address Book

If you plan to have your application use Internet Explorer Address Book, your application must register itself for using the Wab32.dll as a shared DLL. This will prevent the Wab32.dll from being inadvertently uninstalled while your application is still using it. To do this, you need to increment the reference count of the Wab32.dll in the SharedDLLs section in the registry under HKLM\Software\Microsoft\Windows\CurrentVersion\SharedDLLs.

First get the full path of the installed Wab32.dll from:

HKLM\Software\Microsoft\WAB\DLLPath

The default value under this key gives the path of any WAB DLL installed on the computer. (This DLL path is defined in Wabapi.h as WAB_DLL_PATH_KEY; if you are including Wabapi.h in your application, just use the defined WAB_DLL_PATH_KEY symbol as the name of the key to open.) If this key does not exist, the system has a pre-Internet Explorer 4.0 version of Internet Explorer Address Book and you do not need to do any reference counting on the DLL.

If the above key exists, look under:

HKLM\Software\Microsoft\Windows\CurrentVersion\SharedDLLs

Look for the value of <Full WAB32 Path>. If this value doesn't exist, create it using the registry API. This is a DWORD value. The content of this value is a reference count representing the number of clients registered to use Internet Explorer Address Book. You should read the reference count from the value, increment it by one, and then save the incremented value back to the registry.

Loading Wab32.dll at Run Time

On systems that have Internet Explorer 3.0x or earlier, the Wab32.dll file exists in the windows\system directory. However, on Internet Explorer 4.0 and later platforms, Wab32.dll exists elsewhere, and your application cannot assume it will be able to load the DLL by just using LoadLibrary("wab32.dll"). You should also not statically link your application to Wab32.dll because it might not necessarily be on the path.

Under Internet Explorer 4.0, Wab32.dll is set in the registry in the following location:

HKLM\Software\Microsoft\WAB\DLLPath

The only reason to call LoadLibrary("wab32.dll") is if this key does not exist or if the path set in this key is invalid.

The following sample code shows how to run LoadLibrary on Internet Explorer Address Book.

const static TCHAR lpszWABRegPathKey[] = TEXT("Software\\Microsoft\\WAB\\DLLPath");
const static TCHAR lpszWABDll[] = TEXT("WAB32.dll");

// GetWABDllPath - loads the WAB DLL path from the registry
// szPath - ptr to buffer
// cb - sizeof buffer
//
void GetWABDllPath(LPTSTR szPath, ULONG cb)
{
    DWORD  dwType = 0;
    ULONG  cbData = cb;
    HKEY hKey = NULL;
    if(szPath)
    {
        *szPath = '\0';
        if (ERROR_SUCCESS == RegOpenKeyEx( HKEY_LOCAL_MACHINE,
            lpszWABRegPathKey, 0, KEY_READ, &hKey))
            RegQueryValueEx( hKey, "", NULL, &dwType, (LPBYTE) szPath, &cbData);
    }
    if(hKey) RegCloseKey(hKey);
    return;
}

// LoadLibrary_WABDll() - Load the WAB library based on the WAB DLL path
//
HINSTANCE LoadLibrary_WABDll()
{
    TCHAR  szWABDllPath[MAX_PATH];
    HINSTANCE hinst = NULL;

    GetWABDllPath(szWABDllPath, sizeof(szWABDllPath));

    return(hinst = LoadLibrary( (lstrlen(szWABDllPath)) ? szWABDllPath : lpszWABDll ));
}

Creating an Instance of Internet Explorer Address Book

To create and initialize the first instance of Internet Explorer Address Book, use the following sample code as a guide.

LPWABOPEN lpfnWABOpen = NULL;   // defined in WABAPI.H
HINSTANCE hinstWAB = NULL;
//
// Initialize Internet Explorer Address Book and get an instance of IWABObject and IAddrBook
//
HRESULT InitWAB(LPWABOBJECT * lppWABObject,
   LPADRBOOK * lppAdrBook)
{
    HRESULT hr = E_FAIL;
    hinstWAB = LoadLibrary_WABDll();
  if(hinstWAB)
    {
    lpfnWABOpen = (LPWABOPEN) GetProcAddress(hinstWAB, "WABOpen");
  if(lpfnWABOpen)
    hr = lpfnWABOpen(lppAdrBook, lppWABObject, NULL, 0);
    }
 return hr;
}

Using Internet Explorer Address Book Files Under Internet Explorer 3.0x

In Internet Explorer 3.0x installations, the default location of Wab32.dll is in the Windows system directory.

<Windows System Directory>\WAB32.dll

When Internet Explorer 4.0 is installed, the file Wab32.dll is renamed Wab32.ie3 so the old version of the file will not conflict with the newer versions installed by Internet Explorer 4.0 setup. Should it become necessary to uninstall, the old files are given back their original names so that users can revert back to their exact pre-Internet Explorer 4.0 settings.

An application that will be working with Wab32.dll under both Internet Explorer 4.0 and Internet Explorer 3.0x should not rely on being able to find Wab32.dll on the path. To see how you can write a single piece of code that can load the WAB32.dll library under both Internet Explorer 4.0 and Internet Explorer 3.0, refer to the sample code from the previous section, Loading Wab32.dll at Run Time.


Internet Explorer Address Book Functions

This section describes the functions implemented by the Internet Explorer Address Book.

The Internet Explorer Address Book implements the WABOpen and WabOpenEx functions, that are used to access the interfaces included in the address book.

  • WABOpen
  • WABOpenEx


WABOpen

HRESULT WABOpen(
    LPADRBOOK   * lppAdrBook,
    LPWABOBJECT * lppWABObject,
    LPWAB_PARM    lpWP,          // Can be null
    DWORD         Reserved2
);

Gives access to the address book through a number of object interfaces. The root interface is IAddrBook, which is a subset of the MAPI implementation of IAddrBook.

  • Returns S_OK if successful.
lppAdrBook
Returned IAddrBook interface.
lppWABObject
Returned IWABObject interface.
lpWP
Address of a WAB_PARAM structure. (This value can be null.)
Reserved2
Reserved; must be zero.

Back to top


WABOpenEx

HRESULT WABOpenEx(
    LPADRBOOK      * lppAdrBook,
    LPWABOBJECT    * lppWABObject,
    LPWAB_PARM       lpWP,          // Can be null
    DWORD            Reserved2,
    ALLOCATEBUFFER * lpfnAllocateBuffer,
    ALLOCATEMORE   * lpfnAllocateMore,
    FREEBUFFER     * lpfnFreeBuffer
    );

Gives access to the address book through a number of object interfaces. The root interface is IAddrBook, which is a subset of the MAPI implementation of IAddrBook. This function also specifies the memory allocation functions that Internet Explorer Address Book uses to allocate all buffers returned to the client. If you pass in one allocation routine, you must pass them all.

Note When WABOpenEx has been called specifying memory allocation routines, these routines globally replace Internet Explorer Address Book internal routines for this process. Other threads can still call WABOpen, but the memory will still be allocated with those routines previously passed to WABOpenEx. Unless you really need the additional functionality, use WABOpen.

  • Returns S_OK if successful.
lppAdrBook
Returned IAddrBook interface.
lppWABObject
Returned IWABObject interface.
lpWP
Address of a WAB_PARAM structure. (This value can be null.)
Reserved2
Reserved; must be zero.
lpfnAllocateBuffer
Allocation function in the style of MAPIAllocateBuffer. Can be NULL to use Internet Explorer Address Book internal routines.
lpfnAllocateMore
Allocation function in the style of MAPIAllocateMore. Can be NULL to use Internet Explorer Address Book internal routines.
lpfnFreeBuffer
Buffer function in the style of MAPIFreeBuffer. Can be NULL to use Internet Explorer Address Book internal routines.

Back to top


Internet Explorer Address Book Interfaces

Internet Explorer Address Book exports one API, WABOpen. This API gives access to the address book through a number of object interfaces. The root interface is IAddrBook, which is a subset of the MAPI implementation of IAddrBook.

These interfaces are based on the address book interface exposed by Extended MAPI 1.0, but Internet Explorer Address Book does not use or require MAPI in any way. OLE is used only for its user interface functionality, such as drag and drop and shell integration. Nothing in OLE is loaded until it is needed.

The IUnknown interface allows clients to get pointers to other interfaces on a given object through the IUnknown::QueryInterface method, and manage the existence of the object through the IUnknown::AddRef and IUnknown::Release methods. All other COM interfaces are inherited, directly or indirectly, from IUnknown. Therefore, the three methods in IUnknown are the first entries in the vtable for every interface.

In a future release, these objects may be exposed to applications that want an OLE Automation interface. For additional information on the IUnknown interface methods, see the Platform SDK.

The following sections describe the Internet Explorer Address Book interfaces and methods.

  • IABContainer
  • IABTable
  • IAddrBook
  • IDistList
  • IMailUser
  • IWABObject


IABContainer::CopyEntries IABContainer::CopyEntries *
  * Previous Topic: IABContainer
  * Next Topic: IABContainer::CopyProps

IABContainer::CopyEntries

Currently not implemented in Internet Explorer Address Book.

Back to top


IABContainer::CopyProps IABContainer::CopyProps *
  * Previous Topic: IABContainer::CopyEntries
  * Next Topic: IABContainer::CopyTo

IABContainer::CopyProps

Currently not implemented in Internet Explorer Address Book.

Back to top


IABContainer::CopyTo IABContainer::CopyTo *
  * Previous Topic: IABContainer::CopyProps
  * Next Topic: IABContainer::CreateEntry

IABContainer::CopyTo

Currently not implemented in Internet Explorer Address Book.

Back to top


IABContainer::CreateEntry

HRESULT CreateEntry(
    ULONG       cbEntryID,
    LPENTRYID   lpEntryID,
    ULONG       ulCreateFlags,
    LPMAPIPROP  lppMAPIPropEntry
);

Creates a new entry in the address book container. Internet Explorer Address Book supports creating new address book objects IDistList for a distribution list and IMailUser for a messaging user. Internet Explorer Address Book might support creation of subcontainers in a future version.

  • Returns S_OK if successful.
cbEntryID
Size, in bytes, of the existing entry identifier to copy from, in the lpEntryID parameter.
lpEntryID
Entry identifier of the object to copy from.
ulCreateFlags
Bitmask of flags that control how entry creation is performed. The following flags can be set:
CREATE_CHECK_DUP_LOOSE
Indicates a loose level should be used for duplicate entry checking, which returns more matches than setting a strict level with the CREATE_CHECK_DUP_STRICT flag. For example, a provider can define a loose match as any two entries having the same display name.
CREATE_CHECK_DUP_STRICT
Indicates a strict level should be used for duplicate entry checking, which returns fewer matches than setting a loose level with the CREATE_CHECK_DUP_LOOSE flag. For example, a provider can define a strict match as any two entries having the same display name and messaging address.
CREATE_REPLACE
Indicates that duplicate entries replace existing entries within a container.
lppMAPIPropEntry
Returned property interface to a new object.

These flags are valid only for the instance of the object returned by CreateEntry. There is no way in the API to get the SetProps or the SaveChanges method to check for duplicates on an object returned by OpenEntry. To do duplicate checking on SaveChanges of an object returned by OpenEntry, the caller would have to do the following:

  1. Modify any of the name fields in the user interface: PR_SURNAME, PR_GIVEN_NAME, PR_COMPANY_NAME, or PR_DISPLAYNAME.
  2. Delete the old contact.
  3. Use CreateEntry to create a new entry with the CREATE_CHECK_DUP_LOOSE flag, set the properties, and save the changes. On failure, restore the original entry.

Back to top


IABContainer::DeleteEntries

HRESULT DeleteEntries(
    LPENTRYLIST   lpEntries,
    ULONG         ulFlags
);

Removes one or more entries from the address book container.

  • Returns S_OK if successful.
lpEntries
ENTRYLIST structure containing identifiers of entries to be deleted.
ulFlags
Reserved; must be zero.

Back to top


IABContainer::DeleteProps IABContainer::DeleteProps *
  * Previous Topic: IABContainer::DeleteEntries
  * Next Topic: IABContainer::GetContentsTable

IABContainer::DeleteProps

Currently not implemented in Internet Explorer Address Book.

Back to top


IABContainer::GetContentsTable

HRESULT GetContentsTable(
    ULONG    ulFlags,
    LPMAPITABLE FAR *  lppTable
);

Returns a pointer to the contents table of the container.

  • Returns one of the following values:
    S_OK | The contents table was successfully retrieved.
    MAPI_E_BAD_CHARWIDTH | Either the MAPI_UNICODE flag was set and the implementation does not support Unicode, or MAPI_UNICODE was not set and the implementation only supports Unicode.
    MAPI_E_NO_SUPPORT | The container has no contents and cannot provide a contents table.
ulFlags
Bitmask of flags that provide the ability to specify the returned text type. Can be one of the following:
MAPI_DEFERRED_ERRORS | Not supported by Internet Explorer Address Book.
MAPI_UNICODE | Indicates the returned strings are in Unicode format. If the MAPI_UNICODE flag is not set, the strings are in ANSI format. Not supported in the first version of Internet Explorer Address Book.
lppTable
Address of the table object containing the contents table.

Back to top


IABContainer::GetHierarchyTable IABContainer::GetHierarchyTable *
  * Previous Topic: IABContainer::GetContentsTable
  * Next Topic: IABContainer::GetIDsFromNames

IABContainer::GetHierarchyTable

Currently not implemented in Internet Explorer Address Book.

Back to top


IABContainer::GetIDsFromNames IABContainer::GetIDsFromNames *
  * Previous Topic: IABContainer::GetHierarchyTable
  * Next Topic: IABContainer::GetLastError

IABContainer::GetIDsFromNames

Currently not implemented in Internet Explorer Address Book.

Back to top


IABContainer::GetLastError IABContainer::GetLastError *
  * Previous Topic: IABContainer::GetIDsFromNames
  * Next Topic: IABContainer::GetNamesFromIDs

IABContainer::GetLastError

Currently not implemented in Internet Explorer Address Book.

Back to top


IABContainer::GetNamesFromIDs IABContainer::GetNamesFromIDs *
  * Previous Topic: IABContainer::GetLastError
  * Next Topic: IABContainer::GetPropList

IABContainer::GetNamesFromIDs

Currently not implemented in Internet Explorer Address Book.

Back to top


IABContainer::GetPropList IABContainer::GetPropList *
  * Previous Topic: IABContainer::GetNamesFromIDs
  * Next Topic: IABContainer::GetProps

IABContainer::GetPropList

Currently not implemented in Internet Explorer Address Book.

Back to top


IABContainer::GetProps IABContainer::GetProps *
  * Previous Topic: IABContainer::GetPropList
  * Next Topic: IABContainer::GetSearchCriteria

IABContainer::GetProps

Currently not implemented in Internet Explorer Address Book.

Back to top


IABContainer::GetSearchCriteria IABContainer::GetSearchCriteria *
  * Previous Topic: IABContainer::GetProps
  * Next Topic: IABContainer::OpenEntry

IABContainer::GetSearchCriteria

Currently not implemented in Internet Explorer Address Book.

Back to top


IABContainer

The methods that are included within the IABContainer interface provide the mechanisms for creating, deleting, searching, and modifying address book entries. The organization of the method list for IABContainer is arranged in v-table order.
IABContainer methods
GetLastError
SaveChanges
GetProps
GetPropList
OpenProperty
SetProps
DeleteProps
CopyTo
CopyProps
GetNamesFromIDs
GetIDsFromNames
GetContentsTable
GetHierarchyTable
OpenEntry
SetSearchCriteria
GetSearchCriteria
CreateEntry
CopyEntries
DeleteEntries
ResolveNames


IABContainer::OpenEntry

HRESULT OpenEntry(
    ULONG         cbEntryID,
    LPENTRYID     lpEntryID,
    LPCIID        lpInterface,
    ULONG         ulFlags,
    ULONG FAR     *lpulObjType,
    LPUNKNOWN FAR *lppUnk
);

Opens a child container object contained in the open container and returns a pointer to the object to provide further access.

  • Returns S_OK if successful.
cbEntryID
Count of bytes in the entry identifier pointed to by the lpEntryID parameter.
lpEntryID
Address of the entry identifier of the object to open. If lpEntryID is set to NULL, the top-level container in the container's hierarchy is opened.
lpInterface
Address of the interface identifier (IID) representing the interface to be used to access the object. Passing NULL results in the identifier for the object's standard interface being returned. For messages, the standard interface is IMessage; for folders, it is IMAPIFolder. The standard interfaces for address book objects are IDistList for a distribution list and IMailUser for a messaging user.
ulFlags
Bitmask of flags that control how the object is opened. The following flags can be used:
MAPI_BEST_ACCESS | Requests that the object be opened with the maximum network permissions allowed for the user and the maximum client application access. For example, if the client has read/write access, the object should be opened with read/write access; if the client has read-only access, the object should be opened with read-only access.
MAPI_DEFERRED_ERRORS | Not supported by Internet Explorer Address Book at this time.
MAPI_MODIFY | Requests read/write access. By default, objects are opened with read-only access, and clients should not work on the assumption that read/write access has been granted.
lpulObjType
Address of the opened object's type.
lppUnk
Address of a pointer to the interface implementation to use to access the open object.

Back to top


IABContainer::OpenProperty IABContainer::OpenProperty *
  * Previous Topic: IABContainer::OpenEntry
  * Next Topic: IABContainer::ResolveNames

IABContainer::OpenProperty

Currently not implemented in Internet Explorer Address Book.

Back to top


IABContainer::ResolveNames

HRESULT ResolveNames(
    LPSPropTagArray    lpPropTagArray,
    ULONG              ulFlags,
    LPADRLIST          lpAdrList,
    LPFlagList         lpFlagList
);

Resolves entries against the address book container.

  • Returns S_OK if successful.
lpPropTagArray
SPropTagArray structure that specifies the set of properties to be included in the returned ADRLIST structure. Pass NULL to return the default columns.
ulFlags
MAPI_UNICODE flag, which indicates the returned strings of the default column set are in Unicode format. If the MAPI_UNICODE flag is not set, the strings are in ANSI format.

Note Must be zero in the first version of Internet Explorer Address Book.

lpAdrList
Input-output parameter that on input points to an ADRLIST structure containing the address list of entries whose names need to be resolved. On output, this parameter returns the list of resolved names.
lpFlagList
Input-output parameter containing an array of flags; each flag corresponds to an entry in lpAdrList and provides the name-resolution status for that particular entry. The flags in the lpFlagList parameter are in the same order as the entries in lpAdrList. The following flags can be set:
MAPI_AMBIGUOUS | Indicates that the corresponding entry is resolved, but that it did not resolve to a unique entry identifier. If this flag is returned, other containers should ignore this entry when the lpAdrList is passed to them for further name resolution.
MAPI_RESOLVED | Indicates that the corresponding entry has been resolved to a unique entry identifier. If this flag is returned, other containers should ignore this entry in further resolution.
MAPI_UNRESOLVED | Indicates that the corresponding entry is unresolved. Another container can attempt to resolve this entry.

This method takes the address list passed in lpAdrList and tries to resolve all the entries that have their corresponding MAPI_UNRESOLVED flag set in lpFlagList. Entries in lpAdrList that lack the PR_ENTRYID property are considered unresolved.

The array of flags this method returns in lpFlagList is used to track the results of the name resolution operation; the array shows for each entry name whether it is resolved or unresolved or matches more than one entry. If, after looking at an unresolved entry, a container can match that entry uniquely, ResolveNames sets the flag for that entry in lpFlagList to MAPI_RESOLVED and adds the PR_ENTRYID property for that entry to that entry's ADRENTRY structure in the address list in lpAdrList. If a container contains more than one entry that matches a given unresolved entry, ResolveNames sets the flag for the unresolved entry in lpFlagList to MAPI_AMBIGUOUS and leaves that entry's ADRENTRY alone.

If the ResolveNames method is unable to return all the properties requested for an unresolved entry, and these properties don't exist in the ADRENTRY structure passed in, it sets the property type of each property not returned to PT_ERROR. Any property columns that are already included for an entry are retained if that entry is resolved.

Note The ADRENTRY items in ADRLIST should be separately allocated, not allocated with AllocateMore. When ResolveNames replaces an entry, it expects to free the ADRENTRY structure by using FreeBuffer and allocate a new one by using AllocateBuffer.

Back to top


IABContainer::SaveChanges IABContainer::SaveChanges *
  * Previous Topic: IABContainer::ResolveNames
  * Next Topic: IABContainer::SetProps

IABContainer::SaveChanges

Currently not implemented in Internet Explorer Address Book.

Back to top


IABContainer::SetProps IABContainer::SetProps *
  * Previous Topic: IABContainer::SaveChanges
  * Next Topic: IABContainer::SetSearchCriteria

IABContainer::SetProps

Currently not implemented in Internet Explorer Address Book.

Back to top


IABContainer::SetSearchCriteria IABContainer::SetSearchCriteria *
  * Previous Topic: IABContainer::SetProps
  * Next Topic: IABTable

IABContainer::SetSearchCriteria

Currently not implemented in Internet Explorer Address Book.

Back to top


IABTable::Abort IABTable::Abort *
  * Previous Topic: IABTable
  * Next Topic: IABTable::Advise

IABTable::Abort

Currently not implemented by Internet Explorer Address Book.

Back to top


IABTable::Advise IABTable::Advise *
  * Previous Topic: IABTable::Abort
  * Next Topic: IABTable::CollapseRow

IABTable::Advise

Currently not implemented by Internet Explorer Address Book.

Back to top


IABTable::CollapseRow IABTable::CollapseRow *
  * Previous Topic: IABTable::Advise
  * Next Topic: IABTable::CreateBookmark

IABTable::CollapseRow

Currently not implemented by Internet Explorer Address Book.

Back to top


IABTable::CreateBookmark

HRESULT CreateBookmark(
    BOOKMARK FAR * lpbkPosition
);

Creates the address of the current position of the table cursor so a client can return to that position even when the table is updated. The method that calls this method must clean up by freeing the bookmark with FreeBookmark.

  • Returns S_OK if successful, or MAPI_E_UNABLE_TO_COMPLETE if the requested operation could not be completed.
lpbkPosition
Address of the returned bookmark's 32-bit bookmark value.

Back to top


IABTable::ExpandRow IABTable::ExpandRow *
  * Previous Topic: IABTable::CreateBookmark
  * Next Topic: IABTable::FindRow

IABTable::ExpandRow

Currently not implemented by Internet Explorer Address Book.

Back to top


IABTable::FindRow

HRESULT FindRow(
    LPSRestriction  lpRestriction,
    BOOKMARK  BkOrigin,
    ULONG     ulFlags
);

Find the next row in a table that contains a property matching the specified criteria.

  • Returns one of the following values:
    S_OK | The find operation was successful.
    MAPI_E_INVALID_BOOKMARK | The bookmark in the BkOrigin parameter is invalid because it has been removed or because it is beyond the last row requested.
    MAPI_E_NOT_FOUND | No rows were found that matched the restriction.
    MAPI_W_POSITION_CHANGED | The call succeeded, but the bookmark used in the operation is no longer set at the same row as when it was last used; if the bookmark has not been used, it is no longer in the same position as when it was created. When this warning is returned, the call should be handled as successful. To test for this warning, use the FAILED macro.
lpRestriction
Address of an SRestriction structure that describes the search criteria.
BkOrigin
Bookmark identifying the row where FindRow should begin its search. A bookmark can be created using the CreateBookmark method, or one of the following predefined values can be passed:
BOOKMARK_BEGINNING | Searches from the beginning of the table
BOOKMARK_CURRENT | Searches from the row in the table where the cursor is located.
BOOKMARK_END | Searches from the end of the table.
ulFlags
Bitmask of flags that control the direction of the search. The following flag can be set:
DIR_BACKWARD Searches backward from the row identified by the bookmark.

Back to top


IABTable::FreeBookmark

HRESULT FreeBookmark(
    BOOKMARK bkPosition
);

Provides the ability to free a bookmark that was created by CreateBookmark.

  • Returns S_OK if successful, or MAPI_E_INVALID_BOOKMARK if the specified bookmark does not exist.
bkPosition
Address of the bookmark to free.

Back to top


IABTable::GetCollapseState IABTable::GetCollapseState *
  * Previous Topic: IABTable::FreeBookmark
  * Next Topic: IABTable::GetLastError

IABTable::GetCollapseState

Currently not implemented by Internet Explorer Address Book.

Back to top


IABTable::GetLastError IABTable::GetLastError *
  * Previous Topic: IABTable::GetCollapseState
  * Next Topic: IABTable::GetRowCount

IABTable::GetLastError

Currently not implemented by Internet Explorer Address Book.

Back to top


IABTable::GetRowCount

HRESULT GetRowCount(
    ULONG  ulFlags,
    ULONG  FAR *lpulCount
);

Returns the total number of rows in a table view.

  • Returns one of the following values:
    S_OK | The row count was successfully returned.
    MAPI_E_BUSY | Another operation is in progress that prevents the row count retrieval operation from starting. Either the operation in progress should be allowed to complete, or it should be stopped.
    MAPI_E_NO_SUPPORT | The table cannot calculate the number of rows.
    MAPI_W_APPROX_COUNT | The call succeeded, but an approximate row count was returned because the exact row count could not be determined, possibly due to memory constraints. To test for this warning, use the FAILED macro.
ulFlags
Reserved; must be zero.
lpulCount
Address of the number of rows in the table.

Back to top


IABTable::GetStatus IABTable::GetStatus *
  * Previous Topic: IABTable::GetRowCount
  * Next Topic: IABTable::QueryColumns

IABTable::GetStatus

Currently not implemented by Internet Explorer Address Book.

Back to top


IABTable

This interface is based upon the IMAPITable interface. This interface is used for contents tables of Internet Explorer Address Book containers and distribution lists. The organization of the method list for IABTable is arranged in v-table order.
IABTable methods
GetLastError
Advise
Unadvise
GetStatus
SetColumns
QueryColumns
GetRowCount
SeekRow
SeekRowApprox
QueryPosition
FindRow
Restrict
CreateBookmark
FreeBookmark
SortTable
QuerySortOrder
QueryRows
Abort
ExpandRow
CollapseRow
WaitForCompletion
GetCollapseState
SetCollapseState


IABTable::QueryColumns

HRESULT QueryColumns(
    ULONG  ulFlags,
    LPSPropTagArray  FAR * lpPropTagArray
);

Returns a list of columns for the table.

  • Returns one of the following values:
    S_OK | The column set was successfully returned.
    MAPI_E_BUSY | Another operation is in progress that prevents the column set retrieval operation from starting. Either the operation in progress should be allowed to complete, or it should be stopped.
ulFlags
Bitmask of flags that indicate which column set should be returned. The following flag can be set:
TBL_ALL_COLUMNS Returns all available columns.
lpPropTagArray
Address of an SPropTagArray structure containing the property tags for the column set.

Back to top


IABTable::QueryPosition

HRESULT QueryPosition(
    ULONG FAR * lpulRow,
    ULONG FAR * lpulNumerator,
    ULONG FAR * lpulDenominator
);

Gets the current table cursor position, based on a fractional value.

  • Returns S_OK if the method returned valid values in lpulRow, lpulNumerator, and lpulDenominator.
lpulRow
Address of the value that contains the current row number. The row numbers are zero-based in position; row zero is the first row.
lpulNumerator
Address of the value that contains the fractional numerator part of the table position.
lpulDenominator
Address of the value that contains the fractional denominator part of the table position. The lpulDenominator parameter cannot be zero.

Back to top


IABTable::QueryRows

HRESULT QueryRows(
    LONG lRowCount,
    ULONG ulFlags,
    LPSRowSet FAR * lppRows
);

Gets rows of data from a table.

  • Returns one of the following values:
    S_OK | The rows were successfully returned.
    MAPI_E_BUSY | Another operation is in progress that prevents the row retrieval operation from starting. Either the operation in progress should be allowed to complete, or it should be stopped.
    MAPI_E_INVALID_PARAMETER | The lRowCount parameter is set to zero.
lRowCount
Number of rows requested. If positive, rows are read starting at the current position and reading forward. If negative, the cursor position moves backward the indicated number of rows, then reads in forward order.
ulFlags
Flags specifying advancement of the cursor operation. TBL_NOADVANCE prevents the cursor from advancing. Default is that the cursor will advance past the last returned row.
lppRows
Returned SRowSet structure. This buffer must be freed by the caller according to the rules specified in the following comments.

The cRows member in the SRowSet structure returned in lppRows indicates the number of rows returned. If zero rows are returned, there are no more rows to return.

Freeing of the SRowSet structure returned by QueryRows is unusual in that each row must be freed independently; the rows are not allocated with AllocateMore. Memory used for the properties held in the SRow structures that make up the SRowSet in the lppRows parameter and for the rgPropVals members of the ADRENTRY structure is separately allocated for each row, and memory for each row must be separately freed by a call to MAPIFreeBuffer. The SRowSet structure itself must also be freed. Thus, to free all the memory returned for 10 rows requires 11 calls to FreeBuffer. This process might seem complex, but freeing memory for each row separately enables implementations to free different rows at different times. However, when a call to QueryRows returns zero, indicating the beginning or end of the table, only the SRowSet structure itself needs to be freed.

Back to top


IABTable::QuerySortOrder

HRESULT QuerySortOrder(
    LPSSortOrderSet FAR * lppSortCriteria
);

Retrieves the current sort order for the table.

  • Returns one of the following values:
    S_OK | The current sort order was successfully returned.
    MAPI_E_BUSY | Another operation is in progress that prevents the sort order retrieval operation from starting. Either the operation in progress should be allowed to complete, or it should be stopped.
lppSortCriteria
Address of the SSortOrderSet structure holding the current sort order.

Back to top


IABTable::Restrict

HRESULT Restrict(
    lpRestriction,
    ulFlags
);

Applies a restriction to a table, reducing the rows visible to only those matching the restriction criteria.

  • Returns one of the following values:
    S_OK | The filter was successfully applied.
    MAPI_E_BUSY | Another operation is in progress that prevents the restriction operation from starting. Either the operation in progress should be allowed to complete, or it should be stopped.
    MAPI_E_TOO_COMPLEX | The table cannot perform the operation because the particular filter pointed to by the lpRestriction parameter is too complicated.
lpRestriction
Address of an SRestriction structure defining the conditions of the restriction. Passing NULL removes the current restriction.
ulFlags
Flags specifying asynchronous operation. For Internet Explorer Address Book, this value must be zero.

Back to top


IABTable::SeekRow

HRESULT SeekRow(
    BOOKMARK bkOrigin,
    LONG lRowCount,
    LONG FAR * lplRowsSought
);

Moves the table cursor to a specific position.

  • Returns one of the following values:
    S_OK | The seek operation was successful.
    MAPI_E_BUSY | Another operation is in progress that prevents the row seeking operation from starting. Either the operation in progress should be allowed to complete, or it should be stopped.
    MAPI_E_INVALID_BOOKMARK | The bookmark specified in the bkOrigin parameter is invalid because it has been removed or because it is beyond the last row requested.
    MAPI_W_POSITION_CHANGED | The call succeeded, but the bookmark specified in the bkOrigin parameter is no longer set at the same row as when it was last used. If the bookmark has not been used, it is no longer in the same position as when it was created. When this warning is returned, the call should be handled as successful. To test for this warning, use the FAILED macro.
bkOrigin
Bookmark identifying the starting position for the seek operation. A bookmark can be created using the CreateBookmark method, or one of the following predefined values can be passed:
BOOKMARK_BEGINNING | Starts the seek operation from the beginning of the table.
BOOKMARK_CURRENT | Starts the seek operation from the row in the table where the cursor is located.
BOOKMARK_END | Starts the seek operation from the end of the table.
lRowCount
Signed count of the number of rows to move, starting from the bookmark identified by the bkOrigin parameter.
lplRowsSought
If lplRowsSought is a valid pointer on input, on output it points to the number of rows that were processed in the seek operation. If lplRowsSought is NULL on input, the indication is the caller is not interested in the number of rows processed, and nothing is returned on output.

Back to top


IABTable::SeekRowApprox

HRESULT SeekRowApprox(
    ULONG ulNumerator,
    ULONG ulDenominator
);

Moves the cursor to an approximate fractional position in a table.

  • Returns one of the following values:
    S_OK | The seek operation was successful.
    MAPI_E_BUSY | Another operation is in progress that prevents the row seeking operation from starting. Either the operation in progress should be allowed to complete, or it should be stopped.
ulNumerator
Numerator of the fraction representing the table position. If the ulNumerator parameter is zero, it points to the beginning of the table regardless of the denominator value. If ulNumerator is equal to the ulDenominator parameter, the cursor is positioned after the last table row.
ulDenominator
Denominator of the fraction representing the table position. The ulDenominator parameter cannot be zero.

Back to top


IABTable::SetCollapseState IABTable::SetCollapseState *
  * Previous Topic: IABTable::SeekRowApprox
  * Next Topic: IABTable::SetColumns

IABTable::SetCollapseState

Currently not implemented by Internet Explorer Address Book.

Back to top


IABTable::SetColumns

HRESULT SetColumns(
    LPSPropTagArray lpPropTagArray,
    ULONG ulFlags
);

Defines the order of property values, and the order of properties to appear as columns in a table.

  • Returns one of the following values:
    S_OK | The column setting operation was successful.
    MAPI_E_BUSY | Another operation is in progress that prevents the column setting operation from starting. Either the operation in progress should be allowed to complete, or it should be stopped.
lpPropTagArray
Address of an SPropTagArray structure containing a counted array of property tags corresponding to the desired table columns. The lpPropTagArray parameter cannot be set to NULL; every table must have one column as a minimum.
ulFlags
Flags specifying asynchronous operation. For Internet Explorer Address Book, this value must be zero.

Back to top


IABTable::SortTable

HRESULT SortTable(
    LPSSortOrderSet lpSortCriteria,
    ULONG ulFlags
);

Sorts the table rows based on the sort criteria provided.

  • Returns one of the following values:
    S_OK | The sort operation was successful.
    MAPI_E_BUSY | Another operation is in progress that prevents the sort operation from starting. Either the operation in progress should be allowed to complete, or it should be stopped.
    MAPI_E_NO_SUPPORT | The table does not support the type of sorting requested.
    MAPI_E_TOO_COMPLEX | The table cannot perform the operation because the particular sort criteria pointed to by the lpSortCriteria parameter is too complicated.
lpSortCriteria
Address of an SSortOrderSet structure that contains the sort criteria. Passing an SSortOrderSet structure containing zero columns indicates that sorting the table is not desired.
ulFlags
Must be zero in Internet Explorer Address Book.

Back to top


IABTable::Unadvise IABTable::Unadvise *
  * Previous Topic: IABTable::SortTable
  * Next Topic: IABTable::WaitForCompletion

IABTable::Unadvise

Currently not implemented by Internet Explorer Address Book.

Back to top


IABTable::WaitForCompletion IABTable::WaitForCompletion *
  * Previous Topic: IABTable::Unadvise
  * Next Topic: IAddrBook

IABTable::WaitForCompletion

Currently not implemented by Internet Explorer Address Book.

Back to top


IAddrBook::Address

HRESULT Address(
    ULONG FAR * lpulUIParam
    LPADRPARM lpAdrParms,
    LPADRLIST FAR * lppAdrList
);

Displays user interface to browse the address book contents and to select recipients from the address book. The UI behavior is specified by a number of flags and parameters in lpAdrParms. Internet Explorer Address Book will not support some of the customization features of the MAPI IAddrBook::Address method. Internet Explorer Address Book will also not support the MAPI Send Options dialog button.

  • Returns S_OK if successful.
lpulUIParam
Input-output parameter containing the handle of the parent window of the dialog box. On input, a window handle must always be passed. On output, if the DIALOG_SDI flag is set in the lpAdrParms parameter's ADRPARM structure, the window handle of the modeless dialog box is returned.
lpAdrParms
Input-output parameter pointing to an ADRPARM structure that controls the presentation and behavior of the addressing dialog box.
lppAdrList
Input-output parameter that on input points to a variable holding a pointer to an ADRLIST structure holding the current recipient list. On output, the lppAdrList parameter points to a variable where the pointer to an ADRPARM structure updated by IAddrBook::Address is stored. lppAdrList can be NULL on input.

Back to top


IAddrBook::Advise IAddrBook::Advise *
  * Previous Topic: IAddrBook::Address
  * Next Topic: IAddrBook::CompareEntryIDs

IAddrBook::Advise

Currently not implemented by Internet Explorer Address Book.

Back to top


IAddrBook::CompareEntryIDs IAddrBook::CompareEntryIDs *
  * Previous Topic: IAddrBook::Advise
  * Next Topic: IAddrBook::CopyProps

IAddrBook::CompareEntryIDs

Currently not implemented by Internet Explorer Address Book.

Back to top


IAddrBook::CopyProps IAddrBook::CopyProps *
  * Previous Topic: IAddrBook::CompareEntryIDs
  * Next Topic: IAddrBook::CopyTo

IAddrBook::CopyProps

Currently not implemented by Internet Explorer Address Book.

Back to top


IAddrBook::CopyTo IAddrBook::CopyTo *
  * Previous Topic: IAddrBook::CopyProps
  * Next Topic: IAddrBook::CreateOneOff

IAddrBook::CopyTo

Currently not implemented by Internet Explorer Address Book.

Back to top


IAddrBook::CreateOneOff

HRESULT CreateOneOff(
    LPTSTR lpszName,
    LPTSTR lpszAdrType,
    LPTSTR lpszAddress,
    ULONG ulFlags,
    ULONG FAR * lpcbEntryID,
    LPENTRYID FAR * lppEntryID
);

Creates an entry identifier for a one-off address.

  • Returns S_OK if the one-off entry identifier was created successfully.
lpszName
Pointer to the display name of the recipient. The lpszName parameter can be NULL. the PR_DISPLAY_NAME property. The lpszName parameter can be NULL.
lpszAdrType
Pointer to the address type of the recipient, such as FAX or SMTP. The lpszAdrType parameter cannot be NULL.
lpszAddress
Pointer to the address of the recipient. The lpszAddress parameter cannot be NULL.
ulFlags
Bitmask of flags that affect the one-off recipient. The following flags can be set:
MAPI_SEND_NO_RICH_INFO | Indicates the recipient cannot handle formatted message content. If MAPI_SEND_NO_RICH_INFO is set, MAPI sets the recipient's PR_SEND_RICH_INFO property to FALSE. If MAPI_SEND_NO_RICH_INFO is not set, MAPI sets this property to TRUE unless the recipient's messaging address pointed to by lpszAddress is interpreted to be an Internet address. In this case, MAPI sets PR_SEND_RICH_INFO to FALSE.
MAPI_UNICODE | Displays the name, address type, and address are in Unicode format. If the MAPI_UNICODE flag is not set, these strings are in ANSI format.
lpcbEntryID
Address of the count of bytes in the entry identifier pointed to by the lppEntryID parameter.
lppEntryID
Address of a pointer to the entry identifier for the one-off recipient.

Back to top


IAddrBook::DeleteProps IAddrBook::DeleteProps *
  * Previous Topic: IAddrBook::CreateOneOff
  * Next Topic: IAddrBook::Details

IAddrBook::DeleteProps

Currently not implemented by Internet Explorer Address Book.

Back to top


IAddrBook::Details

HRESULT Details(
    ULONG FAR * lpulUIParam,
    LPFNDISMISS lpfnDismiss,
    LPVOID lpvDismissContext,
    ULONG cbEntryID,
    LPENTRYID lpEntryID,
    LPFNBUTTON lpfButtonCallback,
    LPVOID lpvButtonContext,
    LPTSTR lpszButtonText,
    ULONG ulFlags
);

Displays a dialog box showing details for, and allowing editing of, a particular entry in Internet Explorer Address Book. Internet Explorer Address Book does not support the passing in a callback function for buttons through the lpfButtonCallback parameter.

  • Returns S_OK if the dialog box was successfully displayed for the address book entry.
lpulUIParam
Returned HWND of the parent window of the returned dialog box.
lpfnDismiss
DISMISSMODELESS function pointer. This function is called when the modeless dialog box is dismissed. (Not implemented at this time.)
lpvDismissContext
Data passed to lpfnDismiss.
cbEntryID
Size, in bytes, of the entry identifier pointed to by the lpEntryID parameter.
lpEntryID
Address of an entry identifier for the entry for which details are displayed.
lpfButtonCallback
Not supported by Internet Explorer Address Book; must be NULL.
lpvButtonContext
Not supported by Internet Explorer Address Book; must be NULL.
lpszButtonText
Not supported by Internet Explorer Address Book; must be NULL.
ulFlags
Not supported by Internet Explorer Address Book; must be zero.

Back to top


IAddrBook::GetDefaultDir IAddrBook::GetDefaultDir *
  * Previous Topic: IAddrBook::Details
  * Next Topic: IAddrBook::GetIDsFromNames

IAddrBook::GetDefaultDir

Currently not implemented by Internet Explorer Address Book.

Back to top


IAddrBook::GetIDsFromNames IAddrBook::GetIDsFromNames *
  * Previous Topic: IAddrBook::GetDefaultDir
  * Next Topic: IAddrBook::GetLastError

IAddrBook::GetIDsFromNames

Currently not implemented by Internet Explorer Address Book.

Back to top


IAddrBook::GetLastError IAddrBook::GetLastError *
  * Previous Topic: IAddrBook::GetIDsFromNames
  * Next Topic: IAddrBook::GetNamesFromIDs

IAddrBook::GetLastError

Currently not implemented by Internet Explorer Address Book.

Back to top


IAddrBook::GetNamesFromIDs IAddrBook::GetNamesFromIDs *
  * Previous Topic: IAddrBook::GetLastError
  * Next Topic: IAddrBook::GetPAB

IAddrBook::GetNamesFromIDs

Currently not implemented by Internet Explorer Address Book.

Back to top


IAddrBook::GetPAB

HRESULT GetPAB(
    ULONG FAR * lpcbEntryID,
    LPENTRYID FAR * lppEntryID
);

Returns the ENTRYID of the default address book container.

  • Returns S_OK if successful.
lpcbEntryID
Address of the value that contains the size, in bytes, for the identifier pointed to by the lppEntryID parameter.
lppEntryID
Returned ENTRYID of the default address book container.

Back to top


IAddrBook::GetPropList IAddrBook::GetPropList *
  * Previous Topic: IAddrBook::GetPAB
  * Next Topic: IAddrBook::GetProps

IAddrBook::GetPropList

Currently not implemented by Internet Explorer Address Book.

Back to top


IAddrBook::GetProps IAddrBook::GetProps *
  * Previous Topic: IAddrBook::GetPropList
  * Next Topic: IAddrBook::GetSearchPath

IAddrBook::GetProps

Currently not implemented by Internet Explorer Address Book.

Back to top


IAddrBook::GetSearchPath

HRESULT GetSearchPath(
    ULONG ulFlags,
    LPSRowSet FAR * lppSearchPath
);

Returns an ordered list of entry identifiers of containers to be included in the name resolution process initiated by the ResolveName method.

  • Returns S_OK if the search path was successfully retrieved.
ulFlags
Bitmask of flags that control the type of the strings returned in the search path. The following flag can be set:
MAPI_UNICODE Specifies returned strings are in Unicode format. If this flag is not set, the strings are in ANSI format.
lppSearchPath
Address of a pointer to an ordered list of container entry identifiers. GetSearchPath stores the ordered list in an SRowSet structure. If there are no containers in the address book hierarchy, zero is returned in the SRowSet structure.

Back to top


IAddrBook

The IAddrBook interface supports access to the Internet Explorer Address Book and includes operations such as displaying common dialog boxes, opening containers, messaging users (contacts) and distribution lists (groups) in the address book, and performing name resolution. The organization of the method list for IAddrBook is arranged in v-table order.

IAddrBook methods
GetLastError
SaveChanges
GetProps
GetPropList
OpenProperty
SetProps
DeleteProps
CopyTo
CopyProps
GetNamesFromIDs
GetIDsFromNames
OpenEntry
CompareEntryIDs
Advise
Unadvise
CreateOneOff
NewEntry
ResolveName
Address
Details
RecipOptions
QueryDefaultRecipOpt
GetPAB
SetPAB
GetDefaultDir
SetDefaultDir
GetSearchPath
SetSearchPath
PrepareRecips


IAddrBook::NewEntry

HRESULT NewEntry(
    ULONG ulUIParam,
    ULONG ulFlags,
    ULONG cbEIDContainer,
    LPENTRYID lpEIDContainer,
    ULONG cbEIDNewEntryTpl,
    LPENTRYID lpEIDNewEntryTpl,
    ULONG FAR * lpcbEIDNewEntry,
    LPENTRYID FAR * lppEIDNewEntry
);

Adds a new entry to the address book.

  • Returns S_OK if the new address book entry was successfully created.
ulUIParam
Handle of the parent window for the dialog box.
ulFlags
Reserved; must be zero.
cbEIDContainer
Size, in bytes, for the entry identifier pointed to by the lpEIDContainer parameter.
lpEIDContainer
Entry identifier of the container where the new address is to be created. If NULL, creates the entry in the root container. This is different than the MAPI IAddrBook::NewEntry method.
cbEIDNewEntryTpl
Not supported by Internet Explorer Address Book; must be zero.
lpEIDNewEntryTpl
Not supported by Internet Explorer Address Book; must be NULL.
lpcbEIDNewEntry
Address for the value indicating the size, in bytes, for the entry identifier pointed to by the lppEIDNewEntry parameter.
lppEIDNewEntry
Returned entry identifier of the new entry.

Back to top


IAddrBook::OpenEntry

HRESULT OpenEntry(
    ULONG cbEntryID,
    LPENTRYID lpEntryID,
    LPCIID lpInterface,
    ULONG ulFlags,
    ULONG FAR * lpulObjType,
    LPUNKNOWN FAR * lppUnk
);

Opens a container or mail user object and returns a pointer to the object.

  • Returns one of the following values:
    S_OK | The entry was successfully opened.
    MAPI_E_NO_ACCESS | An attempt was made to open an entry for which the user has insufficient permissions.
    MAPI_E_NOT_FOUND | The entry represented by lpEntryID does not exist.
    MAPI_E_UNKNOWN_ENTRYID | The entry identifier specified in lpEntryID is not recognized. This value is typically returned if the address book provider responsible for the corresponding entry is not open.
cbEntryID
Size, in bytes, for the entry identifier to open.
lpEntryID
Entry identifier of the object to open (NULL for the root address book container).
lpInterface
Address of the interface identifier (IID) for the object to open. Pass NULL to specify the standard interface for the object.
ulFlags
Bitmask containing the object access flags. Default is read access only. The following flags can be used for modifications:
MAPI_BEST_ACCESS | Specifies to open with best available access rights.
MAPI_MODIFY | Requests read/write access.
MAPI_DEFERRED_ERRORS | Currently not supported by Internet Explorer Address Book.
lpulObjType
Returned object type.
lppUnk
Returned object pointer.

Back to top


IAddrBook::OpenProperty IAddrBook::OpenProperty *
  * Previous Topic: IAddrBook::OpenEntry
  * Next Topic: IAddrBook::PrepareRecips

IAddrBook::OpenProperty

Currently not implemented by Internet Explorer Address Book.

Back to top


IAddrBook::PrepareRecips

HRESULT PrepareRecips(
    ULONG ulFlags,
    LPSPropTagArray lpSPropTagArray,
    LPADRLIST lpRecipList
);

Prepares a recipient list for later use by the messaging system.

  • Returns S_OK if the recipient list was successfully prepared.
ulFlags
Reserved; must be zero.
lpSPropTagArray
Address of an SPropTagArray structure containing an array of property tags indicating properties that require updating, if any. The lpSPropTagArray parameter can be NULL.
lpRecipList
Address of an ADRLIST structure holding the list of recipients.

Back to top


IAddrBook::QueryDefaultRecipOpt IAddrBook::QueryDefaultRecipOpt *
  * Previous Topic: IAddrBook::PrepareRecips
  * Next Topic: IAddrBook::RecipOptions

IAddrBook::QueryDefaultRecipOpt

Currently not implemented by Internet Explorer Address Book.

Back to top


IAddrBook::RecipOptions IAddrBook::RecipOptions *
  * Previous Topic: IAddrBook::QueryDefaultRecipOpt
  * Next Topic: IAddrBook::ResolveName

IAddrBook::RecipOptions

Currently not implemented by Internet Explorer Address Book.

Back to top


IAddrBook::ResolveName

HRESULT ResolveName(
    ULONG ulUIParam,
    ULONG ulFlags,
    LPTSTR lpszNewEntryTitle,
    LPADRLIST lpAdrList
);

Resolves a partial recipient list to full addresses.

  • Returns one of the following values:
    S_OK | The name resolution process succeeded.
    MAPI_E_AMBIGUOUS_RECIP | At least one recipient in the lpAdrList parameter matched more than one entry in the address book. Usually, this value is returned when the MAPI_DIALOG flag is set, prohibiting the display of a dialog box.
    MAPI_E_NOT_FOUND | At least one recipient in the lpAdrList parameter cannot be resolved. Usually, this value is returned when the MAPI_DIALOG flag is set, prohibiting the display of a dialog box.
ulUIParam
Handle of the parent window.
ulFlags
MAPI_DIALOG flag. Displays a dialog box to prompt the user for additional name-resolution information. If this flag is not set, no dialog box is displayed.
lpszNewEntryTitle
Pointer to text for the title of the control in the dialog box that prompts the user to enter a recipient. The lpszNewEntryTitle parameter can be NULL.
lpAdrList
On input, the address list the list of recipients to resolve. On output, contains the list of resolved recipients.

This method optionally displays a dialog box if ambiguous matches are found. ResolveName goes through the address list passed in the lpAdrList parameter, finds all the names not yet resolved, resolves them, and returns the appropriately modified address list. The address list passed in can be one created using the Address method. If a recipient is ambiguous and the MAPI_DIALOG flag is not specified, ResolveName returns MAPI_E_AMBIGUOUS_RECIP.

Note The ADRENTRY items in ADRLIST should be separately allocated, not allocated with AllocateMore. When ResolveNames replaces an entry, it expects to free the ADRENTRY structure by using FreeBuffer and allocate a new one by using AllocateBuffer.

Back to top


IAddrBook::SaveChanges IAddrBook::SaveChanges *
  * Previous Topic: IAddrBook::ResolveName
  * Next Topic: IAddrBook::SetDefaultDir

IAddrBook::SaveChanges

Currently not implemented by Internet Explorer Address Book.

Back to top


IAddrBook::SetDefaultDir IAddrBook::SetDefaultDir *
  * Previous Topic: IAddrBook::SaveChanges
  * Next Topic: IAddrBook::SetPAB

IAddrBook::SetDefaultDir

Currently not implemented by Internet Explorer Address Book.

Back to top


IAddrBook::SetPAB IAddrBook::SetPAB *
  * Previous Topic: IAddrBook::SetDefaultDir
  * Next Topic: IAddrBook::SetProps

IAddrBook::SetPAB

Currently not implemented by Internet Explorer Address Book.

Back to top


IAddrBook::SetProps IAddrBook::SetProps *
  * Previous Topic: IAddrBook::SetPAB
  * Next Topic: IAddrBook::SetSearchPath

IAddrBook::SetProps

Currently not implemented by Internet Explorer Address Book.

Back to top


IAddrBook::SetSearchPath IAddrBook::SetSearchPath *
  * Previous Topic: IAddrBook::SetProps
  * Next Topic: IAddrBook::Unadvise

IAddrBook::SetSearchPath

Currently not implemented by Internet Explorer Address Book.

Back to top


IAddrBook::Unadvise IAddrBook::Unadvise *
  * Previous Topic: IAddrBook::SetSearchPath
  * Next Topic: IDistList

IAddrBook::Unadvise

Currently not implemented by Internet Explorer Address Book.

Back to top


IDistList::CopyEntries IDistList::CopyEntries *
  * Previous Topic: IDistList
  * Next Topic: IDistList::CopyProps

IDistList::CopyEntries

Currently not implemented by Internet Explorer Address Book.

Back to top


IDistList::CopyProps IDistList::CopyProps *
  * Previous Topic: IDistList::CopyEntries
  * Next Topic: IDistList::CopyTo

IDistList::CopyProps

Currently not implemented by Internet Explorer Address Book.

Back to top


IDistList::CopyTo IDistList::CopyTo *
  * Previous Topic: IDistList::CopyProps
  * Next Topic: IDistList::CreateEntry

IDistList::CopyTo

Currently not implemented by Internet Explorer Address Book.

Back to top


IDistList::CreateEntry

HRESULT CreateEntry(
    ULONG   cbEntryID,
    LPENTRYID   lpEntryID,
    ULONG   ulCreateFlags,
    LPMAPIPROP FAR  * lppMAPIPropEntry
);

Creates a new entry in the distribution list container. Internet Explorer Address Book supports creation of both IMailUser and IDistList objects.

  • Returns S_OK if the entry was successfully created.
cbEntryID
Size of the existing entry identifier to copy from, stored in the lpEntryID parameter. lpEntryID parameter.
lpEntryID
Entry identifier of the object to copy from.
ulCreateFlags
Bitmask that controls the level of duplicate entries. Can be one of the following values:
CREATE_CHECK_DUP_LOOSE | Indicates a loose level should be used for duplicate entry checking, which returns more matches than setting a strict level with the CREATE_CHECK_DUP_STRICT flag. For example, a provider can define a loose match as any two entries having the same display name, while defining a strict match as any two entries having the same display name and messaging address.
CREATE_CHECK_DUP_STRICT | Indicates a strict level should be used for duplicate entry checking, which returns fewer matches than setting a loose level with the CREATE_CHECK_DUP_LOOSE flag.
CREATE_REPLACE | Indicates that duplicate entries replace existing entries within a container.
lppMAPIPropEntry
Returned property interface to the new object.

Back to top


IDistList::DeleteEntries

HRESULT DeleteEntries(
    LPENTRYLIST  lpEntries,
    ULONG  ulFlags
);

Removes one or more entries from the distribution list.

  • Returns one of the following values:
    S_OK | The specified entries have been successfully deleted.
    MAPI_W_PARTIAL_COMPLETION | The call succeeded, but one or more of the entries could not be deleted. When this warning is returned, the call should be handled as successful. To test for this warning, use the FAILED macro.
lpEntries
Address of an array of ENTRYLIST structures containing entry identifiers representing the entries being deleted from the distribution list.
ulFlags
Reserved; must be zero.

Back to top


IDistList::DeleteProps

HRESULT DeleteProps(
    LPSPropTagArray  lpPropTagArray,
    LPSPropProblemArray FAR *  lppProblems
);

Deletes property values from a distribution list object.

  • Returns S_OK if the properties were successfully deleted, or MAPI_E_NO_ACCESS if the method that called this method has insufficient permissions to delete properties.
lpPropTagArray
Returned property tag array to be deleted.
lppProblems
Returned problem array. Must be freed by the caller if a non-NULL value is returned.

Back to top


IDistList::GetContentsTable

HRESULT GetContentsTable(
    ULONG   ulFlags,
    LPMAPITABLE FAR *  lppTable
);

Returns the address to the contents table of the distribution list.

  • Returns one of the following values:
    S_OK | The contents table was successfully retrieved.
    MAPI_E_BAD_CHARWIDTH | Either the MAPI_UNICODE flag was set and the implementation does not support Unicode, or MAPI_UNICODE was not set and the implementation only supports Unicode.
    MAPI_E_NO_SUPPORT | The container has no contents and cannot provide a contents table.
ulFlags
Bitmask of flags that control how the contents table is returned. The following flags can be set:
MAPI_DEFERRED_ERRORS | Currently not supported by Internet Explorer Address Book.
MAPI_UNICODE | Indicates the returned strings are in Unicode format. If this flag is not set, the strings are in ANSI format. Not supported in the first version of Internet Explorer Address Book.
lppTable
Returned table object containing the contents table.

Back to top


IDistList::GetHierarchyTable IDistList::GetHierarchyTable *
  * Previous Topic: IDistList::GetContentsTable
  * Next Topic: IDistList::GetIDsFromNames

IDistList::GetHierarchyTable

Currently not implemented by Internet Explorer Address Book.

Back to top


IDistList::GetIDsFromNames

HRESULT GetIDsFromNames(
    ULONG cPropNames,
    LPMAPINAMEID FAR * lppPropNames,
    ULONG ulFlags,
    LPSPropTagArray FAR * lppPropTags
);

Provides the property identifiers that correspond to one or more property names.

  • Returns one of the following values:
    S_OK | The identifiers for the specified property names were successfully returned.
    MAPI_E_NO_SUPPORT | The object does not support named properties.
    MAPI_E_NOT_ENOUGH_MEMORY | Insufficient memory was available to retrieve the identifiers.
    MAPI_E_TOO_BIG | The operation cannot be performed because it requires too many property tags be returned.
    MAPI_W_ERRORS_RETURNED | The call succeeded overall, but one or more property identifiers could not be returned. The corresponding property type for each inaccessible property is set to PT_ERROR and its identifier to zero. When this warning is returned, handle the call as successful. To test for this warning, use the FAILED macro.
cPropNames
Value that represents the number of property names pointed to by the lppPropNames parameter. If lppPropNames is NULL, the cPropNames parameter must be zero.
lppPropNames
Address of an array of property names, or NULL. Passing NULL requests property identifiers for all property names in all property sets about which the object has information. The lppPropNames parameter must not be NULL if the MAPI_CREATE flag is set in the ulFlags parameter.
ulFlags
Bitmask of flags that indicate how the property identifiers should be returned. The following flag can be set:
MAPI_CREATE Assigns a property identifier to one or more of the names included in the property name array pointed to by lppPropNames if one has not yet been assigned. Internally registers the identifier in the name-to-identifier mapping table.
lppPropTags
Returned array structure of property tags containing existing or newly assigned property identifiers. The property types for the property tags in this array are set to PT_UNSPECIFIED.

Back to top


IDistList::GetLastError IDistList::GetLastError *
  * Previous Topic: IDistList::GetIDsFromNames
  * Next Topic: IDistList::GetNamesFromIDs

IDistList::GetLastError

Currently not implemented by Internet Explorer Address Book.

Back to top


IDistList::GetNamesFromIDs IDistList::GetNamesFromIDs *
  * Previous Topic: IDistList::GetLastError
  * Next Topic: IDistList::GetPropList

IDistList::GetNamesFromIDs

Currently not implemented by Internet Explorer Address Book.

Back to top


IDistList::GetPropList

HRESULT GetPropList(
    ULONG  ulFlags,
    LPSPropTagArray FAR *  lppPropTagArray
);

Retrieves a list of the property tags on the object.

  • Returns one of the following values:
    S_OK | All of the property tags were returned successfully.
    MAPI_E_BAD_CHARWIDTH | Either the MAPI_UNICODE flag was set and the implementation does not support Unicode, or MAPI_UNICODE was not set and the implementation only supports Unicode.
ulFlags
Must be zero for Internet Explorer Address Book.
lppPropTagArray
Returned property tag array. Must be freed by the caller if a non-NULL value is returned.

Back to top


IDistList::GetProps

HRESULT GetProps(
    LPSPropTagArray lpPropTagArray,
    ULONG ulFlags,
    ULONG FAR * lpcValues,
    LPSPropValue FAR * lppPropArray
);

Retrieves the property tag information for the distribution list items.

  • Returns one of the following values:
    S_OK | The property values were successfully retrieved.
    MAPI_W_ERRORS_RETURNED | The call succeeded overall, but one or more properties could not be accessed. The ulPropTag member of the property value for each inaccessible property in the lppPropArray parameter has a property type of PT_ERROR and an identifier of zero. When this warning is returned, the call should be handled as successful. To test for this warning, use the FAILED macro.
    MAPI_E_INVALID_PARAMETER | Zero was passed in the cValues member of the SPropTagArray structure pointed to by lpPropTagArray.
lpPropTagArray
Address of an SPropTagArray structure of properties whose values are to be retrieved. A NULL value specifies that all properties should be retrieved.
ulFlags
MAPI_UNICODE flag. Not supported by Internet Explorer Address Book.
lpcValues
Returned value that represents the number of property values returned. If lppPropArray is NULL, the contents of the lpcValues parameter is zero.
lppPropArray
Returned SPropValue array. Must be freed by the caller.

Back to top


IDistList::GetSearchCriteria IDistList::GetSearchCriteria *
  * Previous Topic: IDistList::GetProps
  * Next Topic: IDistList::OpenEntry

IDistList::GetSearchCriteria

Currently not implemented by Internet Explorer Address Book.

Back to top


IDistList

The IDistList interface is used to provide access to distribution lists in modifiable address book containers. This interface can create, copy, and delete distribution lists, in addition to performing name resolution. The organization of the method list for IDistList is arranged in v-table order.

IDistList methods
GetLastError
SaveChanges
GetProps
GetPropList
OpenProperty
SetProps
DeleteProps
CopyTo
CopyProps
GetNamesFromIDs
GetIDsFromNames
GetContentsTable
GetHierarchyTable
OpenEntry
SetSearchCriteria
GetSearchCriteria
CreateEntry
CopyEntries
DeleteEntries
ResolveNames


IDistList::OpenEntry

HRESULT OpenEntry(
    ULONG cbEntryID,
    LPENTRYID lpEntryID,
    LPCIID lpInterface,
    ULONG ulFlags,
    ULONG FAR * lpulObjType,
    LPUNKNOWN FAR * lppUnk
);

Opens an entry contained in the distribution list and returns a pointer to the object to provide further access.

  • Returns one of the following values:
    S_OK | The entry was successfully opened.
    MAPI_E_NO_ACCESS | An attempt was made to open an entry for which the user has insufficient permissions.
    MAPI_E_NOT_FOUND | The entry represented by lpEntryID does not exist.
    MAPI_E_UNKNOWN_ENTRYID | The entry identifier specified in lpEntryID is not recognized. This value is typically returned if the address book provider responsible for the corresponding entry is not open.
cbEntryID
Value that represents the number of bytes contained in the entry identifier to open.
lpEntryID
Address of an entry identifier of the object to open.
lpInterface
Address of an interface identifier (IID) for the object to open. Pass NULL to specify the standard interface for the object.
ulFlags
Bitmask containing object access flags. The default is read access only. The following flags can be used for modifications:
MAPI_BEST_ACCESS | Specifies to open with best available access rights.
MAPI_MODIFY | Requests read/write access.
MAPI_DEFERRED_ERRORS | Currently not supported by Internet Explorer Address Book.
lpulObjType
Address of the object type of the opened entry.
lppUnk
Returned object pointer to the opened entry.

Back to top


IDistList::OpenProperty IDistList::OpenProperty *
  * Previous Topic: IDistList::OpenEntry
  * Next Topic: IDistList::ResolveNames

IDistList::OpenProperty

Currently not implemented by Internet Explorer Address Book.

Back to top


IDistList::ResolveNames IDistList::ResolveNames *
  * Previous Topic: IDistList::OpenProperty
  * Next Topic: IDistList::SaveChanges

IDistList::ResolveNames

Currently not implemented by Internet Explorer Address Book.

Back to top


IDistList::SaveChanges

HRESULT SaveChanges(
    ULONG ulFlags
);

Provides the ability to save changes to the open distribution list object.

  • Returns one of the following values:
    S_OK | The commitment of changes has been successful.
    MAPI_E_NO_ACCESS | SaveChanges cannot keep the object open for read-only access if KEEP_OPEN_READONLY is set, or read/write access if KEEP_OPEN_READWRITE is set. No changes are committed.
    MAPI_E_OBJECT_CHANGED | The object has changed since it was opened.
    MAPI_E_OBJECT_DELETED | The object has been deleted since it was opened.
ulFlags
Bitmask of flags that control what happens to the object when the SaveChanges method is called. The following flags can be set:
FORCE_SAVE | Writes changes to the object and closes it. Read-write access must have been set for the operation to succeed. This flag forces saving only if MAPI_E_OBJECT_CHANGED was returned from a preceding SaveChanges call. FORCE_SAVE overrides the previous changes made to the object.
KEEP_OPEN_READONLY | Indicates the client requests changes be committed and the object be kept open for reading. This flag informs the provider that the object should not be modified and that the calling implementation will not call SaveChanges again. If the provider cannot keep the object open for read-only access, the entire call fails, changes are not saved, and MAPI_E_NO_ACCESS is returned.
KEEP_OPEN_READWRITE | Indicates the client requests changes be committed and the object be kept open for read-write access. This flag is usually set when the object was initially opened for read-write access. After calling SaveChanges, the client can make further changes to the object if this flag is passed. If the provider cannot keep the object open for read-write access, the entire call fails, changes are not saved, and MAPI_E_NO_ACCESS is returned.
MAPI_DEFERRED_ERRORS | Not supported by Internet Explorer Address Book.

Back to top


IDistList::SetProps

HRESULT SetProps(
    ULONG cValues,
    LPSPropValue lpPropArray,
    LPSPropProblemArray FAR * lppProblems
);

Sets property values on a distribution list object.

  • Returns one of the following values:
    S_OK | The properties were successfully updated. The following values can be returned in the SPropProblemArray structure, but not as return values for SetProps.
    MAPI_E_BAD_CHARWIDTH | Either the MAPI_UNICODE flag was set and the implementation does not support Unicode, or MAPI_UNICODE was not set and the implementation only supports Unicode.
    MAPI_E_COMPUTED | The property cannot be updated because it is read-only, computed by the service provider responsible for the object.
    MAPI_E_INVALID_TYPE | The property type is invalid.
    MAPI_E_NO_ACCESS | An attempt was made to modify a read-only object or to access an object for which the user has insufficient permissions.
    MAPI_E_NOT_ENOUGH_MEMORY | The property cannot be updated because it is larger than the remote procedure call "RPC" buffer size.
    MAPI_E_UNEXPECTED_TYPE | The property type is not the type expected by the calling implementation.
cValues
Count of property values to be set. This parameter must not be zero.
lpPropArray
Address of an array of SPropValue structures containing the properties to set.
lppProblems
Returned problem array. Must be freed by the caller if a non-NULL value is returned.

Back to top


IDistList::SetSearchCriteria IDistList::SetSearchCriteria *
  * Previous Topic: IDistList::SetProps
  * Next Topic: IMailUser

IDistList::SetSearchCriteria

Currently not implemented by Internet Explorer Address Book.

Back to top


IMailUser::CopyProps IMailUser::CopyProps *
  * Previous Topic: IMailUser
  * Next Topic: IMailUser::CopyTo

IMailUser::CopyProps

Currently not implemented by Internet Explorer Address Book.

Back to top


IMailUser::CopyTo IMailUser::CopyTo *
  * Previous Topic: IMailUser::CopyProps
  * Next Topic: IMailUser::DeleteProps

IMailUser::CopyTo

Currently not implemented by Internet Explorer Address Book.

Back to top


IMailUser::DeleteProps

HRESULT DeleteProps(
    LPSPropTagArray  lpPropTagArray,
    LPSPropProblemArray FAR *  lppProblems
);

Deletes property values from a mail user object.

  • Returns S_OK if properties were successfully deleted, or MAPI_E_NO_ACCESS if the caller has insufficient permissions to delete properties.
lpPropTagArray
Address of an array of property tags indicating the properties to delete. The cValues member of the SPropTagArray structure pointed to by lpPropTagArray must not be zero, and the lpPropTagArray parameter itself must not be NULL.
lppProblems
Returned problem array. Must be freed by the caller if a non-NULL value is returned.

Back to top


IMailUser::GetIDsFromNames

HRESULT GetIDsFromNames(
    ULONG  cPropNames,
    LPMAPINAMEID FAR *  lppPropNames,
    ULONG  ulFlags,
    LPSPropTagArray FAR *  lppPropTags
);

Registers named properties with the mail user object.

  • Returns one of the following values:
    S_OK | The identifiers for the specified property names were successfully returned.
    MAPI_E_NO_SUPPORT | The object does not support named properties.
    MAPI_E_NOT_ENOUGH_MEMORY | Insufficient memory was available to retrieve the identifiers.
    MAPI_E_TOO_BIG | The operation cannot be performed because it requires too many property tags be returned.
    MAPI_W_ERRORS_RETURNED | The call succeeded overall, but one or more property identifiers could not be returned. The corresponding property type for each inaccessible property is set to PT_ERROR and its identifier to zero. When this warning is returned, handle the call as successful. To test for this warning, use the FAILED macro.
cPropNames
Count of names to register. If lppPropNames is NULL, the cPropNames parameter must be zero.
lppPropNames
MAPINAMEID structure containing the names and their globally unique identifiers (GUIDs).
ulFlags
Bitmask of flags that indicate how the property identifiers should be returned. The following flag can be set:
MAPI_CREATE Creates a property identifier for any name not already mapped. The default is to fail those non-existent property names.
lppPropTags
Returned SPropTagArray of property tags. Must be freed by the caller.

Back to top


IMailUser::GetLastError IMailUser::GetLastError *
  * Previous Topic: IMailUser::GetIDsFromNames
  * Next Topic: IMailUser::GetNamesFromIDs

IMailUser::GetLastError

Currently not implemented by Internet Explorer Address Book.

Back to top


IMailUser::GetNamesFromIDs IMailUser::GetNamesFromIDs *
  * Previous Topic: IMailUser::GetLastError
  * Next Topic: IMailUser::GetPropList

IMailUser::GetNamesFromIDs

Currently not implemented by Internet Explorer Address Book.

Back to top


IMailUser::GetPropList

HRESULT GetPropList(
    ULONG   ulFlags,
    LPSPropTagArray FAR *  lppPropTagArray
);

Gets a list of the property tags on the object.

  • Returns S_OK if all property tags were returned successfully.
ulFlags
Must be zero for Internet Explorer Address Book.
lppPropTagArray
Returned property tag array. Must be freed by the caller if a non-NULL value is returned.

Back to top


IMailUser::GetProps

HRESULT GetProps(
    LPSPropTagArray lpPropTagArray,
    ULONG ulFlags,
    ULONG FAR * lpcValues,
    LPSPropValue FAR * lppPropArray
);

Gets property values from a mail user object.

  • Returns S_OK if the property values were successfully retrieved, or MAPI_E_INVALID_PARAMETER if zero was passed in the cValues member of the SPropTagArray structure pointed to by lpPropTagArray.
lpPropTagArray
SPropTagArray of properties to be retrieved. A NULL value specifies that all properties should be retrieved.
ulFlags
MAPI_UNICODE flag. Currently not supported by Internet Explorer Address Book.
lpcValues
Returned count of property values returned. This pointer can be NULL if the caller does not want the count of the returned property values.
lppPropArray
Returned SPropValue array. Must be freed by the caller.

Back to top


IMailUser

The IMailUser interface is implemented by messaging user objects. IMailUser inherits from the IMAPIProp interface and has no unique methods of its own. The IMailUser interface provides access to the many properties that are associated with messaging users. The organization of the method list for IMailUser is arranged in v-table order.

IMailUser methods
GetLastError
SaveChanges
GetProps
GetPropList
OpenProperty
SetProps
DeleteProps
CopyTo
CopyProps
GetNamesFromIDs
GetIDsFromNames


IMailUser::OpenProperty IMailUser::OpenProperty *
  * Previous Topic: IMailUser::GetProps
  * Next Topic: IMailUser::SaveChanges

IMailUser::OpenProperty

Currently not implemented by Internet Explorer Address Book.

Back to top


IMailUser::SaveChanges

HRESULT SaveChanges(
    ULONG  ulFlags
);

Saves changes to the open mail user object. Note that the following properties may be calculated and changed at SaveChanges:
PR_DISPLAY_NAME
PR_GIVEN_NAME
PR_SURNAME
PR_LAST_MODIFICATION_TIME

  • Returns one of the following values:
    S_OK | The commitment of changes has been successful.
    MAPI_E_NO_ACCESS | SaveChanges cannot keep the object open for read-only access if KEEP_OPEN_READONLY is set, or read/write access if KEEP_OPEN_READWRITE is set. No changes are committed.
    MAPI_E_OBJECT_CHANGED | The object has changed since it was opened.
    MAPI_E_OBJECT_DELETED | The object has been deleted since it was opened.
ulFlags
Bitmask of flags that control what happens to the object when the SaveChanges method is called. The following flags can be set:
FORCE_SAVE | Writes changes to the object and closes it. Read-write access must have been set for the operation to succeed. This flag forces saving only if MAPI_E_OBJECT_CHANGED was returned from a preceding SaveChanges call. FORCE_SAVE overrides the previous changes made to the object.
KEEP_OPEN_READONLY | Indicates the client requests changes be committed and the object be kept open for reading. This flag informs the provider that the object should not be modified and that the calling implementation will not call SaveChanges again. If the provider cannot keep the object open for read-only access, the entire call fails, changes are not saved, and MAPI_E_NO_ACCESS is returned.
KEEP_OPEN_READWRITE | Indicates the client requests changes be committed and the object be kept open for read-write access. This flag is usually set when the object was initially opened for read-write access. After calling SaveChanges, the client can make further changes to the object if this flag is passed. If the provider cannot keep the object open for read-write access, the entire call fails, changes are not saved, and MAPI_E_NO_ACCESS is returned.
MAPI_DEFERRED_ERRORS | Currently not supported by Internet Explorer Address Book.

Back to top


IMailUser::SetProps

HRESULT SetProps(
    ULONG  cValues,
    LPSPropValue  lpPropArray,
    LPSPropProblemArray FAR *   pProblems
);

Sets the property values on a mail user object.

  • Returns S_OK if the properties were successfully updated.
cValues
Count of property values to be set.
lpPropArray
Array of SPropValue structures containing the properties to set.
pProblems
Returned problem array. Must be freed by the caller if a non-NULL value is returned.

Back to top


IWABObject::AllocateBuffer

HRESULT AllocateBuffer(
    ULONG  cbSize,
    LPVOID FAR *  lppBuffer
);

Allocates a memory for a buffer. This is the allocation routine that should be used for buffers passed to Internet Explorer Address Book methods. The buffer should be freed with FreeBuffer and can be reallocated with AllocateMore.

  • Returns S_OK if the requested buffer was successfully allocated.
cbSize
Specified size, in bytes, of the buffer to be allocated.
lppBuffer
Returned buffer pointer.

Back to top


IWABObject::AllocateMore

HRESULT AllocateMore(
    ULONG           cbSize,
    LPVOID          lpObject,
    LPVOID FAR *    lppBuffer
);

Allocates a memory buffer that is linked to another buffer previously allocated with the AllocateBuffer function.

  • Returns S_OK if the requested AllocateMore method was successful.
cbSize
Size, in bytes, of the buffer to be allocated.
lpObject
Existing buffer object allocated using AllocateBuffer.
lppBuffer
Returned buffer pointer; this buffer is linked to lpObject.

The only way to release a buffer allocated with AllocateMore is to pass the buffer pointer specified in the lpObject parameter to the FreeBuffer function. The link between the memory buffers allocated with AllocateBuffer and AllocateMore enables FreeBuffer to release both buffers with a single call.

Back to top


IWABObject::Backup IWABObject::Backup *
  * Previous Topic: IWABObject::AllocateMore
  * Next Topic: IWABObject::Find

IWABObject::Backup

Currently not implemented in Internet Explorer Address Book.

Back to top


IWABObject::Find

HRESULT Find(
    HWnd
);

Launches the address book's Find dialog box. (Internet Explorer 4.0 only)

  • Returns S_OK if successful.
HWnd
HWND of the parent for the Find dialog box. Can be NULL.

Back to top


IWABObject::FreeBuffer

HRESULT FreeBuffer(
    LPVOID lpBuffer
);

Frees memory allocated with AllocateBuffer or any of the Internet Explorer Address Book methods.

  • Returns S_OK if the call succeeded and freed the memory requested.
lpBuffer
Address of the buffer to free.

Back to top


IWABObject::GetLastError IWABObject::GetLastError *
  * Previous Topic: IWABObject::FreeBuffer
  * Next Topic: IWABObject::GetMe

IWABObject::GetLastError

Currently not implemented in Internet Explorer Address Book.

Back to top


IWABObject::GetMe IWABObject::GetMe *
  * Previous Topic: IWABObject::GetLastError
  * Next Topic: IWABObject::Import

IWABObject::GetMe

Currently not implemented in Internet Explorer Address Book.

Back to top


IWABObject::Import IWABObject::Import *
  * Previous Topic: IWABObject::GetMe
  * Next Topic: IWABObject::LDAPUrl

IWABObject::Import

Currently not implemented in Internet Explorer Address Book.

Back to top


IWABObject

The Internet Explorer Address Book object contains function pointers to memory allocation functions and database maintenance functions. The organization of the method list for IWABObject is arranged in v-table order.

IWABObject methods
GetLastError
AllocateBuffer
AllocateMore
FreeBuffer
Backup
Import
Find
VCardDisplay
LDAPUrl
VCardCreate
VCardRetrieve
GetMe
SetMe


IWABObject::LDAPUrl

HRESULT IWABObject::LDAPUrl (
    HWND  hWnd,
    ULONG ulFlags,
    LPTSTR  lpszLDAPURL,
    LPMailUser * lppMailUser
);

This method processes a given LDAP Url and displays corresponding results. If the URL only contains a server name, the method will display the WAB Find dialog with the server name filled in, enabling the user to manually search the server. If the URL contains an explicit LDAP query, this method performs a search based on the query. If the query produces a single result, the method shows details on the single result, else if the query has multiple results, the method shows the WAB Find dialog with multiple search results filled in. If WABOBJECT_LDAPURL_RETURN_MAILUSER is specified in the ulFlags parameter, the method returns a IMailUser object, if the query returns a single specific result, else returns a MAPI_E_AMBIGUOUS_RECIP if the query returns multiple hits.

  • Returns S_OK if successful.
hWnd
HWND of the parent for displayed dialogs.
ulFlags
Flags specifying behavior. Can be zero, or WABOBJECT_LDAPURL_RETURN_MAILUSER.
lpszLDAPUrl
URL string, starting with ldap://. (Format for LDAP URLs is specified in RFC-1959)
lppMailUser
Returned IMailUser object, if requested. Null otherwise.

Back to top


IWABObject::SetMe IWABObject::SetMe *
  * Previous Topic: IWABObject::LDAPUrl
  * Next Topic: IWABObject::VCardCreate

IWABObject::SetMe

Currently not implemented in Internet Explorer Address Book.

Back to top


IWABObject::VCardCreate

HRESULT VCardCreate(
    lpAdrBook,
    lpFileName,
    lpMailUser
);

Translates the properties of an IMailUser object into a business card (vCard) file. (The vCard file format is an Internet standard for exchanging contact information through text based files).

The complete file name must be specified. If the file already exists, it will be overwritten.

Warning! This API is in development at this time, and is subject to change.

  • Returns S_OK if successful.
lpAdrBook
Address of an IAddrBook object.
lpFileName
Address of a string containing the complete path of the file to create.
lpMailUser
Address of a IMailUser object whose properties will be written into the file.

Back to top


IWABObject::VCardDisplay

HRESULT VCardDisplay(
    lpAdrBook,
    hWnd,
    lpFileName
);

Displays the contents of a business card (vCard) file. The complete file name must be specified.

Warning! This API is in development at this time, and is subject to change.

  • Returns S_OK if successful.
lpAdrBook
Address of an IADRBOOK object.
hWnd
HWND of the parent for displayed dialog boxes.
lpFileName
Full path of vCard file to display. Fails if the file does not exist.

Back to top


IWABObject::VCardRetrieve

HRESULT VCardRetrieve(
    lpAdrBook,
    lpFileName,
    lppMailUser
);

Reads a vCard file and creates a MailUser object containing the vCard properties.

  • Returns S_OK if successful.
lpAdrBook
Address of an IADRBOOK object.
lpFileName
Address of a string containing the complete path of the file to read. Fails if the file is not found.
lppMailUser
Returned MailUser object created containing the properties in the vCard file.

Back to top


ADRENTRY

typedef struct _ADRENTRY {
    ULONG          ulReserved1;
    ULONG          cValues;
    LPSPropValue   rgPropVals;
} ADRENTRY;

Describes zero or more properties belonging to a recipient.

ulReserved1
Reserved; must be zero.
cValues
Count of properties in the property value array pointed to by the rgPropVals member. The cValues member can be zero.
rgPropVals
Address of a property value array describing the properties for the recipient. The rgPropVals member can be NULL.

Back to top


ADRLIST

typedef struct _ADRLIST {
    ULONG          cEntries;
    ADRENTRY       aEntries[MAPI_DIM];
    } ADRLIST;

Describes zero or more properties belonging to one or more recipients.

cEntries
Count of entries in the array specified by the aEntries member.
aEntries[MAPI_DIM]
Array of ADRENTRY structures, one structure for each recipient.

Back to top


ADRPARM

typedef struct _ADRPARM
{
    ULONG            cbABContEntryID;
    LPENTRYID        lpABContEntryID;
    ULONG            ulFlags;
    LPVOID           lpReserved;
    ULONG            ulHelpContext;
    LPTSTR           lpszHelpFileName;
    LPFNABSDI        lpfnABSDI;
    LPFNDISMISS      lpfnDismiss;
    LPVOID           lpvDismissContext;
    LPTSTR           lpszCaption;
    LPTSTR           lpszNewEntryTitle;
    LPTSTR           lpszDestWellsTitle;
    ULONG            cDestFields;
    ULONG            nDestFieldFocus;
    LPTSTR FAR      *lppszDestTitles;
    ULONG FAR       *lpulDestComps;
    LPSRestriction   lpContRestriction;
    LPSRestriction   lpHierRestriction;
} ADRPARM, FAR *LPADRPARM;

Describes the display and behavior of the common address dialog box.

cbABContEntryID
List of entries that can be added to the recipient wells.
lpABContEntryID
Address of an ENTRYID of a container that will supply the list of one-offs that can be added to the recipient wells of the address book common dialog box. The address book container that lpABContEntryID points to determines what is listed in the edit box within the dialog box that holds possible recipient names. Usually, lpABContEntryID is NULL, indicating the use of a custom recipient provider.
ulFlags
Bitmask of flags associated with various address dialog box options. The following flags can be set:
AB_RESOLVE | Causes all names to be resolved after the address book dialog box is closed. The Resolve Name dialog box is displayed if there are ambiguous entries in the recipient list.
AB_SELECTONLY | Disables the creation of custom recipient addresses and direct type-in entries for a recipient list. This flag is used only if the dialog box is modal.
ADDRESS_ONE | Indicates that the user of the dialog box can select exactly one message recipient, instead of a number of recipients from a recipient list. This flag is valid only when cDestFields is zero. This flag is used only if the dialog box is modal.
DIALOG_MODAL | Causes a modal dialog box to be displayed. The client must set either this flag or DIALOG_SDI, but not both.
DIALOG_OPTIONS | Not supported by Internet Explorer Address Book.
DIALOG_SDI | Causes a modeless dialog box to be displayed. This call returns immediately and thus does not modify the ADRLIST structure passed in. The caller must set either this flag or DIALOG_MODAL, but not both.
lpReserved
Reserved; must be zero.
ulHelpContext
Not supported by Internet Explorer Address Book. Should be zero.
lpszHelpFileName
Not supported by Internet Explorer Address Book. Should be NULL.
lpfnABSDI
Address of an Internet Explorer Address Book function based on the ACCELERATEABSDI (see MAPI documentation) prototype, or NULL. This member applies to the modeless version of the dialog box only, as indicated by the DIALOG_SDI flag being set.

Clients building an ADRPARM structure to pass to IAddrBook::Address must always set the lpfnABSDI member to NULL. If the DIALOG_SDI flag is set, Internet Explorer Address Book then sets it to a valid function before returning. Clients call this function from within their message loop to ensure that accelerators in the address book dialog box work. When the dialog box is dismissed and Internet Explorer Address Book calls the function pointed to by the lpfnDismiss member, clients should unhook the ACCELERATEABSDI function from their message loop.

lpfnDismiss
Address of a function based on the DISMISSMODELESS (see MAPI documentation) prototype, or NULL. This member applies only to the modeless version of the dialog box, as indicated by the DIALOG_SDI flag being set. Internet Explorer Address Book calls the DISMISSMODELESS function when the user dismisses the modeless address dialog box, informing a client calling IAddrBook::Address that the dialog box is no longer active.
lpvDismissContext
Address of the context information to be passed to the DISMISSMODELESS function pointed to by the lpfnDismiss member. This member applies to the modeless version of the dialog box only, as indicated by the DIALOG_SDI flag being set.
lpszCaption
Address of the text to be used as a caption for the address book dialog box.
lpszNewEntryTitle
Address of the text to be used as a new-entry prompt for an edit box in an address book dialog box.
lpszDestWellsTitle
Address of text to be used as a title for the set of recipient-name edit boxes that appears in the dialog box. This member is used only if the address book dialog box is modal.
cDestFields
Number of recipient-name edit boxes (that is, destination fields) in the address book dialog box. A number from 0 through 3 is typical. If the cDestFields member is zero and the ADDRESS_ONE flag is not set in ulFlags, the address book is open for browsing only.
nDestFieldFocus
Field in the address book dialog box that should have the initial focus when the dialog box appears. This value must be between 0 and the value of cDestFields minus 1.
lppszDestTitles
Address of an array of text titles to be displayed in the recipient-name edit boxes of the address book dialog box. The size of the array is the value of cDestFields. If the lppszDestTitles member is NULL, the IAddrBook::Address method chooses default titles.
lpulDestComps
Address of an array of recipient types, such as MAPI_TO, MAPI_CC, and MAPI_BCC, associated with each recipient-name edit box. The size of the array is the value of cDestFields. If the lpulDestComps member is NULL, the IAddrBook::Address method chooses default recipient types.
lpContRestriction
Not supported by Internet Explorer Address Book. Should be NULL.
lpHierRestriction
Not supported by Internet Explorer Address Book. Should be NULL.

Back to top


ENTRYID

typedef struct _ENTRYID
{
    BYTE    abFlags[4];
    BYTE    ab[MAPI_DIM];
} ENTRYID, FAR *LPENTRYID;

Contains the entry identifier information for a MAPI object.

abFlags
Bitmask of flags that provide information describing the object.
ab[MAPI_DIM]
Indicates an array of binary data used by service providers. Client applications cannot use this array.

Back to top


ENTRYLIST

typedef
    SBinaryArray ENTRYLIST,
    FAR *LPENTRYLIST;

The ENTRYLIST structure is an array of entry identifiers representing MAPI objects.

Back to top


MAPI_PAB_Schema

The Internet Explorer Address Book schema is based upon the MAPI Personal Address Book, or (PAB) schema. The following properties are defined in table form. Additional properties can be added by client applications by using the named property methods: GetNamesFromIDs and GetIDsFromNames.

MAPI PAB Schema
Property name | Property type | Property identifier
PR_7BIT_DISPLAY_NAME | PT_STRING8 | 0x39FF
PR_ACCOUNT | PT_TSTRING | 0x39FF
PR_ALTERNATE_RECIPIENT | PT_BINARY | 0x3A01
PR_ASSISTANT | PT_TSTRING | 0x3A30
PR_ASSISTANT_TELEPHONE_NUMBER | PT_TSTRING | 0x3A2E
PR_BEEPER_TELEPHONE_NUMBER | PT_TSTRING | PR_PAGER_TELEPHONE_NUMBER
PR_BIRTHDAY | PT_SYSTIME | 0x3A42
PR_BUSINESS_ADDRESS_CITY | PT_TSTRING | PR_LOCALITY
PR_BUSINESS_ADDRESS_COUNTRY | PT_TSTRING | PR_COUNTRY
PR_BUSINESS_ADDRESS_POST_OFFICE_BOX | PT_TSTRING | PR_POST_OFFICE_BOX
PR_BUSINESS_ADDRESS_POSTAL_CODE | PT_TSTRING | PR_POSTAL_CODE
PR_BUSINESS_ADDRESS_STATE_OR_PROVINCE | PT_TSTRING | PR_STATE_OR_PROVINCE
PR_BUSINESS_ADDRESS_STREET | PT_TSTRING | PR_STREET_ADDRESS
PR_BUSINESS_FAX_NUMBER | PT_TSTRING | 0x3A24
PR_BUSINESS_HOME_PAGE | PT_TSTRING | 0x3A51
PR_BUSINESS_TELEPHONE_NUMBER | PT_TSTRING | 0x3A08
PR_BUSINESS_HOME_PAGE | PT_TSTRING | 0x3A51
PR_BUSINESS_TELEPHONE_NUMBER | PT_TSTRING | 0x3A08
PR_BUSINESS2_TELEPHONE_NUMBER | PT_TSTRING | 0x3A1B
PR_CALLBACK_TELEPHONE_NUMBER | PT_TSTRING | 0x3A02
PR_CAR_TELEPHONE_NUMBER | PT_TSTRING | 0x3A1E
PR_CELLULAR_TELEPHONE_NUMBER | PT_TSTRING | PR_MOBILE_TELEPHONE_NUMBER
PR_CHILDRENS_NAMES | PT_MV_TSTRING | 0x3A58
PR_COMMENT | PT_TSTRING | 0x3004
PR_COMPANY_MAIN_PHONE_NUMBER | PT_TSTRING | 0x3A57
PR_COMPANY_NAME | PT_TSTRING | 0x3A16
PR_COMPUTER_NETWORK_NAME | PT_TSTRING | 0x3A49
PR_CONTACT_ADDRTYPES | PT_MV_TSTRING | 0x3A54
PR_CONTACT_DEFAULT_ADDRESS_INDEX | PT_LONG | 0x3A55
PR_CONTACT_EMAIL_ADDRESSES | PT_MV_TSTRING | 0x3A56
PR_CONTACT_ENTRYIDS | PT_MV_BINARY | 0x3A53
PR_CONTACT_VERSION | PT_CLSID | 0x3A03
PR_CONVERSION_PROHIBITED | PT_BOOLEAN | 0x3A03
PR_COUNTRY | PT_TSTRING | 0x3A26
PR_CUSTOMER_ID | PT_TSTRING | 0x3A4A
PR_DEPARTMENT_NAME | PT_TSTRING | 0x3A18
PR_DISCLOSE_RECIPIENTS | PT_BOOLEAN | 0x3A04
PR_DISPLAY_NAME | PT_TSTRING | 0x3001
PR_DISPLAY_NAME_PREFIX | PT_TSTRING | 0x3A45
PR_EMAIL_ADDRESS | PT_TSTRING | 0x3003
PR_ENTRYID | PT_BINARY | 0x0FFF
PR_FTP_SITE | PT_TSTRING | 0x3A4C
PR_GENDER | PT_SHORT | 0x3A4D
PR_GENERATION | PT_TSTRING | 0x3A05
PR_GIVEN_NAME | PT_TSTRING | 0x3A06
PR_GOVERNMENT_ID_NUMBER | PT_TSTRING | 0x3A07
PR_HOBBIES | PT_TSTRING | 0x3A43
PR_HOME_ADDRESS_CITY | PT_TSTRING | 0x3A59
PR_HOME_ADDRESS_COUNTRY | PT_TSTRING | 0x3A5A
PR_HOME_ADDRESS_POST_OFFICE_BOX | PT_TSTRING | 0x3A5E
PR_HOME_ADDRESS_POSTAL_CODE | PT_TSTRING | 0x3A5B
PR_HOME_ADDRESS_STATE_OR_PROVINCE | PT_TSTRING | 0x3A5C
PR_HOME_ADDRESS_STREET | PT_TSTRING | 0x3A5D
PR_HOME_FAX_NUMBER | PT_TSTRING | 0x3A25
PR_HOME_TELEPHONE_NUMBER | PT_TSTRING | 0x3A09
PR_HOME2_TELEPHONE_NUMBER | PT_TSTRING | 0x3A2F
PR_INITIALS | PT_TSTRING | 0x3A0A
PR_ISDN_NUMBER | PT_TSTRING | 0x3A2D
PR_KEYWORD | PT_TSTRING | 0x3A0B
PR_LANGUAGE | PT_TSTRING | 0x3A0C
PR_LOCALITY | PT_TSTRING | 0x3A27
PR_LOCATION | PT_TSTRING | 0x3A0D
PR_MAIL_PERMISSION | PT_BOOLEAN | 0x3A0E
PR_MANAGER_NAME | PT_TSTRING | 0x3A4E
PR_MHS_COMMON_NAME | PT_TSTRING | 0x3A0F
PR_MIDDLE_NAME | PT_TSTRING | 0x3A44
PR_MOBILE_TELEPHONE_NUMBER | PT_TSTRING | 0x3A1C
PR_NICKNAME | PT_TSTRING | 0x3A4F
PR_OBJECT_TYPE | PT_LONG | 0xFFE
PR_OFFICE_LOCATION | PT_TSTRING | 0x3A19
PR_OFFICE_TELEPHONE_NUMBER | PT_TSTRING | PR_BUSINESS_TELEPHONE_NUMBER
PR_OFFICE2_TELEPHONE_NUMBER | PT_TSTRING | PR_BUSINESS2_TELEPHONE_NUMBER
PR_ORGANIZATIONAL_ID_NUMBER | PT_TSTRING | 0x3A10
PR_ORIGINAL_DISPLAY_NAME | PT_TSTRING | 0x3A13
PR_ORIGINAL_ENTRYID | PT_BINARY | 0x3A12
PR_ORIGINAL_SEARCH_KEY | PT_BINARY | 0x3A14
PR_OTHER_ADDRESS_CITY | PT_TSTRING | 0x3A5F
PR_OTHER_ADDRESS_COUNTRY | PT_TSTRING | 0x3A60
PR_OTHER_ADDRESS_POST_OFFICE_BOX | PT_TSTRING | 0x3A64
PR_OTHER_ADDRESS_POSTAL_CODE | PT_TSTRING | 0x3A61
PR_OTHER_ADDRESS_STATE_OR_PROVINCE | PT_TSTRING | 0x3A62
PR_OTHER_ADDRESS_STREET | PT_TSTRING | 0x3A63
PR_OTHER_TELEPHONE_NUMBER | PT_TSTRING | 0x3A1F
PR_PAGER_TELEPHONE_NUMBER | PT_TSTRING | 0x3A21
PR_PERSONAL_HOME_PAGE | PT_TSTRING | 0x3A50
PR_POST_OFFICE_BOX | PT_TSTRING | 0x3A2B
PR_POSTAL_ADDRESS | PT_TSTRING | 0x3A15
PR_POSTAL_CODE | PT_TSTRING | 0x3A2A
PR_PREFERRED_BY_NAME | PT_TSTRING | 0x3A47
PR_PRIMARY_FAX_NUMBER | PT_TSTRING | 0x3A23
PR_PRIMARY_TELEPHONE_NUMBER | PT_TSTRING | 0x3A1A
PR_PROFESSION | PT_TSTRING | 0x3A46
PR_RADIO_TELEPHONE_NUMBER | PT_TSTRING | 0x3A1D
PR_SEND_INTERNET_ENCODING | PT_LONG | 0x3A71
PR_SEND_RICH_INFO | PT_BOOLEAN | 0x3A40
PR_SPOUSE_NAME | PT_TSTRING | 0x3A48
PR_STATE_OR_PROVINCE | PT_TSTRING | 0x3A28
PR_STREET_ADDRESS | PT_TSTRING | 0x3A29
PR_SURNAME | PT_TSTRING | 0x3A11
PR_TELEX_NUMBER | PT_TSTRING | 0x3A2C
PR_TITLE | PT_TSTRING | 0x3A17
PR_TRANSMITABLE_DISPLAY_NAME | PT_TSTRING | 0x3A20
PR_TTYTDD_PHONE_NUMBER | PT_TSTRING | 0x3A4B
PR_USER_CERTIFICATE | PT_BINARY | 0x3A22
PR_USER_X509_CERTIFICATE | PT_MV_BINARY | 0x3A70
PR_WEDDING_ANNIVERSARY | PT_SYSTIME | 0x3A41


SPropProblem

typedef struct _SPropProblem {
    ULONG     ulIndex;
    ULONG     ulPropTag;
    SCODE     scode;
} SPropProblem;

Describes an error relating to an operation involving a property.

ulIndex
Index value into an array of property tags.
ulPropTag
Property tag for the property with the error.
scode
Error value describing the problem with the property.

Back to top


SPropProblemArray

typedef struct _SPropProblemArray {
    ULONG           cProblem;
    SPropProblem    aProblem[MAPI_DIM];
    } SPropProblemArray;

Contains an array of one or more SPropProblem structures.

cProblem
Count of SPropProblem structures in the array indicated by the aProblem member.
aProblem[MAPI_DIM]
Array of SPropProblem structures, each describing a property error.

Back to top


SPropTagArray

typedef struct _SPropTagArray{
    ULONG   cValues;
    ULONG   aulPropTag[MAPI_DIM];
} SPropTagArray;

Contains an array of property tags.

cValues
Count of property tags in the array indicated by the aulPropTag member.
aulPropTag[MAPI_DIM]
Array of property tags.

Back to top


SPropValue

typedef struct _SPropValue {
    ULONG       ulPropTag;
    ULONG       dwAlignPad;
    union _PV   Value;
    } SPropValue;

Contains the property tag values.

ulPropTag
Property tag for the property. Property tags are 32-bit unsigned integers consisting of the property's unique identifier in the high-order 16 bits and the property's type in the low-order 16 bits.
dwAlignPad
Reserved; do not use.
Value
Union of data values, the specific value dictated by the property type. The following table lists, for each property type, the member of the union that should be used and its associated data type.

Table of Property Types
Property type | Value | Data type of Value
PT_I2 or PT_SHORT | i | short int
PT_I4 or PT_LONG (signed) | i | LONG
PT_R4 or PT_FLOAT | flt | FLOAT
PT_R8 or PT_DOUBLE | dbl | double
PT_BOOLEAN | b | unsigned short int
PT_CURRENCY | cur | CURRENCY
PT_APPTIME | at | double
PT_SYSTIME | ft | FILETIME
PT_STRING8 | lpszA | LPSTR
PT_BINARY | bin | BYTE [array]
PT_UNICODE | lpszW | LPWSTR
PT_CLSID | lpguid | LPGUID
PT_I8 or PT_LONGLONG | li | LARGE_INTEGER
PT_MV_I2 | MVi | SShortArray
PT_MV_LONG | MVI | SLongArray
PT_MV_R4 | MVflt | SRealArray
PT_MV_DOUBLE | MVdbl | SDoubleArray
PT_MV_CURRENCY | MVcur | SCurrencyArray
PT_MV_APPTIME | MVat | SAppTimeArray
PT_MV_SYSTIME | MVft | SDateTimeArray
PT_MV_BINARY | MVbin | SBinaryArray
PT_MV_STRING8 | MVszA | SLPSTRArray
PT_MV_UNICODE | MVszW | SLPSTRArray
PT_MV_CLSID | MVguid | SGuidArray
PT_MV_I8 | MVli | SLargeIntegerArray
PT_ERROR | err | SCODE
PT_NULL or PT_OBJECT | x | LONG

Back to top


SRestriction

typedef struct _SRestriction
{
    ULONG   rt;
    union
    {
        SComparePropsRestriction    resCompareProps;
        SAndRestriction             resAnd;
        SOrRestriction              resOr;
        SNotRestriction             resNot;
        SContentRestriction         resContent;
        SPropertyRestriction        resProperty;
        SBitMaskRestriction         resBitMask;
        SSizeRestriction            resSize;
        SExistRestriction           resExist;
        SSubRestriction             resSub;
        SCommentRestriction         resComment;
    } res;
} SRestriction;

Describes a filter for limiting the view of a table to particular rows.

rt
Restriction type. Possible values are:
RES_AND | SRestriction structure describes an AND restriction, which applies a bitwise AND operation to a restriction.
RES_BITMASK | SRestriction structure describes a bitmask restriction, which applies a bitmask to a property value.
RES_COMMENT | SRestriction structure describes a comment restriction, which associates a comment with a restriction.
RES_COMPAREPROPS | SRestriction structure describes a compare properties restriction, which compares two property values.
RES_CONTENT | SRestriction structure describes a content restriction, which searches a property value for specific content.
RES_EXIST | SRestriction structure describes an exist restriction, which determines if a property is supported.
RES_NOT | SRestriction structure describes a NOT restriction, which applies a logical NOT operation to a restriction.
RES_OR | SRestriction structure describes an OR restriction, which applies a logical OR operation to a restriction.
RES_PROPERTY | SRestriction structure describes a property restriction, which determines if a property value matches a particular value.
RES_SIZE | SRestriction structure describes a size restriction, which determines if a property value is a particular size.
RES_SUBRESTRICTION | SRestriction structure describes a subobject restriction, which applies a restriction to a message's attachments or recipients.
res
Union of restriction structures describing the filter to be applied. The specific structure included in the res member depends on the value of the rt member. The mapping between restriction type and structure is listed in the following table.
Restriction type | Structure
RES_AND | SAndRestriction
RES_BITMASK | SBitMaskRestriction
RES_COMMENT | SCommentRestriction
RES_COMPAREPROPS | SComparePropsRestriction
RES_CONTENT | SContentRestriction
RES_EXIST | SExistRestriction
RES_NOT | SNotRestriction
RES_OR | SOrRestriction
RES_PROPERTY | SPropertyRestriction
RES_SIZE | SSizeRestriction
RES_SUBRESTRICTION | SSubRestriction

Back to top


SRow

typedef struct _SRow {
    ULONG         ulAdrEntryPad;
    ULONG         cValues;
    LPSPropValue  lpProps;
    } SRow, FAR *LPSRow;

Describes a row from a table containing selected properties for a specific object.

ulAdrEntryPad
Padding bytes to properly align the property values pointed to by the lpProps member.
cValues
Count of property values pointed to by lpProps.
lpProps
Address of an array of SPropValue structures that describe the property values for the columns in the row.

Back to top


SRowSet

typedef struct _SRowSet {
    ULONG   cRows;
    SRow    aRow[MAPI_DIM];
    } SRowSet;

Contains an array of SRow structures, each SRow structure describing a row from a table.

cRows
Count of SRow structures in the aRow member
aRow[MAPI_DIM]
Array of SRow structures, one for each row in the table.

Back to top


SSortOrder

typedef struct _SSortOrder {
    ULONG ulPropTag;
    ULONG ulOrder;
    } SSortOrder, FAR *LPSSortOrder;

Defines how to sort rows of a table, describing the column to use as the sort key and the direction of the sort.

ulPropTag
Property tag identifying the sort key or, for a categorized sort, the category column.
ulOrder
Order in which the data is to be sorted. Possible values are:
TABLE_SORT_ASCEND | The table should be sorted in ascending order.
TABLE_SORT_COMBINE | The sort operation should create a category that combines the property identified as the sort key column in the ulPropTag member with the sort key column specified in the previous SSortOrder structure.
TABLE_SORT_COMBINE can only be used when the SSortOrder structure is being used as an entry in an SSortOrderSet structure to specify multiple sort orders for a categorized sort. TABLE_SORT_COMBINE cannot be used in the first SSortOrder structure in an SSortOrderSet structure.
TABLE_SORT_DESCEND | The table should be sorted in descending order.

Back to top


SSortOrderSet

typedef struct _SSortOrderSet {
    ULONG      cSorts;
    ULONG      cCategories;
    ULONG      cExpanded;
    SSortOrder aSort[MAPI_DIM];
    } SSortOrderSet, FAR *LPSSortOrderSet;

Defines a collection of sort keys for a table to be used for standard or categorized sorting.

cSorts
Count of SSortOrder structures that are included in the aSort member.
cCategories
Count of columns that are designated as category columns. Possible values range from zero, which indicates a non-categorized or standard sort, to the number indicated by the cSorts member.
cExpanded
Count of categories that start in an expanded state, where all the rows that apply to the category are visible in the table view. Possible values range from zero to the number indicated by cCategories.
aSort[MAPI_DIM]
Array of SSortOrder structures, each defining a sort order.

Back to top


Internet Explorer Address Book Structures

This section contains the data structures and related information that are used by the Internet Explorer Address Book programming interfaces.

  • ADRENTRY
  • ADRLIST
  • ADRPARM
  • ENTRYID
  • ENTRYLIST
  • MAPI_PAB_Schema
  • SPropProblem
  • SPropProblemArray
  • SPropTagArray
  • SPropValue
  • SRestriction
  • SRow
  • SRowSet
  • SSortOrder
  • SSortOrderSet
  • WAB_PARAM


WAB_PARAM

typedef struct _tagWAB_PARAM
{
    ULONG   cbSize;
    HWND    hwnd;
    LPTSTR  szFileName;
    ULONG   ulFlags;
    } WAB_PARAM ;

Contains the input information to pass to WABOpen.

cbSize
Size, in bytes, of the WAB_PARAM structure.
hwnd
hWnd parameter of the calling client application. Can be NULL.
szFileName
Internet Explorer Address Book file name to open. If this parameter is NULL, the default Address Book file is opened.
ulFlags
Currently not implemented in Internet Explorer Address Book.


Cache Container Tool

The Cache Container Tool (Cdcache.exe) is an AutoRun executable file that allows content outside of the cache to be associated with a specified URL, which can be referenced by Microsoft Internet Explorer 4.0. This tool allows you to assign a URL that will reference content from another directory or CD-ROM.

The tool creates a cache container in the Internet Explorer persistent URL cache. When a user enters the URL, the browser looks for the resource in the location specified by the cache container.

If an earlier version of Microsoft Internet Explorer is installed on the computer, a message appears, notifying the user that Microsoft Internet Explorer 4.0 is required, unless the /NoIE4Msg or /Silent command-line option is used.

The tool can be found in the \bin directory of the Internet Client SDK.

Usage

Command-Line Options

Usage

Use the following steps to install a cache container that references a CD-ROM:

  1. Create an Autorun.inf file.
  2. In the Autorun.inf file, enter the following text:
    [autorun]
open=cdcache.exe
icon=cdcache.exe, 1

    If you want to use one of the Command-Line Options, add it to the open= line in the Autorun.inf file. The following example would install the cache container without displaying any user interface.

    [autorun]
open=cdcache.exe /Silent
icon=cdcache.exe,1
  3. In the Autorun.inf file, add one or more entries to create a cache container. This section must contain less than 64K of data. It must be in the following format:
    [Add.CacheContainer]
<Friendly Name>=<INF Section Name>

    The friendly name can be either the name of the company or the name of the product for which the cache container is being created. INF Section Name is the label you will use in the .inf file to define the details of your cache container.

    The following example shows an entry for two cache containers: one for Awesome Computers and one for Trey Research.

    [Add.CacheContainer]
Awesome Computers=AwesomeComp
Trey Research=TreyResearch
  4. In the Autorun.inf file, add a cache container detail section for each cache container defined in the previous step. It must be in the following format:
    [INF Section Name]
CachePrefix=<string>
CacheRoot=<relative path to the data>
KBCacheLimit=<numerical amount in KB>
AutoDelete=<Yes|No>
IncludeSubDirs=<Yes|No>
VolumeTitle=<string>
    CachePrefix | Determines the URL pattern that the cache container will provide data for. For the cache container to work properly, the pattern cannot end with a backslash (/). For example, the URL pattern http://www.awesome_computers.com/ is incorrect. It must be http://www.awesome_computers.com to work properly. The same is true of patterns that include directories. For example, the URL pattern http://www.trey_research.com/awards/ must be set as http://www.trey_research.com/awards.
    CacheRoot Contains the relative path to the data provided by the cache container. The following replaceable parameters can be used for this entry:
    %EXE_DRIVE%
    Automatically replaced with the drive letter (including the colon) of the execution path of the Cdcache.exe tool.
    %EXE_ROOT%
    Automatically replaced with the full directory path of the Cdcache.exe tool.
    KBCacheLimit | Contains the maximum number of kilobytes of data that can be stored in the user's local cache.
    AutoDelete | Determines if the cache container data residing in the user's local cache should be purged after an interval (predetermined by Microsoft Internet Explorer 4.0) of non-use.
    IncludeSubDirs | Specifies whether directories residing below the main CacheRoot= should be used to supply cache container data. Without this flag, only resources in the immediate CacheRoot= directory will be used to supply cache container data.
    VolumeTitle | Contains the title or friendly name of the CD-ROM that the container was created for.

    The following example shows entries for two cache container detail sections.

    [AwesomeComp]
CachePrefix=http://www.awesome_computers.com
CacheRoot=%EXE_DRIVE%\data\http\
KBCacheLimit=1000
AutoDelete=Yes
IncludeSubDirs=Yes

[TreyResearch]
CachePrefix=http://www.trey_research.com/awards
CacheRoot=%EXE_DRIVE%\data\http\awards\
KBCacheLimit=500
AutoDelete=Yes
IncludeSubDirs=Yes
  5. Place the Autorun.inf file at the root directory of the CD-ROM, which contains the content you want to register.

Command-Line Options

The Cdcache.exe tool supports the following command-line options:

/NoIE4Msg | Disables the message that informs the user that Microsoft Internet Explorer 4.0 is required.
/Silent | Installs all cache containers in the Autorun.inf file without displaying any user interface. This option will also cause it to fail silently.
/Remove | Uninstalls all the cache containers listed in the Autorun.inf file.
/Uninstall | Same as /Remove.


Microsoft CryptoAPI 2.0 Microsoft CryptoAPI 2.0 *
  * Previous Topic:

 UDACCEL
  * Next Topic: Microsoft DirectX Media SDK

Microsoft CryptoAPI 2.0

For information about Microsoft Cryptography, see the CryptoAPI site.


COM Objects as Data Providers

To date, IE4/MSHTML has used the typeinfo of a COM object to determine if it was a data provider. This was confusing, non-standard, and less than straightforward to implement with dual interface support.

This document specifies a new method for data providing COM objects to advertise that they are data providers. Additionally, it specifies a notification mechanism that can be used by data consumers to receive notifications when the underlying data set supplied by the object changes.

Recognizing COM Objects as Data Providers

Notifications for Data Set Changes

Recognizing COM Objects as Data Providers

Data-providing COM objects will identify themselves as data providers by implementing a method that, when called, returns an interface pointer to one of the IE4/MSHTML supported data interfaces. The signature for the method is as follows:

HRESULT msDataSourceObject(
    [in] BSTR qualifier,
    [out,retval] IUnknown **ppUnk);

The qualifier parameter will be used when a data-providing COM object supports access to more than one set of data. When the parameter is NULL or a null string (""), the COM object should return the data interface on its default data set. What constitutes the default data set is left to COM object.

IE4/MSHTML 1.0 will only support COM objects that supply a single data set. Therefore, IE4/MSHTML will only use the msDataSourceObject(0) form of the call when invoking the interface.

DISPID

This interface will be available at the reserved DispID -3900.

Notifications for Data Set Changes

There are instances where a consumer already has an interface to a data set supplied by the object, and the shape of the data set changes. For example, the number of columns changes, the name of the columns changes, the type of a column(s) changes, or the entire data set is reordered (result of a sort operation). In such an instance, there needs to be a way for the consumer to be notified of the change so it can retrieve a new interface on the (changed) data—using a call to msDataSourceObject. Consumers will do this by registering with the provider for a notification.

The object must support a method whereby the consumer can register for receiving such notifications. The method has the following signature:

HRESULT addDataSourceListener(
    [in] DataSourceListener *pEvent);

DataSourceListener is defined as follows:

[ local,
    object,
    version(1.0)
    uuid(7c0ffab2-cd84-11d0-949a-00a0c91110ed)
]

interface DataSourceListener : IUnknown
{
    HRESULT dataMemberChanged([in] BSTR qualifier);
    HRESULT dataMemberAdded([in] BSTR qualifier);
    HRESULT dataMemberRemoved([in] BSTR qualifier);
}

When a data change occurs, the object will call the dataMemberChanged method of DataSourceListener to notify the data consumer that the shape has changed. The object will pass the corresponding qualifier to the consumer. IE4/MSHTML 1.0 will only use the value NULL or "" for the qualifier. The dataMemberAdded and dataMemberRemoved methods are called to notify the consumer that a multiple-dataset-capable applet has a new data set available or has removed a previously existing data set. Since IE4/MSHTML 1.0 will not support multiple data sets, these events will be ignored.

Finally, a data consumer can notify a provider that it is no longer interested in data-shape-change notifications by calling addDataSourceListener(NULL). Note that this precludes multicasting event notifications but keeps requirements on controls simple.

IE4/MSHTML 1.0 will never examine the qualifier value in DataSourceListener::dataMemberChanged since providers with multiple datasets are not supported.

DISPID

This interface will be available at the reserved DispID -3901.


IE4/MSHTML Data Binding Interfaces

This section describes the IE4/MSHTML ability to bind data to an HTML page using a COM object or a Java applet. The following contain information on how to use these methods to do data binding.

COM Objects as Data Providers

OLE-DB Simple Provider: A Data Binding API for IE4/MSHTML

Java Applets as Data Providers

OLE-DB Simple Provider for Java: A Data Binding API for IE4/MSHTML


Java Applets as Data Providers

To date, IE4/MSHTML has supported ActiveX™ Controls as data providers when present on an HTML page and when the control supports either the OLE-DB Simple Provider interface or is an instance of the Advanced Data Connector (ADC), which provides OLE-DB interfaces. Note that ADC is the only OLE-DB interface supported in release 1.0 of IE4/MSHTML. As Java becomes more prevalent on the Internet, it will be desirable for IE4/MSHTML to support writing data sources in Java using JavaBeans.

The remainder of this article specifies the conventions to be used when constructing data-providing applets in Java. The internal IE4/MSHTML data binding agent implements support to detect and utilize such applets similar to the current support for ActiveX Controls.

Overview

Recognizing Java Applets as Data Providers

Notifications for Data Set Changes

Overview

Although IE4/MSHTML 1.0 will only support third-party providers that implement the OLE-DB Simple Provider interface, this specification is constructed to allow support for additional provider types when IE4/MSHTML adds support for those providers. All references to the OSP interfaces in this specification can be summarily changed to any of the additional provider interfaces supported by IE4/MSHTML.

Recognizing Java Applets as Data Providers

The applet writer needs a way to allow the IE4/MSHTML binding agent to detect the Java applet as a data provider. The most straightforward way to accomplish this is for the applet to implement a well-known method that the IE4/MSHTML binding agent will call to recognize the applet. The method will have the following signature:

public Object msDataSourceObject( String qualifier );

The qualifier parameter will be used when a data-providing applet supports access to more than one set of data. When the parameter is NULL or a null string (""), the applet should return the data interface on its default data set. What constitutes the default data set is left to the applet.

IE4/MSHTML 1.0 will only support applets that provide a single data set; therefore, it will use only the msDataSourceObject("") form of the call when invoking the interface.

Notifications for Data Set Changes

There are instances where a consumer already has an interface to a data set supplied by an applet, and the shape of the data set changes. For example, the number of columns changes, the name of the columns changes, the type of a column(s) changes, or the entire data set is reordered (result of a sort operation). In such an instance, there needs to be a way for the consumer to get notified of the change so it can retrieve a new interface on the (changed) data—using a call to msDataSourceObject. Consumers will do this by registering with the provider for a notification.

The applet must support a method whereby the consumer can register for receiving such notifications. The method has the following signature:

public void addDataSourceListener( DataSourceListener listener )
    throws java.util.TooManyListenersException;

IDataSourceListener is defined as follows:

public abstract interface DataSourceListener
{
   void dataMemberChanged( String qualifier );
   void dataMemberAdded( String qualifier );
   void dataMemberRemoved( String qualifier );
}

When a data change occurs, the applet will call the dataMemberChanged method on the DataSourceListener interface to notify the data consumer that the shape has changed. The qualifier will indicate which data interface has changed (for IE4/MSHTML 1.0, this will be ignored since data sources can only expose a single data set).

Finally, a data consumer must notify a provider that it is no longer interested in data-shape-change notifications by calling the following method:

public void removeDataSourceListener(
    DataSourceListener listener);

The DataSourceListener should be identical to the one passed to addDataSourceListener.


OLE-DB Simple Provider: A Data Binding API for IE4/MSHTML

IE4/MSHTML supports a very simple, easily implemented API for exposing data to HTML pages. The API supports access to string and variant data types and is built using array-like structures to expose rows and columns. Third parties can use the OLE-DB Simple Provider API to implement their custom data source objects.

Introduction

OLE-DB Simple Provider

OLE-DB Simple Provider Listener

Introduction

OLE-DB Simple Provider (OSP) is an interface specification that hosts can implement to expose their tabular data to HTML elements in IE4/MSHTML. OSP specifies only simple, minimal functionality that requires only minimal effort on the part of control/applet authors to expose their data. OSP specifies methods for adding, deleting, and setting the value of columns, searching through the set of data and receiving notifications on data events.

OLE-DB Simple Provider was formerly called Simple Tabular Data, or STD for short.

OLE-DB Simple Provider

OSP exposes a set of tabular data (data set) in an array-like structure. Elements of the data set are referenced by their row and column indexes.

Data references

Indexes begin with value 1 and increase. There are two special index values.
0 | Reserved for label information in the case of a row, and header information in the case of a column.
-1 | The wildcard value. Refers to an unknown value or all values. For example, Row=-1, Col=2 refers to the entire column 2.

OSP defines two distinct interfaces: OLEDBSimpleProvider and OLEDBSimpleProviderListener. As you would expect, OLEDBSimpleProvider implements the methods used for data access, and OLEDBSimpleProviderListener specifies the methods to be implemented by the host for receiving notification of data changes.

Interface ID

The OLEDBSimpleProvider interface is identified by the following IID:

{E0E270C0-C0BE-11d0-8FE4-00A0C90A6341}

The methods implemented by OLEDBSimpleProvider can be broken down into the following logical areas.

Schema functions

Three functions are provided for obtaining the schema for the underlying rows or columns.

HRESULT getRowCount([out, retval] LONG *pcRows)
Returns the number of rows in the data set.
HRESULT getColumnCount( [out,retval] LONG *pcColumns)
Returns the number of columns in the data set.
HRESULT getRWStatus([in] LONG iRow, [in] LONG iColumn, [out, retval] OSPRW *prwStatus)
Returns the read/write status for the specified row and column. If one or both of iRow and iColumn have a value of -1, the read/write status is returned for the entire column, row, or complete data set.

OSPRW is an enumeration with the following values:
OSPRW_READONLY | Cell, row, column, or data set is read-only.
OSPRW_READWRITE | Cell, row, column, or data set can be modified.
OSPRW_MIXED | Cell, row, column, or data set read-write status unknown or row, column, or data set mixed status.

Variant-oriented functions

Two functions are provided to allow retrieval and setting of variant values in the data set:

HRESULT getVariant([in] LONG iRow, [in] LONG iColumn, [in] OSPFORMAT fFormatted, [ out, retval] VARIANT *pVar)
Retrieves the value of the cell at the row and column indicated into the preallocated variant supplied in pVar. Based on the value specified in fFormatted, pVar will contain either a value with the type of the underlying column, a string that corresponds to the underlying type of the column, or an HTML fragment that corresponds to the underlying type of the column.
HRESULT setVariant([in] LONG iRow, [in] LONG iColumn, [in] OSPFORMAT fFormatted, [in, retval] VARIANT Var)
Sets the value of the cell at the row and column indicated to the value of the variant supplied in pVar in the type requested by the value of fFormatted.

OSPFORMAT is an enumeration with the following values:
OSPFORMAT_RAW | The underlying type of the column should be used to either set the value or get the value.
OSPFORMAT_FORMATTED | The underlying type of the column should be converted to a string and the string returned as a BSTR within the variant.
OSPFORMAT_HTML | The underlying type of the column should be converted to an HTML string.

Notes

  • For both functions, as per the definition of VARIANT, references are not supported.
  • For setVariant with any of the formatting options, it is the provider's responsibility to perform the appropriate coercion to the underlying type of the column. In cases where the coercion cannot be successfully completed, an appropriate error return code should be returned.
  • For setVariant with OSPFORMAT_FORMATTED, the provider is free to interpret the input string however it sees fit. Alternatively, the provider may attempt to parse the input string and heuristically determine an appropriate data type and value to place into the cell—for example, when updating formatted spreadsheet cells.
  • When OSPFORMAT_HTML is requested, the provider may, at its option, return a plain string (unadorned with HTML tags and so on).
  • A database NULL is indicated by returning a variant of type VT_NULL for any of the fFormatted types.
  • Wildcard values (-1) are not valid for the iRow and iColumn attributes in setVariant or getVariant.

Deletion and Insertion

Functions are provided to insert and delete rows. For all functions, the row numbers provide the position within the data set to which the row will be inserted. That is, the row inserted will have the index specified.
HRESULT deleteRows([in] LONG iRow, [in] LONG cRows, [out, retval] LONG *pcRowsDeleted)
Deletes cRows from the data set starting at row iRow. The number of rows successfully deleted is returned in pcRowsDeleted.
HRESULT insertRows([in] LONG iRow, [in] LONG cRows, [out, retval] LONG *pcRowsInserted)
Inserts cRows into the data set starting at row iRow. The number of rows successfully inserted is returned in pcRowsInserted.

Notes

  • In the case of an error, the provider may choose to insert/delete rows up to the point where the error occurred. In such a case, the [out] parameter specifies the number of rows actually inserted/deleted.
  • Values for the inserted rows are not specified. Use the setVariant function to set the value of the cells inserted.

Searching

A function is provided that supports some basic searching capability on the data set. The goal of this function is to be fairly easy for the provider to implement while providing the client with a meaningful set of functionality to perform complex searching.

HRESULT find([in] LONG iRowStart, [in] LONG iColumn, [in] VARIANT varSval, [in] OSPFIND findFlags, [in] OSPCOMP compType, [out, retval] LONG *piRowFound)
Searches for the values specified in varSval in column iColumn starting at row iRowStart. Upon successful completion, the row number with the matching value is returned in piRowFound.

Supported values for OSPFIND are:
OSPFIND_UP | Specifies scan should be decreasing in row number.
OSPFIND_CASESENSITIVE | Specifies that search should be case sensitive.

Supported values for OSPCOMP are:
OSPCOMP_LT | Specifies the first value less than varSval is being searched for.
OSPCOMP_LE | Specifies the first value less than or equal to varSval is being searched for.
OSPCOMP_GT | Specifies the first value greater than varSval is being searched for.
OSPCOMP_GE | Specifies the first value greater than or equal to varSval is being searched for.
OSPCOMP_EQ | Specifies the first value equal to varSval is being searched for.
OSPCOMP_NE | Specifies the first value not equal to varSval is being searched for.

Notes

  • Find does compares using the native type of the underlying column. Providers are encouraged to simply fail when the type of the varSval differs from the underlying type of the column.
  • Comparing string values always compares values as they would be returned from a call to GetVariant with OSPFORMAT_FORMATTED. Providers should not coerce values of varSval obtained from a previous call to GetVariant with OSPFORMAT_HTML.
  • If no corresponding match is found, Find should return the constant -1.

Asynchronous data population

The main function of an OSP is to provide data to an HTML page. In many cases, the data will need to be transported over high-latency, low bandwidth networks, in most cases using a 28.8K modem. The OSP design accounts for making data available as expediently as possible while maintaining an architecture and interface specification that is easy to author.

All OSP authors are encouraged to implement support for populating (or retrieving) the data they expose asynchronously. This allows the host to continue processing during data transmission instead of blocking on a call to the OSP until the entire data set has been transmitted to the client.

The majority of the work required to support asynchronous data delivery does not involve the OSP interface specifically; it is a requirement on the mechanisms to retrieve data from their underlying storages. Accordingly, three methods are required in the OSP interface: one to indicate whether the provider supports asynchronous population; one to return the progress of the asynchronous population; and a third to stop the asynchronous transmission of data.

Two additional events are added to the OSP event notifications. One event indicates when additional data has become available for access through the interface, while the other signals that the asynchronous data population has completed. Both events are specified below in the OLE-DB Simple Provider Events section.

HRESULT isAsync( [out, retval] BOOL *pbAsynch)
Returns a Boolean indicating whether data is being populated asynchronously.

Notes

IsAsynch should never block; it should always return the appropriate state.

HRESULT getEstimatedRows( [out, retval] LONG *piRows)
Returns the estimated total number of rows in the data set. Callers can use this in conjunction with GetRowCount with an asynchronous provider to obtain an estimate of the percentage of data received.

Notes

  • When the number of rows in the data set cannot be estimated, the provider should return the special value -1.
  • Synchronous providers should not block on the call to GetEstimatedRows. They should either return -1 to indicate that they cannot provide an estimate, or the actual row count (same as would be obtained through GetRowCount).
  • Providers should not return the final row count from EstimatedRows prior to firing the TransferComplete event (see below).
HRESULT stopTransfer()
Requests that the OSP discontinue asynchronous transfer of data.

Notes

  • Providers should make every effort to expose the data transferred prior to receiving this request. The provider must expose a valid, consistent OSP interface for such data—appropriate column/row count, read/write status, and so on.
  • Providers that cannot expose the data transferred prior to this request should discontinue the transfer of data and fail all subsequent calls to the OSP interface.

Internationalization

Implementers may have to consider cases where the consumer is running in a different locale from the source of the data. The provider is responsible for ensuring that data conversions are done in an appropriate fashion. In particular, be careful in cases where the string representation of many data types differs according to locale. For example, the float or double number 3.14 would be "3.14" in the US, and "3,14" in Germany. Date representations differ even more. For example, number (especially float, date) to string conversions done by GetVariant or SetVariant with the OSP_FORMATTED option specified should usually be done in the locale of the browser.

The Find method has more complicated issues to deal with to implement its ordered comparisons correctly across locale boundaries. These comparisons should, where possible, also be done in the locale of the browser, although this issue is not as clear cut. (For example, if the data consists of strings containing European accented characters, it is not clear that a browser in the en-us locale has any preferred sorting order for these strings. The sorting order of the provider locale might be more useful.)

It is anticipated that there will be cases where the consumer will need to know the locale of the data in order to perform proper operations on that data. A method is provided for the provider to return this information.

HRESULT getLocale([out,retval] BSTR *pbstrLocale)
Returns a string in pbstrLocale that indicates the locale of the data returned by GetLocale. This is used to perform the appropriate type conversions.

Notes

  • GetLocale should simply return the empty string ("") when the provider does not support localization. This will allow the consuming entity to use the default from the operating system.
  • For all values of pbstrLocale, the category LC_ALL is assumed by the consumer.

Sinking events

Methods are provided to attach and detach a unicast event handler for all events.

HRESULT addOLEDBSimpleProviderListener([in] OLEDBSimpleProviderListener *posplListener)
Registers the event handler interface specified by posplListener to receive notifications of changes to data.

Notes

  • If an event handler was specified previously, addOLEDBSimpleProviderListener releases the previous event handler prior to registering posplListener.
  • OSP events are unicast only. There can be only one listener.
HRESULT removeOLEDBSimpleProviderListener([in] OLEDBSimpleProviderListener *posplListener)
Unregisters the event handler interface specified by posplListener.

Notes

removeOLEDBSimpleProviderListener should always specify the posplListener previously registered. In the event that posplListener differs from the event handler registered, the call should fail.

OLE-DB Simple Provider Listener

OSP implementers fire notifications of changes to the underlying data through a single event handler. There are pre- and post-notifications for each event.

Interface ID

The OLEDBSimpleProviderListener interface can be identified by the following IID:

{E0E270C1-C0BE-11d0-8FE4-00A0C90A6341}

The event handler, registered through OLEDBSimpleProvider::addOLEDBSimpleProviderListener, should implement the following methods:

HRESULT aboutToChangeCell([in] LONG iRow, [in] LONG iColumn)
Indicates that the cell(s) indicated is about to change. This notification is fired when values are modified through SetVariant or internally by a provider. AboutToChangeCell should fire before any data values are changed.

Notes

  • Calls to GetVariant should return the original, unchanged value(s) prior to the return of control from firing the AboutToChangeCell event.
  • In AboutToChangeCell, the value -1 can be specified for iRow, iColumn, or both.
HRESULT cellChanged([in] LONG iRow, [in] LONG iColumn)
Indicates that the cell(s) indicated was changed. This notification is fired when values are modified through SetVariant or internally by a provider.

Notes

  • CellChanged should be fired after the data value(s) has changed. All subsequent calls to GetVariant should return the new value(s).
  • In CellChanged(), the value -1 can be specified for iRow, iColumn, or both.
HRESULT aboutToDeleteRows([in] LONG iRow, [in] LONG cRows)
Indicates that cRows beginning at row iRow are about to be deleted. This notification is fired just prior to the rows being deleted either from a call to DeleteRows or internally by the provider.

Notes

Access to cells in the deleted rows should remain valid until control is returned from the AboutToDeleteRows function.

HRESULT deletedRows([in] LONG iRow, [in] LONG cRows)
Indicates that cRows were deleted beginning at row iRow. This notification is fired when rows are deleted through DeleteRows or internally by a provider.

Notes

DeletedRows should be fired after the rows are deleted.

HRESULT aboutToInsertRows([in] LONG iRow, [in] LONG cRows)
Indicates that cRows beginning at row iRow are about to be inserted. This notification is fired just prior to the rows being inserted either from a call to InsertRows or internally by the provider.
HRESULT insertedRows([in] LONG iRow, [in] LONG cRows)
Indicates that cRows were inserted beginning at row iRow. This notification is fired when rows are inserted through InsertRows or internally by a provider.
HRESULT rowsAvailable([in] LONG iRow, [in] LONG cRows)
Indicates that cRows beginning at iRow are now available. This is useful for providers that obtain and expose their data asynchronously. The event notifies consumers that additional data is available.

Notes

OSP consumers expect periodic notifications when data is available since they will likely be displaying or processing the data as it arrives. Providers should weigh the advantages of code simplification by firing the event once for each row against the performance impact of doing so.

HRESULT transferComplete([in] OSPXFER doneReason)
All providers must fire this event to indicate that the data transfer is complete. The event should be fired after the entire data set exposed by the provider is available. doneReason indicates whether the population was completed successfully, or aborted, or stopped—the reason for why data population is complete.

Supported values for OSPXFER are:
OSPXFER_COMPLETE | Indicates that the data transmission is completed successfully.
OSPXFER_ABORT | Indicates that the data transmission is completed due to a call to the Stop method.
OSPXFER_ERROR | Indicates that the data transmission completed in an error state.

Notes

For providers that retrieve their data asynchronously, this event signifies that no additional RowsAvailable events will be called for this data set.

Notes for all events functions

The returned value is propagated back to the function that resulted in the notification. That is, if CellChanged returns E_BADVALUE, the SetVariant function will also return E_BADVALUE.


OLE-DB Simple Provider for Java: A Data Binding API for IE4/MSHTML

IE4/MSHTML supports a very simple, easily implemented API for exposing data to HTML pages. The API supports access to string and variant data types and is built using array-like structures to expose rows and columns. Third parties can use the OLE-DB Simple Provider API to implement their custom data source objects.

Introduction

OLE-DB Simple Provider

OLE-DB Simple Provider Listener

Interface Summary

Exceptions

Introduction

OLE-DB Simple Provider (OSP) is a JavaBeans interface specification that hosts can implement to expose their tabular data to HTML elements in IE4/MSHTML. OSP specifies only simple, minimal functionality that requires only minimal effort on the part of applet authors to expose their data. OSP specifies methods for adding, deleting, and setting the value of columns, searching through the set of data, and receiving notifications on data events.

OLE-DB Simple Provider

OSP exposes a set of tabular data (data set) in an array-like structure. Elements of the data set are referenced by their row and column indexes.

Data references

Indexes begin with value 1 and increase. There are two special index values:
0 | Reserved for label information in the case of a row, and header information in the case of a column.
-1 | The wildcard value. Refers to an unknown value or all values. For example, Row=-1, Col=2 refers to the entire column 2.

OSP defines two distinct interfaces: OLEDBSimpleProvider and OLEDBSimpleProviderListener. As you would expect, OLEDBSimpleProvider implements the methods used for data access, and OLEDBSimpleProviderListener specifies the methods to be implemented by the host for receiving notification of data changes.

Schema functions

Three functions are provided for obtaining the schema for the underlying rows or columns.

public int getRowCount( ) throws OSPException
Returns the number of rows in the data set.
public int getColumnCount( ) throws OSPException
Returns the number of columns in the data set.
public int getRWStatus(int iRow, int iColumn) throws OSPException
Returns the read/write status for the specified row and column. If one or both of iRow and iColumn have a value of -1, the read/write status is returned for the entire column, row, or complete data set.

OSPRW is an interface that defines the following return values.

public interface OSPRW
{
    public static final int OSPRW_DEFAULT = 1;
    public static final int OSPRW_READONLY = 0;
    public static final int OSPRW_READWRITE = 1;
    public static final int OSPRW_MIXED = 2;
}

The definitions for the values are:
OSPRW_READONLY | Cell, row, column, or data set is read-only.
OSPRW_READWRITE | Cell, row, column, or data set can be modified.
OSPRW_MIXED | Cell, row, column, or data set read-write status unknown or row, column or data set mixed status.

Variant-oriented functions

Two functions are provided to allow retrieval and setting of variant values in the data set.

public Object getVariant(int iRow, int iColumn, int fFormatted) throws OSPException
Returns the value of the cell at the row and column indicated. Based on the value specified in fFormatted, the returned value will contain either a value with the type of the underlying column, a string that corresponds to the underlying type of the column, or an HTML fragment that corresponds to the underlying type of the column.
public void setVariant(int iRow, int iColumn, int fFormatted, Object objVal) throws OSPException
Sets the value of the cell at the row and column indicated to the value of the Object supplied in objVal in the type requested by the value of fFormatted.

OSPFORMAT is an interface that defines the following values:

public interface OSPFORMAT
{
    public static final int OSPFORMAT_RAW = 0;
    public static final int OSPFORMAT_DEFAULT = 0;
    public static final int OSPFORMAT_FORMATTED = 1;
    public static final int OSPFORMAT_HTML = 2;
}

The definitions for the values are:
OSPFORMAT_RAW | The underlying type of the column should be used to either set the value or get the value.
OSPFORMAT_FORMATTED | The underlying type of the column should be converted to a string and the string returned as a BSTR within the variant.
OSPFORMAT_HTML | The underlying type of the column should be converted to an HTML string.

Notes

  • Valid Java class types for these interfaces are Integer, Long, Float, Double, String, Boolean, Date, and null.
  • Types other than those listed immediately above will be represented as String by calling the toString function on the class.
  • For setVariant with any of the formatting options, it is the provider's responsibility to perform the appropriate coercion to the underlying type of the column. In cases where the coercion cannot be successfully completed, an appropriate exception should be thrown.
  • For setVariant with OSPFORMAT_FORMATTED, the provider is free to interpret the input string however it sees fit. Alternatively, the provider may attempt to parse the input string and heuristically determine an appropriate data type and value to place into the cell—for example, when updating formatted spreadsheet cells.
  • When OSPFORMAT_HTML is requested, the provider can, at its option, return a plain string (unadorned with HTML tags and so on).
  • A database NULL is indicated by returning a null.
  • Wildcard values (-1) are not valid for the iRow and iColumn attributes in setVariant or getVariant. That is, only a single value can be returned/set from either call.

Deletion and insertion

Functions are provided to insert and delete rows. For all functions, the row numbers provide the position within the data set to which the row will be inserted. That is, the row inserted will have the index specified.

public int deleteRows(int iRow, int cRows) throws OSPException
Deletes cRows from the data set starting at row iRow. The number of rows successfully deleted is returned.
public int insertRows(int iRow, int cRows) throws OSPException
Inserts cRows into the data set starting at row iRow. The number of rows successfully inserted is returned.

Notes

  • In the case of an error, the provider can choose to insert/delete rows up to the point where the error occurred. In such a case, the return value specifies the number of rows actually inserted/deleted.
  • Values for the inserted rows are not specified. Use the setVariant function to set the value of the cells inside rows that were inserted.

Searching

A function is provided that supports some basic searching capability on the data set. The goal of this function is to be fairly easy for the provider to implement while providing the client with a meaningful set of functionality to perform complex searching.

public int find(int iRowStart, int iColumn, Object objVal, int findFlags, int compType) throws OSPException
Searches for the values specified in objVal in column iColumn starting at row iRowStart. Upon successful completion, the row number with the matching value is returned in piRowFound.

The OSPFIND interface defines the values for findFlags as follows:

public interface OSPFIND
{
    public static final int OSPFIND_DEFAULT = 0;
    public static final int OSPFIND_UP = 1;
    public static final int OSPFIND_CASESENSITIVE = 2;
}

The definitions for the values are:
OSPFIND_UP | Specifies scan should be decreasing in row number.
OSPFIND_CASESENSITIVE | Specifies that search should be case sensitive.

Similarly, the OSPCOMP interface defines the values for compType as follows:

public interface OSPCOMP
{
    public static final int OSPCOMP_EQ = 1;
    public static final int OSPCOMP_DEFAULT = 1;
    public static final int OSPCOMP_LT = 2;
    public static final int OSPCOMP_LE = 3;
    public static final int OSPCOMP_GE = 4;
    public static final int OSPCOMP_GT = 5;
    public static final int OSPCOMP_NE = 6;
}

The definitions for the values are:
OSPCOMP_LT | Specifies the first value less than objVal is being searched for.
OSPCOMP_LE | Specifies the first value less than or equal to objVal is being searched for.
OSPCOMP_GT | Specifies the first value greater than objVal is being searched for.
OSPCOMP_GE | Specifies the first value greater than or equal to objVal is being searched for.
OSPCOMP_EQ | Specifies the first value equal to objVal is being searched for.
OSPCOMP_NE | Specifies the first value not equal to objVal is being searched for.

Notes

  • Find does compares using the native type of the underlying column. Providers are encouraged to simply fail when the type of the objVal differs from the underlying type of the column.
  • Find supports the same object types for objVal as setVariant and getVariant.
  • Comparing string values always compares values as they would be returned from a call to getVariant with OSPFORMAT_FORMATTED. Providers should not coerce values of objVal obtained from a previous call to getVariant with OSPFORMAT_HTML.
  • If no corresponding match is found, Find should return the constant -1.

Asynchronous data population

The main function of an OSP is to provide data to an HTML page. In many cases, the data will need to be transported over high-latency, low bandwidth networks, in most cases using a 28.8K modem. The OSP design accounts for making data available as expediently as possible while maintaining an architecture and interface specification that is easy to author.

All OSP authors are encouraged to implement support for populating (or retrieving) the data they expose asynchronously. This allows the host to continue processing during data transmission instead of blocking on a call to the OSP until the entire data set has been transmitted to the client.

The majority of the work required to support asynchronous data delivery does not involve the OSP interface specifically—it is a requirement on the mechanisms to retrieve data from their underlying storages. Accordingly, three methods are required in the OSP interface: one to indicate whether the provider supports asynchronous population; one to return the progress of the asynchronous population; and a third to stop the asynchronous transmission of data.

Two additional events are added to the OSP event notifications. One event indicates when additional data has become available for access through the interface, while the other signals that the asynchronous data population has completed. Both events are specified below in the OLE-DB Simple Provider Listener section.

public boolean isAsync( ) throws OSPException
Returns a Boolean indicating whether data is being populated asynchronously.

Notes

isAsynch should never block; it should always return the appropriate state.

public int getEstimatedRows( ) throws OSPException
Returns the estimated total number of rows in the data set. Callers can use this in conjunction with getRowCount with an asynchronous provider to obtain an estimate of the percentage of data received.

Notes

  • When the number of rows in the data set cannot be estimated, the provider should return the special value -1.
  • Synchronous providers should not block on the call to getEstimatedRows. They should either return -1 to indicate that they cannot provide an estimate, or the actual row count (same as would be obtained through getRowCount).
  • Providers should not return the final row count from EstimatedRows prior to firing the transferComplete event (see below).
public void stopTransfer( ) throws OSPException
Requests that the OSP discontinue asynchronous transfer of data.

Notes

  • Providers should make every effort to expose the data transferred prior to receiving this request. The provider must expose a valid, consistent OSP interface for such data—appropriate column/row count, read/write status, and so on.
  • Providers that cannot expose the data transferred prior to this request should discontinue the transfer of data and fail all subsequent calls to the OSP interface.

Internationalization

Implementers might have to consider cases where the consumer is running in a different locale from the source of the data. The provider is responsible for ensuring that data conversions are done in an appropriate fashion. In particular, be careful in cases where the string representation of many data types differs according to locale. For example, the float or double number 3.14 would be "3.14" in the US, and "3,14" in Germany. Date representations differ even more. For example, number (especially float, date) to string conversions done by GetVariant or SetVariant with the OSP_FORMATTED option specified should usually be done in the locale of the browser.

The Find method has more complicated issues to deal with to implement its ordered comparisons correctly across locale boundaries. These comparisons should, where possible, also be done in the locale of the browser, although this issue is not as clear cut. (For example, if the data consists of strings containing European accented characters, it is not clear that a browser in the en-us locale has any preferred sorting order for these strings. The sorting order of the provider locale might be more useful.)

It is anticipated that there will be cases where the consumer will need to know the locale of the data in order to perform proper operations on that data. A method is provided for the provider to return this information.

public String getLocale( ) throws OSPException
Returns a string that indicates the locale of the data. This is used to perform the appropriate type conversions.

Notes

  • getLocale should simply return the empty string ("") when the provider does not support localization. This will allow the consuming entity to use the default from the operating system.
  • For all return values the category LC_ALL is assumed by the consumer.

Sinking events

Methods are provided to attach and detach a unicast event handler for all events.

public void addOLEDBSimpleProviderListener(OLEDBSimpleProviderListener objOSPL) throws OSPException
Registers the event handler interface specified by objOSPL to receive notifications of changes to data.

Notes

  • If an event handler was specified previously, addOLEDBSimpleProviderListener replaces the previous event handler.
  • OSP events are unicast only. There can be only one listener.
public void removeOLEDBSimpleProviderListener(OLEDBSimpleProviderListener objOSPL) throws OSPException
Unregisters the event handler interface specified by objOSPL.

Notes

removeOLEDBSimpleProviderListener should always specify the objOSPL previously registered. In the event that objOSPL differs from the event handler registered, the call should fail.

OLE-DB Simple Provider Listener

OSP implementers fire notifications of changes to the underlying data through a single event handler. There are pre- and post-notifications for each event.

The event handler, registered through addOLEDBSimpleProviderListener, should implement the following methods.

public void aboutToChangeCell(int iRow, int iColumn) throws Exception
Indicates that the cell(s) indicated is about to change. This notification is fired when values are modified through setVariant or internally by a provider. aboutToChangeCell should fire before any data values are changed.

Notes

  • Calls to getVariant should return the original, unchanged value(s) prior to the return of control from firing the aboutToChangeCell event.
  • In aboutToChangeCell, the value -1 can be specified for iRow, iColumn, or both.
public void cellChanged(int iRow, int iColumn) throws Exception
Indicates that the cell(s) indicated was changed. This notification is fired when values are modified through setVariant or internally by a provider.

Notes

  • cellChanged should be fired after the data value(s) has changed. All subsequent calls to getVariant should return the new value(s).
  • In cellChanged, the value -1 can be specified for iRow, iColumn, or both.
public void aboutToDeleteRows(int iRow, int cRows) throws Exception
Indicates that cRows beginning at row iRow are about to be deleted. This notification is fired just prior to the rows being deleted either from a call to deleteRows or internally by the provider.

Notes

Access to cells in the deleted rows should remain valid until control is returned from the aboutToDeleteRows function.

public void deletedRows(int iRow, int cRows) throws Exception
Indicates that cRows were deleted beginning at row iRow. This notification is fired when rows are deleted through deleteRows or internally by a provider.

Notes

deletedRows should be fired after the rows are deleted.

public void aboutToInsertRows(int iRow, int cRows) throws Exception
Indicates that cRows beginning at row iRow are about to be inserted. This notification is fired just prior to the rows being inserted either from a call to insertRows or internally by the provider.
public void insertedRows(int iRow, int cRows) throws Exception
Indicates that cRows were inserted beginning at row iRow. This notification is fired when rows are inserted through insertRows or internally by a provider.
public void rowsAvailable(int iRow, int cRows) throws Exception
Indicates that cRows beginning at iRow are now available. This is useful for providers that obtain and expose their data asynchronously. The event notifies consumers that additional data is available.

Notes

OSP consumers expect periodic notifications when data is available since they will likely be displaying or processing the data as it arrives. Providers should weigh the advantages of code simplification by firing the event once for each row against the performance impact of doing so.

public void transferComplete(int doneReason) throws Exception
All providers must fire this event to indicate that the data transfer is complete. The event should be fired after the entire data set exposed by the provider is available. doneReason indicates whether the population was completed successfully, aborted, or was stopped—the reason for why data population is complete.

The OSPXFER interface defines values for doneReason as follows:

public interface OSPXFER
{
    public static final int OSPXFER_COMPLETE = 0;
    public static final int OSPXFER_ABORT = 1;
    public static final int OSPXFER_ERROR = 2;
}

The definitions for the values are:
OSPXFER_COMPLETE | Indicates that data transmission is completed successfully.
OSPXFER_ABORT | Indicates that the data transmission is completed due to a call to the Stop method.
OSPXFER_ERROR | Indicates that the data transmission completed in an error state.

Notes

For providers that retrieve their data asynchronously, this event signifies that no additional rowsAvailable events will be called for this data set.

Notes for all events functions

If your provider does not require any additional processing, it is not necessary to catch exceptions from the event routines. The unhandled exceptions will return up through to the setVariant, or [insert|delete]Rows call from which it initiated. The the exception should be handled there.

Interface Summary

All interfaces are part of the com.ms.osp package. The interfaces are as follows:

public interface OLEDBSimpleProvider
{
    public int getRowCount( ) throws OSPException;
    public int getColumnCount( ) throws OSPException;
    public int getRWStatus(int iRow, int iColumn) throws OSPException;
    public Object getVariant(int iRow, int iColumn, int fFormatted) throws OSPException;
    public void setVariant(int iRow, int iColumn, int fFormatted, Object obj) throws OSPException;
    public int deleteRows(int iRow, int cRows) throws OSPException;
    public int insertRows(int iRow, int cRows) throws OSPException;
    public int find(int iRowStart, int iColumn, Object objVal, int findFlags, int compType)
        throws OSPException;
    public boolean isAsync( ) throws OSPException;
    public int getEstimatedRows( ) throws OSPException;
    public void stopTransfer( ) throws OSPException;
    public String getLocale( ) throws OSPException;
    public void addOLEDBSimpleProviderListener(OLEDBSimpleProviderListener objOSPL)
        throws OSPException,
                                                                                java.util.TooManyListenersException;
    public void removeOLEDBSimpleProviderListener(OLEDBSimpleProviderListener objOSPL)
        throws OSPException;
}

abstract interface OLEDBSimpleProviderListener
{
    public void aboutToChangeCell(int iRow, int iColumn) throws Exception;
    public void cellChanged(int iRow, int iColumn) throws Exception;
    public void aboutToDeleteRows(int iRow, int cRows) throws Exception;
    public void deletedRows(int iRow, int cRows) throws Exception;
    public void aboutToInsertRows(int iRow, int cRows) throws Exception;
    public void insertedRows(int iRow, int cRows) throws Exception;
    public void rowsAvailable(int iRow, int cRows) throws Exception;
    public void transferComplete(int doneReason) throws Exception;
}

public interface OSPRW
{
    public static final int OSPRW_DEFAULT = 1;
    public static final int OSPRW_READONLY = 0;
    public static final int OSPRW_READWRITE = 1;
    public static final int OSPRW_MIXED = 2;
}

public interface OSPFORMAT
{
    public static final int OSPFORMAT_RAW = 0;
    public static final int OSPFORMAT_DEFAULT = 0;
    public static final int OSPFORMAT_FORMATTED = 1;
    public static final int OSPFORMAT_HTML = 2;
}

public interface OSPFIND
{
    public static final int OSPFIND_DEFAULT = 0;
    public static final int OSPFIND_UP = 1;
    public static final int OSPFIND_CASESENSITIVE = 2;
}

public interface OSPCOMP
{
    public static final int OSPCOMP_EQ = 1;
    public static final int OSPCOMP_DEFAULT = 1;
    public static final int OSPCOMP_LT = 2;
    public static final int OSPCOMP_LE = 3;
    public static final int OSPCOMP_GE = 4;
    public static final int OSPCOMP_GT = 5;
    public static final int OSPCOMP_NE = 6;
}

public interface OSPXFER
{
    public static final int OSPXFER_COMPLETE = 0;
    public static final int OSPXFER_ABORT = 1;
    public static final int OSPXFER_ERROR = 2;
}

Exceptions

OSP supports a number of exceptions. They are defined as follows:

  • AccessDeniedException: An inability to read/write the data has occurred.
  • ConversionException: An error occurred attempting to coerce data types.
  • IllegalArgumentException: A method was passed an invalid or inappropriate argument or was invoked on an inappropriate object.
  • NotImplementedException: The functionality of a called method is not implemented.
  • OSPException: A failure has occurred calling an OSP method. This is used in all cases not covered by the previous exceptions.


Hyperlinks

This topic describes ActiveX™ Hyperlinking and the interfaces involved in adding hyperlink navigation to your document or application.

Introduction

Reference

Introduction

One of the most compelling ease-of-use features of World Wide Web applications is the navigation-based user interface model that includes point-and-click hyperlink navigation, a History list (with commands such as Go Back and Go Forward), and a Favorites list. Like other ActiveX-based technologies, ActiveX Hyperlinks enable you to add this hyperlink functionality to your documents and applications, allowing you to integrate them seamlessly with other hyperlinking applications, including Web browsers. ActiveX Hyperlinks allow you to:

  • Add hyperlinking support to existing documents, objects, and applications.
  • Integrate the documents of your application into enabled World Wide Web browsers.
  • Support and integrate with key features of ActiveX Hyperlink applications (History, Favorites, Go Back, Go Forward, Go Home).
  • Support navigation to documents on the Internet or an intranet.

This section provides an overview of hyperlinks, a description of the ActiveX Hyperlinking architecture (including the interfaces required to add hyperlink support to an application), and examples. Applications can choose to support various degrees of integration with the ActiveX Hyperlinking architecture. Where applicable, this document describes how to provide minimal or simple hyperlinking support, and also how to extend this support for more complete hyperlinking integration. For basic COM information, refer to The Component Object Model.

What Is a Hyperlink?

A hyperlink is a COM object that implements, at a minimum, the IHlink interface and acts as a link to an object at another location (the target). This target can be a reference to a location in the same document/object that contains the hyperlink; a different (top-level or embedded) document/object of the same class; or a different document/object of a different class. A hyperlink is made up of four parts:

  • A moniker that identifies the target's location
  • A string for the location within the target
  • A friendly, or displayable, name for the target
  • A string that can contain additional parameters

The data of the document/object can be stored in file system files, computers on the Internet (referred to by URLs, or universal resource locators), or any arbitrary location that can be referenced through monikers. Navigation to the location can be done by binding to the target and then asking it to jump to the location. How a hyperlink is presented to the user is up to the hyperlink container and the context of the hyperlink. While there are no user interface requirements limiting the presentation of hyperlinks, guidelines suggest that the hyperlinks should be made clear through coloring and/or underlining the hyperlink text, or by changing the cursor when selecting the hyperlink with the mouse.

What Is Hyperlink Navigation?

Hyperlink navigation involves a transition from one document, object, or application (the hyperlink container) to another document, object, or application (the hyperlink target). Usually both the hyperlink container and target remain running, but the hyperlink target is displayed over the hyperlink container. Hyperlink containers and targets can be top-level documents or Active Document objects in a browser application. Because of this variation, there are many possible forms of navigation. These include navigating from:

  • One top-level document to another top-level document (in the absence of a browser).
  • A top-level document to an Active Document object in a browser (for example, navigating from a stand-alone application to an HTML document).
  • One Active Document object in a browser to another Active Document object in the same browser (for example, navigating from one HTML document to another).
  • An Active Document object in a browser to an Active Document object in a binder-like application (for example, if the hyperlink target is embedded in an Office Binder document).
  • One location in an object/document to another location in the same object/document.

In the third and fifth cases above, the window is reused. In the other cases, the hyperlink target appears in a new window. The ActiveX Hyperlinks architecture suggests a mechanism for creating the illusion of window reuse in such cases: the hyperlink container passes its current window position to the hyperlink target, and the hyperlink target positions its window in the exact same location. Upon successful navigation, the hyperlink container hides its window.

What Is a Browse Context?

By looking at the possible forms of navigation, it is clear that multiple objects/documents (perhaps from different processes) share some global context. This context knows the order in which documents have been visited. All jumps are recorded with this context, and this context chains them together in a stack that can be navigated using Go Back and Go Forward operations. This global context is called the browse context.

Even though a browse context is global and spans multiple processes, it need not be global per user, such as History and Favorites lists. There can be multiple browse contexts active at once. For example, in certain Web browsers you can start a new browse context using the right-mouse pop-up menu item Open In New Window. ActiveX Hyperlinking defines the interface for the standard system browse context. This allows hyperlink-aware documents and applications to integrate the browse context's navigation stack through the standard hyperlinking interfaces and their methods.

The Simple Hyperlinking API

There are two methods of dealing with hyperlinks, depending on the needed complexity of the hyperlink operation. The simple hyperlink navigation model is a helper API aimed at common navigation scenarios such as a control (like a pushbutton) embedded on a Web page that allows the user to jump to another page when it is clicked.

The simple hyperlink functions are an encapsulation of the more complex full hyperlinking interfaces. These full hyperlinking interfaces offer a much richer set of navigation operations. For example, you can use these interfaces for operations such as supporting navigation to a location within a new document type, or allowing the cutting and pasting or dragging and dropping of hyperlinks. The simple hyperlink navigation API allows hyperlink navigation without knowledge of any other hyperlink interfaces or objects (basically saying, "here is where I want to jump to, now go there"). This API includes the following functions:

  • HlinkSimpleNavigateToString—Jumps to the location pointed to by a URL string.
  • HlinkSimpleNavigateToMoniker—Jumps to the location pointed to by a URL moniker.
  • HlinkGoBack—Jumps to the previous location on the History list (if object pointed to is hosted in an ActiveX hyperlink frame).
  • HlinkGoForward—Navigates to the next location on the History list (if object pointed to is hosted in an ActiveX hyperlink frame).

These functions work within any ActiveX hyperlink frame application. A hyperlink frame is the outer container that contains the document processing the user's request to navigate (when a navigation action occurs). An application must expose the IHlinkFrame interface to be a hyperlink frame application. For example, Microsoft® Internet Explorer 3.0 is a hyperlink frame application that knows the user's current location in the navigation stack, and goes forward and backward properly.

The programmer is shielded from the architectural details of figuring out the History list to move forward and backward. An ActiveX Control or document hosted in a frame simply calls these functions to figure out where to go.

The calling object needs to know where in the navigation stack the user currently is so the user can go forward or backward properly. To do this, all that the calling object must pass in is the interface pointer to itself. In reality, this is the IUnknown pointer to the document or object that is initiating the hyperlink. (Note that this must be the pUnkOuter parameter for an aggregated COM object.) If the pointer is NULL, the hyperlink is assumed to originate from an ActiveX-unaware application (an application that does not expose the IHlinkFrame interface), and the navigation history list will not be updated. Using this object pointer, the API travels through the interface hierarchy of that object to locate its outer container to calculate navigation history and do the in-frame navigation.

The Hyperlink Architecture

The following sections describe the various components in the ActiveX Hyperlinks architecture and the interfaces they implement. Some of the components are standard, system-provided objects; the others are user-defined components that participate in ActiveX hyperlinking because they implement the appropriate interface(s).

The hyperlink target

A hyperlink target is a COM object that implements the IHlinkTarget interface and supplies its moniker, friendly name, and other information that other hyperlink objects will use to navigate to it. This can be a persisted ActiveX object that exposes IHlinkTarget, a persisted ActiveX object that exposes IOleObject, or any file that is viewed when its viewer application is launched through ShellExecute. An object (document) that wants to be targeted by hyperlinks can choose to implement all or part of the IHlinkTarget interface to integrate tightly with ActiveX Hyperlinks. If the object does not support IHlinkTarget, it can still act as a hyperlink target, but it won't be able to support internal navigation, and it will not have access to the common browse context that holds the navigation stack. A hyperlink target can be a top-level container document, an embedded object of arbitrary nesting, or, in general, any object that can be referenced through a moniker.

How to implement IHlinkTarget

An existing application that supports COM linking need only implement the IHlinkTarget interface on the same object that implements IPersistFile and IOleItemContainer. The application can also implement IPersistMoniker to support incremental rendering or asynchronous download as a persistence mechanism, rather than IPersistFile. Supporting IHlinkTarget from an Active Document object is the recommended way to make sure your document is viewable by browsers and participates in hyperlinking smoothly.

The hyperlink object

A hyperlink object implements the IHlink interface and encapsulates four pieces of reference information: a moniker to the hyperlink target; a string for the location within the target; a friendly name for the target; and additional parameters.

The hyperlink object completely encapsulates the behavior of navigating to a referenced location. It also supports the ability to save and load itself through the IPersistStream interface, and the ability to be transferred through the clipboard or through drag-and-drop operations by means of IDataObject. A standard hyperlink object implementation is provided with the system, and it is not advisable to implement another version. A document can use the standard hyperlink object to represent hyperlinks within itself, thus encapsulating the work of navigating, saving, loading, dragging, dropping, cutting, and pasting hyperlinks. Standard hyperlink objects are created through the HlinkCreateFromData, HlinkCreateFromMoniker, HlinkCreateFromString, and OleLoadFromStream functions. The standard hyperlink object implements the IHlink, IPersistStream, and IDataObject interfaces.

The hyperlink container

A hyperlink container is a document or application that contains hyperlinks. The container supports hyperlinks by implementing the IHlinkSite interface and, if the container's objects can be targets of other hyperlinks, the IHlinkTarget interface.

Note Generally, an object that acts as a hyperlink container can also act as a hyperlink target.

The hyperlink site

A hyperlink site is a COM object that implements the IHlinkSite interface and supplies either the moniker or interface identifier of its hyperlink container. One hyperlink site can serve multiple hyperlinks. The moniker supplied by the hyperlink site is used to evaluate relative monikers to the hyperlink target. If the relative moniker is NULL, the target of the link is in the same container object, and IHlink::Navigate can result in an efficient internal jump

Note The standard hyperlink object performs internal jumps by retrieving the container's IHlinkTarget interface using IHlinkSite::GetInterface (which avoids an unnecessary moniker bind). The object then asks the container to navigate directly through the IHlinkTarget::Navigate method.

The hyperlink frame

A hyperlink frame is a COM object that implements the IHlinkFrame interface and controls the top-level navigation and display of hyperlinks for the frame's container and the hyperlink target's server. Browser applications such as Microsoft Internet Explorer and the Microsoft Office Binder are examples of hyperlink frames. Ideally, a hyperlink frame also serves as an Active Document object frame, allowing it to support browsing and hyperlinking between various document objects.

The hyperlink browse context

The hyperlink browse context maintains the navigation stack that is passed during navigation from one document or application to another. As with the hyperlink object, the browse context is a standard object provided with the system.

In addition to maintaining the navigation stack, the browse context knows whether or not to enable Go Back and Go Forward commands. For example, if you navigate from A to B, A would create an instance of the browse context object (if it had not been given one before) and pass it to B. Next, if you navigate to C, B would pass the same browse context pointer to C. At this moment, the navigation stack of the browse context contains A, B, and C. Go Back is enabled but Go Forward is disabled. Now if you do Go Back, you will navigate to B and the navigation stack still contains the same three items. Now both Go Back and Go Forward are enabled. If you Go Back again, you will navigate to A, and again the navigation stack contains the same three elements. But now Go Back is disabled and only Go Forward is enabled.

In addition to maintaining the navigation stack, the browse context object manages the hyperlink frame window and hyperlink target object's window. This window position information allows hyperlinking from one top-level window to another while giving the illusion of window reuse (by positioning the windows on top of each other). Each hyperlink target is passed a browse context (through IHlinkTarget::SetBrowseContext) the first time it is navigated to. The hyperlink target registers with the browse context (through IHlinkBrowseContext::Register) and holds a reference to it. The target must also notify the browse context each time it is navigated to through IHlinkBrowseContext::OnNavigateHlink. The browse context uses this information to maintain the navigation stack, to remember the current item in the stack, and to manage the lifetimes of registered hyperlink target applications.

An Example of Simple Hyperlinking

The navigation in this example takes place between simple hyperlink containers and simple hyperlink targets, none of which understand how to use the hyperlinking browse context. For ActiveX Controls or Active Document objects hosted within a browser such as Microsoft Internet Explorer, this is the only hyperlinking support that is necessary to integrate fully in the navigation stack and history list. The following pseudo-code outlines the order or execution of methods among the various objects during navigation.

Note Simple hyperlinking is simple mainly for the hyperlink container and the hyperlink target, particularly if both are document objects hosted in a document object frame. In these cases, the frame takes over all responsibility for providing a navigation stack and integrated history/favorites. Note that there is no definition of simple hyperlinking for hyperlink frames.

Starting with a hyperlink container

The hyperlink container (for example, a document or an ActiveX Control embedded within a document) initiates the hyperlink navigation using one of the simple hyperlinking functions.

// do the navigation
HlinkSimpleNavigateToString( "http://www.microsoft.com/foo.htm", NULL,  NULL,
    punkMe, 0, pbc, pbsc, 0);

The hyperlink frame (for example, Microsoft Internet Explorer) is called from within the simple navigation API (which packages up the call into a full call to HlinkNavigate). This is the frame's chance to provide an integrated user interface, progress feedback, cancellation options, and so forth. Often the hyperlink frame simply sets some flags and defers to the IHlink::Navigate method. Other frames might choose to do more work. For instance, a frame might decide to provide its own IBindStatusCallback in order to listen in on progress notifications during navigation.

Calling the hyperlink target

Usually, the system-provided hyperlink object gains control to do the navigation on behalf of the container or frame, resulting in a call to the hyperlink target.The hyperlink target then receives control to navigate to the specific location within the target. Notice that support for "sublocations" is optional. Also, the interpretation of location strings is left to the interpretation of the target object.

STDMETHODIMP
IHlinkTarget::Navigate(DWORD grfHLNF, LPCWSTR szLocation)
{
    IHlinkFrame* phlFrame = NULL;
    // if szLocation is not visible show it

    // if this hyperlink target is an Active Document object, try to
    // retrieve the hyperlink frame pointer from the IOleInPlaceFrame
    if (m_poleinplaceframe)
        m_poleinplaceframe->QueryInterface(IID_IHlinkFrame, (void**)&phlFrame);

    // notify the hlink frame and the browse context that the navigation
    // is complete. Note: either phlFrame or m_phlbc may be NULL
    HlinkOnNavigate(phlFrame, NULL, grfHLNF, m_pmk, szLocation, szFriendlyName);

    m_fHide = FALSE;
    m_fHideFrame = FALSE;
}  // IHlinkTarget::Navigate

Receiving success notification

The hyperlink frame next receives notification of a successful navigation from IHlinkTarget::Navigate in order to reposition its windows and update its windows' visibility. If this is the same frame that hosted the hyperlink container that initiated the navigation, the flags set will ensure that the frame remains visible.

An Example of Complex Hyperlinking

The navigation in this example takes place between hyperlink containers and hyperlink targets that understand how to use the hyperlinking browse context. The following pseudo-code outlines the order or execution of methods among the various objects during navigation.

Starting with a hyperlink container

Before any navigation occurs, the container starts with a hyperlink object that has either been created (using HlinkCreateFromData, HlinkCreateFromMoniker, or HlinkCreateFromString) or loaded from persistent data (using OleLoadFromStream). The hyperlink container might initialize the hyperlink through the IHlink::SetHlinkSite method by passing in an IHlinkSite interface and hyperlink-specific data (dwSiteData), which allows the hyperlink container to use the same hyperlink site to service multiple hyperlinks.

When the container decides to navigate the link as a result of user action, it does the following:

// retrieve the hyperlink frame pointer
if (!m_fTriedToGetFrame && m_poleinplaceframe && m_phlFrame == NULL) {
    m_fTriedToGetFrame = TRUE;
    m_poleinplaceframe->QueryInterface(IID_IHlinkFrame,
    (void**)&m_phlFrame);
    }

if (m_phlbc == NULL) {
    // get the browse context pointer
    if (m_phlFrame)
        m_phlFrame->GetBrowseContext(&m_phlbc);
    else
        HlinkCreateBrowseContext(&m_phlbc);
    if (m_phlbc == NULL)
        return E_FAIL;

    // register with the browse context
    m_phlbc->Register(pmkThis, phls, &m_dwRegister);

    // because we want the user to be able to come back to this
    // object via GoBack functionality add self to the
    // navigation stack. This effectively tells the browse context
    // that the current hyperlink container referred to by pmkThis
    // is a member (at the top) of the navigation stack
    m_phlbc->OnNavigateHlink(NULL, pmkThis, szLocation, szFriendlyName);
    }

    if (m_phlFrame == NULL)    {
        HLBWINFO hlbwinfo;

        // initialize hlbwinfo with window locations and flags

        // register the browse window info in the browse context
        // so it is later available to the hyperlink target and
        m_phlbc->SetBrowseWindowInfo(&hlbwinfo)

        // set the flag indicating that this window should be
        // hidden after navigation. But this flag is cleared in the
        // IHlinkTarget::Navigate and IHlinkFrame::OnNavigate methods.
        m_fHide = TRUE;
        v_fHideAppFrame = TRUE;  // only the MDI applications need this
                                 //separate flag
        }
    else {
        m_fHide = FALSE;
        v_fHideAppFrame = FALSE;
    }

    hr = HlinkNavigate(pkl, m_phlFrame, NULL,  pbc /* could be NULL */,
    pibsc, m_phlbc);

    if (hr == NOERROR) {
        if (m_fHide)
            // Hide this document
        if (m_vfHideAppFrame)
            // Hide/Minimize application's frame window
        }

Calling the hyperlink frame

The hyperlink frame is called from within HlinkNavigate. This is the frame's chance to provide an integrated user interface, progress feedback, cancellation ability, and so forth. Often the hyperlink frame simply sets some flags and defers to the IHlink::Navigate method.

STDMETHODIMP
IHlinkFrame::Navigate(DWORD grfHLNF, IBindCtx* pbc,
    IBindStatusCallback* pbsc,  IHlink* phlDest)
{
    // This flag gets cleared in IHlinkFrame::OnNavigate().
    // Thus if the Navigation is within the same frame window
    // then we will get the right behavior as this flag gets
    // cleared in the OnNavigate() method.
    m_fHide = TRUE;

    // some frames need only the following function so that
    // they can properly show and hide themselves.
    // others may hook themselves into the IBindStatusCallback
    // for progress notification
    hr = IHlink::Navigate(NULL, pbc, pbsc, phlDest);
    if (SUCCEEDED(hr) && m_fHide)
        // Hide the frame window
}  // IHlinkFrame::Navigate

Other frames might choose to do more work. For instance, a frame may decide to provide its own IBindStatusCallback in order to listen in on progress notifications during navigation.

Jumping to the hyperlink target

When called by the hyperlink frame, the system hyperlink object gains control to do most of the navigation work and to integrate the results with the browse context. The following code is a sample implementation of a hyperlink object. The system-provided hyperlink object uses similar code.

STDMETHODIMP
IHlink::Navigate(DWORD grfHLNF, IBindCtx* pbc,  IBindStatusCallback*
    pbsc, IHlinkBrowseContext* phlbc)
{
    IHlinkTarget* phlTarget = NULL;
    IMoniker* pmkLeft = NULL;

    if (grfHLNF & HLNF_USEBROWSECONTEXTCLONE) {
        grfHLNF &= ~HLNF_USEBROWSECONTEXTCLONE;
        phlbc->Clone(NULL, IID_IHlinkBrowseContext, &phlbc);
        }
    else {
        hr = m_phlSite->GetMoniker(m_dwSiteData,
        OLEGETMONIKER_ONLYIFTHERE, OLEWHICHMK_CONTAINER, &pmkLeft);
        if (FAILED(hr) || m_pmkTarget->IsEqual(pmkLeft)) {
            hr = m_phlSite->GetInterface(dwSiteData, 0, IID_IHlinkTarget,
                (void**)&phlTarget);
            if (FAILED(hr))
                phlbc->GetObject(m_pmkTarget, &phlTarget);
            }

    if (phlTarget == NULL) {
        // Set the pbsc in the pbc to get asynch and notification
        // binding behavior requested by caller
        m_pmkTarget->BindToObject(pmkLeft, IID_IHlinkTarget, &phlTarget);
        phlTarget->SetBrowseContext(phlbc);
        }

    phlTarget->Navigate(grfHLNF, m_szLocation);
}  // IHlink::Navigate

Setting the browse context

During the execution of the above code, the hyperlink target receives the browse context for the navigation. This provides information about the hyperlink navigation stack and window positions for the hyperlinking.

Note This function is not called in all hyperlinking circumstances, for example in the Simple Hyperlinking example above. A simple hyperlink target need not implement this function.

STDMETHODIMP
CHlinkTarget::SetBrowseContext(IHlinkBrowseContext* phlbc)
{
    if (m_phlbc != NULL) {
        m_phlbc->Revoke(m_dwRegister);
        m_phlbc->Release();
        }
    m_phlbc = phlbc;
    if (m_phlbc != NULL) {
        m_phlbc->AddRef();
        m_phlbc->Register(0, (IUnknown*)this, m_pmk, &m_dwRegister);
        }

    return S_OK;
}  // CHlinkTarget::SetBrowseContext

The hyperlink target then receives control to navigate to the specific location within the target.

STDMETHODIMP
IHlinkTarget::Navigate(DWORD grfHLNF, LPCWSTR szLocation)
{
    IHlinkFrame* phlFrame = NULL;

    // if the object is not visible, activate it and show it.
    // jump to the location indicated by szLocation

    // if this hyperlink target is an Active Document object,
    // try to retrieve the hyperlink frame pointer
    // from the IOleInPlaceFrame
    if (m_poleinplaceframe)
        m_poleinplaceframe->QueryInterface(IID_IHlinkFrame,
        (void**)&phlFrame);

    // notify the hlink frame and the browse context that
    //the navigation is complete.
    // Note: either phlFrame or m_phlbc may be NULL
    HlinkOnNavigate(phlFrame, m_phlbc, grfHLNF, m_pmk, szLocation,
    szFriendlyName);

    if (phlFrame == NULL && !(grfHLNF & HLNF_INTERNALJUMP)) {
        HLBWINFO hlbwi;
        phlbc->GetBrowseWindowInfo(&hlbwi);

        // adjust the document and frame windows according
        // to the dimensions in HLBWI
    }

    m_fHide = FALSE;
    m_fHideFrame = FALSE;
}  // IHlinkTarget::Navigate

Receiving success notification

The hyperlink frame next receives notification of a successful navigation from within IHlinkTarget::Navigate in order to reposition its windows and update their visibility. If this is the same frame that hosted the hyperlink container that initiated the navigation, the m_fHide flag set below will ensure that the frame remains visible.

STDMETHODIMP
IHlinkFrame::OnNavigate(DWORD grfHLNF)
{
    if (!(grfHLNF & HLNF_INTERNALJUMP)) {
        HLBWINFO hlbwi;
        m_phlbc->GetBrowseWindowInfo(&hlbwi);
        // Adjust this document/frame windows according to the
        // dimensions in hlbwi
    }
    m_fHide = FALSE;
}  // IHlinkFrame::OnNavigate

Finally, the browse context receives notification of a successful navigation from IHlinkTarget::Navigate in order to update the navigation stack.

STDMETHODIMP
IHlinkBrowseContext::OnNavigateHlink(DWORD grfHLNF, IMoniker*
    pmkTarget, LPCWSTR szLocation, LPCWSTR szFriendlyName)
{
    // if CreateNoHistory or NavigatingToStackItem, return immediately
    // unless NavigatingBack or NavigatingForward is also set
    if (grfHLNF & (HLNF_CREATENOHISTORY | HLNF_NAVIGATINGTOSTACKITEM)) {
        if (!(grfHLNF & (HLNF_NAVIGATINGBACK | HLNF_NAVIGATINGFORWARD)))
            return NOERROR;
        }
    if (grfHLNF & HLNF_NAVIGATINGBACK)
        --m_iCurrent;
    else if (grfHLNF & HLNF_NAVIGATINGFORWARD)
        ++m_iCurrent;
    else {
        // Add this hyperlink to the navigation stack at m_iCurrent+1;
        // remove all items greater than m_iCurrent+1,

        ++m_iCurrent;
        }
}  // IHlinkBrowseContext::OnNavigateHlink


Reference

This ActiveX Hyperlinks reference contains the following sections:

  • Interfaces
  • Functions
  • Enumerations
  • Structures
  • Objects


Enumerations

This section describes the following enumerations:

  • HLBWIF
  • HLFNAMEF
  • HLID
  • HLINKGETREF
  • HLINKMISC
  • HLINKSETF
  • HLINKWHICHMK
  • HLNF
  • HLQF
  • HLSR


HLBWIF

typedef enum tagHLBWIF
{
    HLBWIF_HASFRAMEWNDINFO,    =  1,
    HLBWIF_HASDOCWNDINFO,      =  2,
    HLBWIF_FRAMEWNDMAXIMIZED,  =  4,
    HLBWIF_DOCWNDMAXIMIZED,    =  8,
} HLBWIF;

Contains values relating to the locations and sizes of frame- and document-level windows within a browse context.

HLBWIF_HASFRAMEWNDINFO
This browse context has available frame-level window positioning information.
HLBWIF_HASDOCWNDINFO
This browse context has available document-level window positioning information.
HLBWIF_FRAMEWNDMAXIMIZED
Only useful in combination with HLBWIF_HASFRAMEWNDINFO. Indicates that frame-level windows of the browse context should appear maximized.
HLBWIF_DOCWNDMAXIMIZED
Only useful in combination with HLBWIF_HASDOCWNDINFO. Indicates that document-level windows of the browse context should appear maximized.

The HLBWINFO structure is retrieved from the browse context using IHlinkBrowseContext::GetBrowseWindowInfo, and put into the browse context using IHlinkBrowseContext::SetBrowseWindowInfo. Hyperlink targets retrieve the HLBWINFO structure during IHlinkTarget::Navigate in order to reposition their user interface properly and ensure as seamless a transition as possible to the new document or object.

See also HLBWINFO, IHlinkBrowseContext::GetBrowseWindowInfo, IHlinkBrowseContext::SetBrowseWindowInfo


HLFNAMEF

typedef enum tagHLFNAMEF
{
    HLFNAMEF_DEFAULT,          =  0,
    HLFNAMEF_TRYCACHE,         =  1,
    HLFNAMEF_TRYPRETTYTARGET,  =  2,
    HLFNAMEF_TRYFULLTARGET,    =  4,
    HLFNAMEF_TRYWIN95SHORTCUT  =  8,
} HLFNAMEF ;

Specifies which friendly name a client is requesting. The flags are used by the IHlink::GetFriendlyName interface.

HLFNAMEF_DEFAULT
The cached friendly name, or else the simplified display name.
HLFNAMEF_TRYCACHE
The friendly name that is cached in the hyperlink object.
HLFNAMEF_TRYPRETTYTARGET
A beautified version of the display name of the hyperlink target.
HLFNAMEF_TRYFULLTARGET
The full display name of the hyperlink target.
HLFNAMEF_TRYWIN95SHORTCUT
A simplified version of the full display name of the hyperlink target.

See also IHlink::GetFriendlyName


HLID

typedef enum tagHLID
{
    HLID_PREVIOUS,
    HLID_NEXT,
    HLID_CURRENT,
    HLID_STACKBOTTOM,
    HLID_STACKTOP
} HLID;

Identifies the logical positions of a hyperlink identifier in the hyperlink navigation stack. The constants are used in the IHlinkBrowseContext interface.

HLID_PREVIOUS
The hyperlink prior to the current one. If the current hyperlink is the first or only hyperlink in the navigation stack, or if there are no hyperlinks in the navigation stack, there is no previous hyperlink, and methods such as IHlinkBrowseContext::GetHlink will return NULL and E_FAIL when passed this value.
HLID_NEXT
The hyperlink after the current one. If the current hyperlink is the last or only hyperlink in the navigation stack, or if there are no hyperlinks in the navigation stack, there is no next hyperlink, and methods such as IHlinkBrowseContext::GetHlink will return NULL and E_FAIL when passed this value.
HLID_CURRENT
The current hyperlink. A browsing tool might offer a command to reload the current page, or to recenter the user interface around the beginning portion of the current hyperlink destination, or to restart animation, sound, or other activity by renavigating to the current hyperlink.
HLID_STACKBOTTOM
The very first hyperlink in the navigation stack. If there are no hyperlinks in the navigation stack, there is no stack-bottom hyperlink, and methods such as IHlinkBrowseContext::GetHlink will return NULL and E_FAIL when passed this value.
HLID_STACKTOP
The very last hyperlink in the navigation stack. If there are no hyperlinks in the navigation stack, there is no stack-top hyperlink, and methods such as IHlinkBrowseContext::GetHlink will return NULL and E_FAIL when passed this value.

For convenience and performance, individual hyperlink objects are often identified in a navigation stack like a browse context or a history/favorites list using a ULONG hyperlink identifier or HLID rather than an IHlink interface pointer. This prevents unnecessary passing of interface pointers across process boundaries in common user-interface scenarios, such as building a drop-down menu or scrollable list of the history, or when testing the current location in the navigation stack to enable Go Back and Go Forward.

See also HLQF, IHlinkBrowseContext::GetHlink, IHlinkBrowseContext::QueryHlink, IHlinkBrowseContext::SetCurrentHlink


HLINKGETREF

typedef enum tagHLINKGETREF
{
    HLINKGETREF_DEFAULT,   =  0,
    HLINKGETREF_ABSOLUTE,  =  1,
    HLINKGETREF_RELATIVE   =  2,
} HLINKGETREF ;

Specifies whether the client is requesting the absolute, relative, or default reference for the hyperlink target. The constants are used in the IHlink::GetMonikerReference and IHlink::GetStringReference methods.

HLINKGETREF_DEFAULT
Used to specify that the client of the hyperlink wants to retrieve the default reference for the hyperlink target. This depends on whether the hyperlink was initialized as a relative or an absolute reference.
HLINKGETREF_ABSOLUTE
Used to specify that the client of the hyperlink wants to retrieve the absolute reference for the hyperlink target.
HLINKGETREF_RELATIVE
Used to specify that the client of the hyperlink wants to retrieve the relative reference for the hyperlink target.

See also IHlink::GetMonikerReference, IHlink::GetStringReference


HLINKMISC

typedef enum tagHLINKMISC
{
    HLINKMISC_RELATIVE,  =  1,
} HLINKMISC ;

Specifies whether the hyperlink object is a relative hyperlink to its target. The constants are used in the IHlink::GetMiscStatus method.

HLINKMISC_RELATIVE
The given hyperlink object contains a relative reference to the hyperlink target.

See also IHlink::GetMiscStatus


HLINKSETF

typedef enum tagHLINKSETF
{
    HLINKSETF_TARGET,     1,
    HLINKSETF_LOCATION,   2,
} HLINKSETF ;

Specifies the operation of IHlink::SetMonikerReference. It allows a caller of this function to specify which Hlink parameter to set.

HLINKSETF_TARGET
Used to specify the setting of the pmkTarget parameter of the Hlink object.
HLINKSETF_LOCATION
Used to specify the setting of the szLocation parameter of the Hlink object.

See also IHlink::SetMonikerReference


HLINKWHICHMK

typedef enum tagHLINKWHICHMK
{
    HLINKWHICHMK_CONTAINER,  =  1,
    HLINKWHICHMK_BASE,       =  2,
} HLINKWHICHMK ;

Specifies whether a moniker being requested is the moniker for the container document or a base moniker specific to a hyperlink site. The constants are used in the IHlinkSite::GetMoniker method.

HLINKWHICHMK_CONTAINER
Used to specify that the hyperlink wants to retrieve the moniker for the hyperlink container corresponding to a particular hyperlink site.
HLINKWHICHMK_BASE
Used to specify that the hyperlink wants to request the base moniker corresponding to the particular hyperlink site. (These might be different, for example, if a BASE tag is used in HTML.)

See also IHlinkSite::GetMoniker


HLNF

typedef enum tagHLNF
{
    HLNF_INTERNALJUMP
    HLNF_OPENINNEWWINDOW
} HLNF;

Indicates how hyperlink navigation is to proceed. The enumeration is also used by the objects participating in the navigation protocol to convey to each other contextual information about the navigation.

HLNF_INTERNALJUMP
The navigation is an internal jump within the current hyperlink target.
HLNF_OPENINNEWWINDOW
An abbreviation for two commonly coincident options: HLNF_USEBROWSECONTEXTCLONE and HLNF_OFFSETWINDOWORG.

See also HlinkSimpleNavigateToMoniker, HlinkSimpleNavigateToString


HLQF

typedef enum tagHLQF
{
    HLQF_ISVALID,    =  1,
    HLQF_ISCURRENT,  =  2
} HLQF;

Specifies query flags used by IHlinkBrowseContext::QueryHlink to determine the state of a particular hyperlink.

HLQF_ISVALID
Used to test the validity of a particular hyperlink. The uHLID parameter can specify either a specific hyperlink within the navigation stack or a relative hyperlink, such as HLID_NEXT or HLID_PREVIOUS.
HLQF_ISCURRENT
Used to test if the specific hyperlink (identified by the uHLID parameter) is the user's current position within the navigation stack.

See also HLID, IHlinkBrowseContext::QueryHlink


HLSR

typedef enum tagHLSR
{
    HLSR_HOME,         =  0,
    HLSR_SEARCHPAGE,   =  1,
    HLSR_HISTORYFOLDER =  2,
} HLSR ;

Specifies which of the special hyperlink references to choose. The constants are used by the HlinkGetSpecialReference and HlinkSetSpecialReference functions.

HLSR_HOME
Used to specify the hyperlink reference to the global user "home" page.
HLSR_SEARCHPAGE
Used to specify the hyperlink reference to the global user "search page."
HLSR_HISTORYFOLDER
Used to specify the hyperlink reference to the global user "history folder" page.

See also HlinkGetSpecialReference, HlinkSetSpecialReference


Functions

This section describes the following functions:

  • HlinkCreateBrowseContext
  • HlinkCreateFromData
  • HlinkCreateFromMoniker
  • HlinkCreateFromString
  • HlinkGetSpecialReference
  • HlinkGoBack
  • HlinkGoForward
  • HlinkNavigate
  • HlinkNavigateMoniker
  • HlinkNavigateString
  • HlinkNavigateToStringReference
  • HlinkOnNavigate
  • HlinkQueryCreateFromData
  • HlinkSetSpecialReference
  • HlinkSimpleNavigateToMoniker
  • HlinkSimpleNavigateToString


HlinkCreateBrowseContext

HRESULT HlinkCreateBrowseContext(
    IUnknown *piunkOuter,    //Controlling unknown for possible aggregation
    REFIID riid,        //Interface identifier to return on the new browse context
    void **ppvObj       //Receives the requested interface's pointer
   );

Creates an empty, default instance of the system browse context object.

  • Returns S_OK if the browse context was created and the interface pointer retrieved.
piunkOuter
[in] Address of the controlling IUnknown interface for the new browse context. Typically NULL, in which case the new browse context is not aggregated. This interface must be derived from IUnknown.
riid
[in] Used to identify the interface to return on the new browse context. Typically IID_IHlinkBrowseContext, although it must be IID_IUnknown when punkOuter is non-NULL so that the aggregator can retrieve the new browse context's inner IUnknown for future delegation of QueryInterface. See the COM aggregation documentation for details.
ppvObj
[out] Location to return the riid interface.

This helper function is identical to calling the following:

coCreateInstance(CLSID_StdHlinkBrowseContext, punkOuter, CLSCTX_SERVER, riid, ppv)

See also IHlinkBrowseContext, IHlinkFrame::GetBrowseContext, IHlinkTarget::GetBrowseContext


HlinkCreateFromData

HRESULT HlinkCreateFromData(
    IDataObject* piDataObj,    //Interface on target data from which to create the hyperlink
    IHlinkSite* pihlsite,      //Interface on hyperlink site
    DWORD dwSiteData,          //Additional site data
    IUnknown *piunkOuter,      //Interface that controls aggregation
    REFIID riid,       //Interface identifier on new hyperlink object
    Void ** ppvObj     //Receives the requested interface's pointer
   );

Creates a standard hyperlink object from a COM object that supports the IDataObject interface.

  • Returns S_OK if the new hyperlink object was created successfully, or E_NOINTERFACE if the object did not support the riid interface.
piDataObj
[in] Address of the IDataObject interface on the data object of interest. Used to access the methods to retrieve the data from the object.
pihlsite
[in] Address of the IHlinkSite interface for the new hyperlink within its container.
dwSiteData
[in] Additional site data associated with the hyperlink site.
piunkOuter
[in] Address of the controlling IUnknown interface for the new hyperlink object. If NULL, the new hyperlink object is not aggregated.
riid
[in] Used to identify the interface to return on the new hyperlink. Typically IID_IHlink, or IID_IUnknown when punkOuter is non-NULL.
ppvObj
[out] On return, indirect pointer to the requested interface.

Typically, this object originates from a data transfer operation, such as copying to and pasting from the clipboard, or through a drag-and-drop operation.

HlinkCreateFromData is one of three helper functions that you can use to create a hyperlink. HlinkCreateFromData creates a hyperlink from a COM object that supports both the IDataObject interface and a hyperlink format CF_HYPERLINK on that IDataObject interface. HlinkQueryCreateFromData is typically called before the call to HlinkCreateFromData to determine if both these conditions are met. To create a hyperlink from a COM object for which you know the moniker, use HlinkCreateFromMoniker. To create a hyperlink from a COM object for which you have the name but not the moniker, use HlinkCreateFromString.

HlinkCreateFromData is typically used by a hyperlink container as part of a user interface that creates new hyperlinks through the clipboard or a drag-and-drop operation.

See also HlinkCreateFromMoniker, HlinkCreateFromString, HlinkQueryCreateFromData


HlinkCreateFromMoniker

HRESULT HlinkCreateFromMoniker(
    IMoniker * pimkTrgt,    //Interface on hyperlink target moniker
    LPCWSTR pwzLocation,    //Named location of hyperlink reference within target
    LPCWSTR pwzFriendlyName,     //Display name of hyperlink
    IHlinkSite * pihlsite,       //Interface on hyperlink site
    DWORD dwSiteData,       //Additional site data
    IUnknown * piunkOuter,       //Whether or not object is part of an aggregate
    REFIID riid,        //Interface identifier on new hyperlink object
    Void * ppvObj       //Receives the requested interface's pointer
   );

Creates a new system hyperlink object from a moniker, a location string, and a friendly name string (used for displaying the hyperlink).

  • Returns S_OK if a new hyperlink object was created successfully.
pimkTrgt
[in] Address of the moniker to the hyperlink target for the new hyperlink. Must not be NULL.
pwzLocation
[in] Address of a named location within the hyperlink target that resolves to the hyperlink reference.
pwzFriendlyName
[in] Address of a string to use as the display name for the hyperlink.
pihlsite
[in] Address of the IHlinkSite object for the new hyperlink within the hyperlink container.
dwSiteData
[in] Additional site data for the new hyperlink object.
piunkOuter
[in] Address of the controlling IUnknown interface for the new hyperlink object. If NULL, the new hyperlink object is not aggregated.
riid
[in] Used to identify the interface to return on the new hyperlink. Typically IID_IHlink, or IID_IUnknown when punkOuter is non-NULL.
ppvObj
[out] On return, indirect pointer to the requested interface.

HlinkCreateFromMoniker is one of three helper functions that you can use to create a hyperlink. HlinkCreateFromData creates a hyperlink from a COM object that supports both the IDataObject interface and a hyperlink format CF_HYPERLINK on that IDataObject interface. HlinkQueryCreateFromData is typically called before the call to HlinkCreateFromData to determine if both these conditions are met. To create a hyperlink from a COM object for which you know the moniker, use HlinkCreateFromMoniker. To create a hyperlink from a COM object for which you have the name but not the moniker, use HlinkCreateFromString.

HlinkCreateFromMoniker creates new hyperlinks from an existing target moniker, a location string within the target, and a friendly name string used to identify how to display the hyperlink. This method's typical use is as part of a user interface for creating new hyperlinks from existing hyperlinks, or for editing existing hyperlinks, using a dialog box or form to prompt for the strings. This function is significantly faster than HlinkCreateFromString.

See also HlinkCreateFromData, HlinkCreateFromString, HlinkQueryCreateFromData


HlinkCreateFromString

HRESULT HlinkCreateFromString(
    LPCWSTR pwzTarget,    //String helping to identify the hyperlink target
    LPCWSTR pwzLocation,        //Location within the hyperlink target of new hyperlink object
    LPCWSTR pwzFriendlyName,    //Friendly name of the hyperlink
    IHlinkSite * pihlsite,      //Site for the new hyperlink object
    DWORD dwSiteData,     //Additional site data for the new hyperlink object
    IUnknown * piunkOuter,      //Whether or not object is part of an aggregate
    REFIID riid,     //Interface identifier on new browse context object
    Void * ppvObj    //Location of the requested interface's pointer
   );

Creates a new hyperlink object from strings representing the hyperlink target, the location within the target, and a friendly name.

  • Returns S_OK if a new hyperlink object was created.
pwzTarget
[in] Address of the string to help identify the hyperlink target. This string is resolved into a moniker through MkParseDisplayNameEx.
pwzLocation
[in] Address of the string representing the location within the hyperlink target for the new hyperlink. Must not be NULL.
pwzFriendlyName
[in] Address of the string to use as the friendly name for the hyperlink. This is typically a display name referenced by the user interface.
pihlsite
[in] Address of the IHlinkSite object for the new hyperlink within the hyperlink container.
dwSiteData
[in] Additional site data for the new hyperlink object.
piunkOuter
[in] Address of the controlling IUnknown interface for the new browse context. If NULL, the new browse context is not aggregated.
riid
[in] Used to identify the interface to return on the new hyperlink. Typically IID_IHlink, or IID_IUnknown when punkOuter is non-NULL.
ppvObj
[out] On return, indirect pointer to the requested interface.

HlinkCreateFromString is one of three helper functions that you can use to create a hyperlink. HlinkCreateFromData creates a hyperlink from a COM object that supports both the IDataObject interface and a hyperlink format CF_HYPERLINK on that IDataObject interface. HlinkQueryCreateFromData is typically called before the call to HlinkCreateFromData to determine if both these conditions are met.

To create a hyperlink from a COM object for which you know the moniker, use HlinkCreateFromMoniker. To create a hyperlink from a COM object for which you have the name but not the moniker, use HlinkCreateFromString.

HlinkCreateFromString is typically used by hyperlink containers as part of the user interface for creating brand new hyperlinks, where the user fills in a form or dialog box of items—target, location, friendly name—that are used to construct the hyperlink.

See also HlinkCreateFromData, HlinkCreateFromMoniker, HlinkQueryCreateFromData


HlinkGetSpecialReference

HRESULT HlinkGetSpecialReference(
    ULONG uReference,    //Special reference flags
    LPWSTR * ppwzReference    //Buffer to return special reference string
   );

For a given value from the HLSR enumeration, this function returns the current user's default global home, search, or history page for browsing as a string.

uReference
[in] A value taken from the HLSR enumeration.
ppwzReference
[out] Indirect pointer to the location to return the special reference string. Must not be NULL.

See also HlinkSetSpecialReference, HLSR


HlinkGoBack

HRESULT HlinkGoBack(
    IUnknown *pUnk    //IUnknown pointer to the initiating document or object
   );

Executes a hyperlink jump backward within the navigation stack.

  • Returns S_OK if the hyperlink jump has executed successfully.
pUnk
[in] Address of the IUnknown interface on the document or object that is initiating the hyperlink. Must not be NULL.

The HlinkGoBack helper function should be used by all applications, documents, and objects that have simple navigational needs. This single function call will "do the right thing" depending on whether the navigation is originating from within a hyperlink frame or within a hyperlink-unaware application.

The specified pointer pUnk must point to an object that is hosted within a hyperlink-aware container, such as Microsoft Internet Explorer or an ActiveX hyperlink frame.

Note that this function will work only if the object calling the function is the current object in the navigation stack. In HTML pages with frame sets, HlinkGoBack only affects the current frame.

See also HlinkGoForward


HlinkGoForward

HRESULT HlinkGoForward(
    IUnknown *pUnk    //IUnknown pointer to the initiating document or object
   );

Executes a hyperlink jump forward within the navigation stack.

  • Returns S_OK if the hyperlink jump has executed successfully.
pUnk
[in] Address of the IUnknown interface on the document or object that is initiating the hyperlink. Must not be NULL.

The HlinkGoForward helper function should be used by all applications, documents, and objects that have simple navigational needs. This single function call will "do the right thing" depending on whether the navigation is originating from within a hyperlink frame or within a hyperlink-unaware application.

The specified pointer pUnk must point to an object that is hosted within a hyperlink-aware container, such as Microsoft Internet Explorer or an ActiveX hyperlink frame.

Note that this function will work only if the object calling the function is the current object in the navigation stack. In HTML pages with frame sets, HlinkGoForward only affects the current frame.

See also HlinkGoBack


HlinkNavigate

HRESULT HlinkNavigate(
    IHlink * pihl,    //The target hyperlink
    IHlinkFrame * pihlframe,    //The hyperlink frame of the hyperlink container
    DWORD grfHLNF,    //Navigation flags
    LPBC pbc,    //Bind context object interface pointer
    IBindStatusCallback * pibsc,    //Bind status callback object interface pointer
    IHlinkBrowseContext * pihlbc    //Browse context object interface pointer
   );

Navigates to a hyperlink, given a hyperlink object and an optional hyperlink frame object.

pihl
[in] Address of the IHlink interface on the target hyperlink.
pihlframe
[in] Address of the IHlinkFrame interface of the hyperlink container. Can be NULL if the hyperlink container does not have a hyperlink frame.
grfHLNF
[in] Value taken from the HLNF enumeration.
pbc
[in] Address of the IBindCtx interface on the bind context to use for any moniker binding performed during the navigation. Must not be NULL.
pibsc
[in] Address of the IBindStatusCallback interface on the bind status context to use for any asynchronous moniker binding performed during the navigation. Can be NULL, in which case the caller is not interested in progress notification, cancellation, pausing, or low-level binding information.
pihlbc
[in] Address of the IHlinkBrowseContext interface pointer to use for this navigation. The browse context includes history information in which this navigation is logged, if !(grfHLNF & HLNF_CREATENOHISTORY).

HlinkNavigate encapsulates the following common sequence of calls:

if (phlFrame)
    phlFrame->Navigate(grfHLNF, pbc, pbsc, phl);
else if (phl)
    phl->Navigate(grfHLNF, pbc, pbsc, phlbc);

See also IHlinkBrowseContext, IHlink::Navigate, IHlinkFrame::Navigate, IHlinkTarget::Navigate


HlinkNavigateMoniker

HRESULT HlinkNavigateMoniker(
    IUnknown * pUnk,        //IUnknown pointer to the initiating document or object
    IMoniker * pmkTarget    //Moniker of the hyperlink target
   );

Executes a hyperlink jump to a new document or object (specified in pmkTarget).

  • Returns S_OK if a hyperlink jump to a new document or object has executed successfully.

    This function can also return any value returned by IHlink::Navigate.

pUnk
[in] Address of the IUnknown interface on the document or object that is initiating the hyperlink. If NULL, it is assumed the hyperlink originates from an ActiveX-unaware application.
pmkTarget
[in] Address of the moniker that identifies the hyperlink target. If NULL, the navigation is within a document.

HlinkNavigateMoniker is implemented as a simple macro that calls the HlinkSimpleNavigateToMoniker function, passing it NULL for most parameters.

The HlinkNavigateMoniker helper function should be used by all applications, documents, and objects that have simple navigation needs. This single function call will "do the right thing" depending on whether the navigation is originating from within a hyperlink frame or within a hyperlink-unaware application.

See also HLNF, HlinkNavigateString, HlinkNavigateToStringReference, HlinkSimpleNavigateToMoniker, IHlink::Navigate


HlinkNavigateString

HRESULT HlinkNavigateString(
    IUnknown * pUnk,    //IUnknown pointer to the initiating document or object
    LPCWSTR szTarget    //Moniker of the hyperlink target
   );

Executes a hyperlink jump to a new document or object (specified in szTarget).

  • Returns S_OK if a hyperlink jump to a new document or object has executed successfully.
pUnk
[in] Address of the IUnknown interface on the document or object that is initiating the hyperlink. If NULL, it is assumed the hyperlink originates from an ActiveX-unaware application.
szTarget
[in] String that helps identify the hyperlink target. This string is resolved into a moniker for underlying binding operations through MkParseDisplayNameEx. If NULL, the navigation is within a document.

HlinkNavigateString is implemented as a simple macro that calls the HlinkSimpleNavigateToString function, passing it NULL for most parameters.

The HlinkNavigateString helper function should be used by all applications, documents, and objects that have simple navigation needs. This single function call will "do the right thing" depending on whether the navigation is originating from within a hyperlink frame or within a hyperlink-unaware application.

See also HLNF, HlinkNavigateMoniker, HlinkNavigateToStringReference, HlinkSimpleNavigateToString, IHlink::Navigate


HlinkNavigateToStringReference

HRESULT HlinkNavigateToStringReference(
    LPCWSTR pwzTarget,        //String helping to identify the hyperlink target
    LPCWSTR pwzLocation,      //Location within the hyperlink target of new hyperlink
    IHlinkSite * pihlsite,    //Site object interface for the new hyperlink object
    DWORD dwSiteData,         //Additional site data for the new hyperlink object
    IHlinkFrame * pihlframe,  //Frame object interface for the new hyperlink object
    DWORD grfHLNF,    //Navigation flags
    LPBC pibc,        //Bind context object
    IBindStatusCallback * pibsc,    //Bind status callback object
    IHlinkBrowseContext * pihlbc    //Browse context object
   );

Creates a hyperlink site from strings representing the hyperlink target, the location within the target, and a friendly name, and then navigates to that site.

  • Returns S_OK if a hyperlink site was created and navigated to.
pwzTarget
[in] Address of the string that helps identify the hyperlink target. This string is resolved into a moniker for underlying binding operations through MkParseDisplayNameEx. Must not be NULL.
pwzLocation
[in] Address of the location within the hyperlink target of the new hyperlink object.
pihlsite
[in] Address of the IHlinkSite interface on the site object for the new hyperlink object. This is optional, in which case szTarget must be an absolute reference.
dwSiteData
[in] Additional site data for the new hyperlink object.
pihlframe
[in] Address of the IHlinkFrame interface for the hyperlink frame object of the hyperlink container object. Can be NULL if the hyperlink container does not have a hyperlink frame.
grfHLNF
[in] Value taken from the HLNF enumeration.
pibc
[in] Address of the IBindCtx interface on the bind context object to use for any moniker binding performed during the navigation. Must not be NULL.
pibsc
[in] Address of the IBindStatusCallback interface on the bind-status-callback object to use for any asynchronous moniker binding performed during the navigation. Can be NULL, in which case the caller is not interested in progress notification, cancellation, pausing, or low-level binding information.
pihlbc
[in] IHlinkBrowseContext interface pointer to the browse context object to use for this navigation. The browse context includes history information in which this navigation is logged, if !(grfHLNF & HLNF_CREATENOHISTORY).

This helper function is identical to calling the following:

// create hyperlink site, IBindStatusCallback,
    // gather bind context, and browse context
HlinkCreateFromString(pwzTarget, pwzLocation,
    pwzFriendlyName, &hlSite, dwSiteData, NULL,
    IID_IHlink, (void**)&phl);
HlinkNavigate(pihl, pihlframe, grfHLNF, pbc, pibsc, pihlbc);
phl->Release();

See also HLNF, HlinkNavigate, HlinkCreateFromString, HlinkSimpleNavigateToString


HlinkOnNavigate

HRESULT HlinkOnNavigate(
    IHlinkFrame * pihlframe,    //Frame object interface for the new hyperlink
    IHlinkBrowseContext * pihlbc,    //Browse context object to use for this navigation
    DWORD grfHLNF,      //Navigation flags
    IMoniker * pimkTarget,      //Moniker interface pointer of the hyperlink target
    LPCWSTR pwzLocation,        //Location within the hyperlink target of new hyperlink
    LPCWSTR pwzFriendlyName,    //Friendly name of the hyperlink
    ULONG * puHLID      // Pointer to hyperlink identifier
   );

Notifies a hyperlink browse context and hyperlink frame, if it exists, that a hyperlink target has been navigated to.

  • Returns S_OK if the browse context and the frame, if it exists, have been notified of the hyperlink navigation.
pihlframe
[in] Address of the IHlinkFrame interface of the hyperlink container. Can be NULL if the hyperlink container does not have a hyperlink frame.
pihlbc
[in] Address of the IHlinkBrowseContext interface for the browse context object to use for this navigation. The browse context includes history information in which this navigation is logged, if !(grfHLNF & HLNF_CREATENOHISTORY).
grfHLNF
[in] Value taken from the HLNF enumeration.
pimkTarget
[in, unique] Address of an IMoniker interface on the hyperlink target.
pwzLocation
[in] Address of the location within the hyperlink target of the new hyperlink object.
pwzFriendlyName
[in] Address of the friendly name of the hyperlink.
puHLID
[out] Address of the hyperlink identifier to set in the current browse context's navigation stack.

HlinkOnNavigate is a helper function typically called during IHlinkTarget::Navigate, which encapsulates the following calls:

phlbc->OnNavigateHlink(grfHLNF, pimkTarget, pwzLocation, pwzFriendlyName);
if (phlFrame)
    phlFrame->OnNavigate(grfHLNF);

See also IHlinkBrowseContext::OnNavigateHlink, IHlinkFrame::OnNavigate, IHlinkSite::OnNavigationComplete


HlinkQueryCreateFromData

HRESULT HlinkQueryCreateFromData(
    IDataObject* piDataObj    //Data object to query
   );

Determines if a new hyperlink can be created from an IDataObject interface.

  • Returns S_OK if a hyperlink can be created from the data object, or S_FALSE if not.
piDataObj
[in] Address of the IDataObject interface supplying the hyperlink formats.

The application must call the HlinkQueryCreateFromData function to find out whether the hyperlink can be created from the data object obtained from the clipboard, from a drag-and-drop operation, or from any other means.

A hyperlink can be created if the IDataObject interface supports one of the following formats: cfHyperlink, cfUniformResourceLocator, CF_HDROP, or cfFileName.

See also HlinkCreateFromData


HlinkSetSpecialReference

HRESULT HlinkSetSpecialReference(
    ULONG uReference,       //Special reference flags
    LPCWSTR pwzReference    //The special reference string
   );

For a given value from the HLSR enumeration, sets the current user's default global home, search, or history page for browsing as a string.

uReference
[in] A value taken from the HLSR enumeration.
pwzReference
[in] Address of the special reference string.

See also HlinkGetSpecialReference, HLSR


HlinkSimpleNavigateToMoniker

HRESULT HlinkSimpleNavigateToMoniker(
    IMoniker * pmkTarget,    //Moniker of the hyperlink target
    LPCWSTR szLocation,      //Optional string representing location within target
    LPCWSTR szTargetFrameName,    //Optional string naming the target frame
    IUnknown * pUnk,         //IUnknown pointer to the initiating document or object
    IBindCtx * pbc,          //Bind context object
    IBindStatusCallback * pbsc,    //Bind status callback
    DWORD grfHLNF,           //Navigation flags
    DWORD dwReserved         //Reserved for future use
   );

Executes a hyperlink jump to a new document or object (specified in pmkTarget).

  • Returns S_OK if a hyperlink knowing the moniker of its target has navigated to it successfully.

    This function can also return any value returned by IHlink::Navigate.

pmkTarget
[in] Address of the moniker that identifies the hyperlink target. If NULL, the navigation is within a document.
szLocation
[in] Optional string representing the location within the hyperlink target for the new hyperlink.
szTargetFrameName
[in] Optional string naming the target frame for the hyperlink navigation. This argument only affects navigation within a document container that understands frame sets.
pUnk
[in] Address of the IUnknown interface on the document or object that is initiating the hyperlink. If NULL, it is assumed the hyperlink originates from an ActiveX-unaware application. Note that if the caller of this function is an ActiveX Control or Document Object, you must pass a valid value for this parameter in order for navigation to work correctly.
pbc
[in] Address of the IBindCtx interface on the bind context to use for any moniker binding performed during the navigation. Must not be NULL.
pbsc
[in] Address of the IBindStatusCallback interface on the bind-status-callback to use for any asynchronous moniker binding performed during the navigation. The bind-status-callback will only return the standard IUnknown methods: AddRef and QueryInterface. When navigating in a new window, the only BindStatusCallback method that gets called is GetBindInfo. If NULL, the caller is not interested in progress notification, cancellation, pausing, or low-level binding information.
grfHLNF
[in] Value taken from the HLNF enumeration.
dwReserved
[in] Reserved for future use; must be set to NULL.

The HlinkSimpleNavigateToMoniker helper function should be used by all applications, documents, and objects that have simple navigation needs. This single function call will "do the right thing" depending on whether the navigation is originating from within a hyperlink frame or within a hyperlink-unaware application.

See also HLNF, HlinkNavigateToStringReference, HlinkSimpleNavigateToString, IHlink::Navigate


HlinkSimpleNavigateToString

HRESULT HlinkSimpleNavigateToString(
    LPCWSTR szTarget,    //String to be resolved into target's moniker
    LPCWSTR szLocation,    //Optional string representing location within target
    LPCWSTR szTargetFrameName,    //Optional string naming the target frame
    IUnknown * pUnk,     //IUnknown pointer to the initiating document or object
    IBindCtx * pbc,      //Bind context object
    IBindStatusCallback * pbsc,   //Bind status callback
    DWORD grfHLNF,       //Navigation flags
    DWORD dwReserved     //Reserved for future use
   );

Executes a hyperlink jump to a new document or object (specified in szTarget).

  • Returns S_OK if a hyperlink knowing the name of its target has navigated to it successfully.
szTarget
[in] String that helps identify the hyperlink target. This string is resolved into a moniker for underlying binding operations through MkParseDisplayNameEx. If NULL, the navigation is within a document. This parameter is required.
szLocation
[in] Optional string representing the location within the hyperlink target for the new hyperlink.
szTargetFrameName
[in] Optional string naming the target frame for the hyperlink navigation. This argument only affects navigation within a document container that understands frame sets.
pUnk
[in] Address of the IUnknown interface on the document or object that is initiating the hyperlink. If NULL, it is assumed the hyperlink originates from an ActiveX-unaware application. Note that if the caller of this function is an ActiveX Control or Document Object, you must pass a valid value for this parameter in order for navigation to work correctly.
pbc
[in] Address of the IBindCtx interface on the bind context to use for any moniker binding performed during the navigation. Must not be NULL.
pbsc
[in] Address of the IBindStatusCallback interface on the bind-status-callback to use for any asynchronous moniker binding performed during the navigation. The bind-status-callback will only return the standard IUnknown methods: AddRef and QueryInterface. When navigating in a new window, the only BindStatusCallback method that gets called is GetBindInfo. If NULL, the caller is not interested in progress notification, cancellation, pausing, or low-level binding information.
grfHLNF
[in] Value taken from the HLNF enumeration.
dwReserved
[in] Reserved for future use; must be set to NULL.

The HlinkSimpleNavigateToString helper function should be used by all applications, documents, and objects that have simple navigation needs. This single function call will "do the right thing" depending on whether the navigation is originating from within a hyperlink frame or within a hyperlink-unaware application.

See also HLNF, HlinkNavigateToStringReference, HlinkSimpleNavigateToMoniker, IHlink::Navigate


Interfaces

This section describes the following interfaces:

  • IHlink
  • IHlinkBrowseContext
  • IHlinkFrame
  • IHlinkSite
  • IHlinkTarget


IHlink::GetAdditionalParams

HRESULT GetAdditionalParams(
    LPWSTR * ppwzAdditionalParams    //Extensible parameter string
   );

Retrieves additional parameters or properties for the hyperlink.

  • Returns S_OK after the hyperlink's additional parameter strings are retrieved.
ppwzAdditionalParams
[out] On return, points to the location to return the string containing a list of parameters or properties for the hyperlink in the following format:
<ID1 = "value1"> <ID2 = "value2"> ... <IDn = "valuen">

The parameters retrieved in this string are primarily interpreted by the hyperlink frame.

See also IHlink::SetAdditionalParams


IHlink::GetFriendlyName

HRESULT GetFriendlyName(
    DWORD grfHLFNAMEF,           //Flag specifying the friendly name to return.
    LPWSTR * ppwzFriendlyName    //Buffer to receive the friendly name.
   );

Retrieves the friendly name of the target. The container normally uses this name to determine how to represent the hyperlink in its user interface.

  • Returns S_OK after the friendly name string of the hyperlink is retrieved.
grfHLFNAMEF
[in] Flag specifying the friendly name to return.
ppwzFriendlyName
[out] Address of the buffer to return the friendly name. This string must be allocated using CoTaskMemAlloc. It is the caller's responsibility to free this string using CoTaskMemFree.

See also IHlink::SetFriendlyName, IHlinkTarget::GetFriendlyName


IHlink::GetHlinkSite

HRESULT GetHlinkSite(
    IHlinkSite * ppihlSite,    //Receives the hyperlink site interface
    DWORD *pdwSiteData         //Receives additional site data
   );

Retrieves the hyperlink site and associated site data from a hyperlink object.

  • Returns S_OK after the hyperlink site and associated data have been successfully retrieved.
ppihlSite
[out] On return, points to the IHlinkSite interface pointer on the hyperlink object. This cannot be a NULL pointer on input.
pdwSiteData
[out] On return, points to the site data of the hyperlink target. This must not be a NULL pointer on input.

See also IHlink::SetHlinkSite


IHlink::GetMiscStatus

HRESULT GetMiscStatus(
    DWORD * pdwStatus    //Receives absolute/relative status of hyperlink
   );

Queries whether the hyperlink is an absolute or a relative link.

  • Returns S_OK after the hyperlink status has been successfully retrieved.
pdwStatus
[out] On return, points to a value from the HLINKMISC enumeration. Must not be NULL.

See also HLINKMISC


IHlink::GetMonikerReference

HRESULT GetMonikerReference(
    DWORD dwWhichRef,          /Absolute or relative reference
    IMoniker * ppimkTarget,    //Receives a pointer to the moniker of the hyperlink target
    LPWSTR * ppwzLocation      //Receives the location portion of the hyperlink target
   );

Retrieves the moniker and location portions of the hyperlink reference.

  • Returns S_OK to indicate the moniker and location portions of the target of the hyperlink target have been successfully supplied.
dwWhichRef
[in] Value from the HLINKGETREF enumeration specifying whether to get the absolute or relative reference to the hyperlink target.
ppimkTarget
[out] On return, points to the IMoniker pointer of the target's moniker object, if any. Can be NULL, in which case the caller is not interested in the moniker to the hyperlink reference.
ppwzLocation
[out] On return, points to the string location portion of the target, if any. If NULL, the caller is not interested in the location portion of the hyperlink reference.

See also HLINKGETREF, IHlinkSite::GetMoniker, IHlinkTarget::GetMoniker


IHlink::GetStringReference

HRESULT GetStringReference(
    DWORD dwWhichRef,         //Absolute or relative reference
    LPWSTR * ppwzTarget,      //Receives the string that helps identify the hyperlink target
    LPWSTR * ppwzLocation     //Receives the location portion of the hyperlink target
   );

Retrieves strings that identify the hyperlink target and the location within the hyperlink target.

  • Returns S_OK to indicate the target and location strings of the hyperlink target have been successfully supplied.
dwWhichRef
[in] Value from the HLINKGETREF enumeration specifying whether to get the absolute or relative reference to the hyperlink target.
ppwzTarget
[out] On return, points to a string that helps identify the hyperlink target of the hyperlink reference. If NULL, the caller is not interested in the target string of the hyperlink reference.
ppwzLocation
[out] On return, points to the location portion of the hyperlink reference. If NULL, the caller is not interested in the location portion of the hyperlink reference.

See also IHlink::GetMonikerReference, HLINKGETREF, HlinkNavigateToStringReference, HlinkSimpleNavigateToString


IHlink::GetTargetFrameName

HRESULT GetTargetFrameName(
    LPWSTR * ppwzTargetFrameName    //Receives the target frame name for the hyperlink
   );

Retrieves the name of the target frame for the hyperlink.

  • Returns S_OK if the target frame name string for the hyperlink was retrieved.
ppwzTargetFrameName
[out] On return, points to the target frame name for the hyperlink. Must not be NULL.

See also IHlink::SetTargetFrameName


Hlink

The IHlink interface enables a COM object known as a hyperlink to completely encapsulate the behavior of navigating to its target location.

Hyperlinks are managed by COM hyperlink container objects, which support the IHlinkSite interface for hyperlinks within the container, and the IHlinkTarget interface for hyperlinks referring to documents or document objects within it.

IHlink provides methods for a hyperlink object to navigate to its target, access a friendly name for display purposes, and identify itself to its container and frame.

Implementing IHlink

Typically, you don't need to implement this interface. A standard implementation of a hyperlink component is provided as part of the system, and it is not advisable to implement another version. A document can use the standard hyperlink object to represent hyperlinks within itself, thus encapsulating the capability of navigating, saving, loading, dragging, dropping, cutting, and pasting hyperlinks. The standard hyperlink object implements IHlink, IPersistStream, and IDataObject interfaces.

The support for IPersistStream means that hyperlink objects can be saved to or loaded from a stream, and the support for IDataObject means that hyperlink objects can be cut and pasted.

Using IHlink

IHlink interfaces are typically called by an application's hyperlink container as part of a user interface for creating new hyperlinks. Standard hyperlink objects are created through the HlinkCreateFromData, HlinkCreateFromMoniker, HlinkCreateFromString, and OleLoadFromStream functions.

While the hyperlink object provides many useful functions that are needed for general-purpose uses, often applications are only interested in navigating to a hyperlink target. For simple navigation needs, there are a number of "helper" functions, such as HlinkSimpleNavigateToString, HlinkSimpleNavigateToMoniker, and HlinkNavigateToStringReference, that allow simple hyperlink navigation without any knowledge of other hyperlink interfaces or objects.

Hyperlink navigation involves transitioning from one document/object/application—a hyperlink container—to another document/object/application—a hyperlink target. Usually, both remain running, but the hyperlink target visually replaces the hyperlink container (from which the navigation originated). There are three "flavors" of hyperlink containers and targets:

  1. Top-level documents.
  2. Active Document objects in a browser.
  3. Active Document objects in an Office Binder-like application that does not support OLE in-place/DocObj server functionality, and, therefore, can't be shown in-place in a browser.

The following are possible forms of navigation:

  • From one top-level document to another top-level document (for example, between Office documents in the absence of a browser).
  • From a top-level document to an Active Document in a browser (for example, from a stand-alone application to an HTML document).
  • From one Active Document object in a browser to another Active Document object in the same browser (for example, one HTML document to another).
  • From one Active Document object in a browser to an Active Document object in a Binder-type application (for example, a hyperlink target embedded as an Active Document object in an Office Binder document; in this scenario, the end-user model gets complicated and confusing if the embedded Active Document object is shown in the browser's window, instead of letting it appear in its own container's window).
  • From one location in an object/document to another location in the same object/document (applicable to all three flavors of hyperlink containers/hyperlink targets).

IHlink Methods in Vtable Order

IHlink methods | Description
SetHlinkSite | Saves the interface pointer on the site object.
GetHlinkSite | Retrieves the interface pointer on the site object.
SetMonikerReference | Sets the moniker reference of the target.
GetMonikerReference | Retrieves the moniker and location portions of the target.
SetStringReference | Sets the name and location portions of the target.
GetStringReference | Retrieves the name and location portions of the target.
SetFriendlyName | Sets the friendly name of the target.
GetFriendlyName | Retrieves the friendly name of the target.
SetTargetFrameName | Sets the name of the target frame.
GetTargetFrameName | Retrieves the name of the target frame.
GetMiscStatus | Queries if hyperlink is absolute or relative.
Navigate | Navigates to the given target.
SetAdditionalParams | Sets additional hyperlink parameters.
GetAdditionalParams | Retrieves additional hyperlink parameters.


IHlink::Navigate

HRESULT Navigate(
    DWORD grfHLNF,    //Navigation flags
    LPBC pibc,        //Bind context interface pointer
    IBindStatusCallback * pibsc,    //Bind-status-context interface pointer
    IHlinkBrowseContext * pihlbc    //Browse context interface pointer
   );

Navigates to the hyperlink reference. IHlink::Navigate is the heart of the navigation process that implements the action of resolving a hyperlink target.

  • Returns S_OK if navigation to the hyperlink has been completed successfully.
grfHLNF
[in] Flags describing how the navigation is to proceed. The value of the flag can be any valid HLNF enumeration value.
pibc
[in, unique] IBindCtx interface pointer to the bind context to be used for any moniker binding during this operation. Cannot be NULL.
pibsc
[in, unique] IBindStatusCallback interface pointer to the bind status context to use for any asynchronous moniker binding performed during the navigation. If NULL, the caller is not interested in progress notification, cancellation, pausing, or low-level binding information
pihlbc
[in, unique] Address of the IHlinkBrowseContext interface to use for this navigation. Cannot be NULL. As part of navigation, this browse context's navigation stack can be updated (depending on the navigation flags in grfHLNF), and its cache of hyperlink targets is consulted for a matching to the current hyperlink target.

See also HlinkNavigate, HLNF, IHlinkFrame::Navigate, IHlinkTarget::Navigate


IHlink::SetAdditionalParams

HRESULT SetAdditionalParams(
    LPCWSTR  pwzAdditionalParams    //Extensible parameter string
   );

Sets the additional parameters or properties for the hyperlink.

  • Returns S_OK if the hyperlink's additional parameters string was set.
pwzAdditionalParams
[in, unique] The string containing a list of parameters or properties for the hyperlink in the following format:
<ID1 = "value1"> <ID2 = "value2"> ... <IDn = "valuen">

The parameters saved in this string are primarily interpreted by the hyperlink frame.

See also IHlink::GetAdditionalParams


IHlink::SetFriendlyName

HRESULT SetFriendlyName(
    LPCWSTR pwzFriendlyName    //Friendly name of the hyperlink
   );

Sets the friendly name for the hyperlink. The friendly name is used by hyperlink containers to represent the hyperlink within their user interface.

  • Returns S_OK if the friendly name string of the hyperlink was set.
pwzFriendlyName
[in, unique] The friendly name string of the hyperlink target.

See also IHlink::GetFriendlyName


IHlink::SetHlinkSite

HRESULT SetHlinkSite(
    IHlinkSite * pihlSite,    //Interface pointer to the new hyperlink site
    DWORD dwSiteData          //Additional site data
   );

Sets the hyperlink site and associated site data on a hyperlink object.

  • Returns S_OK if the hyperlink site object and its site data have been successfully set.
pihlSite
[in, unique] Address of a new IHlinkSite object for this hyperlink.
dwSiteData
[in] DWORD that specifies additional information about the site. For instance, each site can differ in color or style from other sites in the same container.

See also IHlink::GetHlinkSite


IHlink::SetMonikerReference

HRESULT SetMonikerReference(
    DWORD grfHLSETF,    //Specifies whether to set the hyperlink target, the location
                        // within the target, or both.
    IMoniker * pimkTarget,   //Moniker interface pointer of the hyperlink target
    LPCWSTR pwzLocation      //Location within the hyperlink target of new hyperlink
   );

Sets the target moniker or location string values for a hyperlink object.

  • Returns S_OK if the moniker reference for the hyperlink was set.
grfHLSETF
[in] Used to indicate whether to set the hyperlink target, the location within the target, or both.
pimkTarget
[in, unique] Address of an IMoniker interface on the hyperlink target.
pwzLocation
[in, unique] A string identifying the location within the hyperlink target that was navigated to. Must not be NULL.

See also HLINKSETF


IHlink::SetStringReference

HRESULT SetStringReference(
    DWORD grfHLSETF,       //Specifies whether to set the hyperlink target, the location within the target,
                           // or both.
    LPCWSTR pwzTarget,     //Target name for the hyperlink
    LPCWSTR pwzLocation    //Location within the hyperlink target of new hyperlink
   );

Sets the target string or location string values for a hyperlink object.

  • Returns S_OK if the string reference of the hyperlink was set.
grfHLSETF
[in] Used to indicate whether to set the hyperlink target, the location within the target, or both.
pwzTarget
[in, unique] The string target name for the hyperlink.
pwzLocation
[in, unique] A string identifying the location within the hyperlink target that was navigated to. Must not be NULL.

See also HLINKSETF


IHlink::SetTargetFrameName

HRESULT SetTargetFrameName(
    LPCWSTR  pwzTargetFrameName    //Target frame name for the hyperlink
   );

Sets the target frame name for the hyperlink.

  • Returns S_OK if the target frame name string for the hyperlink was set.
pwzTargetFrameName
[in, unique] The string target frame name for the hyperlink.

See also IHlink::GetTargetFrameName


IHlinkBrowseContext::Clone

HRESULT Clone(
    IUnknown* piunkOuter,    //Controlling IUnknown interface for new browse context
    REFIID riid,             //Interface ID to return on the new browse context
    IUnknown** ppiunkObj     //Indirect pointer to the clone of the browse context object
   );

Duplicates a browse context.

  • Returns S_OK if the browse context has been duplicated.
piunkOuter
[in, unique] Address of the controlling IUnknown interface for the new browse context. If NULL, the new browse context is not aggregated.
riid
[in] The interface to return on the new hyperlink. Typically IID_IHlink or IID_IUnknown when punkOuter is non-NULL.
ppiunkObj
[out, iid_is] Indirect pointer to the clone of the browse context object.


IHlinkBrowseContext::Close

HRESULT Close(
    DWORD dwReserved    //Reserved for future use
   );

Closes the hyperlink browse context. Releases all hyperlink targets that have been registered with the browse context.

  • Returns S_OK if the hyperlink browse context has been successfully closed.
dwReserved
[in] Reserved for future use; must be set to zero by the caller. To ensure compatibility with future use, the callee must not check for zero.

See also IHlinkBrowseContext::Register


IHlinkBrowseContext::EnumNavigationStack

HRESULT EnumNavigationStack(
    DWORD dwReserved,     //Reserved for future use
    DWORD grfHLFNAMEF,    //Specifies what kind of friendly names to enumerate for the Hlink objects in the navigation stack.
    IEnumHLITEM ** ppienumhlitem    //Location to receive the enumeration interface pointer
   );

Retrieves an enumerator that can be used to enumerate the current contents of the navigation stack.

  • Returns S_OK if the enumerator has been successfully retrieved.
dwReserved
[in] Reserved for future use; must be set to zero by the caller. To ensure compatibility with future use, the callee must not check for zero.
grfHLFNAMEF
[in] Indicator of what kind of friendly names to enumerate for the Hlink objects in the navigation stack.
ppienumhlitem
[out] Location to return the IEnumHLITEM enumeration interface over the set of hyperlinks in this navigation stack.

See also HLID, HLITEM, IEnumHLITEM


IHlinkBrowseContext::GetBrowseWindowInfo

HRESULT GetBrowseWindowInfo(
    HLBWINFO * phlbwi    //Location to receive the HLBWINFO structure
   );

Retrieves the HLBWINFO structure currently associated with this browse context.

  • Returns S_OK if the HLBWINFO structure for this browse window has been retrieved.
phlbwi
[out] Address of the location to return the current HLBWINFO structure.

See also HLBWINFO, IHlinkBrowseContext::SetBrowseWindowInfo


IHlinkBrowseContext::GetHlink

HRESULT GetHlink(
    ULONG uHLID,       //Hyperlink to retrieve
    IHlink * ppihl     //Buffer to return the IHlink interface of the hyperlink
   );

Retrieves a hyperlink from this browse context.

  • Returns S_OK if the hyperlink has been successfully retrieved from this browse context, or E_FAIL if the specified hyperlink does not exist in this browse context.
uHLID
[in] Used to identify the hyperlink to retrieve. Can be a value taken from the HLID constants to indicate a logically identified hyperlink, such as HLID_PREVIOUS or HLID_NEXT.
ppihl
[out] Address of the buffer to return the IHlink interface pointer of the hyperlink object.

See also HLID, IHlink, IHlinkBrowseContext::SetCurrentHlink


IHlinkBrowseContext::GetObject

HRESULT GetObject(
    IMoniker * pimk,         //Moniker interface pointer of the object being retrieved
    BOOL fBindIfRootRegistered,    //Determines binding to the moniker and retrieval of the object
    IUnknown ** ppiunk       //Location to receive the unknown interface pointer of requested object
   );

Retrieves an object previously registered in the browse context.

  • Returns S_OK to indicate the previously registered object has been retrieved, or S_FALSE to indicate no object indicated by pimk was registered in the browse context.
pimk
[in,unique] Used to identify the object being retrieved.
fBindIfRootRegistered
[in] If set to TRUE, this method binds to the moniker and retrieves the object (if the object referred to by pimk is not registered in the browse context).
ppiunk
[out] Indirect pointer to the IUnknown interface of the object being retrieved.

If the object referred to by pimk is not registered in the browse context, this method binds to the full moniker and retrieves the object if the following conditions are met:

  • fBindIfRootRegistered is set to TRUE.
  • The moniker is referring to an embedded object (the moniker pimk is a generic composite moniker).
  • The root object of the containment hierarchy is registered with the browse context.

See also IHlinkBrowseContext::Register


IHlinkBrowseContext

The IHlinkBrowseContext interface enables a COM object to define and manage the browsing context for an ActiveX hyperlink application.

A hyperlink browse context keeps track of the order in which the object/documents (perhaps belonging to different processes) have been visited and chains them together into a navigation stack. The context also keeps track of enabling or disabling buttons such as Go Forward or Go Back for each entry in the navigation stack. In addition, the context maintains window positioning information for hyperlink targets so that a hyperlink application can provide a seamless user interface.

Browse context objects are not required for hyperlink navigation. HlinkSimpleNavigateToString and HlinkSimpleNavigateToMoniker provide examples of navigation between hyperlink containers and hyperlink targets that do not use a browsing context.

IHlinkBrowseContext provides methods that maintain the hyperlink navigation stack and keep track of window position information.

Implementing IHlinkBrowseContext

The system provides a default implementation.

IHlinkBrowseContext Methods in Vtable Order

IHlinkBrowseContext methods | Description
Register | Registers an object with the browse context.
GetObject | Retrieves an object previously registered in the browse context under the given name.
Revoke | Revokes an object previously registered with this browse context.
SetBrowseWindowInfo | Establishes the browse window information structure of this browse context.
GetBrowseWindowInfo | Retrieves the browse window information structure associated with this browse context.
EnumNavigationStack | Retrieves an enumerator that can be used to enumerate the current contents of the navigation stack.
QueryHlink | Tests the validity of a hyperlink ID value.
GetHlink | Retrieves a hyperlink from this browse context.
SetCurrentHlink | Sets the current hyperlink in this browse context's navigation stack.
OnNavigateHlink | Notifies a browse context that a hyperlink has been navigated.
Clone | Duplicates a browse context.
Close | Closes the hyperlink browse context.


IHlinkBrowseContext::OnNavigateHlink

HRESULT OnNavigateHlink(
    DWORD grfHLNF,      //Navigation flags
    IMoniker * pimkTarget,     //Moniker interface pointer of the hyperlink target
    LPCWSTR pwzLocation,       //Location within the hyperlink target of new hyperlink
    LPCWSTR pwzFriendlyName,   //Friendly name of the hyperlink
    ULONG * puHLID      //Pointer to hyperlink identifier
   );

Notifies a browse context that a hyperlink has been navigated.

  • Returns S_OK if the browse context has been successfully notified that a hyperlink has been navigated.
grfHLNF
[in] Flags describing how the navigation is to proceed. The value of the flag can be any valid HLNF enumeration value.
pimkTarget
[in, unique] Address of an IMoniker interface on the hyperlink target.
pwzLocation
[in, unique] A string identifying the location within the hyperlink target that was navigated to. Must not be NULL.
pwzFriendlyName
[in, unique] The friendly name of the location within the hyperlink target that has been navigated to. Must not be NULL.
puHLID
[out] Address of the hyperlink indentifier to set in the current browse context's navigation stack.

See also HlinkOnNavigate, HLNF, IHlinkFrame::OnNavigate, IHlinkSite::OnNavigationComplete


IHlinkBrowseContext::QueryHlink

HRESULT QueryHlink(
    DWORD grfHLQF,    //Value from the HLQF enumeration
    ULONG uHLID       //Hyperlink identifier to query
   );

Tests the validity of a uHLID value.

  • Returns one of the following values:
    S_OK | If grfHLQF is HLQF_ISVALID, uHLID identifies a valid hyperlink within the browse context. If grfHLQF is HLQF_ISCURRENT, uHLID identifies the current hyperlink of the browse context.
    S_FALSE | If grfHLQF is HLQF_ISVALID, uHLID does not identify a valid hyperlink within the browse context. If grfHLQF is HLQF_ISCURRENT, uHLID does not identify the current hyperlink of the browse context.
grfHLQF
[in] A single value taken from the HLQF enumeration.
uHLID
[in] Used to identify the hyperlink to query about. Can be a value taken from the HLID constants to indicate a logically identified hyperlink, such as HLID_PREVIOUS or HLID_NEXT.

See also HLID, HLQF


IHlinkBrowseContext::Register

HRESULT Register(
    DWORD dwReserved,      //Reserved for future use
    IUnknown piunk,        //Object being registered
    IMoniker * pimk,       //Moniker interface pointer of the object being registered
    DWORD * pdwRegister    //Receives the registration value
   );

Registers an object with the browse context.

  • Returns one of the following values:
    S_OK | The object has been registered.
    MK_S_MONIKERALREADYREGISTERED | The object was successfully registered, but another object (possibly the same object) has already been registered with the same moniker in this browse context.
    E_OUTOFMEMORY | There was insufficient memory to register the object with the browse context.
dwReserved
[in] Reserved for future use; must be set to zero by the caller. To ensure compatibility with future use, the callee must not check for zero.
piunk
[in, unique] The object being registered.
pimk
[in, unique] Address of the IMoniker interface pointer that identifies the object being registered.
pdwRegister
[out] Address of a location to return a value identifying the registration, which can be used to subsequently revoke the registration.

See also HlinkCreateBrowseContext, IHlinkBrowseContext::Close, IHlinkBrowseContext::Revoke


IHlinkBrowseContext::Revoke

HRESULT Revoke(
    DWORD dwRegister    //Object to revoke
   );

Revokes an object previously registered with this browse context.

  • Returns S_OK if the previously registered object has been revoked from this browse context.
dwRegister
[in] Used to identify the object to revoke. Returned by a previous call to IHlinkBrowseContext::Register.

See also IHlinkBrowseContext::Register


IHlinkBrowseContext::SetBrowseWindowInfo

HRESULT SetBrowseWindowInfo(
    HLBWINFO * phlbwi    //Pointer to the new HLBWINFO structure for this browse context
   );

Establishes the HLBWINFO structure of this browse context.

  • Returns S_OK if the HLBWINFO structure for this browse window has been established.
phlbwi
[in,unique] Address of the new HLBWINFO structure for this browse context.

See also HLBWINFO, IHlinkBrowseContext::GetBrowseWindowInfo


IHlinkBrowseContext::SetCurrentHlink

HRESULT SetCurrentHlink(
    ULONG uHLID    //Hyperlink ID to set in the navigation stack
   );

Sets the current hyperlink in this browse context's navigation stack.

  • Returns S_OK to indicate this hyperlink has been successfully set in the current browse context's navigation stack, or E_FAIL if not.
uHLID
[in] Used to identify the hyperlink to set in the current browse context's navigation stack. Can be a value taken from the HLID constants to indicate a logically identified hyperlink, such as HLID_PREVIOUS or HLID_NEXT.

See also HLID, IHlinkBrowseContext::GetHlink


IHlinkFrame::GetBrowseContext

HRESULT GetBrowseContext(
    IHlinkBrowseContext * ppihlbc    //Buffer to receive the interface of the current browse context
   );

Retrieves the browse context of the hyperlink frame.

  • Returns S_OK if the browse context has been successfully retrieved, or E_NOTIMPL if the hyperlink target does not understand browse contexts.
ppihlbc
[out] Location to return the browse context interface's pointer.

See also HlinkCreateBrowseContext, IHlinkBrowseContext, IHlinkFrame::SetBrowseContext, IHlinkTarget


IHlinkFrame

The IHlinkFrame interface provides methods that allow a hyperlink frame to interpose itself in the navigation process to allow an application to provide a seamless user interface when navigating from one document/object/application to another when resolving a hyperlink.

Implementing IHlinkFrame

This interface is typically implemented by a document container object, such as Microsoft Internet Explorer or Microsoft Office Binder. A document container implementing the IHlinkFrame interface can host documents that support in-frame navigation from one to another.

Using IHlinkFrame

You do not normally call the IHlinkFrame methods directly. They are referenced by the IHlink::Navigate routines when a hyperlink frame is detected.

IHlinkFrame Methods in Vtable Order

IHlinkFrame methods | Description
GetBrowseContext | Retrieves the browse context of the hyperlink frame.
Navigate | Navigates to the target hyperlink.
OnNavigate | Notifies the hyperlink frame of a hyperlink navigation.
SetBrowseContext | Sets the browse context of the hyperlink frame.
UpdateHlink | Updates the hyperlink frame.


IHlinkFrame::Navigate

HRESULT Navigate(
    DWORD grfHLNF,    //Navigation flags
    LPBC pbc,        //Bind context interface pointer
    IBindStatusCallback * pibsc,    //Bind-status callback  interface pointer
    IHlink * pihlNavigate           //Hyperlink target interface pointer
   );

Navigates to the hyperlink target.

  • Returns one of the following:
    S_OK | The navigation to the target has been successful.
    IHlink::Navigate errors | Since IHlinkFrame::Navigate calls IHlink::Navigate, the errors associated with this method can be returned.
grfHLNF
[in] Flags describing how the navigation is to proceed. The value of the flag can be any valid HLNF enumeration value.
pbc
[in, unique] Address of the bind context interface to use for any moniker binding during this operation. Must not be NULL.
pibsc
[in, unique] Address of the IBindStatusCallback object interface to use for any asynchronous moniker binding performed during the navigation. If NULL, the caller is not interested in progress notification, cancellation, pausing, or low-level binding information.
pihlNavigate
[in, unique] Address of the IHlink object interface to the hyperlink target.

See also HLNF, IHlink::Navigate


IHlinkFrame::OnNavigate

HRESULT OnNavigate(
    DWORD grfHLNF,            //Navigation flags
    IMoniker * pimkTarget,    //Moniker interface pointer of the hyperlink target
    LPCWSTR pwzLocation,      //Location within the hyperlink target of new hyperlink
    LPCWSTR pwzFriendlyName   //Friendly name of the hyperlink
   );

Notifies the hyperlink frame that a hyperlink has been navigated to.

  • Returns S_OK if the hyperlink frame has been successfully notified.
grfHLNF
[in] Flags describing how the navigation is to proceed. The value of the flag can be any valid HLNF enumeration value.
pimkTarget
[in, unique] Address of an IMoniker interface on the hyperlink target.
pwzLocation
[in, unique] A string identifying the location within the hyperlink target that was navigated to. Must not be NULL.
pwzFriendlyName
[in, unique] The friendly name of the location within the hyperlink target that has been navigated to. Must not be NULL.

See also HlinkOnNavigate, HLNF, IHlinkBrowseContext::OnNavigateHlink, IHlinkSite::OnNavigationComplete


IHlinkFrame::SetBrowseContext

HRESULT SetBrowseContext(
    IHlinkBrowseContext * phlbc    //Interface pointer of the current browse context
   );

Sets the browse context of the hyperlink frame.

  • Returns S_OK if the browse context has been successfully set, or E_NOTIMPL if the hyperlink target does not understand browse contexts.
phlbc
[in] The browse context interface's pointer.

See also HlinkCreateBrowseContext, IHlinkBrowseContext, IHlinkFrame::GetBrowseContext, IHlinkTarget::SetBrowseContext


IHlinkFrame::UpdateHlink

HRESULT UpdateHlink(
    ULONG uHLID,              //Hyperlink to retrieve
    IMoniker * pimkTarget,    //Moniker interface pointer of the hyperlink target
    LPCWSTR pwzLocation,      //Location within the hyperlink target of new hyperlink
    LPCWSTR pwzFriendlyName   //Friendly name of the hyperlink
   );

Updates the hyperlink frame.

  • Returns S_OK if the hyperlink frame has been successfully updated.
uHLID
[in] Used to identify the hyperlink to retrieve. Can be a value taken from the HLID constants to indicate a logically identified hyperlink, such as HLID_PREVIOUS or HLID_NEXT.
pimkTarget
[in, unique] Address of an IMoniker interface on the hyperlink target.
pwzLocation
[in, unique] A string identifying the location within the hyperlink target that was navigated to. Must not be NULL.
pwzFriendlyName
[in, unique] The friendly name of the location within the hyperlink target that has been navigated to. Must not be NULL.

This method is called before navigation, typically by the IHlinkSite::ReadyToNavigate method. An application that does not implement the IHlinkSite interface can call this method before calling the navigation function.

See also HlinkOnNavigate, HLID, IHlinkBrowseContext::OnNavigateHlink, IHlinkSite::OnNavigationComplete


IHlinkSite::GetMoniker

HRESULT GetMoniker(
    DWORD dwSiteData,    //Site data for the new hyperlink object
    DWORD dwAssign,      //Whether or not to create a moniker if one not found
    DWORD dwWhich,       //Which moniker to retrieve
    IMoniker * ppimk     //Buffer to receive the requested moniker interface pointer
   );

Returns the relative moniker of the hyperlink's container.

  • Returns S_OK if the moniker of the hyperlink's site container was successfully supplied, or E_FAIL if a moniker does not exist for this hyperlink target and OLEGETMONIKER_ONLYIFTHERE was specified for dwAssign.
dwSiteData
[in] Used to identify the hyperlink to the hyperlink site. The hyperlink site initializes the hyperlink with this value as part of IHlink::SetHlinkSite.
dwAssign
[in] A value from the OLEGETMONIKER enumeration. This is typically either OLEGETMONIKER_ONLYIFTHERE, indicating the function should not force a moniker to be created if one does not already exist, or OLEGETMONIKER_FORCEASSIGN, indicating that the function should create a moniker if one does not exist.
dwWhich
[in] A value from the OLEWHICHMK enumeration. This is typically OLEWHICHMK_CONTAINER, indicating that the site should return the moniker of the hyperlink container.
ppimk
[out] Location to return the IMoniker interface.

See also IHlink::GetMonikerReference, IHlinkTarget::GetMoniker


IHlinkSite

The IHlinkSite interface provides methods for a hyperlink to retrieve the moniker or the interface on its hyperlink container. The navigation process that resolves a hyperlink uses this information to efficiently handle internal (within the same container) and external (to a different container) hyperlink references.

Implementing IHlinkSite

Implement IHlinkSite when you want to hyperlink to other documents. For each hyperlink object provided by the system, a third party, or that you create, you provide an IHlinkSite object. One site object can support multiple hyperlinks.

IHlinkSite Methods in Vtable Order

IHlinkSite methods | Description
QueryService | Queries any service or other interface from the hyperlink site object.
GetMoniker | Retrieves the moniker to the hyperlink target.
ReadyToNavigate | Notifies the hyperlink site that the hyperlink navigation is about to occur.
OnNavigationComplete | Notifies the hyperlink site that hyperlink navigation is complete.


IHlinkSite::OnNavigationComplete

HRESULT OnNavigationComplete(
    DWORD dwSiteData,    //Site data for the hyperlink object
    DWORD dwReserved,    //Reserved for future use
    HRESULT hrError,     //Result of the hyperlink navigation
    LPCWSTR pwzError     //Description of the failure, if any
   );

Notifies the hyperlink site that a hyperlink navigation has been successful.

  • Returns S_OK if the hyperlink site has been successfully notified.
dwSiteData
[in] Used to identify the hyperlink to the hyperlink site. The hyperlink site initializes the hyperlink with this value as part of IHlink::SetHlinkSite.
dwReserved
[in] Reserved for future use; must be set to zero by the caller. To ensure compatibility with future use, the callee must not check for zero.
hrError
[in] Result of the hyperlink navigation. Either S_OK for success, or E_ABORT or E_FAIL for failure.
pwzError
[in] Address of the string describing the failure that occurred.

This notification is particularly useful if the hyperlink has been navigated asynchronously, because it is the only notification the hyperlink receives to realize that hyperlinking has completed.

See also HlinkOnNavigate, IHlinkBrowseContext::OnNavigateHlink, IHlinkFrame::OnNavigate


IHlinkSite::QueryService

HRESULT QueryService(
    DWORD dwSiteData,        //Site data to identify the hyperlink its site
    REFGUID guidService,    //TBD
    REFIID riid,             //Location to return the riid interface
    IUnknown* ppiunk         //Location to receive the unknown interface pointer of service query
   );

Allows querying of any service or other interface from the hyperlink site object. This is similar to IServiceProvider::QueryService.

  • Returns S_OK if the hyperlink container interface was successfully retrieved, or E_NOINTERFACE if the desired interface is not available.
dwSiteData
[in] Used to identify the hyperlink to the hyperlink site. The hyperlink site initializes the hyperlink with this value as part of IHlink::SetHlinkSite.
guidService
[in] Not currently implemented.
riid
[in] Location to return the riid interface.
ppiunk
[iid_is, out] Location to return the IUnknown interface of the service query.

See also IHlinkSite::GetMoniker


IHlinkSite::ReadyToNavigate

HRESULT ReadyToNavigate(
    DWORD dwSiteData,    //Site data for the hyperlink object
    DWORD dwReserved     //Reserved for future use
   );

Notifies the hyperlink site that the hyperlink navigation is about to occur. To back out of the operation, return E_ABORT.

  • Returns S_OK if the hyperlink site has been successfully notified.
dwSiteData
[in] Used to identify the hyperlink to the hyperlink site. The hyperlink site initializes the hyperlink with this value as part of IHlink::SetHlinkSite.
dwReserved
[in] Reserved for future use; must be set to zero by the caller. To ensure compatibility with future use, the callee must not check for zero.

See also HlinkOnNavigate, IHlinkBrowseContext::OnNavigateHlink, IHlinkFrame::OnNavigate


IHlinkTarget::GetBrowseContext

HRESULT GetBrowseContext(
    IHlinkBrowseContext * ppihlbc    //Buffer to receive the current browse context's interface pointer
   );

Retrieves the browse context in which this hyperlink target is currently running.

  • Returns S_OK if the browse context has been successfully retrieved, or E_NOTIMPL if the hyperlink target does not understand browse contexts.
ppihlbc
[out] Address of the location to return the browse context object's interface pointer.

See also HlinkCreateBrowseContext, IHlinkBrowseContext, IHlinkFrame::GetBrowseContext, IHlinkTarget::SetBrowseContext


IHlinkTarget::GetFriendlyName

HRESULT GetFriendlyName(
    LPCWSTR pwzLocation,     //Hyperlink location within this target
    LPWSTR * ppwzFriendlyName    //Buffer to receive the friendly name
   );

Retrieves a friendly name for the given hyperlink destination within this target.

  • Returns S_OK if the friendly name string of the hyperlink destination with this target has been retrieved, or E_OUTOFMEMORY if there is insufficient memory to retrieve the friendly name.
pwzLocation
[in, unique] String that indicates the position of the hyperlink destination within this hyperlink target.
ppwzFriendlyName
[out] Address of the buffer to return the friendly name. This string must be allocated using CoTaskMemAlloc. It is the caller's responsibility to free this string using CoTaskMemFree.

See also IHlink::GetFriendlyName


IHlinkTarget::GetMoniker

HRESULT GetMoniker(
    LPCWSTR pwzLocation,     //Hyperlink destination within this target
    DWORD dwAssign,     //Whether or not to create a moniker if one not found
    IMoniker * ppimkLocation    //Buffer to receive this moniker
   );

Returns a moniker to the hyperlink target object for the given hyperlink destination szLocation.

  • Returns one of the following
    S_OK | The moniker to the hyperlink target object was retrieved.
    E_FAIL | A moniker does not exist for this hyperlink target, and OLEGETMONIKER_ONLYIFTHERE was specified for dwAssign.
    CreateFileMoniker, MkParseDisplayName, and other moniker creation API errors
pwzLocation
[in, unique] Used to identify the hyperlink destination within this target.
dwAssign
[in] A value from the OLEGETMONIKER enumeration. This is typically either OLEGETMONIKER_ONLYIFTHERE, indicating the function should not force a moniker to be created if one does not already exist, or OLEGETMONIKER_FORCEASSIGN, indicating that the function should create a moniker if one does not exist.
ppimkLocation
[out] Address of location to return the IMoniker interface pointer to the hyperlink target object for this szLocation.

See also HlinkSimpleNavigateToMoniker, IHlink::GetMonikerReference, IHlinkSite::GetMoniker


IHlinkTarget

A hyperlink target implements the IHlinkTarget interface and gives out hyperlink references to its contents.

Implementing IHlinkTarget

Implement this interface when you have an application that can be the target for a hyperlink. In other words, hyperlinks from other applications use this interface to determine how to find, display, and navigate to your target.

An existing OLE document application that supports OLE linking need only implement the IHlinkTarget interface on the same object that implements IPersistFile and IOleItemContainer. The application can also implement IPersistMoniker to support incremental rendering or asynchronous download as a persistence mechanism, rather than IPersistFile.

Note that an Active Document object need not implement this interface if hyperlink navigation is only occuring within a document object container such as Microsoft Internet Explorer. In such a situation, IHlinkTarget provides the capability to navigate to a location within the document, but it is not necessary for navigation to be completed.

Using IHlinkTarget

You do not normally call these methods directly. When an end user selects a hyperlink through an application's user interface, the implementation of IHlink::Navigate calls these methods to determine how to display, locate, and navigate to the target.

IHlinkTarget Methods in Vtable Order

IHlinkTarget methods | Description
SetBrowseContext | Establishes the current browse context for this hyperlink target.
GetBrowseContext | Retrieves the current browse context within which this hyperlink target is currently running.
Navigate | If the given location is not visible, navigates to and shows that position within the target.
GetMoniker | Returns a moniker to the hyperlink target object.
GetFriendlyName | Returns a friendly name for the given hyperlink location within this target.


IHlinkTarget::SetBrowseContext

HRESULT SetBrowseContext(
    IHlinkBrowseContext * pihlbc    //Browse context interface pointer to set for the hyperlink target
   );

Establishes the current browse context for this hyperlink target.

  • Returns S_OK if the browse context has been successfully set, or E_NOTIMPL if the hyperlink target does not understand browse contexts.
pihlbc
[in, unique] Address of the browse context object's interface.

See also HlinkCreateBrowseContext, IHlinkBrowseContext, IHlinkFrame::SetBrowseContext, IHlinkTarget::GetBrowseContext


IHlinkTarget::Navigate

HRESULT Navigate(
    DWORD grfHLNF,    //Value from the HLNF enumeration
    LPCWSTR * pwzJumpLocation    //Location within the hyperlink target to navigate to
   );

If the given location is not visible, navigates to and shows the location position within the object/document.

  • Returns S_OK if navigation to the hyperlink target has been successful.
grfHLNF
[in] Flags describing how the navigation is to proceed. The value of the flag can be any valid HLNF enumeration value.
pwzJumpLocation
[in, unique] The string location portion of the hyperlink reference.

See also HlinkNavigate, HlinkNavigateToStringReference, HLNF, IHlinkFrame::Navigate, IHlink::Navigate


Hyperlink Browse Context Object

The hyperlink browse context maintains the navigation stack that is passed around during navigation from one document or application to another.

In addition to maintaining the navigation stack, the browse context knows whether the Go Forward and Go Back commands should be enabled. It is also used to pass around window-position information so that hyperlinking from one top-level window to another can happen while giving the illusion of window reuse (by positioning the windows on top of each other).

Implementation

Like the hyperlink object, the browse context is a standard object provided by the operating system.

Creation/Access API Functions
HlinkCreateBrowseContext Creates an empty default instance of the system browse context object.

Interfaces
IHlinkBrowseContext Enables a COM object to define and manage the browsing context for an OLE hyperlink application.


Hyperlink Target Object

A hyperlink target is a destination of hyperlink navigation. This can be a persisted OLE object that exposes IHlinkTarget, a persisted OLE object that exposes IOleObject, or any file that is viewed when its viewer application is launched by using ShellExecute.

A hyperlink target can be a top-level container document, an embedded object of arbitrary nesting, or generally any object that can be referenced by using a moniker.

Implementation

If an object (document) wants to be targeted by hyperlinks, it can integrate tightly with OLE hyperlinks by implementing the IHlinkTarget interface. If the object does not support IHlinkTarget, it can still act as a hyperlink target, but it won't be able to support internal navigation, and it will not have access to the common browse context that holds the navigation stack.

An existing OLE document application that supports OLE linking need only implement the IHlinkTarget interface on the same object that implements IPersistFile and IOleItemContainer. The application can also implement IPersistMoniker to support incremental rendering or asynchronous download as a persistence mechanism, rather than IPersistFile. Supporting IHlinkTarget from an OLE document object is the recommended way to make sure your document is viewable by browsers and participates in hyperlinking smoothly.

Creation/Access API Functions

In a document, hyperlink objects implement the IHlink interface. When a user clicks a hyperlink, the application calls IHlink::Navigate, using a helper API function if preferred. The IHlink::Navigate implementation calls BindMoniker to get the pointer of the target object, requests the IHlinkTarget interface, and calls IHlinkTarget::Navigate.

Interfaces
IHlinkTarget | Provides for navigation to locations within the target's objects. A hyperlink target object implements this interface for this reason.
IOleObject | Allows an embedded object to communicate with and provide basic functionality to its container.


Hyperlink Object

A hyperlink object is a reference to another location within either a new or existing document. It encapsulates four pieces of reference information:

  • A moniker to the hyperlink target
  • A string for the sublocation within the target
  • A friendly name for the target
  • Additional parameters

A hyperlink object also supports the ability to save and load itself by using IPersistStream, and the ability to be transferred through the clipboard or through a drag-and-drop operation by using IDataObject.

It is notable that a document can use the standard hyperlink object to represent hyperlinks within itself, thus encapsulating the work of navigating, saving, loading, dragging, dropping, cutting, and pasting hyperlinks.

Implementation

A standard hyperlink implementation is provided with the operating system, and you should be able to use it for your applications. Custom implementations should be used only with the greatest caution.

Creation/Access API Functions
HlinkCreateFromData | Creates a hyperlink object from an object that supports the IDataObject interface (a data object).
HlinkCreateFromMoniker | Creates a new hyperlink from a moniker, a location within the target, and a friendly name string (used for displaying the hyperlink).
HlinkCreateFromString | Creates a new hyperlink object from strings representing the hyperlink target, the location within the target, and a friendly name.
OleLoadFromStream | Allows the hyperlink object to be loaded from persistent data.

Interfaces
IDataObject | Enables data transfer.
IHlink | Enables a hyperlink (a COM object) to encapsulate the behavior of navigating to its target location.
IHlinkSite | Indicates the implemented document/object that contains the hyperlink object. A hyperobject implementation uses this interface (if it's available) for resolving the relative monikers and also to notify before and after the target document/object is displayed.
IPersistStream | Provides methods for saving and loading objects that use a simple serial stream for their storage needs.


Objects

This section describes the following object:

  • Hyperlink Object
  • Hyperlink Browse Context Object
  • Hyperlink Target Object


HLBWINFO

typedef struct tagHLBWINFO
{
    ULONG cbSize;
    DWORD grfHLBWIF;
    RECT rcFramePos;
    RECT rcDocPos;
    HLTBINFO hltbinfo;
} HLBWINFO;

Contains parameters relating to the locations and sizes of frame- and document-level windows within a browse context.

cbSize
Total size of this structure, in bytes.
grfHLBWIF
Values taken from the HLBWIF enumeration.
rcFramePos
If grfHLBWIF & HLBWIF_HASFRAMEWNDINFO, contains the rectangle in screen coordinates of current frame-level windows within the browse context. When grfHLBWIF & HLBWIF_FRAMEWNDMAXIMIZED, frame-level windows are currently being displayed maximized. In this case, rcFramePos is the "normal" size of frame-level windows, that is, the rectangle to use for any frame-level window when it is nonmaximized.
rcDocPos
If grfHLBWIF & HLBWIF_HASDOCWNDINFO, contains the rectangle in screen coordinates of current document-level windows within the browse context. When grfHLBWIF & HLBWIF_DOCWNDMAXIMIZED, document-level windows are currently being displayed maximized. In this case, rcDocPos is the "normal" size of document-level windows, that is, the rectangle to use for any document-level window when it is nonmaximized.
hltbinfo
Provides information on the position of the Web toolbar. This enables the target application to display its toolbar in the same location.

The HLBWINFO structure is retrieved from the browse context using IHlinkBrowseContext::GetBrowseWindowInfo, and put into the browse context using IHlinkBrowseContext::SetBrowseWindowInfo. Hyperlink targets retrieve the HLBWINFO structure during IHlinkTarget::Navigate in order to reposition their user interface properly and ensure as seamless a transition as possible to the new document or object.

See also HLBWIF, IHlinkBrowseContext::GetBrowseWindowInfo, IHlinkBrowseContext::SetBrowseWindowInfo, IHlinkTarget::Navigate


HLITEM

typedef struct tagHLITEM
{
    ULONG uHLID;
    LPWSTR pwzFriendlyName;
} HLITEM;

Indicates the data structure used by the system browse context to track hyperlinks.

uHLID
Used to identify the hyperlink. Standard enumerators never return one of the logical HLID constants in this member, always an identifier.
pwzFriendlyName
Address of the hyperlink's friendly name. Appropriate for display in the user interface.

The HLITEM structure is returned by the IEnumHLITEM enumerator, which is returned from IHlinkBrowseContext::EnumNavigationStack.

See also HLID, IEnumHLITEM, IHlinkBrowseContext::EnumNavigationStack


Structures

This section describes the following structures:

  • HLBWINFO
  • HLITEM


HTML Clipboard Format

The requirements for transferring HTML text by means of the clipboard differ depending on scenario. This article is concerned with cutting and pasting fragments of an HTML document. There may be requirements for transferring entire HTML documents through the clipboard; however, this article is driven by a requirement to transfer fragments of selected HTML text. As such, a method that required the entire HTML document to be copied to the clipboard is seen as too heavyweight.

The CF_HTML clipboard format allows a fragment of raw HTML text and its context to be stored on the clipboard as ASCII. This allows the context of the HTML fragment, which consists of all preceding surrounding tags, to be examined by an application so that the surrounding tags of the HTML fragment can be noted with their attributes. Although it is up to applications to decide how to interpret such fragments, some basic guidelines are included here based on IE4/MSHTML implementations.

The official name of the clipboard (the string used by RegisterClipboardFormat) is HTML Format.

Description

Scenarios

Description

CF_HTML is entirely text format (to be, among other things, in the HTML spirit, and uses UTF-8) and includes a description, an optional context, and, within the context, the fragment.

The following is an example of a clipboard:

Version:0.9
    StartHTML:71
    EndHTML:170
    StartFragment:140
    EndFragment:160
    StartSelection:140
    EndSelection:160
    <!DOCTYPE>
    <HTML>
    <HEAD>
    <TITLE> The HTML Clipboard</TITLE>
    <BASE HREF="http://sample/specs">
    </HEAD>
    <BODY>
    <UL>
    <!--StartFragment -->
    <LI> The Fragment </LI>
    <!--EndFragment -->
    </UL>
    </BODY>
    </HTML>

The description includes the clipboard version number and offsets, indicating where the context and the fragment start and end. The description is a list of ASCII text keywords (min/maj is not meaningful) followed by a string and separated by a colon (:).

Version: vv version number of the clipboard. Starting version is 0.9.
StartHTML: bytecount from the beginning of the clipboard to the start of the context, or -1 if no context.
EndHTML: bytecount from the beginning of the clipboard to the end of the context, or -1 if no context.
StartFragment: bytecount from the beginning of the clipboard to the start of the fragment.
EndFragment: bytecount from the beginning of the clipboard to the end of the fragment.
StartSelection: bytecount from the beginning of the clipboard to the start of the selection.
EndSelection: bytecount from the beginning of the clipboard to the end of the selection.

The StartSelection and EndSelection keywords are optional and must both be omitted if you do not want the application to generate this information.

Other information of this kind could be added here later, since the HTML starts at the StartHTMLoffset. For example, multiple pairs of StartFragment / EndFragment could be added later to support noncontiguous selection of fragments.

For the convenience of the programs generating the bytecounts, bytecounts could be left padded by zeros. For example, programs generating the bytecounts could arbitrarily affect ten (10) zeros to each keyword (StartHTML: 0000000000) and then, when the exact StartHTML bytecount is known (say, 71), the program can replace the appropriate number of zeros by the bytecount (StartHTML: 0000000071).

The only character set supported by the clipboard is Unicode in its UTF-8 encoding. Because the first characters of UTF-8 and ASCII match, the description is always ASCII, but the bytes of the context (starting at StartHTML) could be using any other characters coded in UTF-8.

End of lines in the clipboard format header could be CR or CR/LF or LF.

The fragment contains pure, valid HTML representing the area the user has selected (to Copy, for example). This contains the selected text plus the opening tags and attributes of any element that has an end tag within the selected text, and end tags at the end of the fragment for any start tag included. This is all information required for basic pasting of an HTML fragment.

The fragment should be preceded and followed by the HTML comments <!--StartFragment--> and <!--EndFragment--> (no space allowed between the !-- and the text) to conveniently indicate where the fragment starts and ends. Thus the start and end of the fragment are indicated by the presence of these comments and by StartFragment and EndFragment byte counts in the description. Tools are expected to produce this information. This redundancy has been introduced to be able to rapidly find the start of the fragment (from the byte count) and mark the position of the fragment directly in the HTML tree.

The selection indicates inside the fragment the exact HTML area the user has selected (to Copy, for example). This adds more information to the fragment by indicating the exact selected text, without the opening tags and end tags that have been added to ensure the fragment is well-formed HTML.

The selection is optional, as sufficient information is included in the fragment for basic pasting. If the selection is not stored, both StartSelection and EndSelection are not stored in the header.

The context is a valid, complete HTML document. This article contains the fragment and all preceding surrounding tags (start and end tags; these preceding surrounding tags represent all the parent nodes of the fragment, until the HTML node). The article also contains the complete HEAD, and allows the BASE and TITLE elements, for example, to be included so this additional information can be obtained. An application copying a fragment of HTML to the clipboard can choose to create a BASE element to include in the context if such an element is not already present so that partial URLs in the fragment can be resolved.

The context is optional, as sufficient information is included in the fragment for basic pasting of an HTML fragment to take place. If the context is not stored, the fragment only is stored and the StartHTML=EndHTML=-1.

Scenarios

The following scenarios describe how the IE4/MSHTML HTML editor handles HTML cut and paste; other applications may or may not follow these scenarios. The clipboard format described here is intended to allow flexibility for how an application chooses to function. (These scenarios show only good HTML, that is, no overlapping tags.)

  1. Simple Fragment of HTML.
    • HTML text:
      <BODY>This is normal <B>This is bold </B><I><B>This is bold italic </B>This is italic </I></BODY>
    • Appears as:
      This is normal This is bold This is bold italic This is italic
    • The text between the ** is selected and copied to the clipboard:
      This is normal This is **bold This is bold italic This** is italic
    • This is what will be on the clipboard (note this is IE4/MSHTML's interpretation):
      Version:0.9
      StartHTML:71
      EndHTML:160
      StartFragment:130
      EndFragment:150
      StartSelection:130
      EndSelection:150
      <!DOCTYPE ...>
      <HTML>
      <BODY>
      <!--StartFragment-->
      <B>bold </B><I><B>This is bold italic </B>This</I>
      <!--EndFragment-->
      </BODY>
      </HTML>
    • In this scenario only the BODY tag and the HTML tag appear in the context as it precedes the selected fragment. Note that start tags and end tags are included in the context. The selection, as delimited by StartSelection and EndSelection, is shown in bold.
  2. Fragment of a table in HTML.
    • HTML text:
      <BODY><TABLE BORDER><TR><TH ROWSPAN=2>Head1</TH><TD>Item 1</TD> <TD>Item 2</TD> <TD>Item 3</TD> <TD>Item 4</TD></TR><TR><TD>Item 5</TD> <TD>Item 6</TD> <TD>Item 7</TD> <TD>Item 8</TD></TR><TR><TH>Head2</TH><TD>Item 9</TD> <TD>Item 10</TD> <TD>Item 11</TD> <TD>Item 12</TD></TR></TABLE></BODY>
    • Appears as:
      Head1 | Item 1 | Item 2 | Item 3 | Item 4
      Item 5 | Item 6 | Item 7 | Item 8
      Head2 | Item 9 | Item 10 | Item 11 | Item 12

    • The Item 6, Item7, Item 10, and Item 11 elements of the table are selected as a block and copied to the clipboard.
    • This is what will be on the clipboard (note this is IE4/MSHTML's interpretation):
      <!DOCTYPE ...>
      <HTML><BODY><TABLE BORDER>
      <!--StartFragment-->
      <TR><TD>Item 6</TD> <TD>Item 7</TD></TR><TR><TD>Item 10</TD> <TD>Item 11</TD></TR>
      <!--EndFragment-->
      </TABLE>
      </BODY></HTML>
      The selection, as delimited by StartSelection and EndSelection, is shown in bold.
  3. Pasting a fragment of an ordered list into plain text.
    • HTML text:
      <BODY><OL TYPE = a><LI>Item 1<LI>Item 2<LI>Item 3<LI>Item 4<LI>Item 5<LI>Item 6</OL></BODY>
    • Appears as:
      1. Item 1
      2. Item 2
      3. Item 3
      4. Item 4
      5. Item 5
      6. Item 6
    • The user selects and copies items 3 through 5 to the clipboard.
      The following HTML is in the clipboard:
      <DOCTYPE...><HTML><BODY><OL TYPE = a>
      <!-- StartFragment-->
      <LI>Item 3<LI>Item 4<LI>Item 5
      <!-- EndFragment-->
      </OL></BODY></HTML>
      The selection, as delimited by StartSelection and EndSelection, is show in bold.
    • If this fragment is now pasted into an empty document, the following HTML will be created:
      <BODY><OL TYPE = a><LI>Item 3<LI>Item 4<LI>Item 5</OL></BODY>
    • Appearing as:
      1. Item 3
      2. Item 4
      3. Item 5
  4. Pasting a partially selected region.
    • HTML text:
      <P> IE4/MSHTML is a WYSIWYG Editor that supports :<UL><LI>Cut<LI>Copy<LI>Paste
      </UL> <P>This is a Great Tool !
    • Appears as:
      IE4/MSHTML is a WYSIWYG Editor that supports :
      • Cut
      • Copy
      • Paste
    • The user selects from "WYSIWYG" until "Cop".
      The following HTML is in the clipboard:
      <DOCTYPE...><HTML><BODY>
      <!-- StartFragment-->
      <P>
      WYSIWYG Editor, which supports
      <UL><LI>Cut<LI>Cop
      </UL>
      <!-- EndFragment-->
      </BODY></HTML>
      The selection, as delimited by StartSelection and EndSelection, is shown in bold.
    • The user selects from "opy" until "Great".
      The following HTML is in the clipboard:
      <DOCTYPE...><HTML><BODY>
      <!-- StartFragment-->
      <UL><LI>
      opy<LI>Paste</UL><P> This is a Great
      </P>
      <!-- EndFragment-->
      </BODY></HTML>
      The selection, as delimited by StartSelection and EndSelection, is shown in bold.


Dependencies

The WebBrowser control is implemented in the dynamic-link library file Shdocvw.dll under the custom control name "Microsoft Internet Controls." To use the WebBrowser control object in your application, you need to have Microsoft® Internet Explorer loaded on your computer.


Reusing the WebBrowser and MSHTML

This document describes how to reuse the WebBrowser Control and MSHTML.DLL components of Internet Explorer 4.0 as part of an application. Typical examples of such reuse include browsers, rich content viewers, HTML parsers, and HTML dialogs.

Overview

HTML Dialog Boxes

Reusing the WebBrowser Control

Reusing MSHTML

Advanced Hosting Interfaces

Dependencies

Licensing and Distribution


Licensing and Distribution

Application developers who want to redistribute Microsoft® Internet Explorer technologies, such as the WebBrowser control, Wininet.dll, Urlmon.dll, or Comctl32.dll, must obtain a redistribution license for Microsoft® Internet Explorer 4.0. The Internet Explorer self-extracting executable installs a number of system files and registry entries in addition to the actual WebBrowser control. You can license Microsoft Internet Explorer for Windows® 95, Windows® 3.1, Windows NT® Workstation, and Apple Macintosh® royalty-free to redistribute within your organization or to your customers. Plus, you can use the Microsoft Internet Explorer Administration Kit (IEAK) to easily create Internet Explorer distribution media, which you can customize to specify start and search pages and a favorites list. This lets your organization create and distribute a Web browser that reflects your specific needs and the needs of your users. For more information on redistributing Internet Explorer, see the Microsoft Web page at http://www.microsoft.com/ie/ieak/.

Determining the Installed Version of Internet Explorer 4.0

Using the Internet Explorer 4.0 Minimal Installation Package

Adding an Application to the Warning List for Internet Explorer 4.0 Uninstall

Determining the Installed Version of Internet Explorer 4.0

If your application requires Internet Explorer 4.0 services, you must determine the version of Internet Explorer that is installed, if any, before installing your application. There are two methods that can be used to determine the installed version of Internet Explorer. The first obtains the version information from the registry, and the second obtains the version information from one of the Internet Explorer components.

Determining the Internet Explorer Version from the Registry

To obtain the installed Internet Explorer version from the registry, open the following registry key:

HKEY_LOCAL_MACHINE\
   Software\
      Microsoft\
         Internet Explorer

In this key, obtain the "Version" value. This is a string value that contains the Internet Explorer 4.0 version in the following format:

"<major version>.<minor version>.<build number>.<sub-build number>"

Internet Explorer 3.0x does not install this value, so if this value is retrieved and the major version is "4" and the minor version is "71", then Internet Explorer 4.0 is installed.

Internet Explorer 3.0x does install the "Build" value under this same key. For backward compatibility, Internet Explorer 4.0 modifies or adds the "Build" value also. Internet Explorer 3.0x's "Build" value is a string that contains a four-character build number. Internet Explorer 4.0's "Build" value is a string that contains a five-character value that takes the following format:

"4<build number>"

Therefore, if the "Build" value is the character '4' followed by a four-character build number, Internet Explorer 4.0 is installed.

Determining the Internet Explorer Version from Shdocvw.dll

The Internet Explorer browser is implemented in Shdocvw.dll. The version of this DLL is used to determine which version of Internet Explorer is installed. If this file is not present, Internet Explorer is either not installed or is not properly installed.

The following are the different versions of Shdocvw.dll and the browser version that each represents.

  • Version 4.70 – Internet Explorer 3.0
  • Version 4.71 – Internet Explorer 4.0

The following function retrieves the major and minor version numbers of the Shdocvw.dll that is installed on the local system.

#include <windows.h>
#include <shlwapi.h>

HRESULT GetBrowserVersion(LPDWORD pdwMajor, LPDWORD pdwMinor)
{
HINSTANCE   hBrowser;

if(   IsBadWritePtr(pdwMajor, sizeof(DWORD)) ||
      IsBadWritePtr(pdwMinor, sizeof(DWORD)))
   return E_INVALIDARG;

*pdwMajor = 0;
*pdwMinor = 0;

//Load the DLL.
hBrowser = LoadLibrary(TEXT("shdocvw.dll"));

if(hBrowser)
   {
   HRESULT           hr = S_OK;
   DLLGETVERSIONPROC pDllGetVersion;

   /*
   You must get this function explicitly.
   */
   pDllGetVersion = (DLLGETVERSIONPROC)GetProcAddress(hBrowser, TEXT("DllGetVersion"));

   if(pDllGetVersion)
      {
      DLLVERSIONINFO    dvi;

      ZeroMemory(&dvi, sizeof(dvi));
      dvi.cbSize = sizeof(dvi);

      hr = (*pDllGetVersion)(&dvi);

      if(SUCCEEDED(hr))
         {
         *pdwMajor = dvi.dwMajorVersion;

         *pdwMinor = dvi.dwMinorVersion;
         }
      }
   else
      {
      /*
      If GetProcAddress failed, there is a problem with the DLL.
      */
      hr = E_FAIL;
      }

   FreeLibrary(hBrowser);

   return hr;
   }

return E_FAIL;
}

Using the Internet Explorer 4.0 Minimal Installation Package

The Internet Explorer 4.0 minimal installation package includes the Internet Explorer 4.0 base browser, DirectShow, and the Microsoft Win32 VM for Java. The package can be run in normal mode with user interface and prompts or in automated mode without user interface and prompts. The following installation packages are available:

Installation Package | Target Platform
ie4stw95.exe | Windows® 95
ie4stnt.exe | Windows NT® 4.0 for the Intel X86 processor

The following command line:

ie4stw95.exe /Q:A

will install the Internet Explorer 4.0 minimal installation package with the following options:

  • No setup user interface.
  • No integrated desktop.
  • No reboot prompt.
  • Internet Explorer 4.0 will be made the default browser.
  • The Internet icon will be added to the desktop.

The following command line:

ie4stw95.exe /Q:A /C:"ie4wzd.exe /Q:A /X /I:N /R:N /S:""#e"""

will install the Internet Explorer 4.0 minimal installation package with the following options:

  • No setup user interface.
  • No integrated desktop.
  • No reboot prompt.
  • Internet Explorer 4.0 will not be made the default browser.
  • The Internet icon will not be added to the desktop.

For other installation options, please refer to the Internet Explorer Administration Kit.

Note These examples use the Windows 95 installation package, but the command line options are the same for all packages.

Before installing Internet Explorer 4.0, you must make sure that the setup application has the proper administration rights (if applicable) and that there is enough hard disk space available for the installation. The minimal installation package requires approximately 60 MB of free disk space to accommodate the temporary and installed files.

Once the installation is complete, your setup application must reboot the computer in order for the Internet Explorer 4.0 installation to complete. Your setup application should ask users if they want to reboot the computer and give them an option not to. Internet Explorer 4.0 will not be useable until the computer has been rebooted.

Adding an Application to the Warning List for Internet Explorer 4.0 Uninstall

If your application requires Internet Explorer 4.0 services, you can add your application to the list of applications that require Internet Explorer 4.0 to be installed. When users attempt to uninstall Internet Explorer 4.0, this list will be displayed and they will be told that these applications may not function correctly if Internet Explorer 4.0 is uninstalled. Users will be asked if they still want to uninstall Internet Explorer 4.0.

To add your application to this list, add a string value under the following key:

HKEY_LOCAL_MACHINE\
   Software\
      Microsoft\
         IE4\
            DependentComponents

Under this key, create a string value that takes the following format:

MyApp = "My Application."

The value name in this example is "MyApp". Make sure the value name you create is unique among all other values in the same key. The value's data ("My Application.") is what is actually displayed to the user.

When your application is uninstalled, remember to remove any values you add under this key.


Overview

This document explains the architecture of Microsoft® Internet Explorer 4.0. The document also provides information you'll find helpful when reusing these components.

Architectural Overview

Choosing the Correct Component For Reuse

Providing Extra Control

Controlling the Context Menus

Extending the Dynamic HTML Object Model

Download Control

Security Manager

Architectural Overview

Internet Explorer 4.0 uses ActiveX™ Controls and Active Document interfaces to connect components. The following diagram provides a high-level overview.

Internet Explorer 4.0 Architecture.

At the top level is IExplore.exe, a surprisingly small application that is instantiated when the Internet Explorer 4.0 browser is loaded. This executable uses Internet Explorer 4.0 components to perform the navigation, history maintenance, favorites maintenance, HTML parsing and rendering, and so on, while it supplies the toolbar and frame for the stand-alone browser. This executable directly hosts the Shdocvw.dll component.

Shdocvw.dll in turn hosts the Mshtml.dll component, as well as any other Active Document component (such as a Microsoft® Office application) that can be loaded in-place in the browser when the user navigates to a specific document type. Shdocvw.dll supplies the functionality associated with navigation, in-place linking, favorites and history management, and PICS support. This DLL also exposes interfaces to its host to allow it to be hosted separately as an ActiveX control. The Shdocvw.dll component is more frequently referred to as the WebBrowser control. In-place linking refers to the ability to click a link in the HTML of the loaded document and load a new HTML document in the same instance of the WebBrowser control. If only Mshtml.dll is being hosted, a click on the link will result in a new instance of the browser being instantiated.

Mshtml.dll is the component that performs the HTML parsing and rendering in Internet Explorer 4.0, and also exposes the HTML document through the Dynamic HTML object model. This component hosts the scripting engines, Java VM, ActiveX Controls, Plug-Ins, and other objects that might be referenced in the HTML document that is loaded. Mshtml.dll implements the Active Document server interfaces, which allows it to be hosted using standard COM interfaces.

This architecture is recursive in that Shdocvw.dll is in turn hosted by Mshtml.dll in a frameset situation. In this case, each instance of a frame is another instance of Shdocvw.dll hosting Mshtml.dll.

As this is an OLE-based architecture, the ambient properties that are commonly used by ActiveX Controls can also be applied to the Internet Explorer 4.0 components. In this way, a host of the WebBrowser control can set an ambient property that will filter down to all the frames and controls hosted in the loaded document.

Choosing the Correct Component for Reuse

Because the WebBrowser control provides a rich set of functionality that a host will typically require, such as that for in-place linking, it is much more applicable for most applications to host this control instead of MSHTML for browsing or viewing HTML documents. Hosting MSHTML is recommended only for specialized applications, such as parsing HTML. The WalkAll sample in the Internet Client SDK demonstrates how to host MSHTML.

It should also be noted that although hosting MSHTML is slightly more lightweight than hosting the WebBrowser control, the savings rarely justify the extra work involved in implementing functionality that is already available in the WebBrowser. It is very likely that the WebBrowser will already be loaded in memory, and navigating to a frameset page will also result in the WebBrowser being loaded as part of the standard working set.

Providing Extra Control

Hosts of the WebBrowser and MSHTML components have control over certain functionality. In the case of the WebBrowser control, this includes navigation as well as receiving events when the document is loaded. Hosts of either component can obtain extra control over functionality by implementing the IDocHostUIHandler and IDocHostShowUI interfaces. A common use for these interfaces is overriding the context menus that are supplied by default for the browser (this topic is discussed separately below). Uses also include setting the 3-D border, overriding the location in the registry where options are stored, and extending the Dynamic HTML object mModel.

These interfaces are obtained from the host by the component calling QueryInterface on the IOleClientSite interface implemented by the hosting application.

Controlling the Context Menus

A common requirement of hosting the WebBrowser control is the ability to override or add to the context menus that are displayed as the result of a right-click in the browser window. This is of particular interest to applications that are using the WebBrowser control to view rich content but do not want the user to know that HTML is being viewed. This is also advantageous for applications that do not want the user to be able to view the HTML source for the content.

There are two techniques available to achieve this. The first involves the use of the IDocHostUIHandler interface and allows an application to disable or replace the context menus. The second technique involves the use of the registry and allows the existing context menus to be extended.

Overriding the context menus

The WebBrowser control's context menus can be overridden entirely by implementing the IDocHostUIHandler::ShowContextMenu method. Returning E_NOTIMPL or S_FALSE from this method will indicate to the WebBrowser that it should display its own standard context menu. However, returning S_OK will cause the WebBrowser not to display its menus, and it will assume that the host has performed the appropriate action. The host can disable all context menus or bring up its own context menus. The parameters supplied to the host that implements this method allow the host to identify which of the default menus will be displayed by the WebBrowser, as well as the coordinates where the menu will be displayed. This provides the host the full context for the menu. For example, the host can choose only to override the image context menus and not the standard context menus.

Adding to the standard context menus

Items can be added to the existing context menus of the WebBrowser by placing entries in the registry and linking these to URLs that execute script. To add additional items to the standard WebBrowser context menus, create or open the following key:

HKEY_CURRENT_USER
        Software
            Microsoft
                Internet Explorer
                    MenuExt

Under this key, you create a key whose name contains the text you want displayed in the menu. The default value for this key contains the URL that will be executed. The key name can include the ampersand (&) character, which will cause the character immediately following the & to be underlined. The URL will be loaded inside a hidden HTML dialog box, all the inline script will be executed, and the dialog box will be closed. The hidden HTML dialog's external.menuArguments property contains the window object of the window on which the context menu item was executed.

The following registry entry will add an item with the title "My Menu Item" to the WebBrowser context menu and will execute the inline script contained in the file "c:\myscript.htm".

HKEY_CURRENT_USER
        Software
            Microsoft
                Internet Explorer
                    MenuExt
                        My Menu Item = "file://c:\myscript.htm"

The following are the contents of "c:\myscript.htm".

<SCRIPT LANGUAGE="JavaScript" defer>
    var parentwin = external.menuArguments;
    var doc = parentwin.document;
    var sel = doc.selection;
    var rng = sel.createRange();
    var str = new String(rng.text);
    if(str.length == 0)
        rng.text = "MY INSERTED TEXT";
    else
        rng.text =  str.toUpperCase();
    </SCRIPT>

This script obtains the parent window object from external.menuArguments. The parent window object is the WebBrowser in which the context menu item was executed. The script then obtains the current selection and, if no selection is present, inserts the text "MY INSERTED TEXT" at the point where the context menu was executed. If there is a selection present, the selected text is changed to uppercase.

Optional keys

Under the item registry key created earlier, there are a couple of optional values. One of these specifies on which context menus this item will appear. The other specifies that the script should be run as a dialog.

The "Contexts" DWORD value specifies the context menus in which an item will appear. It is a bit mask consisting of the logical OR of the following values (defined in Mshtmhst.h). These values correspond to the constant passed in an IDocHostUIHandler::ShowContextMenu call.

(0x1 << CONTEXT_MENU_DEFAULT) (evaluates to 0x1)
(0x1 << CONTEXT_MENU_IMAGE) (evaluates to 0x2)
(0x1 << CONTEXT_MENU_CONTROL) (evaluates to 0x4)
(0x1 << CONTEXT_MENU_TABLE) (evaluates to 0x8)
(0x1 << CONTEXT_MENU_TEXTSELECT) (evaluates to 0x10)
(0x1 << CONTEXT_MENU_ANCHOR) (evaluates to 0x20)
(0x1 << CONTEXT_MENU_UNKNOWN) (evaluates to 0x40)

So if, for example, you want this simple extension to appear only in the default menu and the text selection menu, you could create a DWORD value in the registry under the "My Menu Item" key called "Contexts" and set it to 0x11. From C/C++ code, this can be expressed as:

(0x1 << CONTEXT_MENU_DEFAULT) | (0x1 << CONTEXT_MENU_TEXTSELECT)

The other optional registry DWORD value is "Flags". There is only one bit (0x1) valid for this registry value; it is defined as MENUEXT_SHOWDIALOG in Mshtmhst.h. When this bit is set, the script is run just as if it had been called through the showModalDialog method. The window that runs the script is not hidden, and the dialog box is not automatically closed after inline and onload script finishes. The external.menuArguments value still contains the window object where the user selected the menu item.

The context menu event

Whenever a context menu extension is triggered, the event object off the main window (external.menuArguments.event) contains information about where the user clicked and which context menu was shown. The mouse coordinates are valid along with event.srcElement. The event.type value contains one of the following strings, indicating which context menu was shown to the user.

MenuExtDefault
MenuExtImage
MenuExtControl
MenuExtTable
MenuExtTextSelect
MenuExtAnchor
MenuExtUnknown

Another example

This example creates a new context menu item on the default menu. This item, called "Show in New Window", will start whatever is clicked on in a new window. So if something is deeply nested in a frameset, you can easily launch a specific frame in its own window.

Here are the contents of a .reg file that can be run to insert the correct registry settings. Call this Example2.reg. Double-clicking this file in Explorer will insert the settings in your registry.

REGEDIT4

    [HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\MenuExt\Show in &New Window]
    @="file://c:\\example2.htm"
    "Contexts"=dword:00000001

Here are the contents of "C:\example2.htm":

<SCRIPT LANGUAGE="JavaScript" defer>
        open(external.menuArguments.location.href);
    </SCRIPT>

Extending the Dynamic HTML Object Model

It is possible for the hosting application to extend the Dynamic HTML object model so that scripts can refer to functionality implemented by the host. Such scripts refer to the host by specifying the "external" object that is available from the "window" object. For example, a reference to "window.external.speech" will call the host to resolve the name "speech". All standard script within the document will be executed normally.

This extension mechanism is implemented in the host by providing an IDispatch interface for the object model extension that will have GetIDsofNames and Invoke called on it to resolve any references to the external object. The IDispatch that the host provides is obtained by the WebBrowser or MSHTML component by calling the host's IDocHostUIHandler::GetExternal method.

For an example of how to extend the Dynamic HTML object model, see the Driller sample in the Internet Client SDK.

Download Control

Hosts can control certain aspects of downloading, such as frames, images, Java, and so on, by implementing an ambient property defined as DISPID_AMBIENT_DLCTL. When the host's IDispatch::Invoke method is called with dispidMember set to DISPID_AMBIENT_DLCTL, it should place zero or a combination of the following values in pvarResult:

DLCTL_DLIMAGES | The browsing component will download images from the server.
DLCTL_VIDEOS | The browsing component will play any video clips that are contained in the document.
DLCTL_BGSOUNDS | The browsing component will play background sounds associated with the document.
DLCTL_NO_SCRIPTS | The browsing component will not execute any scripts.
DLCTL_NO_JAVA | The browsing component will not execute any Java applets.
DLCTL_NO_RUNACTIVEXCTLS | The browsing component will not execute any ActiveX Controls in the document.
DLCTL_NO_DLACTIVEXCTLS | The browsing component will not download any ActiveX Controls in the document.
DLCTL_DOWNLOADONLY | The browsing component will download the page but not display it.
DLCTL_NO_FRAMEDOWNLOAD | The browsing component will not download frames but will download and parse the frameset page. The browsing component will also ignore the frameset and render no frame tags.
DLCTL_RESYNCHRONIZE | The browsing component will ignore what is in the cache and ask the server for updated information. The cached information will be used if the server indicates that the cached information is up to date. This causes the BINDF_RESYNCHRONIZE flag to be set when making requests through URLMON.
DLCTL_PRAGMA_NO_CACHE | The browsing component will force the request through to the server and ignore the proxy, even if the proxy indicates that the data is up to date. This causes the BINDF_PRAGMA_NO_CACHE flag to be set when making requests through URLMON.
DLCTL_FORCEOFFLINE | The browsing component will always operate in offline mode. This causes the BINDF_OFFLINEOPERATION flag to be set even if the computer is connected to the Internet when making requests through URLMON.
DLCTL_NO_CLIENTPULL | The browsing component will not perform any client pull operations.
DLCTL_SILENT | The browsing component will not display any user interface. This causes the BINDF_SILENTOPERATION flag to be set when making requests through URLMON.
DLCTL_OFFLINEIFNOTCONNECTED | The browsing component will operate in offline mode if not connected to the Internet. This causes the BINDF_GETFROMCACHE_IF_NET_FAIL flag to be set if the computer is connected to the Internet when making requests through URLMON.
DLCTL_OFFLINE | Same as DLCTL_OFFLINEIFNOTCONNECTED.

Security Manager

Hosts of the browsing components can implement their own security management and override the settings that exist for the WebBrowser. This is achieved by implementing the IInternetSecurityManager interface. The browsing component will obtain this interface by calling the host's IServiceProvider::QueryService method with SID_SInternetSecurityManager. For more information on security management, see About URL Security Zones.


Reusing MSHTML

IE4/MSHTML is a rendering engine and parser for HTML. It is the main HTML component of the IE4 Web browser and can be reused in other applications. It hosts ActiveX™ Controls and supports the OC96 specification for windowless controls. Controls that use the OC96 interfaces can gain in performance, and they can be transparent and have an irregular shape.

IE4/MSHTML itself is an Active Document, so it may be hosted by implementing the Active Document interfaces in an application. IE4/MSHTML can also be customized by aggregation to create a special-purpose HTML Active Document. Applications that contain IE4/MSHTML supply their own toolbars and menu UI. The container can also override the default context menus.

It is also possible to use IE4/MSHTML without UI activation to make use of IE4/MSHTML's ability to parse HTML. By loading HTML, you can use the object model to access the underlying HTML and modify any elements. COM objects hosted by IE4/MSHTML (such as ActiveX Controls) also have the ability to access the Dynamic HTML object model and, as a result, closely integrate with the IE4/MSHTML container to affect the host.

For many purposes, it is more appropriate to host the WebBrowser control to integrate browsing into an application. The WebBrowser control implements support for in-place linking and navigation in addition to IE4/MSHTML. For additional information on the WebBrowser control, see Reusing the WebBrowser and MSHTML.

Containing IE4/MSHTML

Replacing IE4/MSHTML's User Interface

Substituting User Preferences

Loading HTML and Referenced Data

Automating IE4/MSHTML

Scripts within IE4/MSHTML

Sending and Receiving Commands

Terminology

Containing IE4/MSHTML

IE4/MSHTML can be hosted to form an integral part of an application. There are two ways that this can be done.

  1. Host IE4/MSHTML as an Active Document. IE4/MSHTML is an Active Document and can be hosted in an application that implements the Active Document Hosting interfaces. In this mode of operation, IE4/MSHTML supplies its own UI for context menus to the containing application, although the container can replace the UI, if required, by implementing additional interfaces.
  2. Aggregate IE4/MSHTML to create an Active Document. If a host needs to provide extra services and functionality, but it still needs to be an Active Document for use within another application, it can do so by aggregating IE4/MSHTML. This allows the host to take advantage of IE4/MSHTML's implementation of Active Document server interfaces without having to re-implement them. This still allows the host to wrap IE4/MSHTML to provide additional functionality and its own UI.

Hosting IE4/MSHTML as an Active Document

As an Active Document, IE4/MSHTML follows the standard OLE mechanisms for negotiating with the container for menu merging and displaying its toolbars. IE4/MSHTML supports only the single view implementation of Active Documents. Commands can be sent and received using the IOleCommandTarget interface that is also part of the Active Document specification. The standard NULL command set is supported as well as a set of extended commands specific to IE4/MSHTML.

A host of IE4/MSHTML can turn off IE4/MSHTML's menus and toolbars and supply its own UI. The host may also intercept any of IE4/MSHTML's UI, such as context menus and message boxes. For more information about intercepting UI, see Replacing IE4/MSHTML's User Interface. For more information about implementing an Active Document host, see Programming an Active Document Container.

Aggregating IE4/MSHTML

If your application is using IE4/MSHTML to implement an Active Document that customizes IE4/MSHTML's behavior, a host may aggregate with IE4/MSHTML to create a new class. IE4/MSHTML is designed to support aggregation. Overriding a small number of interfaces can customize much of IE4/MSHTML's behavior.

Creating a new Active Document

The minimum interfaces that need to be supplied by an aggregator are IOleObject and the IPersist* interfaces.

These interfaces supply the object's ClassID and UserType (through IOleObject::GetUserClassID, IOleObject::GetUserType, and IPersist::GetClassID methods). The aggregator should supply its own implementations to differentiate the new object from IE4/MSHTML.

Some common functionality that can be customized by aggregation includes:

  • Commands can be added. Simply override the IOleCommandTarget interface (described later in this document).
  • Automation interfaces can be added. When doing this, be sure to override IProvideClassInfo as well as IDispatch and IConnectionPointContainer (discussed later in this document).

Other customization can be done by supplying services to IE4/MSHTML.

Supplying services and ambient properties when aggregating

IE4/MSHTML provides or uses interfaces that allow an aggregator to supply ambient properties to it without having to implement a full client site for hosting IE4/MSHTML. The site object normally supplies ambient properties, but a site object has a number of other interfaces that are not trivial to implement. Using this technique, the aggregator can let the container's client site pass through to IE4/MSHTML while the aggregator still supplies ambient properties.

Replacing IE4/MSHTML's User Interface

If IE4/MSHTML is tightly integrated into an application, it may be desirable to have the application supply its own menus, toolbars and other UI. To do this, the host can supply optional services to IE4/MSHTML that allow the host to hook into and replace IE4/MSHTML's UI. In implementing these interfaces, a host knows that IE4/MSHTML is the component being hosted and has knowledge of IE4/MSHTML's command set.

When replacing IE4/MSHTML's UI, the host turns off IE4/MSHTML's menus and toolbars and can replace them. This does not involve any negotiation. A host of IE4/MSHTML can display message boxes, Help UI, and all in-place active UI on behalf of IE4/MSHTML by implementing two interfaces, IDocHostUIHandler and IDocHostShowUI.

To replace the menus, toolbars, and other UI for IE4/MSHTML, the host should implement the IDocHostUIHandler interface. IE4/MSHTML will obtain this interface by calling the host's client site QueryInterface, requesting IID_IDocHostUIHandler. If the host does not implement a client site, it can QueryInterface IE4/MSHTML for the ICustomDoc interface and call the ICustomDoc::SetUIHandler method to set IE4/MSHTML's UI handler.

When IDocHostUIHandler is present, IE4/MSHTML delegates a number of IOleInPlaceObject and IOleInPlaceActiveObject methods directly to it, allowing a host to hook into methods such as IOleInPlaceActiveObject::TranslateAccelerator and IOleInPlaceActiveObject::ResizeBorder. Returning S_OK on the IDocHostUIHandler::ShowUI method called by IE4/MSHTML will cause IE4/MSHTML to hide its menus and toolbars and not call the IOleInPlaceFrame methods for menu merging and border space negotiation.

To supply message boxes and Help UI, the host should implement the IDocHostShowUI interface. IE4/MSHTML will obtain this interface by calling the host's client site QueryInterface, requesting IID_IDocHostShowUI. The site object implements both IOleDocumentSite and IOleClientSite.

Substituting User Preferences

As IE4/MSHTML may be used in a number of different host environments, there is a requirement that each host environment be able to set different default user preferences in the registry. IE4/MSHTML allows its host to specify a special registry key under which to store the default preferences.

IE4/MSHTML calls IDocHostUIHandler::GetOptionKeyPath on the host at initialization to allow the host to specify the registry location for the preference settings. IE4/MSHTML then uses this registry key to store and get the settings for its preference property pages. If the host returns S_FALSE for this method, or the returned registry key path is NULL or empty, then IE4/MSHTML will revert to its own default set of options.

Loading HTML and Referenced Data

There are three situations where IE4/MSHTML needs to resolve URLs or load data:

  1. When an HTML page is loaded into IE4/MSHTML. IE4/MSHTML is capable of loading pages from URLs (or any other asynchronous moniker) or from files.
  2. When data (for example, an <IMG> tag) is referred to on the HTML page. A host can optionally supply a service to IE4/MSHTML to assist in resolving these references.
  3. When a hyperlink needs to be followed. IE4/MSHTML invokes the standard hyperlinking API. A host may optionally provide the hyperlinking support so that IE4/MSHTML can link to the new object within the host frame.

Loading an HTML page

For a host to get IE4/MSHTML to load and display the page at a specific URL, the host constructs a moniker using the CreateURLMoniker API call. Then it calls IPersistMoniker::Load on IE4/MSHTML. IE4/MSHTML's implementation of IPersistMoniker is specifically designed to support the loading of data asynchronously over slow links.

More information about these interfaces can be found in the Asynchronous and URL Monikers Overview section of the Internet Client SDK.

IE4/MSHTML is also capable of simple synchronous loading and saving of HTML through IPersistStreamInit or asynchronous loading from a file through IPersistFile.

Resolving Hyperlinks

If a user clicks on a link within an HTML page viewed in IE4/MSHTML, IE4/MSHTML will call the HlinkNavigate API (after having set up an IHlink object). If the host does not implement IHlinkFrame, this API launches a separate application to follow the hyperlink.

Hosts that wish to act as browsers (and navigate within the same frame) can implement IHlinkFrame on the FRAME object. The HlinkNavigate API calls IHlinkFrame::Navigate, allowing a browser application to hide the previous instance of IE4/MSHTML and create, load, and show a new instance of IE4/MSHTML (or other Active Document) to display the new page.

For more information on hyperlinking, see Hyperlinks.

Because the WebBrowser control has built-in support for hyperlinking, hosting the WebBrowser control is the preferred solution here.

Automating IE4/MSHTML

IE4/MSHTML can be automated using IDispatch and IConnectionPointContainer-style automation interfaces. These interfaces allow a host to automate IE4/MSHTML through the object model.

Scripts within IE4/MSHTML

IE4/MSHTML is responsible for loading and running scripts that appear within HTML. Because scripting is done by using the ActiveX Scripting interfaces, any ActiveX script engine can be hosted by IE4/MSHTML.

For more information about ActiveX scripting engines and hosts, see ActiveX Scripting.

Sending and Receiving Commands

Because IE4/MSHTML is an Active Document, it communicates with its host using the IOleCommandTarget interface. With this interface, the following details are communicated to the hosting frame.

  • Menu/Toolbar Enabling – The common menus and toolbar buttons found on the host (Cut, Copy, Paste, and so on) are enabled and disabled by sending IE4/MSHTML commands and queries.
  • IE4/MSHTML Commands – Common functions like Refresh, Stop, and Hide Toolbars are sent by the host to IE4/MSHTML through commands.
  • Status Bar Updates – Progress and status bar text information is communicated to the hosting frame by IE4/MSHTML through commands.

In addition to the standard command group, IE4/MSHTML supports a group of IE4/MSHTML-specific commands that provide simple access to a number of IE4/MSHTML-specific features. For more information, see the OLECMDID enumeration.

Terminology

ActiveX™ Control – Also known as an OLE Control. An ActiveX Control is a contained mini-application. It can (optionally) maintain state, draw itself, persist itself, have its own window, respond to automation methods, throw events, take keyboard focus, respond to mouse and keyboard input, and show merged menu and toolbar UI. Most of the control interfaces are documented in MSDN. The OC96 and OLE Controls/COM Objects for the Internet specifications introduce a number of new interfaces for controls to improve their performance and make them suitable for the Internet. Further extensions supported by IE4/MSHTML are discussed later in this section.

Active Document – Also known as an OLE Document Object or Doc Object. An Active Document is a contained object; the container provides the frame and some basic UI. In such containers, the Active Document may be interchanged with other Active Documents while the containing frame and its UI remain constant. Examples of Active Document containers include the Office Binder and Internet Explorer 3.0x, where the Active Document could change to Microsoft® Word or Excel while maintaining the same outer frame application. An Active Document is similar to an OLE Embedding scenario or an ActiveX Control, but its interfaces are designed to support an object that is at the top level and takes up the entire content area of the frame. There are specific interfaces required to support Active Document functionality. For more information, see Active Documents.

ActiveX Scripting – A standard set of interfaces that allows for language-independent script integration to applications. Any script engine (VBScript, JScript, or a third party scripting language, for example) that supports the standard interfaces can be integrated with an ActiveX script host such as IE4/MSHTML.

IE4/MSHTML – An Active Document that is capable of rendering HTML and laying out contained ActiveX Controls. In this document, it refers to an instance of the IE4/MSHTML COM object that implements IOleObject, IOleDocument, IOleDocumentView, and many other interfaces.

Aggregation – A kind of run-time inheritance. By aggregating, an object can extend and enhance the functionality of another object but still take advantage of the functionality and interfaces of the aggregated object. Objects can be designed to be aggregated or not. IE4/MSHTML is designed to be aggregated.

Site – The object supplied by a container to a contained object through IOleObject::SetClientSite. Containers of an ActiveX object must supply a site before doing anything else. IE4/MSHTML gets much of its information about its geometry, activation, ambient properties, and so on, from its container site. (In this specification, there's no distinction between IE4/MSHTML's container document site and its view site.) IE4/MSHTML also supplies a site for each ActiveX Control it hosts.

Container – The ActiveX object that owns the site obtained through IOleClientSite::GetContainer (may be null). From the container, the contained objects may be enumerated through IOleContainer::EnumObjects. This concept of containment should not be confused with the concept of containment used for scripting and supplied by automation interfaces. Some contained automation objects are not contained ActiveX objects, and some contained ActiveX objects cannot be automated.

Frame – The outer application frame, with menu and toolbar space, supplied to an ActiveX object through IOleInPlaceSite::GetWindowContext. This is the object with which IE4/MSHTML negotiates for menu and toolbar space and also for hyperlinks.

Document Window – The document window, with toolbar space, supplied to an ActiveX object through IOleInPlaceSite::GetWindowContext. (In MDI it is the document window, and in SDI it is NULL.) IE4/MSHTML currently ignores the document window.

Command – A simple action sent to an ActiveX object through the IOleCommandTarget interface. Commands usually correspond to user-level commands, like the commands on menus, and can be enabled or disabled by the command target. A command can be sent to the frame, the container site, IE4/MSHTML, or a control.

Automation – A set of standards to allow an object to be programmed by scripts. Every object that can be automated can have methods and properties that can be used by a script, as well as events that can trigger scripts to be run.

Dispatch Interface – An interface inheriting from IDispatch that is used to access named automation properties and methods of an object from a script.

Event Interface – A callback interface attached to an object using IConnectionPointContainer. Used by script engines to get notification of events thrown by objects.

Type Info – A structure used to specify properties, methods, and events (automatable or otherwise). Can be obtained from a dispatch interface through IDispatch or an object that supplies IProvideClassInfo*.

X Object – An object that IE4/MSHTML wraps around each hosted control to supply common, per-control, container-owned properties and events. IE4/MSHTML aggregates the X object to the control, if possible, and merges types with the control.

Service – A service supplied by the host to an ActiveX object through the IServiceProvider interface on the container site. Each service is identified by a service identifier (SID), allowing access to interfaces and methods.

Ambient – A property owned by the container and supplied to an ActiveX object through the IDispatch interface on its hosting site.


Advanced Hosting Interfaces

This document describes the interfaces used for customizing the behavior of IE4/MSHTML objects. In addition to the interfaces described here, IE4/MSHTML can be customized through a number of interfaces that match IE4/MSHTML's Object Model. For a more general overview of IE4/MSHTML's hosting and extensibility mechanisms, see Reusing MSHTML.

ICustomDoc Interface

IDocHostUIHandler Interface

IDocHostShowUI Interface


ICustomDoc Interface

The ICustomDoc interface is implemented by IE4/MSHTML to allow a host to set IE4/MSHTML's IDocHostUIHandler interface. Normally, IE4/MSHTML will call the host client site's QueryInterface method to obtain the IDocHostUIHandler interface. IE4/MSHTML implements ICustomDoc so that a host that does not implement a client site can still use IE4/MSHTML's UI customization features.

ICustomDoc is derived from IUnknown. The following is the ICustomDoc specific method:
SetUIHandler


ICustomDoc::SetUIHandler

HRESULT SetUIHandler(
    IDocHostUIHandler *pUIHandler
);

Sets IE4/MSHTML's IDocHostUIHandler.

  • Returns S_OK if successful, or an OLE-defined error code otherwise.
pUIHandler
Address of the host's IDocHostUIHandler interface.

IE4/MSHTML will release its previous IDocHostUIHandler interface (if one is present) and call pUIHandler's AddRef method.


IDocHostShowUI Interface

A host can supply mechanisms for message boxes and Help to be shown by implementing the IDocHostShowUI interface. IE4/MSHTML will obtain this interface by calling the host's client site QueryInterface, requesting IID_IDocHostShowUI. The site is the object that implements the IOleDocumentSite and IOleClientSite interfaces.

IDocHostShowUI is derived from IUnknown. The following are the methods specific to IDocHostShowUI.
ShowHelp
ShowMessage


IDocHostShowUI::ShowHelp

HRESULT STDMETHODCALLTYPE ShowHelp(
    HWND hwnd,
    LPOLESTR pszHelpFile,
    UINT uCommand,
    DWORD dwData,
    POINT ptMouse,
    IDispatch *pDispatchObjectHit
);

Called by IE4/MSHTML when it needs to show Help.

  • Return Values:
    S_OK | Host displayed Help. IE4/MSHTML will not display its Help.
    S_FALSE | Host did not display Help. IE4/MSHTML will display its Help.
hwnd
Handle to the owner window.
pszHelpFile
Help file name.
uCommand
Type of Help. See the WinHelp function.
dwData
Additional data. See the WinHelp function.
ptMouse
Mouse position in screen coordinates.
pDispatchObjectHit
IDispatch of the object at the screen coordinates.

The first four parameters are the same as those passed to the WinHelp function. The ptMouse parameter gives the screen coordinates, and the pDispatchObjectHit parameter allows the host to differentiate the object at the screen coordinates to a greater degree than IE4/MSHTML.


IDocHostShowUI::ShowMessage

HRESULT ShowMessage(
    HWND hwnd,
    LPOLESTR lpstrText,
    LPOLESTR lpstrCaption,
    DWORD dwType,
    LPOLESTR lpstrHelpFile,
    DWORD dwHelpContext,
    LRESULT *plResult
);

Called by IE4/MSHTML when it needs to display a message box.

  • Return Values:
    S_OK | Host displayed its UI. IE4/MSHTML will not display its message box.
    S_FALSE | Host did not display its UI. IE4/MSHTML will display its message box.
hwnd
Handle to the owner window.
lpstrText
Text for the message box.
lpstrCaption
Caption for the message box.
dwType
Type flags (taken from the MessageBox MB_xxxx constants).
lpstrHelpFile
Help file name.
dwHelpContext
Help context identifier.
plResult
Button clicked by user (taken from the MessageBox IDxxx constants).


IDocHostUIHandler::EnableModeless

HRESULT EnableModeless(
    BOOL fEnable
);

Called from the IE4/MSHTML implementation of IOleInPlaceActiveObject::EnableModeless. Also called when IE4/MSHTML displays modal UI. The host should enable or disable its modeless UI as appropriate.

  • Returns S_OK if successful, or an OLE-defined error code otherwise.
fEnable
Indicates if the host's modeless dialog boxes are enabled or disabled. If this value is nonzero, modeless dialog boxes are enabled. If this value is zero, modeless dialog boxes are disabled.


IDocHostUIHandler::FilterDataObject

HRESULT FilterDataObject(
    IDataObject *pDO,
    IDataObject **ppDORet
);

Called on the host by IE4/MSHTML to allow the host to replace IE4/MSHTML's data object. This allows the host to block certain clipboard formats or support additional clipboard formats.

  • Returns S_OK if the data object is replaced, S_FALSE if the data object is not replaced, or an OLE-defined error code if an error occurs.
pDO
Address of the IDataObject interface supplied by IE4/MSHTML.
ppDORet
Address that receives the IDataObject interface pointer supplied by the host. The contents of this parameter should always be initialized to NULL, even if the method fails.


IDocHostUIHandler::GetDropTarget

HRESULT GetDropTarget(
    IDropTarget *pDropTarget,
    IDropTarget **ppDropTarget
);

Called by IE4/MSHTML when it is being used as a drop target to allow the host to supply an alternative IDropTarget.

  • Return Values:
    S_OK | The host wants to replace the IDropTarget with the one specified in ppDropTarget.
    S_FALSE | The host does not want to replace the IDropTarget.
    E_NOTIMPLE | The host has not implemented this method.
pDropTarget
IDropTarget IE4/MSHTML proposes to use.
ppDropTarget
Address of the IDropTarget that receives the IDropTarget interface pointer the host wants to provide.


IDocHostUIHandler::GetExternal

HRESULT GetExternal(
    IDispatch **ppDispatch
);

Called by IE4/MSHTML to obtain the host's IDispatch interface.

  • Returns S_OK if successful, or an OLE-defined error code otherwise.
ppDispatch
Address that receives the IDispatch interface pointer of the host application. If the host exposes an automation interface, it can provide a reference to IE4/MSHTML through this parameter. The contents of this parameter should always be initialized to NULL, even if the method fails.


IDocHostUIHandler::GetHostInfo

HRESULT GetHostInfo(
    DOCHOSTUIINFO FAR *pInfo
);

Retrieves the UI capabilities of the IE4/MSHTML host.

  • Returns S_OK If successful, or an OLE-defined error code otherwise.
pInfo
Address of a DOCHOSTUIINFO structure that receives the host's UI capabilities.


IDocHostUIHandler::GetOptionKeyPath

HRESULT GetOptionKeyPath(
    LPOLESTR *pchKey,
    DWORD dwReserved
);

Returns the registry key under which IE4/MSHTML stores user preferences.

  • Returns S_OK if successful, or S_FALSE otherwise. If S_FALSE, IE4/MSHTML will default to its own user options.
pchKey
Address of an LPOLESTR that receives the registry subkey string where the host stores its default options. This subkey will be under the HKEY_CURRENT_USER key. The implementation must allocate this memory using CoTaskMemAlloc. The calling application is responsible for freeing this memory using CoTaskMemFree. Even if the method fails, this parameter should be set to NULL.
dwReserved
Reserved for future use. Not currently used.

If pchKey is null on return from this function, then IE4/MSHTML uses the default location for storing options in the registry.


IDocHostUIHandler::HideUI

HRESULT HideUI(void);

Called when IE4/MSHTML removes its menus and toolbars.

  • Returns S_OK if successful, or an OLE-defined error code otherwise.

If a host displayed menus and toolbars during the call to IDocHostUIHandler::ShowUI, the host should remove them when this method is called. This method is called regardless of the return value from the ShowUI method.


IDocHostUIHandler Interface

A host can replace the menus, toolbars, and context menus used by IE4/MSHTML by implementing the IDocHostUIHandler interface. IE4/MSHTML will obtain this interface by calling the host's client site QueryInterface, requesting IID_IDocHostUIHandler. This interface has methods that allow IE4/MSHTML to communicate with the host about its UI status.

IDocHostUIHandler is derived from IUnknown. The following are the methods specific to IDocHostUIHandler:
ShowContextMenu
GetHostInfo
ShowUI
HideUI
UpdateUI
EnableModeless
OnDocWindowActivate
OnFrameWindowActivate
ResizeBorder
TranslateAccelerator
GetOptionKeyPath
GetDropTarget
GetExternal
TranslateUrl
FilterDataObject

The following are the structures and enumerations used with the IDocHostUIHandler interface:
DOCHOSTUIINFO
DOCHOSTUIDBLCLK
DOCHOSTUIFLAG


IDocHostUIHandler::OnDocWindowActivate

HRESULT OnDocWindowActivate (
    BOOL fActive
);

Called from the IE4/MSHTML implementation of IOleInPlaceActiveObject::OnDocWindowActivate.

  • Returns S_OK if successful, or an OLE-defined error code otherwise.
fActive
Indicates the state of the document window. If this value is nonzero, the window is being activated. If this value is zero, the window is being deactivated.


IDocHostUIHandler::OnFrameWindowActivate

HRESULT OnFrameWindowActivate (
    BOOL fActive
);

Called from the IE4/MSHTML implementation of IOleInPlaceActiveObject::OnFrameWindowActivate.

  • Returns S_OK if successful, or an OLE-defined error code otherwise.
fActive
Indicates the state of the container's top-level frame window. If this value is nonzero, the window is being activated. If this value is zero, the window is being deactivated.


IDocHostUIHandler::ResizeBorder

HRESULT ResizeBorder(
    LPCRECT prcBorder,
    IOleInPlaceUIWindow FAR *pUIWindow,
    BOOL fFrameWindow
);

Called from the IE4/MSHTML implementation of IOleInPlaceActiveObject::ResizeBorder.

  • Returns S_OK if successful, or an OLE-defined error code otherwise.
prcBorder
New outer rectangle for border space.
pUIWindow
Frame or document window border change.
fFrameWindow
Indicates TRUE if the frame window is calling ResizeBorder, or FALSE otherwise.


IDocHostUIHandler::ShowContextMenu

HRESULT ShowContextMenu(
    DWORD dwID,
    POINT FAR *ppt,
    IUnknown FAR *pcmdtReserved,
    IDispatch FAR *pdispReserved
);

Called from IE4/MSHTML when it is about to show its context menu.

  • Return Values:
    S_OK | Host displayed its own UI. IE4/MSHTML will not attempt to display its UI.
    S_FALSE | Host did not display any UI. IE4/MSHTML will display its UI.
    DOCHOST_E_UNKNOWN | Menu identifier is unknown. IE4/MSHTML may attempt an alternative identifier from a previous version.
dwID
Identifier of the context menu to be displayed.
ppt
Screen coordinates for the menu.
pcmdtReserved
IOleCommandTarget interface used to query command status and execute commands on this object.
pdispReserved
IDispatch interface of the object at the screen coordinates. This allows a host to differentiate particular objects to provide more specific context.

The following menu identifiers are currently used. Note: These identifiers are likely to change and are not currently exposed in a header file as part of the IE4/MSHTML SDK.
#define CONTEXT_MENU_DEFAULT 0
#define CONTEXT_MENU_IMAGE 1
#define CONTEXT_MENU_CONTROL 2
#define CONTEXT_MENU_TABLE 3
#define CONTEXT_MENU_DEBUG 4
#define CONTEXT_MENU_1DSELECT 5
#define CONTEXT_MENU_ANCHOR 6
#define CONTEXT_MENU_IMGDYNSRC 7


IDocHostUIHandler::ShowUI

HRESULT ShowUI(
    DWORD dwID,
    IOleInPlaceActiveObject FAR *pActiveObject,
    IOleCommandTarget FAR *pCommandTarget,
    IOleInPlaceFrame FAR *pFrame,
    IOleInPlaceUIWindow FAR *pDoc
);

Allows the host to replace the IE4/MSHTML menus and toolbars.

  • Return Values:
    S_OK | Host displayed its own UI. IE4/MSHTML will not display its UI.
    S_FALSE | Host did not display its own UI. IE4/MSHTML will display its UI.
    DOCHOST_E_UNKNOWN | Host did not recognize the UI identifier. IE4/MSHTML will either try an alternative identifier for compatibility with a previous version or display its own UI.
dwID
Reserved for future use.
pActiveObject
IOleInPlaceActiveObject interface of the currently active object.
pCommandTarget
IOleCommandTarget interface of the object.
pFrame
IOleInPlaceFrame interface of the object. This is needed for menus and toolbars.
pDoc
IOleInPlaceUIWindow interface for the object. This is needed for toolbars.

This method is called just before IE4/MSHTML displays its menus and toolbars. If the host returns S_FALSE from this method, IE4/MSHTML does not display its UI and assumes that the host is handling the UI.

If the host makes use of any of the interfaces handed to it as part of this function, it should call the interface's AddRef method if it is to be saved for later use. If the host calls the interface's AddRef method, it must also call the interface's Release method when the interface is no longer required.

A host can disable modeless UI on IE4/MSHTML by calling IOleCommandTarget::Exec with IDM_DISABLEMODELESS and IDM_ENABLEMODELESS.


IDocHostUIHandler::TranslateAccelerator

HRESULT TranslateAccelerator(
    LPMSG lpMsg,
    const GUID FAR *pguidCmdGroup,
    DWORD nCmdID
);

Called by IE4/MSHTML when IOleInPlaceActiveObject::TranslateAccelerator or IOleControlSite::TranslateAccelerator is called.

  • Returns S_OK if successful, or S_FALSE otherwise.
lpMsg
Points to the message that might need to be translated.
pguidCmdGroup
Command group identifier.
nCmdID
Command identifier.


IDocHostUIHandler::TranslateUrl

HRESULT TranslateUrl(
    DWORD dwTranslate,
    OLECHAR *pchURLIn,
    OLECHAR **ppchURLOut
);

Called by IE4/MSHTML to allow the host an opportunity to modify the URL to be loaded.

  • Returns S_OK if the URL was translated, S_FALSE if the URL was not translated, or an OLE-defined error code if an error occurred.
dwTranslate
Reserved for future use.
pchURLIn
Address of a string supplied by IE4/MSHTML that represents the URL to be translated.
ppchURLOut
Address of a string pointer that receives the address of the translated URL. The host allocates the buffer using the task memory allocator. The contents of this parameter should always be initialized to NULL, even if the URL is not translated or the method fails.


IDocHostUIHandler::UpdateUI

HRESULT UpdateUI(void);

Notifies the host that the command state has changed.

  • Returns S_OK if successful, or an OLE-defined error code otherwise.

The host should update the state of toolbar buttons. This method is called regardless of the return value from the ShowUI method.


DOCHOSTUIDBLCLK

typedef enum tagDOCHOSTUIDBLCLK{
    DOCHOSTUIDBLCLK_DEFAULT = 0,
    DOCHOSTUIDBLCLK_SHOWPROPERTIES = 1,
    DOCHOSTUIDBLCLK_SHOWCODE = 2
}DOCHOSTUIDBLCLK;

Defines values used to indicate the proper action on a double-click event.

DOCHOSTUIDBLCLK_DEFAULT
Perform the default action.
DOCHOSTUIDBLCLK_SHOWPROPERTIES
Show the item's properties.
DOCHOSTUIDBLCLK_SHOWCODE
Show the page's source.


DOCHOSTUIFLAG

typedef enum tagDOCHOSTUIFLAG{
    DOCHOSTUIFLAG_DIALOG = 1,
    DOCHOSTUIFLAG_DISABLE_HELP_MENU = 2,
    DOCHOSTUIFLAG_NO3DBORDER = 4,
    DOCHOSTUIFLAG_SCROLL_NO = 8,
    DOCHOSTUIFLAG_DISABLE_SCRIPT_INACTIVE = 16,
    DOCHOSTUIFLAG_OPENNEWWIN = 32,
    DOCHOSTUIFLAG_DISABLE_OFFSCREEN = 64,
    DOCHOSTUIFLAG_FLAT_SCROLLBAR = 128
    DOCHOSTUIFLAG_DIV_BLOCKDEFAULT = 256,
    DOCHOSTUIFLAG_ACTIVATE_CLIENTHIT_ONLY = 512
 }DOCHOSTUIFLAG;

Defines a set of flags that indicate the capabilities of a IDocHostUIHandler implementation.

DOCHOSTUIFLAG_DIALOG
IE4/MSHTML will not allow selection of the text in the form.
DOCHOSTUIFLAG_DISABLE_HELP_MENU
IE4/MSHTML will not display context menus.
DOCHOSTUIFLAG_NO3DBORDER
IE4/MSHTML does not use 3-D borders.
DOCHOSTUIFLAG_SCROLL_NO
IE4/MSHTML does not have scroll bars.
DOCHOSTUIFLAG_DISABLE_SCRIPT_INACTIVE
IE4/MSHTML will not execute any script when loading pages.
DOCHOSTUIFLAG_OPENNEWWIN
IE4/MSHTML will open a site in a new window when a link is clicked rather than browse to the new site using the same browser window.
DOCHOSTUIFLAG_DISABLE_OFFSCREEN
Not implemented or used.
DOCHOSTUIFLAG_FLAT_SCROLLBAR
IE4/MSHTML will use flat scroll bars for any UI it displays. Not currently supported.
DOCHOSTUIFLAG_DIV_BLOCKDEFAULT
IE4/MSHTML will insert the <DIV> tag if a return is entered in edit mode. Without this flag, IE4/MSHTML will use the <P> tag.
DOCHOSTUIFLAG_ACTIVATE_CLIENTHIT_ONLY
IE4/MSHTML will only become UI-active if the mouse is clicked in the client area of the window. It will not become UI-active if the mouse is clicked on a nonclient area, such as a scroll bar.


DOCHOSTUIINFO

typedef struct _DOCHOSTUIINFO{
    ULONG cbSize;
    DWORD dwFlags;
    DWORD dwDoubleClick;
}DOCHOSTUIINFO;

Used by the IDocHostUIHandler::GetHostInfo method to allow IE4/MSHTML to retrieve information about the host's UI requirements.

cbSize
Size of this structure, in bytes.
dwFlags
One or more of the DOCHOSTUIFLAG values that specify the UI capabilities of the host.
dwDoubleClick
One of the DOCHOSTUIDBLCLK values that specify the operation that should take place in response to a double-click.


IDocHostUIHandler Structures and Enumerations IDocHostUIHandler Structures and Enumerations *
  * Previous Topic: IDocHostUIHandler::UpdateUI
  * Next Topic: DOCHOSTUIINFO

IDocHostUIHandler Structures and Enumerations

The following are the structures and enumerations used with the IDocHostUIHandler interface.


HTML Dialog Boxes

IE4/MSHTML allows you to create a modal dialog box that displays HTML. This is accomplished using the ShowHTMLDialog function that is implemented in Mshtml.dll.

Using ShowHTMLDialog

Creating an HTML Resource

Using ShowHTMLDialog

To use ShowHTMLDialog, it is necessary to dynamically load and then call this function by using the LoadLibrary and GetProcAddress functions. The SHOWHTMLDIALOGFN type is defined in Mshtmhst.h to define the proper function type for ShowHTMLDialog. The HTMLDlg sample in the Internet Client SDK shows a complete example using ShowHTMLDialog, including how to pass data to and receive data from the dialog. The following example shows how to obtain the address of the ShowHTMLDialog function:

#include <windows.h>
#include <mshtmhst.h>

{
HINSTANCE   hinstMSHTML = LoadLibrary(TEXT("MSHTML.DLL"));

if(hinstMSHTML)
   {
   SHOWHTMLDIALOGFN  *pfnShowHTMLDialog;

   pfnShowHTMLDialog = (SHOWHTMLDIALOGFN*)GetProcAddress(hinstMSHTML, TEXT("ShowHTMLDialog"));

   if(pfnShowHTMLDialog)
      {
      /*
      Perform initialization and then call ShowHTMLDialog.
      */
      }

   FreeLibrary(hinstMSHTML);
   }
}

The HTML for the dialog box is loaded from an IMoniker interface that is passed in the pmk parameter in ShowHTMLDialog. This moniker can be any moniker that evaluates to any HTML source or to a resource that uses the res: protocol. The CreateURLMoniker function can be used to create the IMoniker interface that is passed to ShowHTMLDialog.

The input parameters for the dialog box are passed in the pvaArgIn parameter in ShowHTMLDialog. The input parameters can be any information that can be passed in a VARIANT structure. In the dialog box HTML source, the input parameters are obtained from the dialogArguments property of the window object.

The output parameters for the dialog box are returned in the pvaArgOut parameter in ShowHTMLDialog. This is a VARIANT structure that you allocate. This structure must be initialized using the VariantInit function before calling ShowHTMLDialog. In the dialog box HTML source, the output parameters are set using the returnValue property of the window object.


Creating an HTML Resource

Rather than distribute separate HTML files for your application's use, you can add the raw HTML to your application as a resource. You can then retrieve the HTML from your application when it is needed. ShowHTMLDialog is one example of how HTML can be used from a resource by using the res: protocol.

To add the HTML as a resource, you include a file that contains nothing but the actual HTML in your application's resource script. This file is included as an HTML type resource. The following example shows how to include a file called MyHTML.htm as an HTML resource.

HTML_RESOURCE HTML "MyHTML.htm"

In this example, "HTML_RESOURCE" is the identifier of the resource. This can be either a string or a numerical identifier. "HTML" is the resource type. Visual C++ 5.0 will interpret this as the numeric value 23 and will substitute 23 for "HTML" when the resource file is opened for editing. "MyHTML.htm" is the file that contains the HTML source that will be added. The resource compiler adds this file as is and will not attempt to interpret the contents of the file.

You can specify the HTML resource in any function that will accept a res: protocol. ShowHTMLDialog is one example of how HTML can be used from a resource by using the res: protocol. You can also use FindResource and LoadResource to obtain the HTML resource. In FindResource, specify the RT_HTML value for lpType to find an HTML resource.


SHOWHTMLDIALOGFN

typedef HRESULT STDAPICALLTYPE SHOWHTMLDIALOGFN(
    HWND hwndParent,
    IMoniker *pmk,
    VARIANT *pvarArgIn,
    TCHAR* pchOptions,
    VARIANT *pvarArgOut
);

Defines the function type for ShowHTMLDialog. This function creates a modal dialog box that contains HTML. The function does not return until the dialog box has been dismissed. The address of this function must be obtained by loading Mshtml.dll with LoadLibrary and then getting the address of ShowHTMLDialog with GetProcAddress.

hwndParent
Handle to the window that will be the owner of the dialog box. This window will be disabled for the life of the dialog box. If this value is NULL, the dialog box is not owned.
pmk
Address of an IMoniker interface that identifies the source of the HTML that will be contained in the dialog box.
pvarArgIn
Address of a VARIANT that contains the input data for the dialog box. The data passed in this VARIANT is placed in the window object's dialogArguments property. This parameter can be NULL.
pchOptions
Window ornaments for the dialog box. This parameter can be NULL or the address of a string that contains a combination of values, each separated by a ';'. See the description of the features parameter of the showModalDialog method of the window object for detailed information.
pvarArgOut
Address of a VARIANT that contains the output data for the dialog box. This VARIANT receives the data that was placed in the window object's returnValue property. This parameter can be NULL.


Reference for C/C++ Developers Reference for C/C++ Developers *
  * Previous Topic: TitleChange Event
  * Next Topic: Interface

Reference for C/C++ Developers

This reference contains the following sections:

  • Interface
  • Events
  • Enumerations


Reference for Visual Basic Developers

The following sections are a reference guide for using the WebBrowser control with Microsoft® Visual Basic®. This reference covers all the supported properties, methods, and events associated with the WebBrowser and InternetExplorer objects.

  • Objects
  • Properties
  • Methods
  • Events


Reusing the WebBrowser Control

The WebBrowser control adds browsing, document viewing, and data downloading capabilities to your applications. Applications using this control will allow the user to browse sites on the Internet's World Wide Web, as well as folders in the local file system and on a network. The WebBrowser control supports Web browsing through both point-and-click hyperlinking and Uniform Resource Locator (URL) navigation. The control maintains a history list that allows the user to browse forward and backward through previously browsed sites, folders, and documents.

The actual parsing and rendering of the HTML documents in the WebBrowser control is handled by the Mshtml.dll component of Microsoft® Internet Explorer 4.0. The MSHTML component is an Active Document (also known as an OLE document object) that provides support for parsing and rendering with the Dynamic HTML object model, as well as for hosting ActiveX™ Controls and scripts. The WebBrowser control directly handles the navigation, hyperlinking, history lists, favorites, and security. Applications can also use the WebBrowser control as an Active Document container to host other Active Documents. This means that richly formatted documents, such as a Microsoft® Excel spreadsheet or Microsoft® Word document, can be opened and edited in-place from within the WebBrowser control. WebBrowser is also an ActiveX Control container that can host any ActiveX Control.

Updates in Internet Explorer 4.0

Using the WebBrowser Control from Visual Basic

Using the WebBrowser Control from C/C++

Reference for Visual Basic Developers

Reference for C/C++ Developers

Updates in Internet Explorer 4.0

For Internet Explorer 4.0, the following new properties, methods, and events have been added:
Visual Basic | C/C++ | Type | Description
AddressBar | get_AddressBar | property | Indicates whether the URL address bar is shown.
Offline | get_Offline | property | Determines if the browser is in offline mode.
ReadyState | get_ReadyState | property | Returns the OLE ReadyState bindable object.
RegisterAsBrowser | get_RegisterAsBrowser | property | Indicates whether the WebBrowser control is registered as a top-level browser.
RegisterAsDropTarget | get_RegisterAsDropTarget | property | Indicates whether the WebBrowser control is registered as a drop target.
Resizable | get_Resizable | property | Indicates whether the Internet Explorer object can be resized.
Silent | get_Silent | property | Indicates whether dialog boxes can be shown.
TheaterMode | get_TheaterMode | property | Indicates whether the browser is in "Theater Mode" or a normal browser window.
ExecWB | ExecWB | method | Executes an IOLECommandTarget interface command.
Navigate2 | Navigate2 | method | Navigates the WebBrowser control to a URL.
QueryStatusWB | QueryStatusWB | method | Returns the status of commands using the IOLECommandTarget interface.
ShowBrowserBar | ShowBrowserBar | method | Shows or hides a browser bar.
BeforeNavigate2 | BeforeNavigate2 | event | Occurs before the WebBrowser control navigates to a new URL. (replaces BeforeNavigate and FrameBeforeNavigate)
DocumentComplete | DocumentComplete | event | Occurs when the ReadyState property is changed to READYSTATE_COMPLETE.
NavigateComplete2 | NavigateComplete2 | event | Occurs after the WebBrowser control navigates to a new URL (replaces NavigateComplete and FrameNavigateComplete).
NewWindow2 | NewWindow2 | event | Occurs when navigation occurs with the navOpenInNewWindow flag (replaces NewWindow and FrameNewWindow).
OnFullScreen | OnFullScreen | event | Occurs when the FullScreen property changes.
OnMenuBar | OnMenuBar | event | Occurs when the MenuBarproperty changes.
OnQuit | OnQuit | event | Occurs before the Internet Explorer application quits.
OnStatusBar | OnStatusBar | event | Occurs when the StatusBar property changes.
OnTheaterMode | OnTheaterMode | event | Occurs when the TheaterMode property changes.
OnToolBar | OnToolBar | event | Occurs when the ToolBar property changes.
OnVisible | OnVisible | event | Occurs when the Visible property changes.

Internet Explorer 3.0 Compatibility

The new WebBrowser_V1 object is now included with the WebBrowser control. This object supports the set of properties, methods, and events that exist in Internet Explorer 3.0. You can use the WebBrowser_V1 object in a Visual Basic project to run on computers with either Internet Explorer 3.0 or 4.0 installed. The WebBrowser object requires Internet Explorer 4.0 to access the new properties, methods, and events listed above.

Using the WebBrowser Control from Visual Basic

The WebBrowser control supports properties, methods, and events that allow developers to create a highly customized Web browser with the WebBrowser object. Companies may want to use the WebBrowser control to create a Web browsing application that restricts navigation to a local intranet and company-approved public Web sites.

An application can also create and manipulate an instance of the Internet Explorer application through OLE Automation with the InternetExplorer object. In this context, additional properties and methods not supported by the WebBrowser object are available. These additional features are indicated in the Applies To list for the InternetExplorer object only. If these features are used with the WebBrowser object, error codes will be returned. Errors can be trapped in Visual Basic with the "On Error Resume Next" statement and by accessing the Err object's associated properties such as Err.Number and Err.Description.

To implement the InternetExplorer object in a Visual Basic application, declare the object as indicated in the Application property description. To use the WebBrowser object, simply add the "Microsoft Internet Controls" to your Visual Basic project and place the WebBrowser control on a Visual Basic form. This is accomplished by selecting the "Components..." item on the Project menu in Visual Basic 5.0, or by selecting the "Custom Controls..." item on the Tools menu in Visual Basic 4.0.

Retrieving Information About the WebBrowser Control

Many properties can be used to retrieve information about the WebBrowser control. The LocationName and LocationURL properties can be used to retrieve information about the location that is currently displayed. If the location is an HTML page on the World Wide Web, LocationName retrieves the title of that page, and LocationURL retrieves the URL of that page. If the location is a folder or file on the network or local computer, LocationName and LocationURL both retrieve the Universal Naming Convention (UNC) name or the full path of the folder or file.

The current status of the WebBrowser control can be obtained using the Busy property. This Boolean value indicates whether the control is engaged in a navigation or downloading operation. You should check the value of this property before issuing the Stop method to cancel navigation or downloading operations.

Customizing the User Interface

The WebBrowser control supports properties and associated events to manipulate various user interface elements of an Internet Explorer application or a custom browser. The size and position of the window used by the WebBrowser control can be read or set with the Height, Left, Top, and Width properties. Other user interface elements are enabled with individual properties such as MenuBar, FullScreen, StatusBar, and ToolBar. The associated OnMenuBar, OnFullScreen, OnStatusBar, and OnToolBar events are triggered when the property value changes. These events return a Boolean value to indicate the new state of the property and to provide a mechanism to respond to user actions in the InternetExplorer object.

When using OLE Automation with the InternetExplorer object, the application window can be shown or hidden by setting the value of the Visible property. When changed, the associated OnVisible event returns the current Boolean value of the property. You may also want to retrieve information about the Internet Explorer application itself. To do so, use the Name property to get the Internet Explorer application name, and use the Path and FullName properties to get the Internet Explorer application's path and file name.

Navigating with the WebBrowser Control

Use the Navigate or Navigate2 method to browse HTML pages on the World Wide Web or any file or folder on the network or local computer. In addition to the required URL argument passed to the Navigate or Navigate2 method, you can optionally include flags to specify more detailed information about the navigation, such as the HTML frame name target and the HTTP headers sent to the server. You can browse through the sites maintained in the browser's history list during each browser session by using the GoBack and GoForward methods. If you wish to go directly to the Internet Explorer home or search pages that have been specified in the Internet Explorer Options dialog box, use the GoHome or GoSearch method. To display the most current version of a page the browser is viewing, use the Refresh or Refresh2 method. When using OLE Automation, call the Quit method to close the instance of the Internet Explorer application.

The WebBrowser control triggers a number of different events to notify an application of user- and browser-generated activity. When the browser is about to navigate to a new location, it triggers a BeforeNavigate2 event that specifies the URL or path of the new location and any other data that will be transmitted to the Internet server through the HTTP transaction. The data can include the HTTP header, HTTP post data, and the URL of the referrer. The BeforeNavigate2 event also includes a flag that can be set to cancel the pending navigation request. This event can be useful for checking the requested URL against a database of unauthorized World Wide Web sites or local and network folders, and for canceling the navigation request. The WebBrowser control fires the NavigateComplete2 event after it has navigated to a new location. This event includes the same information as BeforeNavigate2, except NavigateComplete2 does not include the cancel flag.

Whenever the browser is about to begin a download operation, it triggers the DownloadBegin event. The control also generates a number of ProgressChange events as the operation progresses, and then it triggers the DownloadComplete event after completing the operation. Applications typically use these three events to indicate the progress of the download operation, often by displaying a progress bar. An application would show the progress bar in response to DownloadBegin, update the progress bar in response to ProgressChange, and hide the progress bar in response to DownloadComplete.

When an application calls the Navigate or Navigate2 method with the navOpenInNewWindow flag, the NewWindow2 event occurs before the new browser window is created. This event allows the application to create the new browser window or have a new instance of the Internet Explorer application created. Once the new window is created, an accompanying BeforeNavigate2 event occurs.

Note The events discussed in the preceding section that apply to the InternetExplorer object are supported in Visual Basic version 5.0 and later.

Creating a Custom Browser with Limited Functionality

Suppose you want to create a custom browser application to start and display an HTML page that is not the user's home or start page. You also want the custom browser to navigate only to HTML pages on the local domain or view files on the local hard disk. Here's how you could create this simple application:

  1. Use the Navigate2 method to go to the desired HTML page during form loading.
    Private Sub Form_Load()
    On Error Resume Next		'Don't stop execution, continue on next line
    WebBrowser.Navigate2 "http:\\www.xyzcorp.com"
    If Err.Number <> 0 Then MsgBox "Error :" & Err.Description	'Display error message
End Sub
  2. Check the URL in the BeforeNavigate2 event to make sure the location string contains the local domain or disk. If the location string doesn't meet the criteria, cancel the operation and display an error message to the user.
    Private Sub WebBrowser_BeforeNavigate2(ByVal URL As String, ByVal Flags As Long,
        ByVal TargetFrameName As String, PostData As Variant, ByVal Headers As String,
        Cancel As Boolean)
    If (Instr(1,URL,"xyzcorp.com") = 0) And (Instr(1,URL,"C:") = 0) Then
        Cancel = True
        MsgBox "Access denied to URL: " & URL
    End If
End Sub

Printing the Current Page with the WebBrowser Control

The WebBrowser control supports several common file operations—such as Print, Print Preview, Save, Save As, New, and Properties—with the QueryStatusWB and ExecWB methods. These methods directly access the IOleCommandTarget interface for issuing commands on the Active Document or inquiring about which commands it supports. The following example shows the implementation of a Print command button that, when clicked, checks to make sure the Print command is valid and then displays the print dialog box for the WebBrowser control.

Private Sub BtnPrint_Click()
    Dim eQuery As OLECMDF       'return value type for QueryStatusWB

    On Error Resume Next
    eQuery = WebBrowser1.QueryStatusWB(OLECMDID_PRINT)  'get print command status
    If Err.Number = 0 Then
            If eQuery And OLECMDF_ENABLED Then
                WebBrowser1.ExecWB OLECMDID_PRINT, OLECMDEXECOPT_PROMPTUSER, "", ""    'Ok to Print?
          Else
                MsgBox "The Print command is currently disabled."
            End If
    End If
    If Err.Number <> 0 Then MsgBox "Print command Error: " & Err.Description
End Sub

Capturing Events with the InternetExplorer Object

When using OLE Automation to control a separately running instance of an application, you will need to create a mechanism to respond to events triggered by that ActiveX object. To create this mechanism, commonly referred to as an event sink, use the following steps as a guideline.

  1. Create a Standard EXE project in Visual Basic version 5.0.
  2. Select References under the Project menu, and add a reference to the "Microsoft Internet Controls" by checking the appropriate box. If this library is not available, you should browse for the Shdocvw.dll file.
  3. Select Add Class Module under the Project menu.
  4. In the General Declarations section of the class module, add this line of code:
    Public WithEvents m_oWbSink As SHDocVw.InternetExplorer
  5. At this point, you can select the m_oWbSink object in the left-hand object drop-down menu of the code window. After selecting this object, the right-hand procedure drop-down window lists all of the events supported by this object. Select one of the events, and add the code to process the event. This example updates a text box on the form with the current browser status text.
    Private Sub m_oWbSink_StatusTextChange(ByVal Text As String)
    Form1.txtStatus.Text = Text
End Sub
  6. Add the necessary declarations in the "General Declarations" section of the form, as follows:
    'Global reference to an instance of the browser
Dim g_oIE As New SHDocVw.InternetExplorer
'Global reference to an instance of a class that can sink the browser's events
Dim g_oIESink As New Class1
  7. Now you can hook up the event sink to the instance of the browser by placing the following code in the form's "Form_Load" event:
    Set g_oIESink.m_oWbSink = g_oIE
  8. Finally, add any additional desired controls (buttons or text boxes, for example) and code to your project. Any events you need to use will be available in your newly created class module.

Note The preceding steps are unnecessary when using the WebBrowser object. Events are automatically trapped when you select the WebBrowser control in the Visual Basic toolbox and place it directly on a form.

Using the WebBrowser Control from C/C++

This section describes some of the common implementations of the WebBrowser control, including:

  • Adding Internet browsing functionality to your application
  • Printing Web pages with the WebBrowser control
  • Changing fonts with the WebBrowser control
  • Working with WebBrowser events

Adding Internet Browsing Functionality to Your Application

One of the most common uses for the WebBrowser control is to add Internet browsing functionality to your application. Using the IWebBrowser2 interface, you can browse to any location in the local file system, on the network, or on the World Wide Web. You can use the Navigate method to tell the control which location to browse to. The first parameter is a string that contains the name of the location. To browse to a location in the local file system or on the network, specify the full path to the file system location or the Universal Naming Convention (UNC) name of the location on the network. To browse to a site on the World Wide Web, specify the URL of the site. By including a text box in your application, you can let the user specify the location to browse to and then pass the location to the Navigate method.

In this example, the WebBrowser control was inserted into a basic Microsoft Foundation Class Library (MFC) application. A class was added to the project, and the control was dynamically created in the OnCreate handler of the application's View class.

CRect rect;
GetClientRect (&rect);

// Create the control.
m_pBrowser = new CWebBrowser;
ASSERT (m_pBrowser);
if (!m_pBrowser->Create(NULL,NULL,WS_VISIBLE,rect,this,NULL))
{
    TRACE("failed to create browser\n");
    delete m_pBrowser;
    m_pBrowser = NULL;
    return 0;
}

// Initialize the first URL.
COleVariant noArg;
m_pBrowser->Navigate("www.microsoft.com",&noArg,&noArg,&noArg,&noArg);
return 0;

In addition, the Navigate method allows you to target a specific frame on an HTML page, causing the WebBrowser control to display a Web site or file system location in that frame. First, you would call the Navigate method and specify the URL of an HTML page that contains a frame. Then, by specifying the name of the frame in subsequent calls to Navigate, you can direct the control to display subsequent locations within that frame.

You can also use the get_LocationName and get_LocationURL methods to retrieve information about the location that the WebBrowser control is currently displaying. If the location is an HTML page on the World Wide Web, get_LocationName retrieves the title of that page, and get_LocationURL retrieves the URL of that page. If the location is a folder or file on the network or local computer, get_LocationName and get_LocationURL both retrieve the UNC or full path of the folder or file.

Printing Pages with the WebBrowser Control

Although the WebBrowser control does not support a print method, you can print its contents using one of the following methods:

  • Set the focus to the WebBrowser control and send a key combination of CTRL+P.
  • Call the get_Document method, which returns an IDispatch pointer. Using this IDispatch pointer, call QueryInterface on IID_IOleCommandTarget. With the object pointer returned, call Exec (NULL, OLECMDID_PRINT, 0, NULL, NULL).
    LPDISPATCH lpDispatch = NULL;
LPOLECOMMANDTARGET lpOleCommandTarget = NULL;

lpDispatch = m_pBrowser.get_Document();
ASSERT(lpDispatch);

lpDispatch->QueryInterface(IID_IOleCommandTarget, (void**)&lpOleCommandTarget);
ASSERT(lpOleCommandTarget);

lpDispatch->Release();

// Print contents of WebBrowser control.
lpOleCommandTarget->Exec(NULL, OLECMDID_PRINT, 0, NULL,NULL);
lpOleCommandTarget->Release();

Changing Fonts with the WebBrowser Control

The WebBrowser automation model does not support a method that allows you to change the font of the text of the currently displayed page. However, the WebBrowser control exposes this functionality through the IOleCommandTarget interface. Call the get_Document method, which returns an IDispatch pointer. Using this IDispatch pointer, call QueryInterface on IID_IOleCommandTarget. With this IOleCommandTarget interface pointer, call Exec with OLECMDID_ZOOM and use the pvaIn input argument to pass a value in the range of 0 to 5 (where 0 is smallest) indicating the desired scale of the font. This, in effect, mimics the functionality available through the Internet Explorer Fonts command on the View menu.

LPDISPATCH pDisp = NULL;
LPOLECOMMANDTARGET pCmdTarg = NULL;

pDisp = m_pBrowser.get_Document();
ASSERT(pDisp);

pDisp->QueryInterface(IID_IOleCommandTarget, (LPVOID*)&pCmdTarg);
ASSERT(pCmdTarg);

VARIANT vaZoomFactor;   // input arguments
VariantInit(&vaZoomFactor);
V_VT(&vaZoomFactor) = VT_I4;
V_I4(&vaZoomFactor) = fontSize;

pCmdTarg->Exec(NULL,
        OLECMDID_ZOOM,
        OLECMDEXECOPT_DONTPROMPTUSER,
        &vaZoomFactor,
        NULL);
VariantClear(&vaZoomFactor);

if (pCmdTarg)
   pCmdTarg->Release(); // release document's command target
if (pDisp)
   pDisp->Release();    // release document's dispatch interface

Working with WebBrowser Events

The WebBrowser control fires a number of different events to notify an application of user- and browser-generated activity. The events are implemented using the DWebBrowserEvents2 interface. When the control is about to navigate to a new location, it fires a BeforeNavigate2 event that specifies the URL or path of the new location and any other data that will be transmitted to the Internet server through the HTTP transaction. The data can include the HTTP header, HTTP post data, and the URL of the referrer. BeforeNavigate2 also includes a cancel flag that you can set to FALSE to cancel the navigation. The WebBrowser control fires the NavigateComplete2 event after it has navigated to a new location. This event includes the same information as BeforeNavigate2, but NavigateComplete2 does not include the cancel flag.

When the WebBrowser control is about to begin a download operation, it fires the DownloadBegin event. The control fires a number of ProgressChange events as the operation progresses, and then it fires the DownloadComplete event after completing the operation. Applications typically use these three events to indicate the progress of the download operation, often by displaying a progress bar. An application would show the progress bar in response to DownloadBegin, update the progress bar in response to ProgressChange, and hide it in response to DownloadComplete.

When an application calls the Navigate method with the Flags parameter set to navOpenInNewWindow, the WebBrowser control fires the NewWindow2 event before navigating to the new location. The event includes information about the new location and a flag that indicates whether the application or the control is to create the new window. Set this flag to TRUE if your application will create the window or to FALSE if the WebBrowser control should create it.

You will need to implement an event sink to capture and handle the various events. The Internet Client SDK includes a generic event sink class called EVTSINK. For more information, refer to the \Samples\BaseCtl\Objvw subdirectory within your SDK.


BrowserNavConstants

typedef enum BrowserNavConstants {
    navOpenInNewWindow = 0x1,
    navNoHistory       = 0x2,
    navNoReadFromCache = 0x4,
    navNoWriteToCache  = 0x8
    navAllowAutosearch = 0x10,
    navBrowserBar      = 0x20
} BrowserNavConstants;

Contains values used by the IWebBrowser2::Navigate and IWebBrowser2::Navigate2 methods.

Values
navOpenInNewWindow | Open the resource or file in a new window.
navNoHistory | Do not add the resource or file to the history list. The new page replaces the current page in the list.
navNoReadFromCache | Not used.
navNoWriteToCache | Not used.
navAllowAutosearch | If the navigation fails, the autosearch functionality will attempt to navigate common root domains (.com, .edu, and so on). If this still fails, the URL will be passed to a search engine.
navBrowserBar | Causes the current Explorer Bar to navigate to the given item, if possible.

See also DWebBrowserEvents2::BeforeNavigate2, DWebBrowserEvents2::NavigateComplete2, DWebBrowserEvents2::NewWindow2


CommandStateChangeConstants

typedef enum CommandStateChangeConstants {
    CSC_UPDATECOMMANDS = 0xFFFFFFFF,
    CSC_NAVIGATEFORWARD = 0x00000001,
    CSC_NAVIGATEBACK = 0x00000002
} CommandStateChangeConstants;

Contains values used by the DWebBrowserEvents2::CommandStateChange event.

Values
CSC_UPDATECOMMANDS | The enabled state of a toolbar button might have changed.
CSC_NAVIGATEFORWARD | The enabled state of the Forward button has changed.
CSC_NAVIGATEBACK | The enabled state of the Back button has changed.


Enumerations Enumerations *
  * Previous Topic: DWebBrowserEvents2::TitleChange
  * Next Topic: BrowserNavConstants

Enumerations

This section defines enumerations used with the WebBrowser interfaces.


READYSTATE

typedef enum tagREADYSTATE{
    READYSTATE_UNINITIALIZED = 0,
    READYSTATE_LOADING = 1,
    READYSTATE_LOADED = 2,
    READYSTATE_INTERACTIVE = 3,
    READYSTATE_COMPLETE = 4
} READYSTATE;

Contains values that indicate what state an object is in. This is used with the ReadyState property and the IWebBrowser2::get_ReadyState method.

Values
READYSTATE_UNINITIALIZED | The default initialization state.
READYSTATE_LOADING | The object is currently loading its properties.
READYSTATE_LOADED | The object has been initialized.
READYSTATE_INTERACTIVE | The object is interactive, but not all of its data is available.
READYSTATE_COMPLETE | The object has received all of its data.


RefreshConstants

typedef enum RefreshConstants {
    REFRESH_NORMAL = 0,
    REFRESH_IFEXPIRED = 1,
    REFRESH_CONTINUE = 2,
    REFRESH_COMPLETELY = 3
} RefreshConstants;

Contains values used with the Refresh2 and IWebBrowser2::Refresh2 methods.

The "pragma:nocache" header tells the server not to return a cached copy but to ensure that the information is as fresh as possible. Browsers typically send this header when the user selects Refresh, but the header can cause problems for some servers.

Values
REFRESH_NORMAL | Perform a lightweight refresh that does not include sending the HTTP "pragma:nocache" header to the server.
REFRESH_IFEXPIRED | Perform a lightweight refresh if the page has expired.
REFRESH_CONTINUE | For internal use only; do not use.
REFRESH_COMPLETELY | Perform a full refresh that includes sending a "pragma:nocache" header to the server (HTTP URLs only).

See also Refresh, IWebBrowser2::Refresh


BeforeNavigate2 Event

Description

Occurs when the WebBrowser control is about to navigate to a different URL, which may happen as a result of external automation, internal automation from a script, or the user clicking a link or typing in the address bar. The container has an opportunity to cancel the pending navigation.

Syntax

Private Sub object_BeforeNavigate2(ByVal pDisp As Object, ByVal URL As String,
ByVal Flags As Long, ByVal TargetFrameName As String, PostData As Variant,
ByVal Headers As String, Cancel As Boolean)

Value | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
pDisp | An object that evaluates to the top-level or frame WebBrowser object corresponding to the navigation.
URL | A string expression that evaluates to the URL to which the browser is navigating.
Flags | Reserved for future use.
TargetFrameName | A string expression that evaluates to the name of the frame in which the resource will be displayed, or NULL if no named frame is targeted for the resource.
PostData | Data to send to the server if the HTTP POST transaction is being used.
Headers | A value that specifies the additional HTTP headers to send to the server (HTTP URLs only). The headers can specify things like the action required of the server, the type of data being passed to the server, or a status code.
Cancel | A Boolean value that the container can set to TRUE to cancel the navigation operation, or to FALSE to allow it to proceed.

Applies To

InternetExplorer, WebBrowser

See Also

Navigate, Navigate2, NavigateComplete2


CommandStateChange Event

Description

Occurs when the enabled state of a command changes.

Syntax

Private Sub object_CommandStateChange (ByVal Command As Long,
 ByVal Enable As Boolean)

Value | Description
object | An object expression that evaluates to an object in the Applies To list.
Command A long integer specifying the identifier of the command that changed. It can be one of the following constants or values.
Constant | Value | Meaning
CSC_UPDATECOMMANDS | -1 | The enabled state of a toolbar button may have changed; the Enable parameter should be ignored.
CSC_NAVIGATEFORWARD | 1 | The enabled state of the Forward button has changed.
CSC_NAVIGATEBACK | 3 | The enabled state of the Back button has changed.
Enable | A Boolean value that is TRUE if the command is enabled, or FALSE if not.

Applies To

InternetExplorer, WebBrowser


DocumentComplete Event

Description

Occurs when the document that is being navigated to reaches the READYSTATE_COMPLETE state.

Syntax

Private Sub object_DocumentComplete(ByVal pDisp As Object, URL As Variant)

Value | Description
object | An object expression that evaluates to an object in the Applies To list.
pDisp | An object that evaluates to the top-level or frame WebBrowser object corresponding to the event.
URL | A string expression that evaluates to the URL, UNC file name, or PIDL that was navigated to. Note that this URL can be different from the URL that the browser was told to navigate to. One reason is that this URL is the canonicalized and qualified URL; for example, if an application specified a URL of "www.microsoft.com" in a call to the Navigate or Navigate2 method, the URL passed by DocumentComplete will be "http://www.microsoft.com/". Also, if the server has redirected the browser to a different URL, the redirected URL will be reflected here.

Remarks

For a document without frames, this event will fire once when the document is finished loading. On a document containing multiple frames, this event is fired once for each frame. When the multiple-frame document has finished loading, the top-level frame fires the event one final time. To detect the last DocumentComplete event of a multiple-frame document, compare the pDisp object returned from the event to the WebBrowser object itself. The following example indicates how to trap the final DocumentComplete event.

Private Sub WebBrowser1_DocumentComplete(ByVal pDisp As Object, URL As Variant)
    If (pDisp Is WebBrowser1.Object) Then
        Debug.Print "Document is finished loading."
    End If
End Sub

Applies To

InternetExplorer, WebBrowser

See Also

BeforeNavigate2, Navigate, Navigate2, READYSTATE


DownloadBegin Event

Description

Occurs when a navigation operation is beginning. This event is fired shortly after the BeforeNavigate2 event, unless the navigation is canceled. Any animation or "busy" indication that the container needs to display should be connected to this event. Note that any DownloadBegin event will have a corresponding DownloadComplete event.

Syntax

Private Sub object_DownloadBegin

Value | Description
object | An object expression that evaluates to an object in the Applies To list.

Applies To

InternetExplorer, WebBrowser

See Also

Navigate, ProgressChange


DownloadComplete Event

Description

Occurs when a navigation operation finishes, is halted, or fails. Unlike NavigateComplete2, which is fired only when a URL is successfully navigated to, this event is always fired after a navigation starts. Any animation or "busy" indication that the container needs to display should be connected to this event. Note that any DownloadBegin event will have a corresponding DownloadComplete event.

Syntax

Private Sub object_DownloadComplete

Value | Description
object | An object expression that evaluates to an object in the Applies To list.

Applies To

InternetExplorer, WebBrowser

See Also

Navigate, Navigate2, ProgressChange


Events

This section describes the events associated with the WebBrowser control.

BeforeNavigate2 Event

CommandStateChange Event

DocumentComplete Event

DownloadBegin Event

DownloadComplete Event

NavigateComplete2 Event

NewWindow2 Event

OnFullScreen Event

OnMenuBar Event

OnQuit Event

OnStatusBar Event

OnTheaterMode Event

OnToolBar Event

OnVisible Event

ProgressChange Event

PropertyChange Event

StatusTextChange Event

TitleChange Event


NavigateComplete2 Event

Description

Occurs after the browser has successfully navigated to a new location. The document might still be downloading (and in the case of HTML, images may still be downloading), but at least part of the document has been received from the server, and the viewer for the document has been created.

Syntax

Private Sub object_NavigateComplete2(ByVal pDisp As Object, URL As Variant)

Value | Description
object | An object expression that evaluates to an object in the Applies To list.
pDisp | An object that evaluates to the top-level or frame WebBrowser object corresponding to the event.
URL | A string expression that evaluates to the URL, UNC file name, or PIDL that was navigated to. Note that this URL can be different from the URL that the browser was told to navigate to. One reason is that this URL is the canonicalized and qualified URL; for example, if an application specified a URL of "www.microsoft.com" in a call to the Navigate or Navigate2 method, the URL passed by NavigateComplete2 will be "http://www.microsoft.com/". Also, if the server has redirected the browser to a different URL, the redirected URL will be reflected here.

Applies To

InternetExplorer, WebBrowser

See Also

BeforeNavigate2


NewWindow2 Event

Description

Occurs when a new window is to be created for displaying a resource. Some actions that can cause this include the user shift-clicking on a link, the user right-clicking on a link and choosing "open in new window", or a targeted navigation to a frame name that does not yet exist. Your browser application can also trigger this event by calling the Navigate or Navigate2 method with the navOpenInNewWindow flag. The WebBrowser control has an opportunity to handle the new window creation itself. If it does not, a top-level Internet Explorer window is created as a separate (nonhosted) process.

Syntax

Private object_NewWindow2 (ByVal ppDisp As Object, ByVal Cancel As Boolean)

Value | Description
object | An object expression that evaluates to an object in the Applies To list.
ppDisp | An object expression that, optionally, receives a new, hidden WebBrowser or InternetExplorer object with no URL loaded.
Cancel | A Boolean value that, when set to TRUE, is used to cancel the new window creation and attempt the navigation in the current window.

Remarks

The application processing this notification can respond in one of three ways:

  1. Create a new, hidden, non-navigated WebBrowser or InternetExplorer object that is returned in ppDisp. Upon return from this event, the object that fired this event will then configure and navigate (including a BeforeNavigate2 event) the new object to the target location.
  2. Cancel the new window creation by setting Cancel to true. No object is created and the navigation is attempted on the current window (with an accompanying BeforeNavigate2 event).
  3. Do nothing and do not set ppDisp to any value. This will cause the object that fired the event to create a new InternetExplorer object to handle the navigation.

Applies To

InternetExplorer, WebBrowser

See Also

NavigateComplete2


OnFullScreen Event

Description

Occurs when the FullScreen property is changed.

Syntax

Private Sub object_OnFullScreen(ByVal FullScreen As Boolean)

Value | Description
object | An object expression that evaluates to an object in the Applies To list.
FullScreen | If TRUE, the browser window is maximized; if FALSE, it is not.

Remarks

An application hosting the WebBrowser control should respond to this event by enlarging or reducing the window size. When using scripting in an HTML page, this event corresponds to the size properties passed in the window.open method.

Applies To

InternetExplorer, WebBrowser


OnMenuBar Event

Description

Occurs when the MenuBar property is changed.

Syntax

Private Sub object_OnMenuBar(ByVal MenuBar As Boolean)

Value | Description
object | An object expression that evaluates to an object in the Applies To list.
MenuBar | If TRUE, the menu bar is shown; if FALSE, the menu bar is hidden.

Remarks

An application hosting the WebBrowser control should respond to this event by hiding or showing the menu bar, if applicable. When using scripting in an HTML page, this event corresponds to the menu bar property passed in the window.open method.

Applies To

InternetExplorer, WebBrowser


OnQuit Event

Description

Occurs before the Internet Explorer application quits.

Syntax

Private Sub object_OnQuit()

Value | Description
object | An object expression that evaluates to an object in the Applies To list.

Applies To

InternetExplorer

See Also

Quit


OnStatusBar Event

Description

Occurs when the StatusBar property is changed.

Syntax

Private Sub object_OnStatusBar(ByVal StatusBar As Boolean)

Value | Description
object | An object expression that evaluates to an object in the Applies To list.
StatusBar | If TRUE, the status bar is shown; if FALSE, the status bar is hidden.

Remarks

An application hosting the WebBrowser control should respond to this event by hiding or showing the status bar, if applicable.

Applies To

InternetExplorer, WebBrowser


OnTheaterMode Event

Description

Occurs when the TheaterMode property is changed.

Syntax

Private Sub object_OnTheaterMode(ByVal TheaterMode As Boolean)

Value | Description
object | An object expression that evaluates to an object in the Applies To list.
TheaterMode | If TRUE, the browser is in theater mode; if FALSE, the browser is in normal viewing mode. The default value is FALSE.

Remarks

Theater mode uses the entire screen to display the content.

Applies To

InternetExplorer, WebBrowser


OnToolBar Event

Description

Occurs when the ToolBar property is changed.

Syntax

Private Sub object_OnToolBar(ByVal ToolBar As Boolean)

Value | Description
object | An object expression that evaluates to an object in the Applies To list.
ToolBar | If TRUE, the toolbar is shown; if FALSE, the toolbar is hidden.

Remarks

An application hosting the WebBrowser control should respond to this event by hiding or showing the toolbar, if applicable. When using scripting in an HTML page, this event corresponds to the toolbar property passed in the window.open method.

Applies To

InternetExplorer, WebBrowser


OnVisible Event

Description

Occurs when the Visible property is changed.

Syntax

Private Sub object_OnVisible(ByVal Visible As Boolean)

Value | Description
object | An object expression that evaluates to an object in the Applies To list.
Visible | If TRUE, the WebBrowser window should be shown; if FALSE, the window should be hidden.

Applies To

InternetExplorer, WebBrowser


ProgressChange Event

Description

Occurs when the progress of a download operation is updated.

Syntax

Private Sub object_ProgressChange(ByVal Progress As Long, ByVal ProgressMax As Long)

Value | Description
object | An object expression that evaluates to an object in the Applies To list.
Progress | A long integer that specifies the amount of total progress to show, or -1 when progress is complete.
ProgressMax | A long integer that specifies the maximum progress value.

Remarks

The container can use the information provided by this event to display the number of bytes downloaded so far or to update a progress indicator.

To calculate the percentage of progress to show in a progress indicator, multiply the value of Progress by 100 and divide by the value of ProgressMax (unless Progress is -1, in which case the container can indicate that the operation is finished or hide the progress indicator).

Applies To

InternetExplorer, WebBrowser

See Also

DownloadBegin, DownloadComplete, Navigate


PropertyChange Event

Description

Occurs when the PutProperty method changes the value of a property.

Syntax

Private Sub object_PropertyChange(ByVal szProperty As String)

Value | Description
object | An object expression that evaluates to an object in the Applies To list.
szProperty | A string expression that contains the name of the property whose value has changed.

Applies To

InternetExplorer

See Also

GetProperty


StatusTextChange Event

Description

Occurs when the status bar text has changed.

Syntax

Private Sub object_StatusTextChange(ByVal Text As String)

Value | Description
object | An object expression that evaluates to an object in the Applies To list.
Text | A string containing the new status bar text.

Remarks

The container can use the information provided by this event to update the text of a status bar. When using scripting in an HTML page, this event corresponds to the status property passed in the window.open method.

Applies To

InternetExplorer, WebBrowser

See Also

StatusBar, StatusText


TitleChange Event

Description

Occurs when the title of a document in the WebBrowser control becomes available or changes. Because the title might change while an HTML page is downloading, the URL of the document is set as the title. After the title specified in the HTML page, if there is one, is parsed, the title is changed to reflect the actual title.

Syntax

Private Sub object_TitleChange(ByVal Text As String)

Value | Description
object | An object expression that evaluates to an object in the Applies To list.
Text | A string containing the new document title.

Applies To

InternetExplorer, WebBrowser


Events Events *
  * Previous Topic: IWebBrowser2::put_Width
  * Next Topic: DWebBrowserEvents2

Events

This section describes the event methods exposed by the DWebBrowserEvents2 interface.


Interface

This section describes the new IWebBrowser2 interface that replaces the IWebBrowser and IWebBrowserApp interfaces from previous releases.


DWebBrowserEvents2::BeforeNavigate2

void BeforeNavigate2(
    [in] IDispatch* pDisp,
    [in] VARIANT* URL,
    [in] VARIANT* Flags,
    [in] VARIANT* TargetFrameName,
    [in] VARIANT* PostData,
    [in] VARIANT* Headers,
    [out] VARIANT_BOOL* Cancel
);

Fires before a navigation occurs in the given WebBrowser (on either a window or frameset element).

  • No return value.
pDisp
Address of the frame's IDispatch interface.
URL
URL to be navigated to.
Flags
Reserved for future use.
TargetFrameName
String that contains the name of the frame in which to display the resource, or NULL if no named frame is targeted for the resource.
PostData
Address of data to send to the server if the HTTP POST transaction is being used.
Headers
Additional HTTP headers to send to the server (HTTP URLs only). The headers can specify things like the action required of the server, the type of data being passed to the server, or a status code.
Cancel
Address of a cancel flag. An application can set this parameter to TRUE to cancel the navigation operation, or to FALSE to allow it to proceed.

The pDisp parameter is that of the top-level or frame WebBrowser object corresponding to the navigation. The processing of this navigation can be modified by setting the Cancel parameter to TRUE and either ignoring or reissuing a modified navigation method to the WebBrowser object. The URL parameter can be a PIDL in the case of a shell namespace entity for which there is no URL representation.

The post data specified by PostData is passed as a SAFEARRAY structure. The variant should be of type VT_ARRAY and point to a SAFEARRAY. The SAFEARRAY should be of element type VT_UI1, dimension one, and have an element count equal to the number of bytes of post data.

This event replaces the BeforeNavigate and FrameBeforeNavigate events, which should no longer be used. Internet Explorer 4.0 will continue to fire the BeforeNavigate and FrameBeforeNavigate events for compatibility with Internet Explorer 3.0.

Providing the pDisp pointer of the corresponding WebBrowser object gives the host better information and control over the Internet Explorer 3.0 specification, which used FrameBeforeNavigate and a target frame name to identify the target of navigation (target frame names are not unique).

Applies To

WebBrowser, Internet Explorer

See also DWebBrowserEvents2::NavigateComplete2, IWebBrowser2::Navigate2


DWebBrowserEvents2::CommandStateChange

void CommandStateChange(
    [in] long Command,
    [in] VARIANT_BOOL Enable
);

Notifies an application that the enabled state of a WebBrowser command has changed.

  • No return value.
Command
Identifier of the command whose enabled state has changed.
Enable
Enabled state. This parameter is TRUE if the command is enabled, or FALSE if it is disabled.


DWebBrowserEvents2::DocumentComplete

void DocumentComplete(
    [in] IDispatch* pDisp,
    [in] Variant * URL
);

Notifies an application that a document has reached the READYSTATE_COMPLETE state.

  • Returns S_OK to indicate that the operation was successful.
pDisp
Address of the frame's IDispatch interface. In the case of a document that contains multiple frames, each frame will fire this event. The top-level frame will fire this event after each subframe is completed.
URL
String expression that evaluates to the URL, UNC file name, or PIDL that was navigated to. Note that this URL can be different from the URL that the browser was told to navigate to. One reason is that this URL is the canonicalized and qualified URL; for example, if an application specified a URL of "www.microsoft.com" in a call to the Navigate or Navigate2 method, the URL passed by DocumentComplete would be "http://www.microsoft.com/". Also, if the server has redirected the browser to a different URL, the redirected URL will be reflected here.

The URL parameter can be a PIDL in the case of a shell namespace entity for which there is no URL representation.

Not every frame will fire this event, but each frame that fires a DownloadBegin event will fire a corresponding DocumentComplete event.

Applies To

WebBrowser, Internet Explorer

See also READYSTATE


DWebBrowserEvents2::DownloadBegin

void DownloadBegin(void);

Notifies an application that a navigation operation is beginning.

  • No return value.

This event is fired shortly after the BeforeNavigate2 event, unless the navigation is canceled. Any animation or "busy" indication that the container needs to display should be connected to this event.

Each DownloadBegin event will have a corresponding DownloadComplete event.


DWebBrowserEvents2::DownloadComplete

void DownloadComplete(void);

Occurs when a navigation operation finishes, is halted, or fails.

  • No return value.

Unlike NavigateComplete2, which is fired only when a URL is successfully navigated to, this event is always fired after a navigation starts. Any animation or "busy" indication that the container needs to display should be connected to this event.

Each DownloadBegin event will have a corresponding DownloadComplete event.

See also DWebBrowserEvents2::DownloadBegin


DWebBrowserEvents2

DWebBrowserEvents2 designates an event sink interface that an application must implement in order to receive event notifications from a WebBrowser control or from the Internet Explorer application.

Methods in Vtable Order

DWebBrowserEvents2 methods | Description
StatusTextChange | Occurs when the status bar text has changed.
ProgressChange | Occurs when the progress of a download operation is updated.
CommandStateChange | Occurs when the enabled state of a command changes.
DownloadBegin | Occurs when a navigation operation is beginning, shortly after the BeforeNavigate2 event, unless the navigation is canceled.
DownloadComplete | Occurs when a navigation operation finishes, is halted, or fails.
TitleChange | Occurs when the title of a document in the WebBrowser control becomes available or changes.
PropertyChange | Occurs when the IWebBrowser2::PutProperty method changes the value of a property.
BeforeNavigate2 | Occurs when the WebBrowser control is about to navigate to a new URL.
NewWindow2 | Occurs when a new window is to be created for displaying a resource.
NavigateComplete2 | Occurs after the browser has successfully navigated to a new location.
DocumentComplete | Occurs when the document being navigated to is ready.
OnQuit | Occurs when the Internet Explorer application is ready to quit.
OnVisible | Occurs when the window for the WebBrowser should be shown/hidden.
OnToolBar | Occurs when the ToolBar property has changed.
OnMenuBar | Occurs when the MenuBar property has changed.
OnStatusBar | Occurs when the StatusBar property has changed.
OnFullScreen | Occurs when the FullScreen property has changed.
OnTheaterMode | Occurs when the TheaterMode property has changed.


DWebBrowserEvents2::NavigateComplete2

void NavigateComplete2(
    [in] IDispatch* pDisp,
    [in] Variant * URL
);

Fires after a navigation to a hyperlink is completed (on either a window or frameset element).

  • Returns S_OK to indicate that the operation was successful.
pDisp
Address of the frame's IDispatch interface.
URL
String expression that evaluates to the URL, UNC file name, or PIDL that was navigated to. Note that this URL can be different from the URL that the browser was told to navigate to. One reason is that this URL is the canonicalized and qualified URL; for example, if an application specified a URL of "www.microsoft.com" in a call to the Navigate or Navigate2 method, the URL passed by NavigateComplete2 would be "http://www.microsoft.com/". Also, if the server has redirected the browser to a different URL, the redirected URL will be reflected here.

The URL parameter can be a PIDL in the case of a shell namespace entity for which there is no URL representation.

This event replaces the NavigateComplete and FrameNavigateComplete events, which should no longer be used. Internet Explorer 4.0 continues to fire the NavigateComplete and FrameNavigateComplete events for compatibility with Internet Explorer 3.0.

Applies To

WebBrowser, Internet Explorer


DWebBrowserEvents2::NewWindow2

void NewWindow2(
    [out] IDispatch** ppDisp,
    [out] VARIANT_BOOL * Cancel
);

Occurs when a new window is to be created for displaying a resource. This event precedes the creation of a new window from within the WebBrowser (for example, in response to a navigation targeted to a new window, or to a scripted window.open method).

ppDisp
Address of an interface pointer that, optionally, receives the IDispatch interface pointer of a new WebBrowser or InternetExplorer object.
Cancel
Address of a cancel flag. An application can set this parameter to TRUE to cancel the navigation operation, or to FALSE to allow it to proceed.

The application processing this notification can respond in one of three ways:

  1. Create a new, hidden, non-navigated WebBrowser or InternetExplorer object that is returned in ppDisp. Upon return from this event, the object that fired this event will then configure and navigate (including a BeforeNavigate2 event) the new object to the target location.
  2. Cancel the new window creation by setting Cancel to TRUE. No object is created and the navigation is attempted on the current window (with an accompanying BeforeNavigate2 event).
  3. Do nothing and do not set ppDisp to any value. This will cause the object that fired the event to create a new InternetExplorer object to handle the navigation.

Applies To

WebBrowser, Internet Explorer


DWebBrowserEvents2::OnFullScreen

void OnFullScreen(
    [in] VARIANT_BOOL FullScreen
);

Occurs when the FullScreen property has changed.

FullScreen
Nonzero if Internet Explorer is in full-screen mode, or zero otherwise.

Applies To

Internet Explorer


DWebBrowserEvents2::OnMenuBar

void OnMenuBar(
    [in] VARIANT_BOOL MenuBar
);

Occurs when the MenuBar property is changed.

MenuBar
Nonzero if Internet Explorer's menu bar is visible, or zero otherwise.

Applies To

Internet Explorer


DWebBrowserEvents2::OnQuit DWebBrowserEvents2::OnQuit *
  * Previous Topic: DWebBrowserEvents2::OnMenuBar
  * Next Topic: DWebBrowserEvents2::OnStatusBar

DWebBrowserEvents2::OnQuit

void OnQuit(void);

Notifies an application that the Internet Explorer application is ready to quit.

Applies To

Internet Explorer


DWebBrowserEvents2::OnStatusBar

void OnStatusBar(
    [in] VARIANT_BOOL StatusBar
);

Occurs when the StatusBar property is changed.

StatusBar
Nonzero if Internet Explorer's status bar is visible, or zero otherwise.

Applies To

Internet Explorer


DWebBrowserEvents2::OnTheaterMode

void OnTheaterMode(
    [in] VARIANT_BOOL TheaterMode
);

Occurs when the TheaterMode property is changed.

TheaterMode
Nonzero if Internet Explorer is in theater mode, or zero otherwise.

Applies To

Internet Explorer


DWebBrowserEvents2::OnToolBar

void OnToolBar(
    [in] VARIANT_BOOL ToolBar
);

Occurs when the ToolBar property is changed.

ToolBar
Nonzero if Internet Explorer's toolbar is visible, or zero otherwise.

Applies To

Internet Explorer


DWebBrowserEvents2::OnVisible

void OnVisible(
    [in] VARIANT_BOOL Visible
);

Occurs when the window for the WebBrowser should be shown/hidden. This allows the host window to behave the same way the Internet Explorer window would.

Visible
Nonzero if the object is visible, or zero otherwise.

Applies To

WebBrowser, Internet Explorer


DWebBrowserEvents2::ProgressChange

void ProgressChange(
    [in] long Progress,
    [in] long ProgressMax
);

Notifies an application that the progress of a download operation has been updated.

  • No return value.
Progress
Amount of total progress to show, or -1 when progress is complete.
ProgressMax
Maximum progress value.

The container can use the information provided by this event to display the number of bytes downloaded so far or to update a progress indicator.

To calculate the percentage of progress to show in a progress indicator, multiply the value of Progress by 100 and divide by the value of ProgressMax (unless Progress is -1, in which case the container can indicate that the operation is finished or hide the progress indicator).

See also DWebBrowserEvents2::DownloadBegin, DWebBrowserEvents2::DownloadComplete


DWebBrowserEvents2::PropertyChange

void PropertyChange(
    BSTR szProperty,
);

Notifies an application that the PutProperty method has changed the value of a property.

  • No return value.
szProperty
Caller-allocated buffer that contains the name of the property.

See also IWebBrowser2::GetProperty, IWebBrowser2::PutProperty


DWebBrowserEvents2::StatusTextChange

void StatusTextChange(
    [in] BSTR bstrText
);

Notifies an application that the text of the status bar associated with the WebBrowser control has changed.

  • No return value.
bstrText
String that contains the new status bar text.


DWebBrowserEvents2::TitleChange

void TitleChange(
    [in] BSTR Text
);

Notifies an application if the title of a document in the WebBrowser control becomes available or changes.

  • No return value.
Text
Caller-allocated buffer that contains the new document title.

Because the title might change while an HTML page is downloading, the URL of the document is set as the title. After the title specified in the HTML page, if there is one, is parsed, the title is changed to reflect the actual title.

See also DWebBrowserEvents2::CommandStateChange, DWebBrowserEvents2::StatusTextChange


IWebBrowser2::ClientToWindow

HRESULT ClientToWindow(
    int FAR* pcx,
    int FAR* pcy
);

Converts the client coordinates of a point to window coordinates. Client coordinates are relative to the upper-left corner of the client area; window coordinates are relative to the upper-left corner of a window.

  • Returns S_OK to indicate that the operation was successful.
pcx
The x-coordinate of the point to convert, in client coordinates. When ClientToWindow returns, this variable contains the x-coordinate of the point in window coordinates.
pcy
The y-coordinate of the point to convert, in client coordinates. When ClientToWindow returns, this variable contains the y-coordinate of the point in window coordinates.

Applies To

Internet Explorer


IWebBrowser2::ExecWB

HRESULT ExecWB(
    [in] OLECMDID cmdID,
    [in] OLECMDEXECOPT cmdexecopt,
    [in] VARIANT * pvaIn,
    [out, in] VARIANT * pvaOut)

Implements a wrapper that allows you to execute a command on an OLE object using the IOleCommandTarget::Exec method.

cmdID
OLECMDID value that specifies the command to execute.
cmdexecopt
OLECMDEXECOPT value that specifies the command options.
pvaIn
Address of a VARIANT structure that specifies command input arguments. This argument may be NULL.
pvaOut
Address of a VARIANT structure that receives command output. This argument may be NULL.

Applies To

WebBrowser, Internet Explorer

See also IWebBrowser2::QueryStatusWB


IWebBrowser2::get_AddressBar

HRESULT get_AddressBar(
    VARIANT_BOOL FAR* pValue
);

Determines if the Internet Explorer object's address bar is visible.

  • Returns S_OK if successful, or an OLE-defined error code otherwise.
pValue
Address of a variable that receives a nonzero value if the address bar is visible, or zero if it is not visible.

Applies To

Internet Explorer

See also IWebBrowser2::put_AddressBar


IWebBrowser2::get_Application

HRESULT get_Application(
    IDispatch * FAR* ppDisp
);

Retrieves the automation interface supported by the Internet Explorer application.

  • Returns S_OK if successful, or E_NOINTERFACE if the interface is not supported.
ppDisp
Address of a variable that receives the pointer to the application's IDispatch interface.

Applies To

WebBrowser, Internet Explorer

See also IWebBrowser2::get_Container, IWebBrowser2::get_Document, IWebBrowser2::get_Parent


IWebBrowser2::get_Busy

HRESULT get_Busy(
    VARIANT_BOOL FAR* pBool
);

Discovers whether Internet Explorer is engaged in a downloading operation or other activity.

  • Returns S_OK if successful, or an OLE-defined error code otherwise.
pBool
Address of a variable that receives TRUE if Internet Explorer is busy, or FALSE if not.

Applies To

WebBrowser, Internet Explorer


IWebBrowser2::get_Container

HRESULT get_Container(
    IDispatch * FAR* ppDisp
);

Retrieves a pointer to the IDispatch interface of the container.

  • Returns one of these values:
    S_OK | The operation was successful.
    E_FAIL | The operation failed.
    E_NOINTERFACE | The interface is not supported.
ppDisp
Address of a variable that receives the pointer to the container's IDispatch interface.

Applies To

WebBrowser, Internet Explorer

See also IWebBrowser2::get_Application, IWebBrowser2::get_Document, IWebBrowser2::get_Parent


IWebBrowser2::get_Document

HRESULT get_Document(
    IDispatch * FAR* ppDisp
);

Retrieves a pointer to the IDispatch interface of the Active Document object.

  • Returns one of these values:
    S_OK | The operation was successful.
    E_FAIL | The operation failed.
    E_INVALIDARG | One or more parameters are invalid.
    E_NOINTERFACE | The interface is not supported.
ppDisp
Address of a variable that receives the pointer to the object's IDispatch interface.

Applies To

WebBrowser, Internet Explorer

See also IWebBrowser2::get_Application, IWebBrowser2::get_Container, IWebBrowser2::get_Parent


IWebBrowser2::get_FullName

HRESULT get_FullName(
    BSTR FAR* pbstrFullName
);

Retrieves the fully qualified path of the Internet Explorer executable file.

  • Returns one of these values:
    S_OK | The operation was successful.
    E_FAIL | The operation failed.
    E_OUTOFMEMORY | Out of memory.
pbstrFullName
Address of a callee-allocated buffer that receives the path of the executable file. The caller frees this buffer with the SysFreeString API.

Applies To

Internet Explorer, WebBrowser


IWebBrowser2::get_FullScreen

HRESULT get_FullScreen(
    VARIANT_BOOL FAR* pbFullScreen
);

Determines if Internet Explorer is in full-screen or normal window mode.

  • Returns S_OK if successful, or an OLE-defined error code otherwise.
pbFullScreen
Address of a variable that receives TRUE if Internet Explorer is in full-screen mode, or FALSE if it is in normal window mode.

In full-screen mode, the Internet Explorer main window is maximized and the status bar, toolbar, menu bar, and title bar are hidden.

Applies To

WebBrowser, Internet Explorer

See also IWebBrowser2::put_FullScreen


IWebBrowser2::get_Height

HRESULT get_Height(
    long FAR* pl
);

Retrieves the height of the Internet Explorer main window.

  • Returns S_OK to indicate that the operation was successful.
pl
Address of a variable that receives the height, in pixels, of the main window.

Applies To

WebBrowser, Internet Explorer

See also IWebBrowser2::get_Width, IWebBrowser2::put_Height


IWebBrowser2::get_HWND

HRESULT get_HWND(
    long FAR* pHWND
);

Retrieves the handle to the Internet Explorer main window.

  • Returns S_OK to indicate that the operation was successful.
pHWND
Address of a variable that receives the window handle.

Applies To

Internet Explorer


IWebBrowser2::get_Left

HRESULT get_Left(
    long FAR* pl
);

Retrieves the screen coordinate of the left edge of the Internet Explorer main window.

  • Returns S_OK to indicate that the operation was successful.
pl
Address of a variable that receives the screen coordinate of the main window's left edge.

Applies To

WebBrowser, Internet Explorer

See also IWebBrowser2::get_Top, IWebBrowser2::put_Left


IWebBrowser2::get_LocationName

HRESULT get_LocationName(
    BSTR FAR* pbstrLocationName
);

Retrieves the name of the resource that Internet Explorer is currently displaying.

  • Returns S_OK if the operation was successful.
pbstrLocationName
Address of a callee-allocated buffer that receives the name of the location. The caller frees this buffer with the SysFreeString API.

If the resource is an HTML page on the World Wide Web, the name is the title of that page. If the resource is a folder or file on the network or local computer, the name is the UNC or full path of the folder or file.

Applies To

Internet Explorer, WebBrowser

See also IWebBrowser2::get_LocationURL


IWebBrowser2::get_LocationURL

HRESULT get_LocationURL(
    BSTR FAR* pbstrLocationURL
);

Retrieves the URL of the resource that Internet Explorer is currently displaying.

  • Returns S_OK if the operation was successful.
pbstrLocationURL
Address of a callee-allocated buffer that receives the URL. The caller frees this buffer with the SysFreeString API.

If the resource is a folder or file on the network or local computer, the name is the UNC or full path of the folder or file.

Applies To

Internet Explorer, WebBrowser

See also IWebBrowser2::get_LocationName


IWebBrowser2::get_MenuBar

HRESULT get_MenuBar(
    VARIANT_BOOL FAR* Value
);

Returns a value that indicates whether the Internet Explorer menu bar is visible.

  • Returns S_OK if successful, or an OLE-defined error code otherwise.
Value
Address of a variable that receives TRUE if the menu bar is visible, or FALSE if it is not.

Applies To

WebBrowser, Internet Explorer

See also IWebBrowser2::put_MenuBar


IWebBrowser2::get_Name

HRESULT get_Name(
    BSTR FAR* pbstrName
);

Retrieves the name of the object that contains the WebBrowser control used by Internet Explorer.

  • Returns S_OK if the operation was successful.
pbstrName
Address of a callee-allocated buffer that receives the name of the object that contains the WebBrowser control. The caller frees this buffer with the SysFreeString API.

Applies To

Internet Explorer


IWebBrowser2::get_Offline

HRESULT get_Offline(
    VARIANT_BOOL FAR* pbOffline
);

Returns a value indicating whether the WebBrowser control is currently operating in offline mode. In offline mode, the browser is forced to read HTML pages from the local cache rather than from the source document.

  • Returns S_OK if successful, or an OLE-defined error code otherwise.
pbOffline
Address of a variable that receives TRUE if WebBrowser is offline, or FALSE if not.

Applies To

WebBrowser, Internet Explorer


IWebBrowser2::get_Parent

HRESULT get_Parent(
    IDispatch * FAR* ppDisp
);

Retrieves a pointer to the IDispatch interface of the object that is the container of the WebBrowser control.

  • Returns one of these values:
    S_OK | The operation was successful.
    E_FAIL | The operation failed.
    E_NOINTERFACE | The interface is not supported.
ppDisp
Address of a variable that receives the pointer to the container's IDispatch interface.

Applies To

WebBrowser, Internet Explorer

See also IWebBrowser2::get_Application, IWebBrowser2::get_Container, IWebBrowser2::get_Document


IWebBrowser2::get_Path

HRESULT get_Path(
    BSTR FAR* pbstrPath
);

Retrieves the full path of the Internet Explorer application.

  • Returns one of these values:
    S_OK | The operation was successful.
    E_FAIL | The operation failed.
    E_OUTOFMEMORY | Out of memory.
pbstrPath
Address of a callee-allocated buffer that receives the full path. The caller frees this buffer with the SysFreeString API.

Applies To

Internet Explorer


IWebBrowser2::get_ReadyState

HRESULT get_ReadyState(
    [retval, out] long *plReadyState
);

Retrieves the ready state of the object.

  • Returns S_OK if successful, or an OLE-defined error code otherwise.
plReadyState
Address of a long variable that receives the ReadyState property. This will be one of the READYSTATE values.

Applies To

WebBrowser, Internet Explorer


IWebBrowser2::get_RegisterAsBrowser

HRESULT get_RegisterAsBrowser(
    VARIANT_BOOL FAR* pbRegister
);

Returns a value indicating whether the WebBrowser control is registered as a top-level browser for target name resolution.

  • Returns S_OK if successful, or an OLE-defined error code otherwise.
pbRegister
Boolean expression that determines whether the object is registered as a top-level browser. If TRUE, the WebBrowser is registered as a top-level browser; if FALSE, it is not a top-level browser. The default value is FALSE.

Applies To

WebBrowser, Internet Explorer


IWebBrowser2::get_RegisterAsDropTarget

HRESULT get_RegisterAsDropTarget(
    VARIANT_BOOL FAR* pbRegister
);

Returns a value indicating whether the WebBrowser control is registered as a drop target for navigation.

  • Returns S_OK if successful, or an OLE-defined error code otherwise.
pbRegister
Optional. A Boolean expression that determines whether the object is registered as a drop target for navigation. If TRUE, the object is registered as a drop target; if FALSE, it is not a drop target. The default value is FALSE.

Applies To

WebBrowser, Internet Explorer


IWebBrowser2::get_Resizable

HRESULT get_Resizable(
    VARIANT_BOOL FAR* pValue
);

Retrieves the Internet Explorer object's resizable property.

  • Returns S_OK if successful, or an OLE-defined error code otherwise.
pValue
Address of a variable that receives a nonzero value if the object is resizable or zero if it is not resizable.

Applies To

Internet Explorer

See also IWebBrowser2::put_Resizable


IWebBrowser2::get_Silent

HRESULT get_Silent(
    VARIANT_BOOL FAR* pbSilent
);

Returns a value indicating whether any dialog boxes can be shown.

  • Returns S_OK if successful, or an OLE-defined error code otherwise.
pbSilent
Optional. A Boolean expression that determines whether the WebBrowser can show any dialog boxes. If TRUE, dialog boxes will not be displayed; if FALSE, dialog boxes will be displayed. The default value is FALSE.

Applies To

WebBrowser, Internet Explorer


IWebBrowser2::get_StatusBar

HRESULT get_StatusBar(
    VARIANT_BOOL FAR* pBool
);

Returns a value that indicates whether the Internet Explorer status bar is visible.

  • Returns S_OK if successful, or an OLE-defined error code otherwise.
pBool
Address of a variable that receives TRUE if the status bar is visible, or FALSE if it is not.

Applies To

Internet Explorer

See also IWebBrowser2::put_StatusBar


IWebBrowser2::get_StatusText

HRESULT get_StatusText(
    BSTR FAR* pbstr
);

Retrieves the text of the Internet Explorer status bar.

  • Returns S_OK if successful, or an OLE-defined error code otherwise.
pbstr
Address of a callee-allocated buffer that receives the text of the status bar. The caller frees this buffer with the SysFreeString API.

Applies To

Internet Explorer

See also IWebBrowser2::put_StatusText


IWebBrowser2::get_TheaterMode

HRESULT get_TheaterMode(
    VARIANT_BOOL FAR* pbTheaterMode
);

Retrieves a value indicating whether the WebBrowser control is in theater mode.

  • Returns S_OK if successful, or an OLE-defined error code otherwise.
pbTheaterMode
Optional. A Boolean value that receives the TheaterMode property. If this value is nonzero, the WebBrowser is in theater mode. If this value is zero, the WebBrowser is not in theater mode. The default value is zero.

Applies To

WebBrowser, Internet Explorer


IWebBrowser2::get_ToolBar

HRESULT get_ToolBar(
    int FAR* pValue
);

Retrieves a value that indicates whether the Internet Explorer toolbar is visible.

  • Returns S_OK if successful, or an OLE-defined error code otherwise.
pValue
Address of a variable that receives TRUE if the toolbar is visible, or FALSE if it is not.

Applies To

WebBrowser, Internet Explorer

See also IWebBrowser2::put_ToolBar


IWebBrowser2::get_Top

HRESULT get_Top(
    long FAR* pl
);

Retrieves the screen coordinate of the top edge of the Internet Explorer main window.

  • Returns S_OK to indicate that the operation was successful.
pl
Address of a variable that receives the screen coordinate of the main window's top edge.

Applies To

WebBrowser, Internet Explorer

See also IWebBrowser2::get_Left, IWebBrowser2::put_Top


IWebBrowser2::get_TopLevelContainer

HRESULT get_TopLevelContainer(
    VARIANT_BOOL FAR* pBool
);

Determines if Internet Explorer is the top-level container of the WebBrowser control.

  • Returns S_OK to indicate that the operation was successful.
pBool
Address of a variable that receives TRUE if the container is a top-level container, or FALSE otherwise.

Applies To

WebBrowser, Internet Explorer


IWebBrowser2::get_Type

HRESULT get_Type(
    BSTR FAR* pbstrType
);

Retrieves the type name of the contained document object.

  • Returns one of these values:
    S_OK | The operation was successful.
    E_FAIL | The operation failed.
    E_OUTOFMEMORY | Out of memory.
pbstrType
Address of a callee-allocated buffer that receives the type name. The caller frees this buffer with the SysFreeString API.

Applies To

Internet Explorer, WebBrowser


IWebBrowser2::get_Visible

HRESULT get_Visible(
    VARIANT_BOOL FAR* pBool
);

Determines whether the object is visible or hidden.

  • Returns S_OK to indicate that the operation was successful.
pBool
Address of a variable that receives TRUE if the object is visible, or FALSE if it is hidden.

Applies To

Internet Explorer, WebBrowser

See also IWebBrowser2::put_Visible


IWebBrowser2::get_Width

HRESULT get_Width(
    long FAR* pl
);

Retrieves the width of the Internet Explorer main window.

  • Returns S_OK to indicate that the operation was successful.
pl
Address of a variable that receives the width, in pixels, of the main window.

Applies To

Internet Explorer

See also IWebBrowser2::get_Height, IWebBrowser2::put_Width


IWebBrowser2::GetProperty

HRESULT GetProperty(
    BSTR szProperty,
    VARIANT FAR* pvtValue
);

Retrieves the value of a property associated with the given object.

  • Returns S_OK if the operation is successful, or E_INVALIDARG if one or more parameters are invalid.
szProperty
Caller-allocated buffer that contains the name of the property to retrieve.
pvtValue
Address of a variable that receives the value associated with the given property.

Applies To

Internet Explorer

See also IWebBrowser2::PutProperty


IWebBrowser2::GoBack

HRESULT GoBack(void);

Navigates backward one item in the history list.

  • Returns S_OK to indicate that the operation was successful.

Applies To

WebBrowser, Internet Explorer

See also IWebBrowser2::GoForward, IWebBrowser2::GoHome, IWebBrowser2::GoSearch


IWebBrowser2::GoForward

HRESULT GoForward(void);

Navigates forward one item in the history list.

  • Returns S_OK to indicate that the operation was successful.

Applies To

WebBrowser, Internet Explorer

See also IWebBrowser2::GoBack, IWebBrowser2::GoHome, IWebBrowser2::GoSearch


IWebBrowser2::GoHome

HRESULT GoHome(void);

Navigates to the current home or start page, as specified in the Internet Explorer Options dialog box and Internet Control Panel.

  • Returns S_OK to indicate that the operation was successful.

Applies To

WebBrowser, Internet Explorer

See also IWebBrowser2::GoBack, IWebBrowser2::GoForward, IWebBrowser2::GoSearch


IWebBrowser2::GoSearch

HRESULT GoSearch(void);

Navigates to the current search page, as specified in the Internet Explorer Options dialog box and Internet Control Panel.

  • Returns S_OK to indicate that the operation was successful.

Applies To

WebBrowser, Internet Explorer

See also IWebBrowser2::GoBack, IWebBrowser2::GoForward, IWebBrowser2::GoHome


IWebBrowser2

IWebBrowser2 designates an interface that allows applications to implement an instance of the WebBrowser control in an application (ActiveX Control) or control an instance of the Internet Explorer application (OLE Automation). For methods applicable to the Internet Explorer object only, the description section in the following table uses the "Internet Explorer only" notation, and throughout the reference sections the "Applies To" heading also indicates which object (WebBrowser or Internet Explorer) that method applies to. The Exdisp.h file defines all the WebBrowser interfaces as well as the GUIDs (globally unique identifiers).

Methods in Vtable Order

IWebBrowser2 methods | Description
GoBack | Navigates to the previous item in the history list.
GoForward | Navigates to the next item in the history list.
GoHome | Navigates to the current home or start page.
GoSearch | Navigates to the current search page.
Navigate | Navigates to a resource identified by a Universal Resource Locator (URL).
Refresh | Reloads the current file.
Refresh2 | Reloads the current file and optionally prevents the "pragma:nocache" header from being sent.
Stop | Stops opening a file.
get_Application | Returns an application object representing the application that contains the current instance of the Internet Explorer application.
get_Parent | Returns the automation object.
get_Container | Returns the container of the WebBrowser control.
get_Document | Returns the active document.
get_TopLevelContainer | Returns a value indicating whether the current object is the top-level container of the WebBrowser control.
get_Type | Returns the type name of the document object.
get_Left | Returns the screen coordinate of the left edge of the Internet Explorer main window.
put_Left | Sets the horizontal position of the Internet Explorer main window.
get_Top | Returns the screen coordinate of the top edge of the Internet Explorer main window.
put_Top | Sets the vertical position of the Internet Explorer main window.
get_Width | Returns the width of the Internet Explorer main window.
put_Width | Sets the width of the Internet Explorer main window.
get_Height | Returns the height of the Internet Explorer main window.
put_Height | Sets the height of the Internet Explorer main window.
get_LocationName | Returns the name of the resource that WebBrowser is currently displaying.
get_LocationURL | Returns the URL of the resource that WebBrowser is currently displaying.
get_Busy | Returns a value indicating whether a download or other activity is still in progress.
Quit | Closes the Internet Explorer application. (Internet Explorer only)
ClientToWindow | Converts the client coordinates of a point to window coordinates. (Internet Explorer only)
PutProperty | Sets the value of a property associated with the given object. (Internet Explorer only)
GetProperty | Retrieves the current value of a property associated with the given object. (Internet Explorer only)
get_Name | Returns the name of the object that contains the WebBrowser control used by Internet Explorer. (Internet Explorer only)
get_HWND | Returns the window handle to the Internet Explorer main window. (Internet Explorer only)
get_FullName | Returns the full path of the file that Internet Explorer is currently displaying. (Internet Explorer only)
get_Path | Returns a string that evaluates to the full path of the resource that Internet Explorer is currently displaying. (Internet Explorer only)
get_Visible | Returns a value indicating whether the object is visible or hidden.
put_Visible | Sets a value indicating whether the object is visible or hidden.
get_StatusBar | Returns a value that indicates whether the status bar is visible.
put_StatusBar | Sets a value that determines whether the status bar is visible.
get_StatusText | Returns the text of the status bar.
put_StatusText | Sets the text for the status bar.
get_ToolBar | Returns a value that indicates whether the toolbar is visible.
put_ToolBar | Sets a value that determines whether the toolbar is visible.
get_MenuBar | Returns a value that indicates whether the menu bar is visible.
put_MenuBar | Sets a value that determines whether the menu bar is visible.
get_FullScreen | Returns a value indicating whether Internet Explorer is in full-screen or normal window mode.
put_FullScreen | Sets a value that determines whether Internet Explorer is in full-screen or normal window mode.
Navigate2 | Navigates to a resource identified by a pointer to an item identifier list (PIDL).
QueryStatusWB | Queries the object for status of commands.
ExecWB | Executes a command.
ShowBrowserBar | Shows or hides a specified browser bar.
get_ReadyState | Returns a standard OLE ReadyState bindable property for the WebBrowser control.
get_Offline | Returns a value that determines whether the control is offline.
put_Offline | Sets a value that determines whether the control is offline.
get_Silent | Returns a value indicating whether any dialog boxes can be shown.
put_Silent | Sets a value indicating whether any dialog boxes can be shown.
get_RegisterAsBrowser | Returns a value indicating whether the WebBrowser control is registered as a top-level browser for target name resolution.
put_RegisterAsBrowser | Sets a value indicating whether the WebBrowser control is registered as a top-level browser for target name resolution.
get_RegisterAsDropTarget | Returns a value indicating whether the WebBrowser control is registered as a drop target for navigation.
put_RegisterAsDropTarget | Sets a value indicating whether the WebBrowser control is registered as a drop target for navigation.
get_TheaterMode | Retrieves a value indicating whether the WebBrowser control is in theater mode.
put_TheaterMode | Sets a value indicating whether the WebBrowser control is in theater mode.
get_AddressBar | Determines if the Internet Explorer object's address bar is visible.
put_AddressBar | Shows or hides the Internet Explorer object's address bar.
get_Resizable | Retrieves the Internet Explorer object's resizable property.
put_Resizable | Sets the Internet Explorer object's resizable property.


IWebBrowser2::Navigate

HRESULT IWebBrowser2::Navigate(
    BSTR URL,
    VARIANT FAR* Flags,
    VARIANT FAR* TargetFrameName,
    VARIANT FAR* PostData,
    VARIANT FAR* Headers,
);

Navigates to a resource identified by a Uniform Resource Locator (URL) or to the file identified by a full path.

  • Returns one of these values:
    S_OK | The operation was successful.
    E_INVALIDARG | One or more parameters are invalid.
    E_OUTOFMEMORY | Out of memory.
URL
A caller-allocated string that contains the URL to navigate to or the full path of the file to display.
Flags
Address of a variable that specifies whether to add the resource to the history list, whether to read to or write from the cache, and whether to display the resource in a new window. The variable can be a combination of the values defined by the BrowserNavConstants enumeration.
TargetFrameName
Address of a string that contains the name of the frame in which to display the resource.
PostData
Address of data to send with the HTTP POST transaction. For example, the POST transaction is used to send data gathered by an HTML form. If this parameter does not specify any post data, Navigate issues an HTTP GET transaction. This parameter is ignored if URL is not an HTTP URL.
Headers
Address of a value that specifies the HTTP headers to send to the server. These headers are added to the default Internet Explorer headers. The headers can specify things like the action required of the server, the type of data being passed to the server, or a status code. This parameter is ignored if URL is not an HTTP URL.

The post data specified by PostData is passed as a SAFEARRAY structure. The variant should be of type VT_ARRAY and point to a SAFEARRAY. The SAFEARRAY should be of element type VT_UI1, dimension one, and have an element count equal to the number of bytes of post data.

Applies To

WebBrowser, Internet Explorer

See also DWebBrowserEvents2::BeforeNavigate2, DWebBrowserEvents2::NavigateComplete2


IWebBrowser2::Navigate2

HRESULT Navigate2(
    [in] VARIANT * URL,
    [in, optional] VARIANT * Flags,
    [in, optional] VARIANT * TargetFrameName,
    [in, optional] VARIANT * PostData,
    [in, optional] VARIANT * Headers,
);

Navigates the browser to a location that may not be able to be expressed as a URL, such as a pointer to an item identifier list (PIDL) for an entity in the Windows shell namespace.

  • Returns one of these values:
    S_OK | The operation was successful.
    E_INVALIDARG | One or more parameters are invalid.
    E_OUTOFMEMORY | Out of memory.
URL
A caller-allocated string that contains the URL to navigate to or the full path of the file to display.
Flags
Address of a variable that specifies whether to add the resource to the history list, whether to read to or write from the cache, and whether to display the resource in a new window. The variable can be a combination of the values defined by the BrowserNavConstants enumeration.
TargetFrameName
Address of a string that contains the name of the frame in which to display the resource.
PostData
Address of data to send with the HTTP POST transaction. For example, the POST transaction is used to send data gathered by an HTML form. If this parameter does not specify any post data, the Navigate2 method issues an HTTP GET transaction. This parameter is ignored if URL is not an HTTP URL.
Headers
Address of a value that specifies the HTTP headers to send to the server. These headers are added to the default Internet Explorer headers. The headers can specify things like the action required of the server, the type of data being passed to the server, or a status code. This parameter is ignored if URL is not an HTTP URL.

This method extends the Navigate method to allow for shell integration; however, the original Navigate method can still be used for URL navigations (Navigate2 does not make Navigate obsolete).

The post data specified by PostData is passed as a SAFEARRAY structure. The variant should be of type VT_ARRAY and point to a SAFEARRAY. The SAFEARRAY should be of element type VT_UI1, dimension one, and have an element count equal to the number of bytes of post data.

Applies To

WebBrowser, Internet Explorer

See also DWebBrowserEvents2::BeforeNavigate2, DWebBrowserEvents2::NavigateComplete2


IWebBrowser2::put_AddressBar

HRESULT put_AddressBar(
    VARIANT_BOOL FAR* pValue
);

Shows or hides the Internet Explorer object's address bar.

  • Returns S_OK if the operation was successful, or an OLE-defined error code otherwise.
pValue
Address of a variable that contains a nonzero value if the address bar is to be shown, or zero if it is to be hidden.

Applies To

Internet Explorer

See also IWebBrowser2::get_AddressBar


IWebBrowser2::put_FullScreen

HRESULT put_FullScreen(
    VARIANT_BOOL bFullScreen
);

Sets Internet Explorer to either full-screen or normal window mode.

  • Returns S_OK to indicate that the operation was successful.
bFullScreen
Full-screen flag. If this parameter is TRUE, Internet Explorer is set to full-screen mode; if FALSE, it is set to normal window mode.

In full-screen mode, the Internet Explorer main window is maximized and the status bar, toolbar, menu bar, and title bar are hidden.

The WebBrowser object ignores this property.

Applies To

WebBrowser, Internet Explorer

See also IWebBrowser2::get_FullScreen


IWebBrowser2::put_Height

HRESULT put_Height(
    long Height
);

Sets the height of the Internet Explorer main window.

  • Returns S_OK to indicate that the operation was successful.
Height
Height, in pixels, of the main window.

Applies To

WebBrowser, Internet Explorer

See also IWebBrowser2::get_Height, IWebBrowser2::put_Width


IWebBrowser2::put_Left

HRESULT put_Left(
    long Left
);

Sets the horizontal position of the Internet Explorer main window.

  • Returns S_OK to indicate that the operation was successful.
Left
Screen coordinate of the left edge of the main window.

Applies To

WebBrowser, Internet Explorer

See also IWebBrowser2::get_Left, IWebBrowser2::put_Top


IWebBrowser2::put_MenuBar

HRESULT put_MenuBar(
    VARIANT_BOOL Value
);

Shows or hides the Internet Explorer menu bar.

  • Returns S_OK if successful, or an OLE-defined error code otherwise.
Value
Show flag. A value of TRUE shows the menu bar; a value of FALSE hides it.

The WebBrowser object ignores this property.

Applies To

WebBrowser, Internet Explorer

See also IWebBrowser2::get_MenuBar


IWebBrowser2::put_Offline

HRESULT put_Offline(
    VARIANT_BOOL pbOffline
);

Sets a value indicating whether the WebBrowser control is currently operating in offline mode. In offline mode, the browser is forced to read HTML pages from the local cache rather than from the source document.

  • Returns S_OK if successful, or an OLE-defined error code otherwise.
pbOffline
Address of a variable that receives the Offline flag. If this parameter is TRUE, the WebBrowser control is reading from the local cache. If this parameter is FALSE, the control will attempt to read from the source document.

Applies To

WebBrowser, Internet Explorer


IWebBrowser2::put_RegisterAsBrowser

HRESULT put_RegisterAsBrowser(
    VARIANT_BOOL bRegister
);

Sets a value indicating whether the WebBrowser control is registered as a top-level browser for target name resolution.

  • Returns S_OK if successful, or an OLE-defined error code otherwise.
bRegister
Boolean expression that determines whether Internet Explorer is registered as a top-level browser. If TRUE, the WebBrowser is registered as a top-level browser; if FALSE, it is not a top-level browser. The default value is FALSE.

Applies To

WebBrowser, Internet Explorer


IWebBrowser2::put_RegisterAsDropTarget

HRESULT put_RegisterAsDropTarget(
    VARIANT_BOOL bRegister
);

Sets a value indicating whether the WebBrowser control is registered as a drop target for navigation.

  • Returns S_OK if successful, or an OLE-defined error code otherwise.
bRegister
Optional. A Boolean expression that determines if the object is registered as a drop target for navigation. If TRUE, the object is registered as a drop target; if FALSE, it is not a drop target. The default value is FALSE.

Applies To

WebBrowser, Internet Explorer


IWebBrowser2::put_Resizable

HRESULT put_Resizable(
    VARIANT_BOOL FAR* pValue
);

Sets the Internet Explorer object's resizable property.

  • Returns S_OK if successful, or an OLE-defined error code otherwise.
pValue
Address of a variable that contains a nonzero value if the object is resizable, or zero if it is not resizable.

Applies To

Internet Explorer

See also IWebBrowser2::get_Resizable


IWebBrowser2::put_Silent

HRESULT put_Silent(
    VARIANT_BOOL FAR* pbSilent
);

Sets a value indicating whether any dialog boxes can be shown.

  • Returns S_OK if successful, or an OLE-defined error code otherwise.
pbSilent
Optional. A Boolean expression that determines whether the object can show any dialog boxes. If TRUE, dialog boxes will not be displayed; if FALSE, dialog boxes will be displayed. The default value is FALSE.

Applies To

WebBrowser, Internet Explorer


IWebBrowser2::put_StatusBar

HRESULT put_StatusBar(
    VARIANT_BOOL Value
);

Shows or hides the Internet Explorer status bar.

  • Returns S_OK if successful, or an OLE-defined error code otherwise.
Value
Show flag. A value of TRUE shows the status bar; a value of FALSE hides it.

The WebBrowser object ignores this property.

Applies To

Internet Explorer, WebBrowser

See also IWebBrowser2::get_StatusBar


IWebBrowser2::put_StatusText

HRESULT put_StatusText(
    BSTR bstr
);

Sets the text of the Internet Explorer status bar.

  • Returns S_OK if successful, or an OLE-defined error code otherwise.
bstr
Status bar text.

The WebBrowser object ignores this property.

Applies To

Internet Explorer, WebBrowser

See also IWebBrowser2::get_StatusText


IWebBrowser2::put_TheaterMode

HRESULT put_TheaterMode(
    VARIANT_BOOL bTheaterMode
);

Sets the TheaterMode property for the WebBrowser control.

  • Returns S_OK if successful, or an OLE-defined error code otherwise.
bTheaterMode
Optional. A Boolean value that contains the TheaterMode property. If this value is nonzero, the WebBrowser changes to theater mode. If this value is zero, the WebBrowser is taken out of theater mode. The default value is zero.

The WebBrowser object ignores this property.

Applies To

WebBrowser, Internet Explorer


IWebBrowser2::put_ToolBar

HRESULT put_ToolBar(
    int Value
);

Shows or hides the Internet Explorer toolbar.

  • Returns S_OK if successful, or an OLE-defined error code otherwise.
Value
Show flag. A value of TRUE shows the toolbar; a value of FALSE hides it.

The WebBrowser object ignores this property.

Applies To

WebBrowser, Internet Explorer

See also IWebBrowser2::get_ToolBar


IWebBrowser2::put_Top

HRESULT put_Top(
    long Top
);

Sets the vertical position of the Internet Explorer main window.

  • Returns S_OK to indicate that the operation was successful.
Top
Screen coordinate of the top edge of the main window.

Applies To

WebBrowser, Internet Explorer

See also IWebBrowser2::get_Top, IWebBrowser2::put_Left


IWebBrowser2::put_Visible

HRESULT put_Visible(
    VARIANT_BOOL Value
);

Sets the visibility state of the object.

  • Returns S_OK to indicate that the operation was successful.
Value
Visibility flag. If this parameter is TRUE, the object is visible; if FALSE, it is hidden.

Applies To

Internet Explorer, WebBrowser

See also IWebBrowser2::get_Visible


IWebBrowser2::put_Width

HRESULT put_Width(
    long Width
);

Sets the width of the Internet Explorer main window.

  • Returns S_OK to indicate that the operation was successful.
Width
Width, in pixels, of the main window.

Applies To

Internet Explorer

See also IWebBrowser2::get_Width, IWebBrowser2::put_Height


IWebBrowser2::PutProperty

HRESULT PutProperty(
    BSTR szProperty,
    VARIANT vtValue
);

Sets the value of a property associated with the given object.

  • Returns one of these values:
    S_OK | The operation was successful.
    E_INVALIDARG | One or more parameters are invalid.
    E_OUTOFMEMORY | Out of memory.
szProperty
Caller-allocated buffer that contains the name of the property to set.
vtValue
New value for the given property.

Applies To

Internet Explorer

See also IWebBrowser2::GetProperty


IWebBrowser2::QueryStatusWB

HRESULT QueryStatusWB(
    [in] OLECMDID nCmdID,
    [out, retval] OLECMDF *pcmdf
);

Implements a wrapper that allows you to query an OLE object for status of commands using the IOleCommandTarget::QueryStatus method.

nCmdID
OLECMDID value of the command for which the caller needs status information.
pcmdf
Address of an OLECMDF value that receives the status of the command.

Applies To

WebBrowser, Internet Explorer

See also IWebBrowser2::ExecWB


IWebBrowser2::Quit

HRESULT Quit(void);

Closes the Internet Explorer application.

  • Returns S_OK to indicate that the operation was successful.

Applies To

Internet Explorer


IWebBrowser2::Refresh

HRESULT Refresh(void);

Reloads the file that Internet Explorer is currently displaying.

  • Returns S_OK if successful, or E_FAIL otherwise.

Applies To

WebBrowser, Internet Explorer


IWebBrowser2::Refresh2

HRESULT Refresh2(
    VARIANT FAR* Level
);

Reloads the file that Internet Explorer is currently displaying. Unlike IWebBrowser2::Refresh, this method contains a parameter that specifies the refresh level.

  • Returns S_OK if successful, or E_FAIL otherwise.
Level
Address of a variable that specifies the level of refresh operation to perform. The variable can contain a type defined by the RefreshConstants enumeration.

Applies To

WebBrowser, Internet Explorer


IWebBrowser2::ShowBrowserBar

HRESULT ShowBrowserBar(
    VARIANT FAR* pvaClsid,
    VARIANT FAR* pvarShow,
    VARIANT FAR* pvarSize
);

Shows or hides a specified browser bar.

  • Returns S_OK if successful, or E_FAIL otherwise.
pvaClsid
Address of a string VARIANT that contains the class identifier of the browser bar to show or hide. This object must be registered as an Explorer Bar object with the CATID_InfoBand component category. For more information, see Band Objects.
pvarShow
Address of a BOOL VARIANT that specifies if the browser bar should be shown or hidden. If this is nonzero, the browser bar is shown. If this is zero, the browser bar is hidden.
pvarSize
Not currently used.

Applies To

Internet Explorer


IWebBrowser2::Stop

HRESULT Stop(void);

Cancels any pending navigation or download operation and stops any dynamic page elements, such as background sounds and animations.

  • Returns S_OK to indicate that the operation was successful.

Applies To

WebBrowser, Internet Explorer

See also DWebBrowserEvents2::BeforeNavigate2, DWebBrowserEvents2::DownloadBegin, DWebBrowserEvents2::ProgressChange, IWebBrowser2::Quit, IWebBrowser2::Refresh


ClientToWindow Method

Description

Converts the client coordinates of a point to window coordinates. Client coordinates are relative to the upper-left corner of the client area; window coordinates are relative to the upper-left corner of a window.

Syntax

object.ClientToWindow pcx, pcy

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
pcx | Required. A long integer value that specifies the x-coordinate of the point in client coordinates. When ClientToWindow returns, this variable contains the x-coordinate of the point in window coordinates.
pcy | Required. A long integer value that specifies the y-coordinate of the point in client coordinates. When ClientToWindow returns, this variable contains the y-coordinate of the point in window coordinates.

Applies To

InternetExplorer

See Also

Height, Width


ExecWB Method

Description

Executes a command on an OLE object and returns the status of the command execution using the IOLECommandTarget interface.

Syntax

object.ExecWB nCmdID, nCmdExecOpt, [pvaIn], [pvaOut]

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
nCmdID | Required. A long integer that represents the identifier of the command to execute.
nCmdExecOpt | Required. A long integer that represents the options set for executing the command.
pvaIn | Optional. A variant used for specifying command input arguments.
pvaOut | Optional. A variant used for specifying command output arguments.

Applies To

InternetExplorer, WebBrowser


GetProperty Method

Description

Retrieves the current value of a property associated with the given object.

Syntax

object.GetProperty szProperty, vtValue

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
szProperty | Required. A string expression that contains the name of the property to retrieve.
vtValue | Required. A variable that receives the current value of the property.

Applies To

InternetExplorer

See Also

PropertyChange, PutProperty


GoBack Method

Description

Navigates backward one item in the history list.

Syntax

object.GoBack

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.

Remarks

During a browsing session, the WebBrowser control and Internet Explorer application maintain a history list of all Web sites visited during a session (unless you specify the navNoHistory flag when using the Navigate method). Use the CommandStateChange event to check the enabled state of backward navigation. If the event's CSC_NAVIGATEBACK command is disabled, the beginning of the history list has been reached and the GoBack method should not be used.

Applies To

InternetExplorer, WebBrowser

See Also

GoForward, GoHome, GoSearch, Navigate, CommandStateChange


GoForward Method

Description

Navigates forward one item in the history list.

Syntax

object.GoForward

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.

Remarks

During a browsing session, the WebBrowser control and Internet Explorer application maintain a history list of all Web sites visited during a session (unless you specify the navNoHistory flag when using the Navigate method). Use the CommandStateChange event to check the enabled state of forward navigation. If the event's CSC_NAVIGATEFORWARD command is disabled, the end of the history list has been reached and the GoForward method should not be used.

Applies To

InternetExplorer, WebBrowser

See Also

GoBack, GoHome, GoSearch


GoHome Method

Description

Navigates to the current home or start page, as specified in the Internet Explorer Options dialog box and Internet Control Panel.

Syntax

object.GoHome

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.

Applies To

InternetExplorer, WebBrowser

See Also

GoBack, GoForward, GoSearch


GoSearch Method

Description

Navigates to the current search page, as specified in the Internet Explorer Options dialog box and Internet Control Panel.

Syntax

object.GoSearch

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.

Applies To

InternetExplorer, WebBrowser

See Also

GoBack, GoForward, GoHome


Methods

This section describes the methods associated with the WebBrowser control.

ClientToWindow Method

ExecWB Method

GetProperty Method

GoBack Method

GoForward Method

GoHome Method

GoSearch Method

Navigate Method

Navigate2 Method

PutProperty Method

QueryStatusWB Method

Quit Method

Refresh Method

Refresh2 Method

ShowBrowserBar Method

Stop Method


Navigate Method

Description

Navigates to the resource identified by a Universal Resource Locator (URL) or to the file identified by a full path.

Syntax

object.Navigate URL [Flags,] [TargetFrameName,] [PostData,] [Headers]

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
URL | Required. A string expression that evaluates to the URL, full path, or Universal Naming Convention (UNC) location and name of the resource to display.
Flags Optional. A constant or value that specifies whether to add the resource to the history list, whether to read from or write to the cache, and whether to display the resource in a new window. It can be a combination of the following constants or values.
Constant | Value | Meaning
navOpenInNewWindow | 1 | Open the resource or file in a new window.
navNoHistory | 2 | Do not add the resource or file to the history list. The new page replaces the current page in the list.
navNoReadFromCache | 4 | Do not read from the disk cache for this navigation.
navNoWriteToCache | 8 | Do not write the results of this navigation to the disk cache.
TargetFrameName Optional. String expression that evaluates to the name of an HTML frame in URL to display in the browser window. The possible values for this parameter are:
_blank | Load the link into a new unnamed window.
_parent | Load the link into the immediate parent of the document the link is in.
_self | Load the link into the same window the link was clicked in.
_top | Load the link into the full body of the current window.
<window_name> | A named HTML frame. If no frame or window exists that matches the specified target name, a new window is opened for the specified link.
PostData | Optional. Data to send to the server during the HTTP POST transaction. For example, the POST transaction is used to send data gathered by an HTML form to a program or script. If this parameter does not specify any post data, the Navigate method issues an HTTP GET transaction. This parameter is ignored if URL is not an HTTP URL.
Headers | Optional. A value that specifies additional HTTP headers to send to the server. These headers are added to the default Internet Explorer headers. The headers can specify things like the action required of the server, the type of data being passed to the server, or a status code. This parameter is ignored if URL is not an HTTP URL.

Remarks

The WebBrowser control or InternetExplorer object can browse to any location in the local file system, on the network, or on the World Wide Web. Use the Navigate method to tell the browser which location to browse to. By including a text box in your application, you can let the user specify the location to browse to and then pass the location to the Navigate method.

Applies To

InternetExplorer, WebBrowser

See Also

Navigate2


Navigate2 Method

Description

Navigates to the resource identified by a Universal Resource Locator (URL) or to the file identified by a full path. The Navigate2 method extends the Navigate method to support browsing on special folders—such as Desktop and My Computer—that are represented by a pointer to an item identifier list (PIDL). However, this is not applicable to the Visual Basic programming language. For information on this functionality, see the Using the WebBrowser Control from C/C++ section.

Syntax

object.Navigate2 URL [Flags,] [TargetFrameName,] [PostData,] [Headers]

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
URL | Required. A string expression that evaluates to the URL of the resource to display or the full path to the file location.
Flags Optional. A constant or value that specifies whether to add the resource to the history list, whether to read from or write to the cache, and whether to display the resource in a new window. It can be a combination of the following constants or values.
Constant | Value | Meaning
navOpenInNewWindow | 1 | Open the resource or file in a new window.
navNoHistory | 2 | Do not add the resource or file to the history list. The new page replaces the current page in the list.
navNoReadFromCache | 4 | Do not read from the disk cache for this navigation.
navNoWriteToCache | 8 | Do not write the results of this navigation to the disk cache.
TargetFrameName Optional. String expression that evaluates to the name of an HTML frame in URL to display in the browser window. The possible values for this parameter are:
_blank | Load the link into a new unnamed window.
_parent | Load the link into the immediate parent of the document the link is in.
_self | Load the link into the same window the link was clicked in.
_top | Load the link into the full body of the current window.
<window_name> | A named HTML frame. If no frame or window exists that matches the specified target name, a new window is opened for the specified link.
PostData | Optional. Data to send to the server during the HTTP POST transaction. For example, the POST transaction is used to send data gathered by an HTML form to a program or script. If this parameter does not specify any post data, the Navigate2 method issues an HTTP GET transaction. This parameter is ignored if URL is not an HTTP URL.
Headers | Optional. A value that specifies additional HTTP headers to send to the server. These headers are added to the default Internet Explorer headers. The headers can specify things like the action required of the server, the type of data being passed to the server, or a status code. This parameter is ignored if URL is not an HTTP URL.

Applies To

InternetExplorer, WebBrowser

See Also

Navigate


PutProperty Method

Description

Sets the value of a property associated with the given object.

Syntax

object.PutProperty szProperty, vtValue

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
szProperty | Required. A string expression that contains the name of the property to set.
vtValue | Required. A variable that specifies the new value of the property.

Applies To

InternetExplorer

See Also

GetProperty, PropertyChange


QueryStatusWB Method

Description

Queries an OLE object and returns the status of commands using the IOLECommandTarget interface.

Syntax

object.QueryStatusWB nCmdID

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
nCmdID | Required. A long integer that represents the identifier of the command on which the caller needs status information. This will be one of the OLECMDID values.

Return Value

Returns an unsigned long that is one of the OLECMDF values.

Applies To

InternetExplorer, WebBrowser


Quit Method

Description

Closes the Internet Explorer application.

Syntax

object.Quit

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.

Applies To

InternetExplorer

See Also

OnQuit, Stop


Refresh Method

Description

Reloads the page currently displayed in the WebBrowser control.

Syntax

object.Refresh

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.

Remarks

The WebBrowser control and Internet Explorer application store Web pages from recently visited sites in cached memory on the user's hard disk. This saves time when revisiting a site by reloading the page from the local disk rather than downloading it again across the network from the remote HTTP server. You can force the WebBrowser control or Internet Explorer application to redownload a page by using the Refresh or Refresh2 method to ensure that you are viewing the most current version of the page. Also, you can disable the cache from being used by specifying the navNoReadFromCache and navNoWriteToCache flags when calling the Navigate or Navigate2 method.

Applies To

InternetExplorer, WebBrowser

See Also

Refresh2, Stop


Refresh2 Method

Description

Reloads the page currently displayed in the WebBrowser control. Unlike the Refresh method, this method contains a parameter that specifies the refresh level.

Syntax

object.Refresh2 [Level]

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
Level Optional. A constant or value that specifies the refresh level. It can be one of the following constants or values.
Constant | Value | Meaning
REFRESH_NORMAL | 0 | Perform a lightweight refresh that does not include sending the HTTP "pragma:nocache" header to the server.
REFRESH_IFEXPIRED | 1 | Perform a lightweight refresh if the page has expired.
REFRESH_COMPLETELY | 3 | Perform a full refresh that includes sending a "pragma:nocache" header to the server (HTTP URLs only).

Remarks

The "pragma:nocache" header tells the server not to return a cached copy. This ensures that the information is as fresh as possible. Browsers typically send this header when the user selects refresh, but the header can cause problems for some servers.

Applies To

InternetExplorer, WebBrowser

See Also

Quit, Refresh, Stop


ShowBrowserBar Method

Description

Shows or hides a specified browser bar.

Syntax

object.ShowBrowserBar pvaClsid, [pvarShow,] [pvarSize]

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
pvaClsid Required. A string containing the class identifier of the browser bar to show or hide. This object must be registered as an Explorer Bar object with the CATID_InfoBand component category. For more information, see Band Objects. The standard browser bars use the following class identifiers:

Browser Bar Name | Class ID
Search | {30D02401-6A81-11D0-8274-00C04FD5AE38}
Favorites | {EFA24E61-B078-11D0-89E4-00C04FC9E26E}
History | {EFA24E62-B078-11D0-89E4-00C04FC9E26E}
Channels | {EFA24E63-B078-11D0-89E4-00C04FC9E26E}

pvarShow | Optional. A Boolean value that specifies whether the browser bar should be shown or hidden. If this is TRUE, the browser bar is shown. If this is FALSE, the browser bar is hidden. The default value is TRUE.
pvarSize | Optional. Not currently used.

Remarks

Browser bars, also known as Explorer Bars, can be shown or hidden by the user from Internet Explorer's View menu. The ShowBrowserBar method is ignored by the WebBrowser object.

Applies To

InternetExplorer, WebBrowser


Stop Method

Description

Cancels any pending navigation or download operation and stops any dynamic page elements, such as background sounds and animations.

Syntax

object.Stop

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.

Remarks

Before calling the Stop method, you can use the object's Busy property to determine if the browser is currently in the process of navigating to a new location or downloading a file.

Applies To

InternetExplorer, WebBrowser

See Also

BeforeNavigate2, Busy, DownloadBegin, ProgressChange, Refresh, Refresh2


InternetExplorer Object

Description

The InternetExplorer object controls a remote instance of the Internet Explorer application through OLE Automation.

Properties

AddressBar, Application, Busy, Container, Document, FullName, FullScreen, Height, HWND, Left, LocationName, LocationURL, MenuBar, Name, Offline, Parent, Path, ReadyState, RegisterAsBrowser, RegisterAsDropTarget, Resizable, Silent, StatusBar, StatusText, TheaterMode, ToolBar, Top, TopLevelContainer, Type, Visible, Width

Methods

ClientToWindow, ExecWB, GetProperty, GoBack, GoForward, GoHome, GoSearch, Navigate, Navigate2, PutProperty, QueryStatusWB, Quit, Refresh, Refresh2, ShowBrowserBar, Stop

Events

BeforeNavigate2, CommandStateChange, DocumentComplete, DownloadBegin, DownloadComplete, NavigateComplete2, NewWindow2, OnFullScreen, OnMenuBar, OnQuit, OnStatusBar, OnTheaterMode, OnToolBar, OnVisible, ProgressChange, PropertyChange, StatusTextChange, TitleChange


Objects

This section describes the WebBrowser and InternetExplorer objects.

WebBrowser Object

InternetExplorer Object


WebBrowser Object

Description

The WebBrowser object adds browsing capabilities to your applications. Applications hosting this ActiveX™ Control will support browsing sites on the World Wide Web, as well as directories on the local computer and on network servers.

Properties

AddressBar ,Application, Busy, Container, Document, FullScreen, Height, Left, LocationName, LocationURL, MenuBar, Offline, Parent, ReadyState, RegisterAsBrowser, RegisterAsDropTarget, Resizable, Silent, StatusBar, StatusText, TheaterMode, ToolBar, Top, TopLevelContainer, Type, Visible, Width

Methods

ExecWB, GoBack, GoForward, GoHome, GoSearch, Navigate, Navigate2, Quit, Refresh, Refresh2, ShowBrowserBar, Stop

Events

BeforeNavigate2, CommandStateChange, DocumentComplete, DownloadBegin, DownloadComplete, NavigateComplete2, NewWindow2, OnFullScreen, OnMenuBar, OnStatusBar, OnTheaterMode, OnToolBar, OnVisible, ProgressChange, StatusTextChange, TitleChange


AddressBar Property

Description

Returns or sets a value that determines whether the Internet Explorer application URL address bar is visible or hidden.

Syntax

object.AddressBar

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.

Remarks

The WebBrowser object ignores the AddressBar property.

Applies To

InternetExplorer, WebBrowser


Application Property

Description

Returns the automation object supported by the application that contains the WebBrowser control, if the object is accessible; otherwise, this property returns the WebBrowser control's automation object.

Syntax

object.Application

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.

Remarks

Use this property with the Set and CreateObject commands or with the GetObject command to create and manipulate an instance of the Internet Explorer application as shown in the following early binding example.

Dim IE As SHDocVw.InternetExplorer

Set IE = CreateObject("InternetExplorer.Application")

Applies To

InternetExplorer, WebBrowser


Busy Property

Description

Returns a Boolean value indicating whether the WebBrowser control or Internet Explorer application is engaged in a navigation or downloading operation. If the control is busy, you can use the Stop method to cancel the navigation or download operation before it is completed.

Syntax

object.Busy

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.

Remarks

The Busy property returns TRUE if a download or navigation operation is currently in progress, or FALSE otherwise.

Applies To

InternetExplorer, WebBrowser

See Also

Stop


Container Property

Description

Returns an object that evaluates to the container of the WebBrowser control, if any.

Syntax

object.Container

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.

Applies To

InternetExplorer, WebBrowser

See Also

Document


Document Property

Description

Returns the automation object of the active document, if any. This provides access to the contents of the HTML document through the object model. For more information, see the document object section in the Dynamic HTML reference.

Syntax

object.Document

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.

Applies To

InternetExplorer, WebBrowser

See Also

Container


FullName Property

Description

Returns a string that evaluates to the fully qualified path of the executable file that contains the Internet Explorer application.

Syntax

object.FullName

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.

Applies To

InternetExplorer


FullScreen Property

Description

Returns or sets a value indicating whether the Internet Explorer window is maximized.

Syntax

object.FullScreen [= value]

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
value | Optional. A Boolean expression that determines whether Internet Explorer is maximized. If TRUE, the browser window is maximized; if FALSE, it is not. The default value is FALSE.

Remarks

The WebBrowser object ignores the FullScreen property.

Applies To

InternetExplorer, WebBrowser


Height Property

Description

Returns or sets the vertical dimension, in pixels, of the frame window that contains the WebBrowser control.

Syntax

object.Height [= height]

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
height | Optional. A long integer value that specifies the vertical dimension of the frame window, in pixels.

Applies To

InternetExplorer, WebBrowser

See Also

ClientToWindow, Width


HWND Property

Description

Returns the window handle to the Internet Explorer main window.

Syntax

object.HWND

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.

Applies To

InternetExplorer


Left Property

Description

Returns or sets the distance between the internal left edge of the WebBrowser control and the left edge of its container.

Syntax

object.Left [= distance]

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
distance | Optional. A long integer expression that specifies the distance between the internal left edge of the WebBrowser control and the left edge of its container.

Remarks

The Left property is measured in units depending on the coordinate system of its container. The values for this property change as the object is moved by the user or by code.

Applies To

InternetExplorer, WebBrowser


LocationName Property

Description

Returns a string that contains the name of the resource that the WebBrowser control is currently displaying. If the resource is an HTML page on the World Wide Web, the name is the title of that page. If the resource is a folder or file on the network or local computer, the name is the full path of the folder or file in the Universal Naming Convention (UNC) format.

Syntax

object.LocationName

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.

Applies To

InternetExplorer, WebBrowser

See Also

LocationURL


LocationURL Property

Description

Returns a string that contains the URL of the resource that the WebBrowser control or Internet Explorer application is currently displaying. If the resource is a folder or file on the network or local computer, the name is the full path of the folder or file in the Universal Naming Convention (UNC) format.

Syntax

object.LocationURL

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.

Applies To

InternetExplorer, WebBrowser

See Also

LocationName


MenuBar Property

Description

Returns or sets a value that determines whether the Internet Explorer application menu bar is visible or hidden.

Syntax

object.MenuBar [= value]

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
value | Optional. A Boolean expression that determines whether the menu bar is visible. If TRUE, the menu bar is visible; if FALSE, it is hidden. The default value is TRUE.

Remarks

Setting this property to FALSE prevents the user from accessing the File, Edit, View, Go, Favorites, and Help menus. This can be used for limiting the functionality of an Internet Explorer application from a controlling application.

Remarks

The WebBrowser object ignores the MenuBar property.

Applies To

InternetExplorer, WebBrowser


Name Property

Description

Returns a string that evaluates to the name of the Internet Explorer application—that is, "Microsoft Internet Explorer."

Syntax

object.Name

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.

Remarks

This property is read-only.

Applies To

InternetExplorer


Offline Property

Description

Returns or sets a value indicating whether the WebBrowser control is currently operating in offline mode. In offline mode, the browser is forced to read HTML pages from the local cache rather than from the source document.

Syntax

object.Offline [= value]

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
value | Optional. A Boolean expression that determines whether the WebBrowser control is in offline mode. If TRUE, the WebBrowser will read data about its current URL from its local cache; if FALSE, it will attempt to read the source document. The default value is FALSE.

Applies To

InternetExplorer, WebBrowser


Parent Property

Description

Returns an object that evaluates to the form on which the WebBrowser control is located, or to the automation object supported by Internet Explorer.

Syntax

object.Parent

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.

Applies To

InternetExplorer, WebBrowser


Path Property

Description

Returns a string that evaluates to the full path of the Internet Explorer application.

Syntax

object.Path

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.

Applies To

InternetExplorer


Properties

This section describes the properties associated with the WebBrowser control.

AddressBar Property

Application Property

Busy Property

Container Property

Document Property

FullName Property

FullScreen Property

Height Property

HWND Property

Left Property

LocationName Property

LocationURL Property

MenuBar Property

Name Property

Offline Property

Parent Property

Path Property

ReadyState Property

RegisterAsBrowser Property

RegisterAsDropTarget Property

Resizable Property

Silent Property

StatusBar Property

StatusText Property

TheaterMode Property

ToolBar Property

Top Property

TopLevelContainer Property

Type Property

Visible Property

Width Property


ReadyState Property

Description

Retrieves the ready state of the object. This will be one of the READYSTATE values.

Syntax

object.ReadyState

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.

Applies To

InternetExplorer, WebBrowser, READYSTATE


RegisterAsBrowser Property

Description

Returns or sets a value indicating whether the WebBrowser control is registered as a top-level browser for target name resolution.

Syntax

object.RegisterAsBrowser [= value]

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
value | Optional. A Boolean expression that determines whether Internet Explorer is registered as a top-level browser. If TRUE, the WebBrowser is registered as a top-level browser; if FALSE, it is not a top-level browser. The default value is FALSE.

Applies To

InternetExplorer, WebBrowser


RegisterAsDropTarget Property

Description

Returns or sets a value indicating whether the WebBrowser control is registered as a drop target for navigation.

Syntax

object.RegisterAsDropTarget [= value]

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
value | Optional. A Boolean expression that determines whether Internet Explorer is registered as a drop target for navigation. If TRUE, the WebBrowser is registered as a drop target; if FALSE, it is not a drop target. The default value is FALSE.

Applies To

InternetExplorer, WebBrowser


Resizable Property

Description

Sets or retrieves a value indicating whether the object can be resized.

Syntax

object.Resizable [= value]

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
value | Optional. A Boolean expression that sets the object's resizable property. If this value is TRUE, the object can be resized. If this value is FALSE, the object cannot be resized. The default value is TRUE.

Remarks

The WebBrowser object ignores the Resizable property.

Applies To

InternetExplorer, WebBrowser


Silent Property

Description

Returns or sets a value indicating whether any dialog boxes can be shown.

Syntax

object.Silent [= value]

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
value | Optional. A Boolean expression that determines whether the WebBrowser can show any dialog boxes. If TRUE, dialog boxes will not be displayed; if FALSE, dialog boxes will be displayed. The default value is FALSE.

Applies To

InternetExplorer, WebBrowser


StatusBar Property

Description

Returns or sets a value that determines whether the status bar is visible.

Syntax

object.StatusBar [= value]

Part | Description
object | Required. An object expression that evaluates to an InternetExplorer object.
value | Optional. A Boolean expression that determines whether the status bar is visible. If TRUE, the status bar is visible; if FALSE, it is hidden. The default is TRUE.

Remarks

The WebBrowser object ignores the StatusBar property.

Applies To

InternetExplorer, WebBrowser

See Also

StatusText, StatusTextChange, ToolBar, Visible


StatusText Property

Description

Returns or sets the text for the status bar.

Syntax

object.StatusText [= value]

Part | Description
object | Required. An object expression that evaluates to an InternetExplorer object.
value | Optional. A string that evaluates to the text for the status bar.

Remarks

The WebBrowser object ignores the StatusText property.

Applies To

InternetExplorer, WebBrowser

See Also

StatusBar, StatusTextChange


TheaterMode Property

Description

Returns or sets a value indicating whether Internet Explorer is in theater or normal window mode. In theater mode, the Internet Explorer main window fills the entire screen and displays a toolbar with a minimal set of navigational buttons. A status bar is also provided in the upper right-hand corner of the screen. Channels, Search, History, and Favorites browser bars appear (if enabled) as an autohide pane on the left edge of the screen in theater mode.

Syntax

object.TheaterMode [= value]

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
value | Optional. A Boolean expression that determines whether Internet Explorer is in theater or normal window mode. If TRUE, the object is in theater mode; if FALSE, it is in normal mode. The default value is FALSE.

Remarks

The WebBrowser object ignores the TheaterMode property.

Applies To

InternetExplorer, WebBrowser


ToolBar Property

Description

Returns or sets a value that determines whether the toolbar is visible.

Syntax

object.ToolBar [= value]

Part | Description
object | Required. An object expression that evaluates to an InternetExplorer object.
value | Optional. A Boolean expression that determines whether the toolbar is visible. If TRUE, the toolbar is visible; if FALSE, it is hidden. The default is TRUE.

Remarks

The WebBrowser object ignores the ToolBar property.

Applies To

InternetExplorer, WebBrowser

See Also

StatusBar, Visible


Top Property

Description

Returns or sets the distance between the internal top edge of the WebBrowser control and the top edge of its container.

Syntax

object.Top [= value]

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
value | Optional. A long integer expression that specifies the distance.

Remarks

The Top property is measured in units depending on the coordinate system of its container. The values for this property change as the object is moved by the user or by code.

Applies To

InternetExplorer, WebBrowser


TopLevelContainer Property

Description

Returns a Boolean value indicating whether the given object is a top-level container.

Syntax

object.TopLevelContainer

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.

Applies To

InternetExplorer, WebBrowser


Type Property

Description

Returns a string expression that specifies the type name of the contained document object—that is, "Windows HTML Viewer."

Syntax

object.Type

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.

Applies To

InternetExplorer, WebBrowser


Visible Property

Description

Returns or sets a value indicating whether the object is visible or hidden.

Syntax

object.Visible [= value]

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
value | Optional. A Boolean expression specifying the visible state of Internet Explorer. If TRUE, the window is visible; if FALSE, it is hidden. The default value is FALSE.

Remarks

Although the Internet Explorer application is hidden when it is first created, it becomes visible after using the Navigate or GoSearch method.

Applies To

InternetExplorer, WebBrowser


Width Property

Description

Returns or sets the horizontal dimension, in pixels, of the frame window that contains the WebBrowser control.

Syntax

object.Width [= width]

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
width | Optional. A long integer value that specifies the horizontal dimension of the frame window, in pixels.

Applies To

InternetExplorer, WebBrowser

See Also

ClientToWindow, Height


Information Delivery API

This section describes the Microsoft® Information Delivery API, which allows you to create subscriptions and add channels that can be used to deliver content to a user's computer.

Microsoft Information Delivery API Overview

Microsoft Information Delivery API Reference


Microsoft Information Delivery API Overview

The Microsoft® Information Delivery API allows you to create subscriptions and add channels that can be used to deliver content to a user's computer. This section is an overview of the services provided by the Information Delivery API.

The Microsoft Information Delivery API Overview no longer includes information on the notification manager and the interfaces and methods related to it. The implementation of the underlying architecture for the Information Delivery API will be changed after Microsoft Internet Explorer 4.0 is released, so the sections that will be affected (such as the notification manager) have been removed for this release.

Introduction

About the Channel Manager

About the Subscription Manager

Checking Updates

Refreshing the Channel Pane

Introduction

The Microsoft® Information Delivery API provides a channel manager and subscription manager to manage channels and subscriptions.

The channel manager is used to add and delete Active Channels and channel categories from the channel pane. The channel manager can also retrieve an enumerator that can be used to enumerate all of the current Active Channels. The channel manager does not create a subscription to an Active Channel. To create a subscription to an Active Channel, the client application must access the subscription manager.

The subscription manager provides the ability to create and delete subscriptions to Web sites and Active Channels. The subscription manager also provides the ability to start an update for a specified subscription or all subscriptions.

To use the channel manager, the Chanmgr.h header file must be included. Also, the Subsmgr.h header file must be included for any C/C++ programs that utilize the subscription manager.

This documentation assumes that the reader has an understanding of OLE/COM programming and a basic understanding of Active Desktop and other features of Microsoft Internet Explorer 4.0. For more information, see Introducing Internet Explorer 4.0 in the Internet Client SDK.

About the Channel Manager

The channel manager allows a client application to add and delete categories and Active Channels in the desktop channel bar. The channel manager can also provide an enumerator that will allow a client application to enumerate all of the Active Channels. The channel manager does not create a subscription to the Active channel. To subscribe to an Active Channel, the subscription manager must be used.

About the Subscription Manager

The subscription manager gives a client application the ability to create, update, and delete subscriptions to Web sites and channels. The subscription manager also provides the ability to get information about a subscription type and information on a specific subscription.

Checking Updates

Currently, the Information Delivery API does not provide a programatic way of checking the last time a file has been updated. If the file is stored in the Internet cache or in a cache container, the Win32 Interenet function, GetUrlCacheEntryInfoEx, can be used to retrieve information on the cache entry. This information includes:

  • Last modified time
  • Expire time
  • Last access time
  • Last synchronization time
  • Returned headers
  • Hit rate
  • File size
  • Local file name
  • User count

For more information on the retrieving cache entry information, see Retrieving cache entry information in the Microsoft Win32 Internet Function Overview. The article demonstrates the use of the GetUrlCacheEntryInfo function, which is almost identical to GetUrlCacheEntryInfoEx, except GetUrlCacheEntryInfo does not translate through the offline redirects.

Refreshing the Channel Pane

The Information Delivery API does not provide any programatic way to refresh the channel pane. To refresh the channel pane, the client application needs to use the SHChangeNotify function with the full path of the channel shortcut.

The following sample demonstrates a call to SHChangeNotify to refresh the channel pane to show changes to the Awesome Computers channel.

SHChangeNotify(SHCNE_UPDATEDIR, SHCNF_PATH,
                                    (void*)"c:\windows\favorites\channels\awesome_computer", NULL);


Microsoft Information Delivery API Reference

This reference describes the objects, interfaces, agents, methods, structures, types, flags, and properties included in the Information Delivery API.

The Microsoft Information Delivery API Reference no longer includes information on the notification manager and the interfaces and methods related to it. The implementation of the underlying architecture for the Information Delivery API will be changed after Microsoft Internet Explorer 4.0 is released, so the sections that will be affected (such as the notification manager) have been removed for this release.

Objects

Interfaces

Methods

Structures

Enumerated Types

Return Values


Return Values

The following list contains possible return values for the Information Delivery API.

INET_E_AGENT_CACHE_SIZE_EXCEEDED
Maximum cache limit has been reached.
INET_E_AGENT_CONNECTION_FAILED
Failed to connect to the Internet.
INET_E_AGENT_MAX_SIZE_EXCEEDED
Subscription size limit has been reached.
INET_S_AGENT_PART_FAIL
Agent has completed the operation after encountering a few errors.


CHANNEL_AGENT_FLAGS

typedef enum CHANNEL_AGENT_FLAGS {
    CHANNEL_AGENT_DYNAMIC_SCHEDULE = 0x0001,
    CHANNEL_AGENT_PRECACHE_SOME = 0x0002,
    CHANNEL_AGENT_PRECACHE_ALL = 0x0004,
    CHANNEL_AGENT_PRECACHE_SCRNSAVER = 0x0008
} CHANNEL_AGENT_FLAGS;

Contains the flags that control the channel agent.

CHANNEL_AGENT_DYNAMIC_SCHEDULE
Use the information in the CDF file to create a schedule.
CHANNEL_AGENT_PRECACHE_SOME
Store any item that has an ITEM tag with the value PRECACHE=YES in the cache.
CHANNEL_AGENT_PRECACHE_ALL
Store all items in the cache that don't have an ITEM tag with the value PRECACHE=NO.
CHANNEL_AGENT_PRECACHE_SCRNSAVER
Store any item that has a USAGE tag with value equal to "ScreenSaver".


CHANNELENUMFLAGS

typedef enum _tagChannelEnumFlags{
    CHANENUM_CHANNELFOLDER = 0x00000001,
    CHANENUM_SOFTUPDATEFOLDER = 0x00000002,
    CHANENUM_DESKTOPFOLDER = 0x0000004,
    CHANENUM_TITLE = 0x00010000,
    CHANENUM_PATH = 0x00020000,
    CHANENUM_URL = 0x00040000,
    CHANENUM_SUBSCRIBESTATE = 0X00080000
} CHANNELENUMFLAGS;

Enumerated type that contains the channel enumerator flags that define what cahnnels are returned and what information will be returned for each channel enumerated.

CHANENUM_CHANNELFOLDER
Retrieve all channels in the channel folder.
CHANENUM_SOFTUPDATEFOLDER
Retrieve all channels in the software update folder.
CHANENUM_DESKTOPFOLDER
Retrieve all channels on the desktop.
CHANENUM_TITLE
Return the title of each channel enumerated.
CHANENUM_PATH
Return the path to the channel shortcut for each channel enumerated.
CHANENUM_URL
Return the URL of the CDF file for each channel enumerated.
CHANENUM_SUBSCRIBESTATE
Return the subscription state of each channel enumerated.


CREATESUBSCRIPTIONFLAGS

typedef enum CREATESUBSCRIPTIONFLAGS{
    CREATESUBS_ADDTOFAVORITES = 0x0001,
    CREATESUBS_FROMFAVORITES = 0x0002,
    CREATESUBS_NOUI = 0x0004,
    CREATESUBS_NOSAVE = 0x0008,
    CREATESUBS_SOFTWAREUPDATE = 0x0010,
} CREATESUBSCRIPTIONFLAGS;

Contains the flags used when creating a subscription.

CREATESUBS_ADDTOFAVORITES
Add subscription to Favorites menu.
CREATESUBS_FROMFAVORITES
Create the subscription for a site that already has a listing in the Favorites menu. Used in conjunction with the CREATESUBS_ADDTOFAVORITES value. This value will skip the section of the user interface that is used to add a Favorite and display the subscription options only.
CREATESUBS_NOUI
Create the subscription without displaying any user interface.
CREATESUBS_NOSAVE
Creates the subscription in the Subscriptions folder and then copies the information back to the SUBSCRIPTIONINFO structure that was passed in. Normally, the information is saved to the disk and the structure is not updated.
CREATESUBS_SOFTWAREUPDATE
Create a subscription for a Software Update Channel. Used in conjunction SUBSTYPE_CHANNEL value. If used with the CREATESUBS_ADDTOFAVORITES value, the method will display a different user inteface and add the listing to the software updates folder.


Enumerated Types

This section defines the enumerated types in the Information Delivery API.

CHANNEL_AGENT_FLAGS
CHANNELENUMFLAGS
CREATESUBSCRIPTIONFLAGS
SUBSCRIPTIONINFOFLAGS
SUBSCRIPTIONSCHEDULE
SUBSCRIPTIONSTATE
SUBSCRIPTIONTYPE
WEBCRAWL_RECURSEFLAGS


SUBSCRIPTIONINFOFLAGS

typedef enum SUBSCRIPTIONINFOFLAGS {
    SUBSINFO_SCHEDULE = 0x0001,
    SUBSINFO_RECURSE = 0x0002,
    SUBSINFO_WEBCRAWL = 0x0004,
    SUBSINFO_MAILNOT = 0x0008,
    SUBSINFO_MAXSIZEKB = 0x0010,
    SUBSINFO_USER = 0x0020,
    SUBSINFO_PASSWORD = 0x0040,
    SUBSINFO_GLEAM = 0x0200,
    SUBSINFO_CHANGESONLY = 0x0400,
    SUBSINFO_CHANNELFLAGS = 0x0800,
    SUBSINFO_FRIENDLYNAME = 0x2000,
    SUBSINFO_NEEDPASSWORD = 0x4000,
    SUBSINFO_TYPE = 0x8000
} SUBSCRIPTIONINFOFLAGS;

Contains the type information about subscriptions.

SUBSINFO_SCHEDULE
Update schedule the subscription is on.
SUBSINFO_RECURSE
Number of levels to recurse.
SUBSINFO_WEBCRAWL
Flags for the link crawling agent.
SUBSINFO_MAILNOT
User should be notified through e-mail.
SUBSINFO_MAXSIZEKB
Maximum download size in kilobytes.
SUBSINFO_USER
User name for authentication.
SUBSINFO_PASSWORD
Password for authentication.
SUBSINFO_GLEAM
Add a gleam to notify the user of an update to the site.
SUBSINFO_CHANGESONLY
Notify the user of changes only.
SUBSINFO_CHANNELFLAGS
Channel flags.
SUBSINFO_FRIENDLYNAME
Friendly name for the subscription.
SUBSINFO_NEEDPASSWORD
Subscription requires a password.
SUBSINFO_TYPE
Type of subscription.


SUBSCRIPTIONSCHEDULE

typedef enum SUBSCRIPTIONSCHEDULE {
    SUBSSCHED_AUTO = 0,
    SUBSSCHED_DAILY = 1,
    SUBSSCHED_WEEKLY = 2,
    SUBSSCHED_CUSTOM = 3,
    SUBSSCHED_MANUAL = 4
} SUBSCRIPTIONSCHEDULE;

Contains the values that indicate the update frequency.

SUBSSCHED_AUTO
Automatically schedule updates.
SUBSSCHED_DAILY
Update the subscription daily.
SUBSSCHED_WEEKLY
Update the subscription weekly.
SUBSSCHED_CUSTOM
Update the subscription using a custom schedule.
SUBSSCHED_MANUAL
Update the subscription manually.


SUBSCRIPTIONSTATE

typedef enum _tagSubscriptionState{
    SUBSTATE_NOTSUBSCRIBED,
    SUBSTATE_PARTIAL_SUBSCRIPTION,
    SUBSTATE_FULLSUBSCRIPTION
} SUBSCRIPTIONSTATE;

Contains the different subscription states.

SUBSTATE_NOTSUBSCRIBED
Not subscribed to the channel.
SUBSTATE_PARTIALSUBSCRIPTION
Partially subscribed to the channel.
SUBSTATE_FULLSUBSCRIPTION
Subscribed to the channel.


SUBSCRIPTIONTYPE

typedef enum SUBSCRIPTIONTYPE {
    SUBSTYPE_URL = 0,
    SUBSTYPE_CHANNEL = 1,
    SUBSTYPE_DESKTOPCOMPONENT = 2
} SUBSCRIPTIONTYPE;

Contains the different types of subscriptions.

SUBSTYPE_URL
Subscription is an Internet resource.
SUBSTYPE_CHANNEL
Subscription is a channel.
SUBSTYPE_DESKTOPCOMPONENT
Subscription is a desktop component.


WEBCRAWL_RECURSEFLAGS

typedef enum WEBCRAWL_RECURSEFLAGS {
    WEBCRAWL_DONT_MAKE_STICKY = 0x0001,
    WEBCRAWL_GET_IMAGES = 0x0002,
    WEBCRAWL_GET_VIDEOS = 0x0004,
    WEBCRAWL_GET_BGSOUNDS = 0x0008,
    WEBCRAWL_GET_CONTROLS = 0x0010,
    WEBCRAWL_LINKS_ELSEWHERE = 0x0020,
    WEBCRAWL_IGNORE_ROBOTSTXT = 0x0080
} WEBCRAWL_RECURSEFLAGS;

Contains the flags for the default link crawling agent included with the Information Delivery API.

WEBCRAWL_DONT_MAKE_STICKY
Instructs the agent to cache the downloaded resources normally. If this value is not set, the agent makes the entries sticky, which prevents the entry from being removed during a normal clean-up operation.
WEBCRAWL_GET_IMAGES
Instructs the agent to download any images associated with the resource.
WEBCRAWL_GET_VIDEOS
Instructs the agent to download any videos associated with the resource.
WEBCRAWL_GET_BGSOUNDS
Instructs the agent to download any background sounds associated with the resource.
WEBCRAWL_GET_CONTROLS
Instructs the agent to download any controls associated with the resource.
WEBCRAWL_LINKS_ELSEWHERE
Instructs the agent to follow links that go to sites outside the site that the resource resides on.
WEBCRAWL_IGNORE_ROBOTSTXT
Instructs the agent to ignore any robot scripts.


Methods

This section describes the methods in the Information Delivery API.

IChannelMgr::AddCategory
IChannelMgr::AddChannelShortcut
IChannelMgr::DeleteCategory
IChannelMgr::DeleteChannelShortcut
IChannelMgr::EnumChannels
IEnumChannels::Clone
IEnumChannels::Next
IEnumChannels::Reset
IEnumChannels::Skip
ISubscriptionMgr::CreateSubscription
ISubscriptionMgr::DeleteSubscription
ISubscriptionMgr::GetDefaultInfo
ISubscriptionMgr::GetSubscriptionInfo
ISubscriptionMgr::IsSubscribed
ISubscriptionMgr::ShowSubscriptionProperties
ISubscriptionMgr::UpdateAll
ISubscriptionMgr::UpdateSubscription


Interfaces Interfaces *
  * Previous Topic: Subscription Manager Object
  * Next Topic: IChannelMgr

Interfaces

This section describes the interfaces included in the Information Delivery API.


IChannelMgr::AddCategory

HRESULT AddCategory(
    [in] CHANNELCATEGORYINFO *pCategoryInfo
);

Adds a channel category to the desktop channel bar.

  • Returns E_INVALIDARG if any of the required fields in the CHANNELCATEGORYINFO structure are not provided.
pCategoryInfo
Address of the CHANNELCATEGORYINFO structure associated with the category to be added to the desktop channel bar.


IChannelMgr::AddChannelShortcut

HRESULT AddChannelShortcut(
    [in] CHANNELSHORTCUTINFO *pChannelInfo
);

Adds an Active Channel to the desktop channel bar.

  • Returns E_INVALIDARG if any of the required fields in the CHANNELSHORTCUTINFO structure are not provided.
pChannelInfo
Address of a CHANNELSHORTCUTINFO structure that contains the information associated with the Active Channel to be added.

This method only adds an entry into the desktop channel bar. To subscribe to the Active Channel, the client application must use the subscription manager.


IChannelMgr::DeleteCategory

HRESULT DeleteCategory(
    [in] LPWSTR pszTitle
);

Deletes a channel category from the desktop channel bar.

  • Returns S_FALSE if the specified channel category does not exist.
pszTitle
String value that contains the title of the channel category to be deleted from the desktop channel bar.


IChannelMgr::DeleteChannelShortcut

HRESULT DeleteChannelShortcut(
    [in] LPWSTR pszTitle
);

Deletes an Active Channel from the desktop channel bar.

  • Returns S_FALSE if the specified Active Channel does not exist.
pszTitle
String value that contains the title of the Active Channel to be deleted from the desktop channel bar.

This method does not delete the subscription, if one was created, for this Active Channel. The ISubscriptionMgr::DeleteSubscription method must be used to remove the subscription.


IChannelMgr::EnumChannels

HRESULT EnumChannels(
    [in] DWORD dwEnumFlags,
    [in] LPCWSTR pszURL,
    [out] IEnumChannels **pIEnumChannels
);

Creates a channel enumerator.

dwEnumFlags
Unsigned integer value that contains the flags that control the enumeration. Can be one of the CHANNELENUMFLAGS values or one of the following aggregate values:
CHANENUM_ALL | Aggregate of all the CHANNELENUMFLAGS values.
CHANENUM_ALLDATA | Aggregate of the CHANENUM_TITLE, CHANENUM_PATH, CHANENUM_URL, and the CHANENUM_SUBSCRIBESTATE values.
CHANENUM_ALLFOLDERS | Aggregate of the CHANENUM_CHANNELFOLDER, CHANENUM_SOFTUPDATEFOLDER, and CHANENUM_DESKTOPFOLDER values.
pszURL
Optional. String value that contains the URL of the CDF file.
pIEnumChannels
Address of the pointer to the IEnumChannels interface of the enumerator.


IChannelMgr

Provides the ability to add and delete Active Channels and channel categories in the desktop channel bar.

Methods
AddCategory
Adds a channel category to the desktop channel bar.
AddChannelShortcut
Installs an Active Channel into the desktop channel bar.
DeleteCategory
Deletes a channel category from the desktop channel bar.
DeleteChannelShortcut
Deletes an existing Active Channel.
EnumChannels
Creates a channel enumerator.


IEnumChannels::Clone

HRESULT Clone(
    [in] IEnumChannels **ppenum
);

Creates another enumerator that contains the same enumeration state as the current enumeration.

ppenum
Address of a pointer to the IEnumChannels interface of the clone.


IEnumChannels

Enumerates channels.

Methods
Clone
Creates another enumeration that contains the same enumeration state as the current enumeration.
Next
Retrieves a specified number of items in the enumeration sequence.
Reset
Resets the enumeration sequence.
Skip
Skips over a specified number of items in the enumeration sequence.


IEnumChannels::Next

HRESULT Next(
    [in] ULONG celt,
    [out] CHANNELENUMINFO *rgChanInf,
    [out] ULONG *pceltFetched
);

Retrieves a specified number of items in the enumeration sequence.

celt
Unsigned long integer value that contains the number of CHANNELENUMINFO structures being requested.
rgChanInf
Address of a buffer containing the CHANNELENUMINFO structures.
pceltFetched
Unsigned long integer value that indicates the actual number of structures received.


IEnumChannels::Reset IEnumChannels::Reset *
  * Previous Topic: IEnumChannels::Next
  * Next Topic: IEnumChannels::Skip

IEnumChannels::Reset

HRESULT Reset();

Resets the enumeration sequence.


IEnumChannels::Skip

HRESULT Skip(
    [in] ULONG celt;
);

Skips over a specified number of items in the enumeration sequence.

celt
Unsigned long integer value containing the number of CHANNELENUMINFO structures to skip.


ISubscriptionMgr::CreateSubscription

HRESULT CreateSubscription(
    [in] HWND hwnd;
    [in] LPCWSTR pwszURL,
    [in] LPCWSTR pwszFriendlyName,
    [in] DWORD dwFlags,
    [in] SUBSCRIPTIONTYPE subsType,
    [in,out] SUBSCRIPTIONINFO *pInfo
);

Creates a subscription.

hwnd
Handle to the parent window.
pwszURL
String value that contains the URL of the site to subscribe to.
pwszFriendlyName
String value that contains a friendly name for the site.
dwFlags
Unsigned long integer value that contains the flags that control the creation of the subscription. Can be a combination of the CREATESUBSCRIPTIONFLAGS values.
subType
SUBSCRIPTIONTYPE value that determines how the subscription will be handled.
pInfo
Address of a SUBSCRIPTIONINFO structure containing the subscription information.


ISubscriptionMgr::DeleteSubscription

HRESULT DeleteSubscription(
    [in] LPCWSTR pwszURL,
    [in] HWND hwnd
);

Deletes a subscription.

pwszURL
String value containing the URL of the subscription to delete.
hwnd
Handle of the parent window.


ISubscriptionMgr::GetDefaultInfo

HRESULT GetDefaultInfo(
    [in] SUBSCRIPTIONTYPE subType,
    [out] SUBSCRIPTIONINFO *pInfo
);

Retrieves the default information associated with a subscription type.

subType
SUBSCRIPTIONTYPE value that contains the subscription type.
pInfo
Address of a SUBSCRIPTIONINFO structure containing the default information for the specified subscription type.


ISubscriptionMgr::GetSubscriptionInfo

HRESULT GetSubscriptionInfo(
    [in] LPCWSTR pwszURL,
    [out] SUBSCRIPTIONINFO *pInfo
);

Retrieves the information associated with a specific subscription.

pwszURL
String value that contains the URL associated with the subscription.
pInfo
Address of the SUBSCRIPTIONINFO structure containing the information about the specified subscription.


ISubscriptionMgr::IsSubscribed

HRESULT IsSubscribed(
    [in] LPCWSTR pwszURL,
    [out] BOOL *pfSubscribed
);

Checks if the user is subscribed to a particular site.

pwszURL
String value containing the URL to look for.
pfSubscribed
Address of a Boolean value that will be TRUE if a subscription exists, or FALSE otherwise.


ISubscriptionMgr

Allows a client program to control the subscription manager.

Methods
CreateSubscription
Creates a subscription.
DeleteSubscription
Deletes a subscription.
GetDefaultInfo
Retrieves the default information associated with a subscription type.
GetSubscriptionInfo
Retrieves the information associated with a specific subscription.
IsSubscribed
Checks if the user is subscribed to a particular site.
ShowSubscriptionProperties
Displays the subscription properties.
UpdateAll
Updates all the subscriptions.
UpdateSubscription
Updates the specified subscription.


ISubscriptionMgr::ShowSubscriptionProperties

HRESULT ShowSubscriptionProperties(
    [in] LPCWSTR pwszURL,
    [in] HWND hwnd
);

Displays the subscription properties.

pwszURL
String value containing the URL of the subscription.
hwnd
Handle to the parent window.


ISubscriptionMgr::UpdateAll ISubscriptionMgr::UpdateAll *
  * Previous Topic: ISubscriptionMgr::ShowSubscriptionProperties
  * Next Topic: ISubscriptionMgr::UpdateSubscription

ISubscriptionMgr::UpdateAll

HRESULT UpdateAll()

Updates all subscriptions immediately.


ISubscriptionMgr::UpdateSubscription

HRESULT UpdateSubscription(
    [in] LPCWSTR pwszURL
);

Updates the specified subscription immediately.

pwszURL
String containing the URL of the subscription to update.


Channel Manager Object Channel Manager Object *
  * Previous Topic: Objects
  * Next Topic: Subscription Manager Object

Channel Manager Object

CLSID_ChannelMgr

Manages channels.

Interface
IChannelMgr


Objects Objects *
  * Previous Topic: Microsoft Information Delivery API Reference
  * Next Topic: Channel Manager Object

Objects

This section describes the objects included in the Information Delivery API.


Subscription Manager Object Subscription Manager Object *
  * Previous Topic: Channel Manager Object
  * Next Topic: Interfaces

Subscription Manager Object

CLSID_SubscriptionMgr

Handles subscriptions.

Interface
ISubscriptionMgr


CHANNELCATEGORYINFO

typedef _tagChannelCategoryInfo {
    DWORD cbSize;
    LPWSTR pszTitle;
    LPWSTR pszURL;
    LPWSTR pszLogo;
    LPWSTR pszIcon;
    LPWSTR pszWideLogo;
} CHANNELSHORTCUTINFO;

Contains the information associated with a category on the channel bar.

cbSize
Required. Double word value that contains the size of the structure. This value must be specified.
pszTitle
Required. String value that contains the title of the category.
pszURL
Optional. String value that contains the URL to an HTML page for the category.
pszLogo
Optional. String value that contains the URL of the logo associated with the category.
pszIcon
Optional. String value that contains the URL of the icon associated with the category.
pszWideLogo
Optional. String value that contains the URL of the wide logo associated with the channel.


CHANNELENUMINFO

typedef struct _tagChannelInfo{
    LPOLESTR pszTitle;
    LPOLESTR pszPath;
    LPOLESTR pszURL;
    SUBSCRIPTIONSTATE stSubscriptionState;
} CHANNELENUMINFO;

Contains the information on a channel in an enumeration.

pszTitle
String value that contains the channel title. Must use CoTaskMemFree to free the allocated memory when the application is finished using the structure.
pszPath
String value that contains the path to the channel shortcut. Must use CoTaskMemFree to free the allocated memory when the application is finished using the structure.
pszURL
String value that contains the URL of the CDF file for the given channel. Must use CoTaskMemFree to free the allocated memory when the application is finished using the structure.
stSubscriptionState
SUBSCRIPTIONSTATE value that indicates the current state of the subscription.


CHANNELSHORTCUTINFO

typedef _tagChannelShortcutInfo {
    DWORD cbSize;
    LPWSTR pszTitle;
    LPWSTR pszURL;
    LPWSTR pszLogo;
    LPWSTR pszIcon;
    LPWSTR pszWideLogo;
    BOOL bIsSoftware;
} CHANNELSHORTCUTINFO;

Contains the information associated with a channel entry in the channel bar.

cbSize
Required. Double word value that contains the size of the structure. This value must be specified.
pszTitle
Required. String value that contains the channel title. To add the channel to an existing category on the channel bar, the category title should be included in the channel title using the following format:

<category title>\\<channel title>

pszURL
Required. String value that contains the URL of the channel's CDF file.
pszLogo
Optional. String value that contains the URL of the logo associated with the channel.
pszIcon
Optional. String value that contains the URL of the icon associated with the channel.
pszWideLogo
Optional. String value that contains the URL of the wide logo associated with the channel.
bIsSoftware
Boolean value that indicates whether or not this shortcut is a software update.


Structures Structures *
  * Previous Topic: ISubscriptionMgr::UpdateSubscription
  * Next Topic: CHANNELCATEGORYINFO

Structures

This section describes the structures used with the Information Delivery API.


SUBSCRIPTIONINFO

typedef struct _tagSubscriptionInfo {
    DWORD cbSize;
    DWORD fUpdateFlags;
    SUBSCRIPTIONSCHEDULE schedule;
    CLSID customGroupCookie;
    LPVOID pTrigger;
    DWORD dwRecurseLevels;
    DWORD fWebcrawlerFlags;
    BOOL bMailNotification;
    BOOL bGleam;
    BOOL bChangesOnly;
    BOOL bNeedPassword;
    DWORD fChannelFlags;
    BSTR bstrUserName;
    BSTR bstrPassword;
    BSTR bstrFriendlyName;
    DWORD dwMaxSizeKB;
    SUBSCRIPTIONTYPE subType;
    DWORD fTaskFlags;
    DWORD dwReserved;
} SUBSCRIPTIONINFO, *LPSUBSCRIPTIONINFO, *PSUBSCRIPTIONINFO;

Contains the details of a subscription.

cbSize
Unsigned long integer value that contains the size of the structure.
fUpdateFlags
Unsigned long integer value that contains the update flags. Can be a combination of the SUBSCRIPTIONINFOFLAGS. Can also be set to SUBSINFO_ALLFLAGS to set all of the flags.
schedule
SUBSCRIPTIONSCHEDULE value that indicates how often the subscription is updated.
customGroupCookie
CLSID value that contains the cookie associated with the group.
pTrigger
Addresss of a pointer to the TASK_TRIGGER structure.
dwRecurseLevels
Unsigned long integer value that contains the number of levels to recurse.
fWebcrawlerFlags
Unsigned long integer value that contains the flags to control what resources are downloaded by the link crawler. Can be a combination of the WEBCRAWL_RECURSEFLAGS values.
bMailNotification
Boolean value that indicates whether to notify the user through e-mail when the subscribed site has been updated.
bGleam
Boolean value that indicates whether a gleam is displayed when the subscribed site has been updated.
bChangesOnly
Boolean value that indicates whether to only check for changes, or check for changes and download content.
bNeedPassword
Boolean value that indicates whether authentication is required for the subscribed site.
fChannelFlags
Unsigned long integer value containing the flags that control the channel agent. Can be one of the CHANNEL_AGENT_FLAGS.
bstrUserName
String value containing the user name used for authentication.
bstrPassword
String value containing the password used for authentication.
bstrFriendlyName
String value that contains the friendly name for the subscription.
dwMaxSizeKB
Unsigned long integer value that contains the maximum download size (in kilobytes) for this subscripton.
subType
SUBSCRIPTIONTYPE value that indicates the type of subscription.
fTaskFlags
Unsigned long integer value that contains the task flags. Can be one of the TASK_FLAG_* values defined in the Task Scheduler Reference.
dwReserved
Reserved. Must be set to zero.


Hit Logging API

The Channel Definition Format (CDF) files allow content providers to determine which hits get logged for the items included in the CDF file. These logs are posted to the server during a scheduled update and cleared. This API allows developers to verify if hit logging is enabled and write customized entries in the log.

To use these functions, make sure the Urlmon.h header file is in the include directory, and the Urlmon.lib library file is in the library directory of the C/C++ compiler you use.

About Logging

Functions

Structures

About Logging

The logs that are created contain the URL of the resource, the browsing context, whether the information was viewed from the cache, date viewed, time that the viewing started, duration it was viewed, and the custom information. Only the browsing context (normal browser window, theater view, Active Desktop Item, or Microsoft Internet Exporer screen saver) cannot be set by the WriteHitLogging function.

For more information about logging, see the Page-Hit Logging and Client-Side Logging sections in the Creating Active Channels documentation.


Functions Functions *
  * Previous Topic: Hit Logging API
  * Next Topic: IsLoggingEnabled

Functions

The following section contains the functions used for hit logging.


IsLoggingEnabled

BOOL IsLoggingEnabled
    IN LPCTSTR pszUrl
);

Determines if hit logging is enabled for the specified Internet site.

  • Returns TRUE if logging is enabled for the specified URL, or FALSE otherwise.
pszUrl
String value containing the URL of the resource to check.


WriteHitLogging

BOOL WriteHitLogging(
    IN LPHIT_LOGGING_INFO lpLogginginfo
);

Writes an entry into the log for the given resource.

  • Returns TRUE if the log was entered, or FALSE otherwise. Call GetLastError for specific error information. Can be one of the following error codes:
    ERROR_FILE_NOT_FOUND | The URL was not located in the cache log index.
    ERROR_NOT_ENOUGH_MEMORY | Insufficient memory is available in the cache to write this log.
lpLogginginfo
Address of the HIT_LOGGING_INFO structure that contains the information to add to the log.


HIT_LOGGING_INFO

typedef struct _HIT_LOGGING_INFO (
    DWORD dwStructSize;
    LPSTR lpszLoggedUrlName;
    SYSTEMTIME StartTime;
    SYSTEMTIME EndTime;
    LPSTR lpszExtendedInfo
) HIT_LOGGING_INFO, *LPHIT_LOGGING_INFO;

Contains the information to write into a hit log.

dwStructSize
Unsigned long integer value that contains the size, in bytes, of this structure.
lpszLoggedUrlName
String value that contains the name of the cache entry. The name string should not contain any escape characters.
StartTime
SYSTEMTIME value that contains the time to start logging for this URL.
EndTime
SYSTEMTIME value that contains the time to stop logging for this URL. This time is used to determine the duration that the user viewed the resource.
lpszExtendedInfo
String value containing custom information.


Structures

The following section contains the structure used for hit logging.

HIT_LOGGING_INFO


Internet Mail and News Registry Layout

This topic describes how to make your e-mail reader or newsreader available in the list of mail/news programs for Microsoft® Internet Explorer, and how to integrate tightly with Internet Explorer.

Client Registry Settings Overview

Mail Keys

News Keys

Client Registry Settings Overview

Internet Explorer 3.0 supports an open architecture for non-HTTP clients, such as mail and news. This section outlines the registry settings used by Internet Explorer to determine which clients to use and how to use them. The section also outlines the registry settings that third-party clients must provide in order to be recognized and used by the system as the default client.

A new "Clients" key has been defined under HKEY_LOCAL_MACHINE\SOFTWARE. Right now, there are two defined clients: mail and news, which are subkeys of this key.

Key Value Meaning
HKLM\SOFTWARE\Clients\Mail (default) Subkey name where information about the default mail client can be found.

The root key of the information for this client can be found by appending this string to HKLM\Software\Clients\Mail.

HKLM\SOFTWARE\Clients\News (default) Subkey name where information about the default news client can be found.

The root key of the information for this client can be found by appending this string to HKLM\Software\Clients\News

So, for example, if this value is "Internet Mail and News", information about this client can be found at HKLM\SOFTWARE\Clients\Mail\Internet Mail and News.

Mail Keys

Key | Value | Meaning
HKLM\SOFTWARE\Clients\Mail\clientname (default) Friendly name for this client.

The list of clients in the Internet Control Panel is generated by enumerating all the client subkeys and appending the friendly name for each to the list.

HKLM\SOFTWARE\Clients\Mail\clientname\Protocols\mailto (various) Contains a mirror of the registry settings that the application needs to have written under HKEY_CLASSES_ROOT\mailto in order to service mailto URLs.

This entire registry hierarchy will replace the existing mailto: registry hierarchy.

HKLM\SOFTWARE\Clients\Mail\clientname\shell\open\command | (default) | Contains the command line that will launch the mail client into its default view (typically the Inbox).

News Keys

Key | Value | Meaning
HKLM\SOFTWARE\Clients\News\clientname (default) Friendly name for this client.

The list of clients in the Internet Control Panel is generated by enumerating all the client subkeys and appending the friendly name for each to the list.

HKLM\SOFTWARE\Clients\News\clientname\Protocols\news (various) Contains a mirror of the registry settings that the application needs to have written under HKEY_CLASSES_ROOT\news in order to service news URLs.

This entire registry hierarchy will replace the existing news: registry hierarchy.

HKLM\SOFTWARE\Clients\News\clientname\Protocols\nntp (various) Contains a mirror of the registry settings that the application needs to have written under HKEY_CLASSES_ROOT\nntp in order to service nntp URLs.

This entire registry hierarchy will replace the existing nntp: registry hierarchy.

HKLM\SOFTWARE\Clients\News\clientname\Protocols\snews (various) Contains a mirror of the registry settings that the application needs to have written under HKEY_CLASSES_ROOT\snews in order to service snews URLs.

This entire registry hierarchy will replace the existing snews: registry hierarchy.

HKLM\SOFTWARE\Clients\News\clientname\shell\open\command | (default) | Contains the command line that will launch the news client into its default view.


Appendix A: MIME Type Detection in Internet Explorer 4.0

The purpose of MIME type detection, or datasniffing, is to determine the MIME type (also known as content type or media type) of downloaded content using information from the following four sources:

  • The server-supplied MIME type, if available
  • An examination of the actual contents associated with a downloaded URL
  • The file name associated with the downloaded content (assumed to be derived from the associated URL)
  • Registry settings (file extension/MIME type associations or registered applications) in effect during the download

MIME type determination occurs in URL monikers through the FindMimeFromData method. Determining the MIME type allows URL monikers and other components to find and launch the correct object server or application to handle the associated content. This section provides a brief summary of the logic used in determining the MIME type from these sources, and discusses some of the issues involved.

FindMimeFromData contains hard-coded tests for (currently 26) separate MIME types (see Known MIME Types). This means that if a given buffer contains data in the format of one of these MIME types, a test exists in FindMimeFromData that is designed (by scanning through the buffer contents) to recognize the corresponding MIME type. A MIME type is known if it is one of these N MIME types. A MIME type is ambiguous if it is 'text/plain', 'application/octet-stream', an empty string, or null (that is, the server failed to provide it). A MIME type that is neither known nor ambiguous is termed unknown. The MIME types 'text/plain' and 'application/octet-stream' are termed ambiguous because they generally do not provide clear indications of which application or CLSID should be associated as the content handler. A MIME type inferred from any one of the four possible sources can be categorized into one of these three classifications.

FindMimeFromData typically receives three parameters when invoked—the cache file name (assumed to be derived from the associated URL), a pointer to a buffer containing up to the first 256 bytes of the content, and a "suggested" MIME type that typically corresponds to the server-provided MIME type (through the Content-type header). Determining the MIME type proceeds as follows:

  1. If the "suggested" (server-provided) MIME type is unknown (not known and not ambiguous), FindMimeFromData immediately returns this MIME type as the final determination. The reason for this is that new MIME types are continually emerging, and these MIME types might have formats that are difficult to distinguish from the set of hard-coded MIME types for which tests exist. A good example of this is SGML, which can easily be classified incorrectly as HTML because it contains many of the same tags. Rather than weakening the hard-coded tests or risk incorrectly classifying new and as-yet-unknown MIME types for hard-coded known ones, priority is given to the server-supplied MIME type if it is unknown, since these MIME types are both specific and likely uncommon, and there are no hard-coded tests that can positively identify them.
  2. If the server-provided MIME type is either known or ambiguous, the buffer is scanned in an attempt to verify or obtain a MIME type from the actual content. If a positive match is found (one of the hard-coded tests succeeded), this MIME type is immediately returned as the final determination, overriding the server-provided MIME type (this type of behavior is necessary to identify a .gif file being sent as text/html). During scanning, it is determined if the buffer is predominantly text or binary.
  3. If no positive match is obtained during the data scan, and if the server-provided MIME type is known, an attempt is made to determine if the format (text or binary) of the known MIME type conflicts with the format (text or binary) that was determined from scanning the buffer. If no conflict exists (the data scan indicates primarily text and the server-provided MIME type has a text format, or the data scan indicates binary and the server-provided MIME type is a binary format), the server-provided MIME type is returned. The reasoning behind this is that new formats of MIME types might be added over time (image/tif is one example) and the hard-coded tests might not recognize these new formats (a different pattern match might be required). With the assumption that the basic format of MIME types will not change over time from primarily text to binary or vice-versa, it will suffice that the formats of the server-provided MIME type and the format found from scanning the data do not disagree. If this is the case, the server-provided MIME type is returned. The format types for known MIME types are stored in a media information structure in URL monikers.
  4. If no positive match is obtained during the data scan, and the server-provided MIME type is ambiguous or the server-provided MIME type is known, and the data format agreement test in the previous step failed, an attempt is made to parse a file extension from the file name passed in. If this is successful, an attempt is made to find the MIME type associated with the file extension in the registry. This will be returned as the final determination if the MIME type associated with the file extension is unknown. The reason for this added requirement is as follows: If the file extension yields an ambiguous MIME type, this adds no information to what was already obtained through scanning the data. If the file extension yields a known MIME type, this MIME type should have been found during scanning. Since it was not, it is suspect, and is rejected. An example of this is an arbitrary plain-text file being returned through an ISAPI DLL, with the server returning 'text/plain' as the MIME type. Since the server-provided MIME type is ambiguous, a scan of the data is conducted that only confirms that the data is plain text. Subsequently, the file name is parsed for an extension. In this case, because the contents were downloaded using an ISAPI DLL, the URL and hence the cache file name will have a .dll file extension that has the MIME type 'application/x-msdownload' associated in the registry. This MIME type was already scanned for (application/x-msdownload is a known MIME type), was not found, and is therefore the wrong determination (this results in a file download as opposed to the desired behavior, which is to display the text in-pane).
  5. If all of the preceding steps have failed to yield an unambiguous MIME type, a last check is made to see if any application is associated in the registry with the file extension parsed from the file name, if one exists. If an associated application is found, the final determination is automatically set to 'application/octet-stream'. This default value ensures that the registered application will be launched by the shell with the downloaded data, rather than displaying the data in-pane. As an example, this is necessary when downloading, among others, .bat and .cmd files, which are plain text files, are frequently identified by the server as 'text/plain', and have no associated MIME type in the registry. Without the final check for an associated application, these would be displayed in-pane, whereas the desired behavior is to launch the command interpreter. This is ensured by checking for an associated application, and defaulting to the final determined MIME type of 'application/octet-stream'. Other types of files, such as .reg files, behave similarly.
  6. Finally, if no file extension is found, or one is found with no associated MIME type or registered application, the MIME type 'text/plain' is returned if the data scan indicated predominantly text, or 'application/octet-stream' if the data scan indicated binary, since this is the furthest correct determination that could be made.

Known MIME Types

Hard-coded tests exist for the following MIME types that currently exist in URL Moniker:
text/richtext
text/html
audio/x-aiff
audio/basic
audio/wav
image/gif
image/jpeg
image/pjpeg
image/tiff
image/x-png
image/x-xbitmap
image/bmp
image/x-jg
image/x-emf
image/x-wmf
video/avi
video/mpeg
application/postscript
application/base64
application/macbinhex40
application/pdf
application/x-compressed
application/x-zip-compressed
application/x-gzip-compressed
application/java
application/x-msdownload

Registry Locations

Location used by FindMimeFromData to find MIME type and progid from file extension:

HKEY_CLASSES_ROOT\.***

Location used by FindMimeFromData to find application from progid:

HKEY_CLASSES_ROOT\<ProgId>\shell\open\command

Location used by URL monikers to find CLSIDs from MIME types:

HKEY_CLASSES_ROOT\MIME\Database\Content Type


Asynchronous and URL Monikers

Asynchronous monikers allow an application to bind monikers to an object asynchronously. A URL Moniker, which is an application of asynchronous monikers, allows an application to bind a resource specified by the given Uniform Resource Locator (URL) to a moniker.

Asynchronous and URL Monikers Overview

Asynchronous and URL Monikers Reference


Asynchronous and URL Monikers Overview

Monikers bind objects or Uniform Resource Locators (URLs). This section covers the moniker functionality exported by the Urlmon.dll dynamic-link library (DLL).

Introduction

About URLs and Name Spaces

About Monikers

Creating a URL Moniker

Handling BINDINFO Structures

Using the URL Functions

Appendix A: MIME Type Detection in Internet Explorer 4.0

Introduction

If you want to compile programs that use the functionality provided in Urlmon.dll, you must make sure the Urlmon.h header file is in the include directory, and the Urlmon.lib library file is in the library directory, of the C/C++ compiler you use.

This documentation assumes that you have an understanding of Microsoft® Win32® programming. Also, for asynchronous monikers, asynchronous pluggable protocols, and URL monikers you should have an understanding of OLE and COM programming. For the Internet-related interfaces, methods, and functions, an understanding of the format and syntax of URLs is also required. For more information, see RFC 1738, Uniform Resource Locators (URL). You can find this document at http://ds.internic.net/rfc/rfc1738.txt. External Link

About URLs and Name Spaces

A Uniform Resource Locator (URL) follows the syntax described in RFC 1738, which specifies a protocol scheme followed by a scheme-specific portion (<scheme>:<scheme-specific portion>). For example, in the URL http://www.microsoft.com/, "http" is the scheme and "//www.microsoft.com/" is the scheme-specific portion.

The beginning portion of the scheme-specific portion of the URL contains the server name. This portion of the URL is often referred to as the URL name space.

About Monikers

Monikers are used as the basis for linking in OLE. After a moniker is bound to an object, the moniker's IMoniker interface can be used to locate, activate, and access the bound object without having any other specific information on where the actual object is located. For standard monikers, this binding process occurs synchronously, which does not impact performance dramatically because the moniker and object are usually on a local system. Examples of objects that can be bound to a moniker include files, items, and pointers.

Binding a moniker to a URL synchronously impacts performance because the process has to wait for responses from the network before completing the binding process. That is where asynchronous monikers, URL monikers, and the URL functions come in.

Asynchronous Monikers

The functionality provided in Urlmon.dll allows a client program to create monikers that can instantiate a named object and return a pointer to one of the object's interfaces asynchronously.

Interfaces related to asynchronous monikers

  • IAsyncMoniker
  • IBinding
  • IBindStatusCallback
  • IPersistMoniker

Functions related to asynchronous monikers

  • CreateAsyncBindCtx
  • IsAsyncMoniker
  • RegisterBindStatusCallback
  • RevokeBindStatusCallback

URL Monikers

A URL moniker is a specific implementation of asynchronous monikers that allows a client program to create a moniker whose data is referenced by a URL.

Interfaces related to URL monikers

  • IAuthenticate
  • IBindHost
  • ICodeInstall
  • IHttpNegotiate
  • IHttpSecurity
  • IWindowForBindingUI
  • IWinInetHttpInfo
  • IWinInetInfo

Functions related to URL monikers

  • CoGetClassObjectFromURL
  • CreateFormatEnumerator
  • CreateURLMoniker
  • FindMediaTypeClass
  • IsValidURL
  • MkParseDisplayNameEx
  • RegisterFormatEnumerator
  • RegisterMediaTypeClass
  • RegisterMediaTypes
  • RevokeFormatEnumerator
  • UrlMkGetSessionOption
  • UrlMkSetSessionOption

URL Functions

The URL functions combine the capabilities of asynchronous monikers and URL monikers into easy-to-use functions.

URL functions

  • URLDownloadToCacheFile
  • URLDownloadToFile
  • URLOpenBlockingStream
  • URLOpenPullStream
  • URLOpenStream

Creating a URL Moniker

Follow these steps to create a URL moniker for an application:

  1. Optional, but recommended. Implement the IBindStatusCallback interface.
  2. Optional, but recommended. Create an instance of your IBindStatusCallback interface.
  3. Call CreateURLMoniker with the URL and get the IMoniker interface.
  4. Call CreateAsyncBindCtx and get the IBindCtx interface.
  5. If IBindStatusCallback has been implemented, call RegisterBindStatusCallback with the IBindCtx and IBindStatusCallback interfaces.
  6. Call one of the IMoniker binding methods (either IMoniker::BindToStorage or IMoniker::BindToObject) with the IBindCtx interface. In the asynchronous case (where IBindStatusCallback has been implemented), the client application may get a pointer to the IStream or IStorage interface. The client application should call the IUnknown::Release method on the interface and use the interface returned in the IBindStatusCallback::OnDataAvailable call.
  7. If IBindStatusCallback has been implemented, the IBindStatusCallback::GetBindInfo method is called by the IMoniker binding method to get the bind information.

    Warning The size of the BINDINFO structure used by IBindStatusCallback::GetBindInfo has changed with the release of Microsoft Internet Explorer 4.0. Developers must write code that checks the size of the BINDINFO structure that is passed into their implementation of the IBindStatusCallback::GetBindInfo method before writing to members of the structure. For more information, see the Handling BINDINFO Structures section.

  8. If IBindStatusCallback has been implemented, the IBindStatusCallback::OnStartBinding method will be called.
  9. If IBindStatusCallback has been implemented, the IBindStatusCallback::OnProgress method will be called.
  10. If IBindStatusCallback has been implemented, either IBindStatusCallback::OnDataAvailable (if IMoniker::BindToStorage was used) or IBindStatusCallback::OnObjectAvailable (if IMoniker::BindToObject was used) will be called.
  11. If IBindStatusCallback has been implemented, steps 9 and 10 are repeated until the binding is completed.
  12. If IBindStatusCallback has been implemented, the IBindStatusCallback::OnStopBinding method will be called.

Follow these steps to create a URL moniker for a control:

  1. Optional, but recommended. Implement the IBindStatusCallback interface.
  2. Optional, but recommended. Create an instance of the IBindStatusCallback interface.
  3. Call CreateAsyncBindCtx and get the IBindCtx interface.
  4. Call IBindHost::CreateMoniker with the IBindCtx interface and get the IMoniker interface.
  5. Call one of the IBindHost binding methods (either IBindHost::MonikerBindToStorage or IBindHost::MonikerBindToObject) with the IBindCtx, IMoniker, and IBindStatusCallback (if implemented) interfaces.
  6. If IBindStatusCallback has been implemented, the IBindStatusCallback::GetBindInfo method is called by the IMoniker binding method to get the bind information.

    Warning The size of the BINDINFO structure used by IBindStatusCallback::GetBindInfo has changed with the release of Microsoft Internet Explorer 4.0. Developers must write code that checks the size of the BINDINFO structure that is passed into their implementation of the IBindStatusCallback::GetBindInfo method before writing to members of the structure. For more information, see the Handling BINDINFO Structures section.

  7. If IBindStatusCallback has been implemented, the IBindStatusCallback::OnStartBinding method will be called.
  8. If IBindStatusCallback has been implemented, the IBindStatusCallback::OnProgress method will be called.
  9. If IBindStatusCallback has been implemented, either IBindStatusCallback::OnDataAvailable (if IBindHost::MonikerBindToStorage was used) or IBindStatusCallback::OnObjectAvailable (if IBindHost::MonikerBindToObject was used) will be called.
  10. If IBindStatusCallback has been implemented, steps 8 and 9 are repeated until the binding is completed.
  11. If IBindStatusCallback has been implemented, the IBindStatusCallback::OnStopBinding method will be called.

Note IE4/MSHTML does not support the IBindStatusCallback interface. Applications that are hosting IE4/MSHTML and want to get callbacks on the progress of the bind operation should implement the IPropertyNotifySink interface.

Handling BINDINFO Structures

The BINDINFO structure is used by methods, such as IBindStatusCallback::GetBindInfo, to pass information that specifies how a bind operation should be handled. To properly write information to this structure, the client application should:

  • Clear the BINDINFO structure.
  • Check the size of the BINDINFO structure to determine what version has been passed.

Clearing the BINDINFO structure, before writing information into it, prevents members that are not being used from containing incorrect data. The following code fragment demonstrates how to clear the structure.

//pbindinfo is a pointer to a BINDINFO structure
DWORD cbSize = pbindinfo->cbSize;
memset(pbindinfo,0,cbSize);
pbindinfo->cbSize = cbSize;

Since the size of the BINDINFO structure has increased in Internet Explorer 4.0, client applications should check the size of the structure that is passed into their implementation of any methods that use this structure.

The following sample demonstrates how to check the size of the structure for accessing members of the BINDINFO structure beyond cbstgmedData.

if (pbindinfo->cbSize >= offsetof(BINDINFO, dwReserved))
{
    // Write to additional fields.
}
else
{
    // Added functionality is not available, so make any adjustments necessary.
}

Using the URL Functions

The URLDownloadToCacheFile, URLDownloadToFile, URLOpenBlockingStream, URLOpenPullStream, and URLOpenStream functions combine the capabilities of asynchronous monikers and URL monikers into easy-to-use functions.

The following sample demonstrates how to use the URLOpenBlockingStream function.

IStream* pStream;
char buffer[0x100];
DWORD dwGot;
HRESULT hr = NOERROR;

// Open a blocking type stream to the web site stored in the string szWebSite.
URLOpenBlockingStream( 0, szWebSite, &pStream, 0, 0);

do {
    hr = pStream->Read( buffer, sizeof(buffer), &dwGot );
    // Do something with contents of buffer.
} while( SUCCEEDED(hr) && hr != S_FALSE);

return TRUE;

pStream->Release();


Asynchronous and URL Monikers Reference

This reference covers the APIs that are exported from the Urlmon.dll dynamic-link library. These APIs allow a developer to:

  • Create monikers that can instantiate a named object and return a pointer to one of the object's interfaces asynchronously.
  • Create an asynchronous moniker whose data is referenced by a URL (Uniform Resource Locator).
  • Implement customized URL protocols, name space handlers, and MIME filters.
  • Use functions that combine the functionality of asynchronous monikers and URL monikers.
  • Manage URL security zones.

The reference contains the interfaces, methods, functions, structures, enumerated types, security zone flags, and error codes used by these APIs.

Interfaces

Methods

Functions

Structures

Enumerated Types

Error Codes


Error Codes

This section lists the error codes and messages exposed by monikers, URLs, security zones, and pluggable protocols.

INET_E_AUTHENTICATION_REQUIRED
Authentication is needed to access the object.
INET_E_CANNOT_CONNECT
The attempt to connect to the Internet has failed.
INET_E_CANNOT_INSTANTIATE_OBJECT
CoCreateInstance failed.
INET_E_CANNOT_LOAD_DATA
The object could not be loaded.
INET_E_CANNOT_LOCK_REQUEST
The requested resource could not be locked.
INET_E_CONNECTION_TIMEOUT
The Internet connection has timed out.
INET_E_DATA_NOT_AVAILABLE
An Internet connection was established, but the data cannot be retrieved.
INET_E_DEFAULT_ACTION
Use the default action.
INET_E_DOWNLOAD_FAILURE
The download has failed (the connection was interrupted).
INET_E_INVALID_REQUEST
The request was invalid.
INET_E_INVALID_URL
The URL could not be parsed.
INET_E_NO_SESSION
No Internet session was established.
INET_E_NO_VALID_MEDIA
The object is not in one of the required types.
INET_E_OBJECT_NOT_FOUND
The object was not found.
INET_E_QUERYOPTION_UNKNOWN
The requested option is unknown.
INET_E_REDIRECT)TO_DIR
The request is being redirected to a directory.
INET_E_REDIRECTING
The request is being redirected.
INET_E_RESOURCE_NOT_FOUND
The server or proxy was not found.
INET_E_SECURITY_PROBLEM
A security problem was encountered.
INET_E_UNKNOWN_PROTOCOL
The protocol is not known and no pluggable protocols have been entered that match.
INET_E_USE_DEFAULT_PROTOCOLHANDLER
Use the default protocol handler.
INET_E_USE_DEFAULT_SETTINGS
Use the default settings.


BINDF

typedef  {
    BINDF_ASYNCHRONOUS = 0x00000001,
    BINDF_ASYNCSTORAGE = 0x00000002,
    BINDF_NOPROGRESSIVERENDERING = 0x00000004,
    BINDF_OFFLINEOPERATION = 0x00000008,
    BINDF_GETNEWESTVERSION = 0x00000010,
    BINDF_NOWRITECACHE = 0x00000020,
    BINDF_NEEDFILE = 0x00000040,
    BINDF_PULLDATA = 0x00000080,
    BINDF_IGNORESECURITYPROBLEM = 0x00000100,
    BINDF_RESYNCHRONIZE = 0x00000200,
    BINDF_HYPERLINK = 0x00000400,
    BINDF_NO_UI = 0x00000800,
    BINDF_SILENTOPERATION = 0x00001000,
    BINDF_PRAGMA_NO_CACHE = 0x00002000,
    BINDF_FREE_THREADED = 0x00010000,
    BINDF_DIRECT_READ = 0x00020000,
    BINDF_FORMS_SUBMIT = 0x00040000,
    BINDF_GETFROMCACHE_IF_NET_FAIL = 0x00080000
} BINDF;

Values from the BINDF enumeration are returned to the moniker from the client's IBindStatusCallback::GetBindInfo method. These values specify the type of binding the client wants from the moniker.

BINDF_ASYNCHRONOUS
Moniker should return immediately from IMoniker::BindToStorage or IMoniker::BindToObject. The actual result of the object bind or the data backing the storage arrives asynchronously. The client is notified through calls to its IBindStatusCallback::OnDataAvailable or IBindStatusCallback::OnObjectAvailable method. If the client does not specify this flag, the bind operation will be synchronous, and the client will not receive any data from the bind operation until the IMoniker::BindTo Xxx call returns.
BINDF_ASYNCSTORAGE
Client of the IMoniker::BindToStorage method prefers that the storage and stream objects returned in IBindStatusCallback::OnDataAvailable return E_PENDING when they reference data not yet available through their read methods, rather than blocking until the data becomes available. This flag applies only to BINDF_ASYNCHRONOUS operations. Note that asynchronous stream objects return E_PENDING while data is still downloading and return S_FALSE for the end of the file.
BINDF_NOPROGRESSIVERENDERING
Do not allow progressive rendering.
BINDF_OFFLINEOPERATION
Bind to a cached version of the resource.
BINDF_GETNEWESTVERSION
Bind operation should retrieve the newest version of the data/object possible. For URL monikers, this flag maps to the Win32 Internet API flag, INTERNET_FLAG_RELOAD, which forces a dowload of the requested resource.
BINDF_NOWRITECACHE
Bind operation should not store retrieved data in the disk cache.
BINDF_NEEDFILE
Downloaded resource must be saved in the cache.
BINDF_PULLDATA
Asynchronous moniker allows the client of IMoniker::BindToStorage to drive the bind operation by pulling the data, rather than having the moniker drive the operation by pushing the data to the client. Specifically, when this flag is specified, new data is only read/downloaded after the client finishes reading all data that is currently available. This means data is only downloaded for the client after the client does an IStream::Read operation that blocks or returns E_PENDING. When the client specifies this flag, it must be sure to read all the data it can, even data that is not necessarily available yet. When this flag is not specified, the moniker continues downloading data and calls the client with IBindStatusCallback::OnDataAvailable whenever new data is available. This flag applies only to BINDF_ASYNCHRONOUS bind operations.
BINDF_IGNORESECURITYPROBLEM
Ignore any security problems.
BINDF_RESYNCHRONIZE
Resynchronizes the resource. For URL monikers, this flag maps to the Win32 Internet API flag, INTERNET_FLAG_RESYNCHRONIZE, which reloads an HTTP resource if the resource has been modified since the last time it was downloaded. All FTP and Gopher resources are reloaded.
BINDF_HYPERLINK
Allow hyperlinks.
BINDF_NO_UI
Do not display any user interfaces.
BINDF_SILENTOPERATION
Operate silently. No user interface or user notification should occur.
BINDF_PRAGMA_NO_CACHE
Do not store the resource in the cache.
BINDF_FREE_THREADED
Reserved for future use.
BINDF_DIRECT_READ
Client does not need to know the exact size of the data available, so the information is read directly from the source.
BINDF_FORMS_SUBMIT
Handle this transaction as a forms submittal.
BINDF_GETFROMCACHE_IF_NET_FAIL
Retrieve the resource from the cache if the attempt to download the resource from the network fails.

See also IBindStatusCallback::OnDataAvailable, IBindStatusCallback::OnObjectAvailable, IBindStatusCallback::OnStartBinding


BINDINFOF

typedef enum tagBINDINFOF {
    BINDINFOF_URLENCODESTGMEDDATA,
    BINDINFOF_URLENCODEDEXTRAINFO
} BINDINFOF;

Values from the BINDINFOF enumeration are passed to the moniker as part of the BINDINFO structure. The moniker calls the IBindStatusCallback::GetBindInfo method on the client to obtain additional information about the bind operation in the BINDINFO structure. The grfBindInfoF member of the BINDINFO structure determines the use of URL encoding during the binding operation.

BINDINFOF_URLENCODESTGMEDDATA
Use URL encoding to pass in the data provided in the stgmedData member of the BINDINFO structure for PUT and POST operations.
BINDINFOF_URLENCODEDEXTRAINFO
Use URL encoding to pass in the data provided in the szExtraInfo member of the BINDINFO structure.

See also IBindStatusCallback::GetBindInfo, BINDINFO


BINDSTATUS

typedef enum tagBINDSTATUS {
    BINDSTATUS_FINDINGRESOURCE,
    BINDSTATUS_CONNECTING,
    BINDSTATUS_REDIRECTING,
    BINDSTATUS_BEGINDOWNLOADDATA,
    BINDSTATUS_DOWNLOADINGDATA,
    BINDSTATUS_ENDDOWNLOADDATA,
    BINDSTATUS_BEGINDOWNLOADCOMPONENTS,
    BINDSTATUS_INSTALLINGCOMPONENTS,
    BINDSTATUS_ENDDOWNLOADCOMPONENTS,
    BINDSTATUS_USINGCACHEDCOPY,
    BINDSTATUS_SENDINGREQUEST,
    BINDSTATUS_CLASSIDAVAILABLE,
    BINDSTATUS_MIMETYPEAVAILABLE,
    BINDSTATUS_CACHEFILENAMEAVAILABLE,
    BINDSTATUS_BEGINSYNCOPERATION,
    BINDSTATUS_ENDSYNCOPERATION,
    BINDSTATUS_BEGINUPLOADDATA,
    BINDSTATUS_UPLOADINGDATA,
    BINDSTATUS_ENDUPLOADINGDATA,
    BINDSTATUS_PROTOCOLCLASSID,
    BINDSTATUS_ENCODING,
    BINDSTATUS_VERFIEDMIMETYPEAVAILABLE,
    BINDSTATUS_CLASSINSTALLLOCATION,
    BINDSTATUS_DECODING
} BINDSTATUS;

A single value from the BINDSTATUS enumeration is passed to the client in the IBindStatusCallback::OnProgress method to indicate the progress of the bind operation.

BINDSTATUS_FINDINGRESOURCE
Bind operation is finding the resource that holds the object or storage being bound to. The szStatusText parameter to the IBindStatusCallback::OnProgress method provides the display name of the resource being searched for (for example, "www.microsoft.com").
BINDSTATUS_CONNECTING
Bind operation is connecting to the resource that holds the object or storage being bound to. The szStatusText parameter to the IBindStatusCallback::OnProgress method provides the display name of the resource being connected to (for example, an IP address).
BINDSTATUS_REDIRECTING
Bind operation has been redirected to a different data location. The szStatusText parameter to the IBindStatusCallback::OnProgress method provides the display name of the new data location.
BINDSTATUS_BEGINDOWNLOADDATA
Bind operation has begun receiving the object or storage being bound to. The szStatusText parameter to the IBindStatusCallback::OnProgress method provides the display name of the data location.
BINDSTATUS_DOWNLOADINGDATA
Bind operation continues to receive the object or storage being bound to. The szStatusText parameter to the IBindStatusCallback::OnProgress method provides the display name of the data location.
BINDSTATUS_ENDDOWNLOADDATA
Bind operation has finished receiving the object or storage being bound to. The szStatusText parameter to the IBindStatusCallback::OnProgress method provides the display name of the data location.
BINDSTATUS_BEGINDOWNLOADCOMPONENTS
Bind operation is beginning to download the component.
BINDSTATUS_INSTALLINGCOMPONENTS
Bind operation is installing the component.
BINDSTATUS_ENDDOWNLOADCOMPONENTS
Bind operation has finished downloading the component.
BINDSTATUS_USINGCACHEDCOPY
Bind operation is retrieving the requested object or storage from a cached copy. The szStatusText parameter to the IBindStatusCallback::OnProgress method is NULL.
BINDSTATUS_SENDINGREQUEST
Bind operation is requesting the object or storage being bound to. The szStatusText parameter to the IBindStatusCallback::OnProgress method provides the display name of the object (for example, a file name).
BINDSTATUS_CLASSIDAVAILABLE
CLSID available.
BINDSTATUS_MIMETYPEAVAILABLE
MIME type is available.
BINDSTATUS_CACHEFILENAMEAVAILABLE
Temporary or cache file name is available. The temporary file name may be returned if BINDF_NOWRITECACHE is called. The temporary file will be deleted once the storage is released.
BINDSTATUS_BEGINSYNCOPERATION
Synchronous operation started.
BINDSTATUS_ENDSYNCOPERATION
Synchronous operation completed.
BINDSTATUS_BEGINUPLOADDATA
File upload started.
BINDSTATUS_UPLOADINGDATA
File upload in progress.
BINDSTATUS_ENDUPLOADINGDATA
File upload completed.
BINDSTATUS_PROTOCOLCLASSID
CLSID associated with the protocol scheme is available.
BINDSTATUS_ENCODING
Encoding data.
BINDSTATUS_VERFIEDMIMETYPEAVAILABLE
Verfied MIME type available.
BINDSTATUS_CLASSINSTALLLOCATION
Class install location available.
BINDSTATUS_DECODING
Decoding data.

See also IBindStatusCallback::OnProgress


BINDSTRING

typedef enum tagBINDSTRING{
    BINDSTRING_HEADERS = 1,
    BINDSTRING_ACCEPT_MIMES,
    BINDSTRING_EXTRA_URL,
    BINDSTRING_LANGUAGE,
    BINDSTRING_USERNAME,
    BINDSTRING_PASSWORD,
    BINDSTRING_UA_PIXELS,
    BINDSTRING_UA_COLOR,
    BINDSTRING_OS,
    BINDSTRING_USERAGENT,
    BINDSTRING_ACCEPT_ENCODINGS,
    BINDSTRING_POST_COOKIE,
    BINDSTRING_POST_DATA_MIME,
    BINDSTRING_URL
} BINDSTRING;

Contains the values for the bind string types available for IInternetBindInfo::GetBindString.

BINDSTRING_HEADERS
Retrieve the headers associated with the request.
BINDSTRING_ACCEPT_MIMES
Retrieve the accepted MIME types.
BINDSTRING_EXTRA_URL
BINDSTRING_LANGUAGE
Retrieve the language types accepted.
BINDSTRING_USERNAME
Retrieve the username sent with the request.
BINDSTRING_PASSWORD
Retrieve the password sent with the request.
BINDSTRING_UA_PIXELS
BINDSTRING_UA_COLOR
BINDSTRING_OS
Retrieve the server's operating system.
BINDSTRING_USERAGENT
Retrieve the user agent string used.
BINDSTRING_ACCEPT_ENCODINGS
Retrieve the encoding types accepted.
BINDSTRING_POST_COOKIE
Retrieve the posted cookie.
BINDSTRING_POST_DATA_MIME
Retrieve the MIME type of the posted data.
BINDSTRING_URL
Retrieve the URL.


BINDVERB

typedef enum {
    BINDVERB_GET,
    BINDVERB_POST,
    BINDVERB_PUT,
    BINDVERB_CUSTOM
} BINDVERB;

Values from the BINDVERB enumeration are passed to the moniker as part of the BINDINFO structure. The moniker calls the IBindStatusCallback::OnProgress method on the client to obtain additional information about the bind operation in the BINDINFO structure. The dwBindVerb member of the BINDINFO structure specifies an action, such as an HTTP request, to be performed during the binding operation.

BINDVERB_GET
Perform an HTTP GET operation, the default operation. The stgmedData member of the BINDINFO structure should be set to TYMED_NULL for the GET operation.
BINDVERB_POST
Perform an HTTP POST operation. The data to be posted should be specified in the stgmedData member of the BINDINFO structure.
BINDVERB_PUT
Perform an HTTP PUT operation. The data to put should be specified in the stgmedData member of the BINDINFO structure.
BINDVERB_CUSTOM
Perform a custom operation that is protocol-specific. See the szCustomVerb member of the BINDINFO structure. The data to be used in the custom operation should be specified in the stgmedData member of the BINDINFO structure.

See also IBindStatusCallback::GetBindInfo, BINDINFO


BSCF

typedef {
    BSCF_FIRSTDATANOTIFICATION,
    BSCF_INTERMEDIATEDATANOTIFICATION
    BSCF_LASTDATANOTIFICATION,
    BSCF_DATAFULLYAVAILABLE,
    BSCF_AVAILABLEDATASIZEUNKNOWN
} BSCF;

Values from the BSCF enumeration are passed to the client in IBindStatusCallback::OnDataAvailable to indicate the type of data that is available.

BSCF_FIRSTDATANOTIFICATION
Identify the first call to IBindStatusCallback::OnDataAvailable for a given bind operation.
BSCF_INTERMEDIATEDATANOTIFICATION
Identify an intermediate call to IBindStatusCallback::OnDataAvailable for a bind operation.
BSCF_LASTDATANOTIFICATION
Identify the last call to IBindStatusCallback::OnDataAvailable for a bind operation.
BSCF_DATAFULLYAVAILABLE
All of the requested data is available.
BSCF_AVAILABLEDATASIZEUNKNOWN
Size of the data available is unknown.


*
  * Previous Topic: BSCF
  * Next Topic: QUERYOPTION

CIP_STATUS

Obsolete. Do not use.


Enumerated Types

This section contains the enumerated types that are exposed by Urlmon.dll.
BINDF
BINDINFOF
BINDSTATUS
BINDSTRING
BINDVERB
BSCF
CIP_STATUS
QUERYOPTION


QUERYOPTION

typdef enum _tagQUERYOPTION {
    QUERY_EXPIRATION_DATE = 1,
    QUERY_TIME_OF_LAST_CHANGE,
    QUERY_CONTENT_ENCODING,
    QUERY_CONTENT_TYPE,
    QUERY_REFRESH,
    QUERY_RECOMBINE,
    QUERY_CAN_NAVIGATE,
    QUERY_USES_NETWORK,
    QUERY_IS_CACHED,
    QUERY_IS_INSTALLEDENTRY,
    QUERY_IS_CACHED_OR_MAPPED,
    QUERY_USES_CACHE
} QUERYOPTION;

This enumerated type contains the available query options.

QUERY_EXPIRATION_DATE
Request the expiration date in a SYSTEMTIME format.
QUERY_TIME_OF_LAST_CHANGE
Request the last changed date in a SYSTEMTIME format.
QUERY_CONTENT_ENCODING
Request the content encoding schema.
QUERY_CONTENT_TYPE
Request the content type header.
QUERY_REFRESH
Request a refresh.
QUERY_RECOMBINE
Combine the page URL with the nearest base URL if TRUE.
QUERY_CAN_NAVIGATE
Check if the protocol can navigate.
QUERY_USES_NETWORK
Check if the URL needs to access the network.
QUERY_IS_CACHED
Check if the resource is cached locally.
QUERY_IS_INSTALLEDENTRY
Check if this resource is installed locally on a CD-ROM.
QUERY_IS_CACHED_OR_MAPPED
Check if this resource is stored in the cache or if it is on a mapped drive (in a cache container).
QUERY_USES_CACHE
Check if the specified protocol uses the Internet cache.


CoGetClassObjectFromURL

STDAPI CoGetClassObjectFromURL(
    [in] REFCLSID rclsid,
    [in] LPCWSTR szCodeURL,
    [in] DWORD dwFileVersionMS,
    [in] DWORD dwFileVersionLS,
    [in] LPCWSTR szContentType,
    [in] LPBINDCTX pBindCtx,
    [in] DWORD dwClsContext,
    [in] LPVOID pvReserved,
    [in] REFIID riid,
    [out] VOID ppv * *
);

Returns a factory object for a given CLSID.

  • Returns one of the following values:
    S_OK | The operation completed successfully and the ppv parameter contains the requested interface pointer.
    E_NOINTERFACE | The desired interface pointer is not available.
    MK_S_ASYNCHRONOUS | Component code will be downloaded and installed asynchronously. The client will receive notifications through the IBindStatusCallback interface registered on pBindCtx.
rclsid
CLSID of the ActiveX™ object to be installed. If the value is CLSID_NULL, szContentType is used to determine the CLSID.
szCodeURL
URL pointing to the code for the ActiveX object.
dwFileVersionMS
Major version number for the object to be installed. If this value and the value for dwFileVersionLS are both 0xFFFFFFFF, it is assumed that the latest version of the code is always desired. This means that Internet Component Download will always attempt to download new code.
dwFileVersionLS
Minor version number for the object to be installed. If this value and the value for dwFileVersionMS are both 0xFFFFFFFF, it is assumed that the latest version of the code is always desired. This means that Internet Component Download will always attempt to download new code.
szContentType
MIME type to be understood by the installed ActiveX object. If rclsid is CLSID_NULL, this string is used to determine the CLSID of the object to be installed. Note that this parameter is useful only when trying to download a viewer for a particular media type, when the MIME type of media is known but the CLSID is not.
pBindCtx
Bind context to use for downloading/installing component code. Register IBindStatusCallback in this bind context to receive callbacks during the download and installation process.
dwClsContext
Values taken from the CLSCTX enumeration specifying the execution context for the class object.
pvReserved
Reserved. Must be set to NULL.
riid
Interface to obtain on the factory object. Usually, this interface is IClassFactory.
ppv
Upon return for synchronous calls, the pointer in which to store the interface pointer.

If no CLSID is specified (CLSID_NULL), this function chooses the appropriate CLSID for interpreting the Internet mail extensions (MIME) type specified in szContentType. If the desired object is installed on the system, it is instantiated. Otherwise, the necessary code is downloaded and installed from the location specified in szCodeURL.


CoInternetCombineUrl

STDAPI CoInternetCombineUrl(
    LPCWSTR pwzBaseUrl,
    LPCWSTR pwzRelativeUrl,
    DWORD dwCombineFlags,
    LPWSTR pwzResult,
    DWORD cchResult,
    DWORD *pcchResult,
    DWORD dwReserved
);

Combines a base and relative URL into a full URL.

  • Returns one of the following values:
    S_OK | Success.
    S_FALSE | The buffer was too small to contain the resulting URL.
    INET_E_DEFAULT_ACTION
pwzBaseUrl
String value containing the base URL.
pwzRelativeUrl
String value containing the relative URL.
dwCombineFlags
Double-word value that controls the combining process.
pwzResult
String variable where the full URL will be stored.
cchResult
Double-word value that contains the size of the buffer.
pcchResult
Address of a double-word value to store the size of the information stored in the buffer.
dwReserved
Reserved. Must be set to zero.


CoInternetCompareUrl

STDAPI CoInternetCompareUrl(
    [in] LPCWSTR pwzUrl1,
    [in] LPCWSTR pwzUrl2,
    [in] DWORD dwCompareFlags
);

Compares two URLs and determines if they are equal.

  • Returns S_OK if equal, or S_FALSE otherwise.
pwzUrl1
String value that contains the first URL.
pwzUrl2
String value that contains the second URL.
dwCompareFlags
Double-word value that controls how the comparison should be done. Set to TRUE to ignore slashes, FALSE otherwise.


CoInternetQueryInfo

STDAPI CoInternetQueryInfo(
    LPCWSTR pwzUrl,
    QUERYOPTION QueryOption,
    DWORD dwQueryFlags,
    LPVOID pvBuffer,
    DWORD cbBuffer,
    DWORD *pcbBuffer,
    DWORD dwReserved
);

Retrieves information related to the specified URL.

  • Returns one of the following values:
    S_OK | Success.
    S_FALSE | The buffer was too small to store the information.
    INET_E_QUERYOPTION_UNKNOWN | The option requested is unknown.
pwzUrl
String value containing the URL.
QueryOption
QUERYOPTION value that indicates what option to query.
dwQueryFlags
Double-word value containing the query flags.
pvBuffer
Address of the buffer where the information will be stored.
cbBuffer
Double-word value containing the size of the buffer.
pcbBuffer
Address of a double-word variable where the size of the requested information will be stored.
dwReserved
Reserved. Must be set to zero.


CopyBindInfo

HRESULT CopyBindInfo(
    const BINDINFO *pcbiSrc,
    BINDINFO *pcbiDest
);

Copies the given BINDINFO structure.

pcbiSrc
Address of the BINDINFO structure to be copied.
pcbiDest
Address of the BINDINFO structure to store the copy.


CopyStgMedium

HRESULT CopyStgMedium(
    const STGMEDIUM *pcstgmedSrc,
    STGMEDIUM *pstgmedDest
);

Copies the given STGMEDIUM structure.

pcstgmedSrc
Address of the STGMEDIUM structure to copy.
pstgmedDest
Address of the STGMEDIUM structure to store the copy in.


CreateAsyncBindCtx

HRESULT CreateAsyncBindCtx(
    [in] DWORD dwReserved,
    [in] IBindStatusCallback *pbsc,
    [in] IEnumFORMATETC *penumfmtetc,
    [out] IBindCtx **ppbc
);

Creates an asynchronous bind context for use with asynchronous monikers.

  • Returns one of the following values:
    S_OK | Success.
    E_INVALIDARG | One or more parameters are invalid.
    E_OUTOFMEMORY | The method ran out of memory and did not complete.
dwReserved
Reserved for future use; must be zero.
pbsc
Address of the IBindStatusCallback interface used for receiving data availability and progress notification.
penumfmtetc
Address of the IEnumFORMATETC interface that can be used to enumerate formats for format negotiation during binding. This parameter can be NULL, in which case the calling application is not interested in format negotiation during binding, and the default format of the object will be bound to it.
ppbc
Indirect pointer to the IBindCtx interface for the new bind context.

This function automatically registers the IBindStatusCallback and the IEnumFORMATETC interfaces with the bind context. If the client does not want to receive certain notifications, it can choose to implement those callback methods as empty function stubs (returning E_NOTIMPL), and they should not be called.

The RegisterBindStatusCallback function can also be used to register callback interfaces in the bind context.

See also IBindStatusCallback, RegisterBindStatusCallback


CreateAsyncBindCtxEx

STDAPI CreateAsyncBindCtxEx(
    IBindCtx *pbc,
    DWORD dwOptions,
    IBindStatusCallback *pBSCb,
    IEnumFORMATETC *pEnum,
    IBindCtx **ppBC,
    DWORD reserved
);

Creates an asynchronous bind context for use with asynchronous monikers.

pbc
Address of the IBindCtx interface.
dwOptions
Double-word value that contains the option values.
pBSCb
Address of the IBindStatusCallback interface.
pEnum
Address of the IEnumFORMATETC interface.
ppBC
Address of a pointer to the IBindCtx interface that is returned.
reserved
Reserved. Must be set to zero.


CreateFormatEnumerator

HRESULT CreateFormatEnumerator(
    [in] UINT cfmtetc,
    [in] FORMATETC *rgfmtetc,
    [out] IEnumFORMATETC **ppenumfmtetc
);

Creates an object that implements IEnumFORMATETC over a static array of FORMATETC structures.

  • Returns S_OK if successful, or E_INVALIDARG if one or more parameters are invalid.
cfmtetc
Number of FORMATETC structures in the static array specified by the rgfmtetc parameter. The cfmtetc parameter cannot be zero.
rgfmtetc
Address of a static array of FORMATETC structures.
ppenumfmtetc
Indirect pointer to the IEnumFORMATETC interface on the enumerator object.

See also RegisterFormatEnumerator, RevokeFormatEnumerator


CreateURLBinding

STDAPI CreateURLBinding(
    LPCWSTR lpszUrl,
    IBindCtx *pbc,
    IBinding **ppBdg
);

Creates an IBinding interface associated with the specified URL.

lpszUrl
String value that contains the URL.
pbc
Address of the IBindCtx interface associated with the URL.
ppBdg
Address of a pointer to the IBinding interface that is created.


CreateURLMoniker

HRESULT CreateURLMoniker(
    [in] IMoniker *pmkContext,
    [in] LPWSTR szURL,
    [out] IMoniker **ppmk
);

Creates a URL moniker from either a full URL string or from a base context URL moniker and a partial URL string.

  • Returns one of the following values:
    S_OK | Success.
    E_OUTOFMEMORY | The operation ran out of memory.
    MK_E_SYNTAX | A moniker could not be created because szURL does not correspond to valid URL syntax for a full or partial URL. This is uncommon, because most parsing of the URL occurs during binding and because the syntax for URLs is extremely flexible.
pmkContext
Address of the IMoniker interface for the URL moniker to use as the base context when the szURL parameter is a partial URL string. The pmkContext parameter can be NULL.
szURL
Display name to be parsed.
ppmk
Indirect pointer to an IMoniker interface for the new URL moniker.


FindMediaType

STDAPI FindMediaType(
    LPCSTR rgszTypes,
    CLIPFORMAT *rgcfTypes
);

Retrieves the media type.

rgszTypes
String value that contains the media types.
rgcfTypes
Address of the CLIPFORMAT value.


FindMediaTypeClass

HRESULT FindMediaTypeClass(
    [in] LPBC pbc,
    [in] LPCSTR szType,
    [out] CLSID *pclsID,
    [in] DWORD dwReserved
);

Retrieves the CLSID for the specified media type.

  • Returns S_OK if successful, or E_INVALIDARG if one or more parameters are invalid.
pbc
Address of the bind context on which the media type is registered.
szType
String identifying the media types. This parameter cannot be NULL.
pclsID
Address of the CLSID corresponding to the specified media types in szType.
dwReserved
Reserved for future use; must be zero.

See also RegisterMediaTypeClass, RegisterMediaTypes


FindMimeFromData

FindMimeFromData(
    LPBC pBC,
    LPCWSTR pwzUrl,
    LPVOID pBuffer,
    DWORD cbSize,
    LPCWSTR pwzMimeProposed,
    DWORD dwMimeFlags,
    LPWSTR *ppwzMimeOut,
    DWORD dwReserved
);

Determines the MIME type from the data provided.

pBC
Address of the bind context. Can be set to NULL.
pwzUrl
String value that contains the URL of the data. Can be set to NULL if pBuffer contains the data to be sniffed.
pBuffer
Address of the buffer containing the data to be sniffed. Can be set to NULL if pwzUrl contains a valid URL.
cbSize
Double-word value that contains the size of the buffer.
pwzMimeProposed
String value containing the proposed MIME type. Can be set to NULL.
dwMimeFlags
Not currently defined. Must be set to zero.
ppwzMimeOut
Address of a string value containing the suggested MIME type.
dwReserved
Reserved. Must be set to zero.


Functions

This section describes the functions included in monikers, URLs, security zones, and pluggable protocols.
CoGetClassObjectFromURL
CoInternetCombineUrl
CoInternetCompareUrl
CoInternetQueryInfo
CopyBindInfo
CopyStgMedium
CreateAsyncBindCtx
CreateAsyncBindCtxEx
CreateFormatEnumerator
CreateURLBinding
CreateURLMoniker
FindMediaType
FindMediaTypeClass
FindMimeFromData
GetClassURL
IsAsyncMoniker
IsValidURL
MkParseDisplayNameEx
ObtainUserAgentString
RegisterBindStatusCallback
RegisterFormatEnumerator
RegisterMediaTypeClass
RegisterMediaTypes
ReleaseBindInfo
RevokeBindStatusCallback
RevokeFormatEnumerator
URLDownloadToCacheFile
URLDownloadToFile
UrlMkGetSessionOption
UrlMkSetSessionOption
URLOpenBlockingStream
URLOpenPullStream
URLOpenStream


GetClassURL

STDAPI GetClassURL(
    LPCWSTR szURL,
    CLSID *pClsID
);

Gets the class identification associated with the URL.

szURL
String that contains the URL.
pClsID
Address of the class identification associated with the URL.


IsAsyncMoniker

HRESULT IsAsyncMoniker(
    [in] IMoniker *pmk
);

Tests if a moniker supports asynchronous binding.

  • Returns S_OK if the specified moniker is asynchronous, or E_INVALIDARG if the pmk parameter is invalid.
pmk
Address of the IMoniker interface on the moniker to be tested.

A moniker implementation indicates that it is asynchronous by supporting the IAsyncMoniker interface, an empty interface that is just an implementation of IUnknown. The IsAsyncMoniker function tests for support of IAsyncMoniker and also handles composite monikers correctly.

See also IAsyncMoniker


IsValidURL

HRESULT IsValidURL(
    [in] LPBC pBC,
    [in] LPCWSTR szURL,
    [in] DWORD dwReserved
);

Determines if a specified string is a valid URL.

  • Returns one of the following values:
    S_OK | The szURL parameter contains a valid URL.
    S_FALSE | The szURL parameter does not contain a valid URL.
    E_INVALIDARG | One of the parameters is invalid.
pBC
Address of the IBindCtx interface. Optional and currently ignored. Should be set to NULL.
szURL
URL whose validity is to be checked. For the purposes of this function, a valid URL must specify an absolute path.
dwReserved
Reserved for future use. Must be set to zero.

Relative URLs are not considered valid by this function.


MkParseDisplayNameEx

HRESULT MkParseDisplayNameEx(
    [in] IBindCtx*pbc,
    [in] LPWSTR  szDisplayName,
    [out] ULONG *pcchEaten,
    [out] IMoniker **ppmk
);

Given a string, returns a moniker of the object that the string denotes.

  • Returns one of the following values:
    S_OK | Success.
    E_OUTOFMEMORY | The operation ran out of memory.
    MK_E_SYNTAX | Parsing failed because szDisplayName could only be partially resolved into a moniker. In this case, pcchEaten has the number of characters that were successfully parsed into a moniker prefix.
pbc
Address of the bind context in which to accumulate bound objects.
szDisplayName
Display name to be parsed.
pcchEaten
Address of the number of characters of the display name that were successfully parsed. Most useful on syntax error, when a nonzero value is often returned and therefore a subsequent call to MkParseDisplayNameEx with the same pbc parameter and a shortened szDisplayName parameter should return a valid moniker.
ppmk
Indirect pointer to the resulting moniker.

See also IParseDisplayName


ObtainUserAgentString

HRESULT ObtainUserAgentString(
    DWORD dwOption,
    LPCSTR pcszUAOut,
    DWORD *cbSize
);

Retrieves the user agent string in use.

dwOption
Reserved. Must be set to zero.
pcszUAOut
String value that contains the user agent string currently being used.
cbSize
Address of an unsigned long integer value that contains the length of the string.


RegisterBindStatusCallback

HRESULT RegisterBindStatusCallback(
    [in] IBindCtx *pbc,
    [in] IBindStatusCallback *pbsc,
    [out] IBindStatusCallback **ppbscPrevious,
    [in] DWORD  dwReserved
);

Registers a callback interface with an existing bind context.

  • Returns one of the following values:
    S_OK | Success.
    E_INVALIDARG | One or more parameters are invalid.
    E_OUTOFMEMORY | There was insufficient memory to register the callback with the bind context.
pbc
Address of the IBindCtx interface to receive callbacks from.
pbsc
Address of the IBindStatusCallback interface implementation to be registered.
ppbscPrevious
Address of a pointer to a previously registered instance of IBindStatusCallback.
dwReserved
Reserved for future use.

The IBindStatusCallback interface passed into the pbsc parameter will receive callbacks on any binding operations using the bind context passed into the pbc parameter.

Only the last IBindStatusCallback interface that was registered to a particular bind context will receive callbacks. The implementation of IBindStatusCallback could pass the callbacks it receives to the previously registered IBindStatusCallback interface using the address of a pointer in the ppbscPrevious parameter.

See also IBindStatusCallback, RevokeBindStatusCallback


RegisterFormatEnumerator

HRESULT RegisterFormatEnumerator(
    [in] LPBC pBC,
    [in] IEnumFORMATETC *pEFetc,
    [in] DWORD  reserved
);

Registers a FORMATETC enumerator object onto the given bind context.

  • Returns S_OK if successful, or E_INVALIDARG if one or more parameters are invalid.
pBC
Address of the IBindCtx interface for the bind context on which to register the enumerator.
pEFetc
Address of the IEnumFORMATETC interface for the enumerator to be registered.
reserved
Reserved. Must be set to zero.

The enumerator is used to determine what format types are preferred for the bind operation. Typically, the pEFetc parameter would be the pointer obtained through a call to CreateFormatEnumerator.

See also CreateFormatEnumerator, RevokeFormatEnumerator


RegisterMediaTypeClass

HRESULT RegisterMediaTypeClass(
    [in] LPBC pbc,
    [in] UINT ctypes,
    [in] LPCSTR  *rgszTypes,
    [in] CLSID  *rgclsID,
    [in] DWORD  dwReserved
);

Registers a mapping of media types to CLSIDs to override the default mapping specified in the registry. The new mapping is used in calls to IMoniker::BindToObject when binding objects in the specified bind context.

  • Returns S_OK if successful, or E_INVALIDARG if one or more parameters are invalid.
pbc
Address of the IBindCtx interface for the bind context in which the media types are to be registered.
ctypes
Number of media type strings in the rgszTypes array. This parameter cannot be zero.
rgszTypes
Address of an array of strings identifying the media types to be registered. None of these strings can be NULL.
rgclsID
Address of an array of CLSIDs corresponding to the media type strings in the rgszTypes array.
dwReserved
Reserved for future use; must be zero.

This function is primarily used by moniker clients calling IMoniker::BindToObject to override the default registry mapping between MIME types and CLSIDs. In most cases, the default mapping provided in the registry is used. However, a Web browser might want the CLSID for its HTML viewer to be associated with .txt files without changing the default registry association for text files. The override is used for all bind operations using the specified bind context.

See also RegisterMediaTypes


RegisterMediaTypes

HRESULT RegisterMediaTypes (
    [in] UINT  ctypes,
    [in] LPCSTR *rgszTypes,
    [out] CLIPFORMAT *rgcfTypes
);

Registers media type strings.

  • Returns S_OK if successful, or E_INVALIDARG if one or more parameters are invalid.
ctypes
Number of media type strings in the rgszTypes array. This parameter cannot be zero.
rgszTypes
Address of an array of strings identifying the media types to be registered. None of the strings in the array can be NULL. Can be one of the values in the following list.
Value | Meaning
CF_NULL | 0
SZ_URLCONTEXT | (L"URL Context")
CFSTR_MIME_FRACTALS | (TEXT("application/fractals"))
CFSTR_MIME_POSTSCRIPT | (TEXT("application/postscript"))
CFSTR_MIME_RAWDATA | (TEXT("application/octet"))
CFSTR_MIME_AIIF | (TEXT("audio/aiif"))
CFSTR_MIME_BASICAUDIO | (TEXT("audio/basic"))
CFSTR_MIME_WAV | (TEXT("audio/wav"))
CFSTR_MIME_X_AIIF | (TEXT("audio/x-aiif"))
CFSTR_MIME_X_REALAUDIO | (TEXT("audio/x-pn-realaudio"))
CFSTR_MIME_X_WAV | (TEXT("audio/x-wav"))
CFSTR_MIME_BMP | (TEXT("image/bmp"))
CFSTR_MIME_GIF | (TEXT("image/gif"))
CFSTR_MIME_JPEG | (TEXT("image/jpeg"))
CFSTR_MIME_TIFF | (TEXT("image/tiff"))
CFSTR_MIME_XBM | (TEXT("image/xbm"))
CFSTR_MIME_X_BITMAP | (TEXT("image/x-bitmap"))
CFSTR_MIME_HTML | (TEXT("text/html"))
CFSTR_MIME_TEXT | (TEXT("text/plain"))
CFSTR_MIME_AVI | (TEXT("video/avi"))
CFSTR_MIME_MPEG | (TEXT("video/mpeg"))
CFSTR_MIME_QUICKTIME | TEXT("video/quicktime"))
CFSTR_MIME_X_MSVIDEO | (TEXT("video/x-msvideo"))
CFSTR_MIME_X_SGI_MOVIE | (TEXT("video/x-sgi-movie"))
rgcfTypes
Address of an array of the 32-bit values assigned to corresponding media types in rgszTypes.

See also RegisterMediaTypeClass


ReleaseBindInfo

ReleaseBindInfo(
    BINDINFO *pbindinfo
);

Releases the resources used by the specified BINDINFO structure.

pbindinfo
Address of the specified BINDINFO structure.


RevokeBindStatusCallback

HRESULT RevokeBindStatusCallback(
    [in] IBindCtx *pbc,
    [in] IBindStatusCallback *pbsc
);

Revokes a bind status callback interface previously registered on a bind context.

  • Returns one of the following values:
    S_OK | Success.
    E_FAIL | The callback interface specified is not registered on the specified bind context.
    E_INVALIDARG | One or more parameters are invalid.
pbc
Address of the IBindCtx interface for the bind context from which the callback interface is to be revoked.
pbsc
Address of the IBindStatusCallback interface to revoke.

This function will not succeed if it is made during a bind operation.

Note that it is not necessary to make this call for every use of a bind context. It is possible, although not recommended, to reuse the same bind context and the same callback for several bind operations. Upon calling the IUnknown::Release method, all registered objects on that bind context are revoked, including the callback interfaces. Therefore, releasing a bind context implicitly releases all registered callbacks. However, if you choose to reuse a bind context, you can use RevokeBindStatusCallback to remove a registered callback so it is not reused.

See also IBindStatusCallback, RegisterBindStatusCallback


RevokeFormatEnumerator

HRESULT RevokeFormatEnumerator(
    [in] LPBC pbc,
    [in] IEnumFORMATETC *pEFetc
);

Removes a format enumerator from the given bind context.

  • Returns S_OK if the enumerator was successfully removed, or E_INVALIDARG if one or more parameters are invalid.
pbc
Address of the IBindCtx interface for the bind context from which the enumerator is to be revoked.
pEFetc
Address of the IEnumFORMATETC interface for the enumerator to revoke.

This function removes a format enumerator from the bind context specified in pbc. It must previously have been registered with a call to RegisterFormatEnumerator.

Note that it is not necessary to make this call for every use of a bind context. It is possible (although not recommended) to reuse the same bind context and the same format enumerator for several bind operations. Upon calling IUnknown::Release, all registered objects on that bind context are revoked, including the format enumerator interfaces. Therefore, releasing a bind context implicitly releases all registered format enumerators. However, if you choose to reuse a bind context, you can use RevokeFormatEnumerator to remove a registered format enumerator so it is not reused.

See also RegisterFormatEnumerator


URLDownloadToCacheFile

HRESULT URLDownloadToCacheFile(
    LPUNKNOWN lpUnkcaller,
    LPCSTR szURL,
    LPTSTR szFileName,
    DWORD dwBufLength,
    DWORD dwReserved,
    IBindStatusCallback *pBSC
);

Downloads data into the Internet cache and returns the file name of the cache location for retrieving the bits. The client can choose to be notified of progress through a notification callback.

lpUnkcaller
Address of the controlling IUnknown interface of the calling ActiveX™ component (if the caller is an ActiveX component). If the caller is not an ActiveX component, this value can be set to NULL. Otherwise, the caller is a COM object that is contained in another component (such as an ActiveX control within the context of an HTML page). This parameter represents the outermost IUnknown of the calling component. The function attempts the download within the context of the ActiveX client framework and allows the caller's container to receive callbacks on the progress of the download.
szURL
URL to be downloaded. Cannot be NULL.
szFileName
Name of the downloaded file. Cannot be NULL.
dwBufLength
DWORD value that contains the size of the szFileName buffer or a flag. If a flag is set to dwBufLength, the buffer is assumed to be of size MAX_PATH. The flag can be one of the following values:
URLOSTRM_GETNEWESTVERSION | Download the resource from the Internet, if it is newer, and store it in the cache.
URLOSTRM_USECACHEDCOPY | Download the resource from the cache if it is available; otherwise, download it from the Internet.
URLOSTRM_USECACHEDCOPY_ONLY | Only download the resource from the cache.
dwReserved
Reserved. Must be set to zero.
pBSC
Address of the caller's IBindStatusCallback interface. URLDownloadToCacheFile calls this interface's IBindStatusCallback::OnProgress method on a connection activity, including the arrival of data. IBindStatusCallback::OnDataAvailable is never called. Implementing IBindStatusCallback::OnProgress allows a caller to implement a user interface or other progress monitoring functionality. It also allows the download operation to be canceled by returning E_ABORT from the IBindStatusCallback::OnProgress call. Can be NULL.

This function always returns a file name if the download operation succeeds. If the given URL is a "file:" URL, URLDownloadToCacheFile directly returns the file name for the "file:" URL rather than making a copy to the cache. If the given URL is an Internet URL ("http:", "ftp:"), URLDownloadToCacheFile downloads this file and returns the local file name of the cached copy. Using this function ensures that a file name is returned without unnecessary copying of data.


URLDownloadToFile

HRESULT URLDownloadToFile(
    LPUNKNOWN pCaller,
    LPCSTR szURL,
    LPCSTR szFileName,
    DWORD dwReserved,
    LPBINDSTATUSCALLBACK lpfnCB
);

Downloads bits from the Internet and saves them to a file. The client can choose to be notified of progress through a notification callback.

pCaller
Address of the controlling IUnknown interface of the calling ActiveX component (if the caller is an ActiveX component). If the calling application is not an ActiveX component, this value can be set to NULL. Otherwise, the caller is a COM object that is contained in another component (such as an ActiveX control within the context of an HTML page). This parameter represents the outermost IUnknown of the calling component. The function attempts the download within the context of the ActiveX client framework and allows the caller's container to receive callbacks on the progress of the download.
szURL
String containing the URL to be downloaded. Cannot be NULL.
szFileName
String containing the name of the file to create for bits that come from the download.
dwReserved
Reserved for future use. Must be zero.
lpfnCB
Address of the caller's IBindStatusCallback interface. URLDownloadToFile calls this interface's IBindStatusCallback::OnProgress method on a connection activity, including the arrival of data. IBindStatusCallback::OnDataAvailable is never called. Implementing IBindStatusCallback::OnProgress allows a caller to implement a user interface or other progress monitoring functionality. It also allows the download operation to be canceled by returning E_ABORT from the IBindStatusCallback::OnProgress call. Can be NULL.


UrlMkGetSessionOption

WINOLEAPI UrlMkGetSessionOption(
    [in] DWORD dwOption,
    [in] LPVOID pBuffer,
    [in] DWORD dwBufferLength,
    [out] DWORD *pdwBufferLength,
    [in] DWORD dwReserved
);

Sets options for the current Internet session.

  • Returns one of the following values:
    S_OK | Option was successfully set.
    E_INVALIDARG | The option is not supported.
    E_FAIL | Unable to set the option.
dwOption
Unsigned long integer value containing the session options to be retrieved. Currently, URL monikers support only the URLMON_OPTION_USERAGENT value, which retrieves the current user agent string.
pBuffer
Address of the buffer containing the new session settings.
dwBufferLength
Double-word value containing the size of pBuffer.
pdwBufferLength
Address of a double-word value containing the size of the data stored in the buffer or the size required to store the data if the buffer size was insufficient.
dwReserved
Reserved for future use. Must be set to zero.


UrlMkSetSessionOption

HRESULT UrlMkSetSessionOption(
    [in] DWORD dwOption,
    [in] LPVOID pBuffer,
    [in] DWORD dwBufferLength,
    [in] DWORD dwReserved
);

Sets options for the current Internet session.

  • Returns S_OK if options were successfully set, or E_INVALIDARG if one of the parameters is invalid.
dwOption
Session option to be set. Can be one of the following values:
INTERNET_OPTION_PROXY | Sets the proxy settings. pBuffer must contain an INTERNET_PROXY_INFO structure. INTERNET_OPTION_PROXY and INTERNET_PROXY_INFO are defined in the Wininet.h file. For more information, see the Microsoft Win32 Internet Function Reference.
INTERNET_OPTION_REFRESH | Sets the value that determines if the proxy information can be reread from the registry. The value TRUE indicates that the proxy information can be reread from the registry. For more information on this value, see the Microsoft Win32 Internet Function Reference.
pBuffer
Buffer containing the new session settings.
dwBufferLength
Size of pBuffer.
dwReserved
Reserved for future use. Must be set to zero.

This function maps directly to the Windows® Internet function InternetSetOption, although UrlMkSetSessionOption allows only global options to be set.

To use this function, the client code must include the Wininet.h header file, which declares values for the dwOption parameter and structures for the pBuffer parameter.


URLOpenBlockingStream

HRESULT URLOpenBlockingStream(
    LPUNKNOWN pCaller,
    LPCSTR szURL,
    LPSTREAM *ppStream,
    DWORD dwReserved,
    LPBINDSTATUSCALLBACK lpfnCB
);

Creates a blocking type stream object from a URL and downloads the data from the Internet. When the data is downloaded, the client application or control can read it using the IStream::Read method.

pCaller
Address of the controlling IUnknown interface. If the client application or control is not a COM object or ActiveX control, the parameter can be set to NULL.
szURL
String containing the URL to be converted to a stream object. Cannot be NULL.
ppStream
Address of the IStream interface on the stream object created by this function. The caller can read from the stream as soon as it has this pointer.
dwReserved
Reserved for future use. Must be zero.
lpfnCB
Address of the caller's IBindStatusCallback interface. Can be set to NULL.

This function is synchronous and will only return after all the data has been downloaded from the Internet.

URLOpenBlockingStream calls the IBindStatusCallback::OnProgress method (if provided) on a connection activity, including the arrival of data. IBindStatusCallback::OnDataAvailable is never called. Implementing IBindStatusCallback::OnProgress allows a caller to implement a user interface or other progress monitoring functionality. It also allows the download operation to be canceled by returning E_ABORT from the IBindStatusCallback::OnProgress call.


URLOpenPullStream

HRESULT URLOpenPullStream(
    LPUNKNOWN pCaller,
    LPCSTR szURL,
    DWORD dwReserved,
    LPBINDSTATUSCALLBACK lpfnCB
);

Creates a pull type stream object from a URL.

pCaller
Address of the controlling IUnknown interface of the calling ActiveX component (if the caller is an ActiveX component). If the caller is not an ActiveX component, this value can be set to NULL. Otherwise, the caller is a COM object that is contained in another component (such as an ActiveX control within the context of an HTML page). This parameter represents the outermost IUnknown of the calling component. The function attempts the download within the context of the ActiveX client framework and allows the caller's container to receive callbacks on the progress of the download.
szURL
String containing the URL to be converted to a stream object. Cannot be NULL.
dwReserved
Reserved for future use. Must be zero.
lpfnCB
Address of the caller's IBindStatusCallback interface, on which URLOpenPullStream calls IBindStatusCallback::OnDataAvailable when data arrives from the Internet. IBindStatusCallback::OnDataAvailable can return E_ABORT to abort the download.

The pull model is slightly more cumbersome than the push model, but it allows the client to control the amount of Internet access for the download.

The data is downloaded from the Internet on demand. If not enough data is available locally to satisfy the requests, the IStream::Read call will not block until enough data has arrived. Instead, IStream::Read immediately returns E_PENDING, and URLOpenPullStream requests the next packet of data from the Internet server.


URLOpenStream

HRESULT URLOpenStream(
    LPUNKNOWN pCaller,
    LPCSTR szURL,
    DWORD dwReserved,
    LPBINDSTATUSCALLBACK lpfnCB
);

Creates a push type stream object from a URL.

pCaller
Address of the controlling IUnknown interface of the calling ActiveX component (if the caller is an ActiveX component). If the caller is not an ActiveX component, this value can be set to NULL. Otherwise, the caller is a COM object that is contained in another component (such as an ActiveX control within the context of an HTML page). This parameter represents the outermost IUnknown of the calling component. The function attempts the download within the context of the ActiveX client framework and allows the caller's container to receive callbacks on the progress of the download.
szURL
String containing the URL to be converted to a stream object. Cannot be NULL.
dwReserved
Reserved for future use. Must be zero.
lpfnCB
Address of the caller's IBindStatusCallback interface, on which URLOpenStream calls IBindStatusCallback::OnDataAvailable when data arrives from the Internet. IBindStatusCallback::OnDataAvailable can return E_ABORT to abort the download.

The data is downloaded from the Internet as fast as possible. When data is available, it is pushed at the client through a notification callback.


Interfaces

This section contains the interfaces exposed by monikers, URLs, security zones, and pluggable protocols.
IAsyncMoniker
IAuthenticate
IBindHost
IBinding
IBindProtocol
IBindStatusCallback
ICodeInstall
IHttpNegotiate
IHttpSecurity
IPersistMoniker
ISoftDistExt
IWindowForBindingUI
IWinInetHttpInfo
IWinInetInfo


Methods

This section contains the methods exposed by monikers, URLs, security zones, and pluggable protocols.
IAuthenticate::Authenticate
IBindHost::CreateMoniker
IBindHost::MonikerBindToObject
IBindHost::MonikerBindToStorage
IBinding::Abort
IBinding::GetBindResult
IBinding::GetPriority
IBinding::Resume
IBinding::SetPriority
IBinding::Suspend
IBindStatusCallback::GetBindInfo
IBindStatusCallback::GetPriority
IBindStatusCallback::OnDataAvailable
IBindStatusCallback::OnLowResource
IBindStatusCallback::OnObjectAvailable
IBindStatusCallback::OnProgress
IBindStatusCallback::OnStartBinding
IBindStatusCallback::OnStopBinding
IHttpNegotiate::BeginningTransaction
IHttpNegotiate::OnResponse
IHttpSecurity::OnSecurityProblem
IPersistMoniker::GetCurMoniker
IPersistMoniker::IsDirty
IPersistMoniker::Load
IPersistMoniker::Save
IPersistMoniker::SaveCompleted
IWindowForBindingUI::GetWindow
IWinInetHttpInfo::QueryInfo
IWinInetInfo::QueryOption


IAsyncMoniker

IAsyncMoniker provides an implementation of the IUnknown interface, which allows client programs to determine if a moniker supports asynchronous binding. No additional methods are supported by this interface.


IAuthenticate::Authenticate

HRESULT Authenticate(
    [out] HWND *phwnd,
    [out] LPWSTR *pszUserName,
    [out] LPWSTR *pszPassword
);

Supplies authentication support to a URL moniker from a client application.

  • Returns one of the following values:
    S_OK | Authentication was successful.
    E_ACCESSDENIED | Authentication failed.
    E_INVALIDARG | One or more of the parameters are invalid.
phwnd
Address of a client-provided HWND of the parent window for a default user interface. If no user interface is desired, the client must provide a username and password in the other parameters, and this handle is set to zero.
pszUserName
String that contains the username to use for authentication. If the client returns a value here, it should also set phwnd to zero.
pszPassword
String that contains the password to use for authentication. If the client returns a value here, it should also set phwnd to zero.

The default user interface is able to handle any authentication schemes recognized by the Win32 Internet API. Currently, the username and password options only handle the Basic authentication scheme.

This method is related to the InternetErrorDlg function in the Win32 Internet API. For more information about the Win32 Internet API, see Win32 Internet Functions Overview.


IAuthenticate

This interface is implemented by the client application to provide the URL moniker with information to authenticate the user.
IAuthenticate method | Description
Authenticate | Supplies authentication support to a URL moniker from a client application.

Urlmon.dll uses the IUnknown::QueryInterface method on your implementation of IBindStatusCallback to obtain a pointer to your IAuthenticate interface. If the application is hosting Mshtml.dll, Mshtml.dll will request a pointer to your IAuthenticate interface by calling IUnknown::QueryInterface on your IServiceProvider interface.

See also IHttpNegotiate, IServiceProvider, IWindowForBindingUI, IWinInetInfo


IBindHost::CreateMoniker

HRESULT CreateMoniker (
    [in] LPOLESTR szName,
    [in] IBindCtx *pBC,
    [out] IMoniker **ppmk,
    [in] DWORD dwReserved
);

Creates a moniker to bind to a URL.

szName
URL to bind to.
pBC
Address of the IBindCtx interface.
ppmk
Address of the pointer to the moniker that is created.
dwReserved
Reserved. Must be set to zero.


IBindHost

This interface is implemented by an ActiveX container that wants controls to do asynchronous data transfers through it.
IBindHost methods | Description
CreateMoniker | Creates a moniker to bind to a URL.
MonikerBindToObject | Binds the moniker to an object.
MonikerBindToStorage | Binds the moniker to storage.


IBindHost::MonikerBindToObject

HRESULT MonikerBindToObject (
    [in] IMoniker *pMk,
    [in] IBindCtx *pBC,
    [in] IBindStatusCallback *pBSC,
    [in] REFIID riid,
    [out] void **ppvObj
);

Binds a moniker to an object.

pMk
Address of the IMoniker interface.
pBC
Address of the IBindCtx interface.
pBSC
Address of the IBindStatusCallback interface.
riid
IID of the interface that the client application wants to use to communicate with the object.
ppvObj
Address of the interface identified by riid. If ppvObj is non-NULL, the application must call the IUnknown::AddRef method on the interface and call IUnknown::Release when it is finished using the interface.


IBindHost::MonikerBindToStorage

HRESULT MonikerBindToStorage (
    [in] IMoniker *pMk,
    [in] IBindCtx *pBC,
    [in] IBindStatusCallback *pBSC,
    [in] REFIID riid,
    [out] void **ppvObj
);

Binds a moniker to storage.

pMk
Address of the IMoniker interface.
pBC
Address of the IBindCtx interface.
pBSC
Address of the IBindStatusCallback interface.
riid
IID of the storage interface requested.
ppvObj
Address of the storage interface. If ppvObj is non-NULL, the application must call the IUnknown::AddRef method on the interface and call IUnknown::Release when it is finished using the interface.


IBinding::Abort

HRESULT Abort(void);

Permanently ends the bind operation.

  • Returns one of the following values:
    S_OK | Success.
    E_FAIL | The bind operation could not be aborted.
    S_FALSE | The bind operation was already aborted.

This method cannot be called from within an implementation of the IBindStatusCallback::OnStartBinding method.

After aborting the bind operation, the client must still release any pointers obtained during the binding. No IBindStatusCallback notifications will be called except IBindStatusCallback::OnStopBinding.

Releasing the last IBinding interface does not terminate the bind operation.

See also IBindStatusCallback::OnStopBinding


IBinding::GetBindResult

HRESULT GetBindResult(
    [out] CLSID *pclsidProtocol,
    [out] DWORD *pdwBindResult,
    [out] LPWSTR *pszBindResult,
    [in] DWORD dwReserved
);

Queries the protocol-specific outcome of a bind operation.

  • Returns S_OK if successful, or E_INVALIDARG if one of the parameters is not valid.
pclsidProtocol
Address of the CLSID variable for the protocol used.
pdwBindResult
Address of the DWORD variable containing the protocol-specific bind result string.
pszBindResult
Address of the LPWSTR variable containing the protocol-specific bind result.
dwReserved
Reserved for future use; must be NULL.

This method is typically called by the client of an asynchronous moniker when the client's IBindStatusCallback::OnStopBinding method is called.

See also IBindStatusCallback::OnStopBinding


IBinding::GetPriority IBinding::GetPriority *
  * Previous Topic: IBinding::GetBindResult
  * Next Topic: IBinding::Resume

IBinding::GetPriority

HRESULT GetPriority(
    [out] LONG *pnPriority
);

Not currently implemented.


IBinding

This interface provides methods that allow the client program using an asynchronous moniker to control the progress of the bind operation. An asynchronous moniker calls the client's IBindStatusCallback::OnStartBinding method to provide the client program with a pointer to the IBinding interface.
IBinding methods | Description
Abort | Permanently ends the bind operation
GetBindResult | Queries the protocol-specific outcome of a bind operation.
GetPriority | Not currently implemented.
Resume | Not currently implemented.
SetPriority | Not currently implemented.
Suspend | Not currently implemented.


IBinding::Resume IBinding::Resume *
  * Previous Topic: IBinding::GetPriority
  * Next Topic: IBinding::SetPriority

IBinding::Resume

HRESULT Resume(void);

Not currently implemented.


IBinding::SetPriority IBinding::SetPriority *
  * Previous Topic: IBinding::Resume
  * Next Topic: IBinding::Suspend

IBinding::SetPriority

HRESULT SetPriority(
    [in] LONG nPriority
);

Not currently implemented.


IBinding::Suspend IBinding::Suspend *
  * Previous Topic: IBinding::SetPriority
  * Next Topic: IBindStatusCallback::GetBindInfo

IBinding::Suspend

HRESULT Suspend(void);

Suspends the bind operation.


IBindProtocol IBindProtocol *
  * Previous Topic: IBinding
  * Next Topic: IBindStatusCallback

IBindProtocol

Not currently supported.


IBindStatusCallback::GetBindInfo

HRESULT GetBindInfo(
    [out] DWORD *pgrfBINDF,
    [in, out] BINDINFO *pbindinfo
);

Obtains the bind information for the bind operation when called by an asynchronous moniker.

  • Returns S_OK if successful, or E_INVALIDARG if one or more parameters are invalid.
pgrfBINDF
Address of a value taken from the BINDF enumeration indicating whether the bind should proceed synchronously or asynchronously.
pbindinfo
Address of the BINDINFO structure, which describes how the client wants the binding to occur.

The moniker calls this method in its implementations of the IMoniker::BindToObject and IMoniker::BindToStorage methods to obtain information about the specific bind operation.

Asynchronous moniker clients should be aware that a moniker might call this method more than once during a bind operation. A proper implementation of IBindStatusCallback::GetBindInfo should prepare for this possibility. If returning data in the pbindinfo parameter, the implementation should allocate the appropriate data (szExtraInfo and/or stgmedData) at the time of each call. In this way, if the callback is never called, data is never allocated; if the callback is called more than once, it will work correctly. The first time this callback is received by the asynchronous moniker client is before the call to IMoniker::BindToStorage or IMoniker::BindToObject.

Even when the value of pgrfBINDF is BINDF_ASYNCHRONOUS, it is possible that the original call to IMoniker::BindToStorage or IMoniker::BindToObject might return synchronously rather than returning the MK_S_ASYNCHRONOUS flag. Clients of asynchronous monikers should always prepare for this possibility. Specifically, to avoid memory leaks, it is important to make sure to release the pointer returned by a call to either method.

One way to deal with this case is to call your own implementation of IBindStatusCallback::OnDataAvailable or IBindStatusCallback::OnObjectAvailable in order to use the same code path (regardless of whether you bind synchronously or asynchronously).

If the BINDF_PULLDATA value is not set in the pgrfBINDF parameter, Urlmon.dll sets the BINDF_NEEDFILE value. If BINDF_NEEDFILE is set, binding of resources that cannot be cached (such as an https resource) will fail.

Warning The size of the BINDINFO structure has changed with the release of Microsoft Internet Explorer 4.0. Developers must write code that checks the size of the BINDINFO structure that is passed into their implementation of this method before writing to members of the structure. See Handling BINDINFO Structures in Asynchronous and URL Monikers Overview for more information.

See also BINDF, BINDINFO, RegisterBindStatusCallback


IBindStatusCallback::GetPriority

HRESULT GetPriority(
    [out] LONG *pnPriority
);

Obtains the priority for the bind operation when called by an asynchronous moniker.

  • Returns S_OK if successful, or E_INVALIDARG if the pnPriority parameter is invalid.
pnPriority
Address of a LONG value indicating the priority of this bind operation. Priorities can be any of the constants defined for prioritizing threads. For details, see the Win32 documentation for SetThreadPriority and GetThreadPriority.

The moniker calls this method, typically prior to initiating the bind operation, to obtain the priority for the bind operation. This method can be called at any time during the bind operation if the moniker needs to make new priority decisions.

The moniker can use pnPriority to set the priority of a thread associated with a bind operation, but more commonly it will interpret the priority to perform its own scheduling among multiple bind operations. Note that the policy for determining priority for URL monikers is not yet determined. The moniker must not change the priority of the thread used for calling IMoniker::BindToStorage or IMoniker::BindToObject.

Notes to implementers

A client can return E_UNIMPL or S_OK if it is not interested in receiving this notification.


IBindStatusCallback

This interface accepts information on an asynchronous binding operation. A client requesting an asynchronous bind operation must provide a notification object exposing the IBindStatusCallback interface. The asynchronous moniker provides information on the bind operation to the client by calling notification methods on the client's IBindStatusCallback interface. This interface also allows the client to pass additional bind information to the moniker by calling IBindStatusCallback::GetBindInfo and IBindStatusCallback::GetPriority after receiving a call from IMoniker::BindToObject or IMoniker::BindToStorage.

Only the last IBindStatusCallback interface that was registered will be called.
IBindStatusCallback methods | Description
GetBindInfo | Gets bind information for the bind operation.
GetPriority | Gets data during asynchronous bind operations.
OnDataAvailable | Provides data to the client as it becomes available during asynchronous bind operations.
OnLowResource | Not currently implemented.
OnObjectAvailable | Passes the requested object interface pointer to the client.
OnProgress | Indicates the current progress of this bind operation.
OnStartBinding | Tells the client which callback methods it is registered to receive.
OnStopBinding | Indicates the end of the bind operation.


IBindStatusCallback::OnDataAvailable

HRESULT OnDataAvailable(
    [in] DWORD  grfBSCF,
    [in] DWORD  dwSize,
    [in] FORMATETC *pfmtetc,
    [in] STGMEDIUM *pstgmed
);

Provides data to the client as it becomes available during asynchronous bind operations.

  • Returns S_OK if successful, or E_INVALIDARG if one or more parameters are invalid.
grfBSCF
DWORD value taken from the BSCF enumeration indicating the kind of data available.
dwSize
Size, in bytes, of total data available from the current bind operation.
pfmtetc
Address of the FORMATETC structure that indicates the format of the available data. This parameter is used when the bind operation is a result of the IMoniker::BindToStorage method. If there is no format associated with the available data, pfmtetc might contain CF_NULL. Each different call to IBindStatusCallback::OnDataAvailable can pass in a new value for this parameter, although they all should always point to the same data.
pstgmed
Address of the STGMEDIUM structure that contains the pointers to the interfaces (such as IStream and IStorage) that can be used to access the data. In the asynchronous case, client applications may have received a second pointer to the IStream or IStorage interface from the IMoniker::BindToStorage method, upon which the client application must call IUnknown::Release to avoid memory leaks.

During asynchronous IMoniker::BindToStorage bind operations, an asynchronous moniker calls this method to provide data to the client as it becomes available.

Note that the behavior of the storage returned in pstgmed depends on the BINDF flags returned in the IBindStatusCallback::GetBindInfo method. This storage can be asynchronous or blocking, and the bind operation can follow a data pull model or a data push model. Furthermore, it is important to note that for BINDF_PULLDATA bind operations, it is not possible to seek backward into data streams provided in IBindStatusCallback::OnDataAvailable. On the other hand, for data push model bind operations, it is commonly possible to seek back into a data stream and read any data that has been downloaded for an ongoing IMoniker::BindToStorage operation.

See also BINDF, BSCF, IBindStatusCallback::GetBindInfo


IBindStatusCallback::OnLowResource IBindStatusCallback::OnLowResource *
  * Previous Topic: IBindStatusCallback::OnDataAvailable
  * Next Topic: IBindStatusCallback::OnObjectAvailable

IBindStatusCallback::OnLowResource

HRESULT OnLowResource(
    [in] DWORD  dwReserved
);

Not currently implemented.


IBindStatusCallback::OnObjectAvailable

HRESULT OnObjectAvailable(
    [in] REFIID  riid,
    [in] IUnknown *punk
);

Passes the requested object interface pointer to the client. This method is called in response to an IMoniker::BindToObject operation.

  • Returns S_OK if successful, or E_INVALIDARG if one or more parameters are invalid.
riid
Interface identifier of the requested interface.
punk
Address of the IUnknown interface on the object requested in the call to IMoniker::BindToObject. The client should call AddRef on this pointer to maintain a reference to the object.

This method is never called for IMoniker::BindToStorage operations.

See also IBindStatusCallback::OnDataAvailable


IBindStatusCallback::OnProgress

HRESULT OnProgress(
    [in] ULONG  ulProgress,
    [in] ULONG  ulProgressMax,
    [in] ULONG  ulStatusCode,
    [in] LPCWSTR  szStatusText
);

Indicates the current progress of the bind operation.

  • Returns S_OK if successful, or E_INVALIDARG if one or more parameters are invalid.
ulProgress
Current progress of the bind operation relative to the expected maximum indicated in the ulProgressMax parameter.
ulProgressMax
Expected maximum value of the ulProgress parameter for the duration of calls to IBindStatusCallback::OnProgress for this bind operation. Note that this value might change across calls to this method. A value of zero means that the maximum value of ulProgress is unknown (for example, in the IMoniker::BindToStorage method when the data download size is unknown).
ulStatusCode
Additional information regarding the progress of the bind operation. Valid values are taken from the BINDSTATUS enumeration and include:
BINDSTATUS_BEGINDOWNLOADCOMPONENTS | The download operation has begun downloading code for COM components that will be installed before the object can be instantiated. The szStatusText parameter accompanying IBindStatusCallback::OnProgress provides the display name of the component being downloaded.
BINDSTATUS_INSTALLINGCOMPONENTS | The download operation has downloaded code and is installing it. The szStatusText parameter accompanying IBindStatusCallback::OnProgress provides the display name of the component being installed.
BINDSTATUS_ENDDOWNLOADCOMPONENTS | The download operation has finished downloading and installing all the necessary code. The szStatusText parameter accompanying IBindStatusCallback::OnProgress provides the display name of the newly installed component.
szStatusText
Textual information indicating the current progress of the bind operation. The text reflects the BINDSTATUS value of the ulStatusCode parameter and is appropriate for display in the user interface of the client.

The moniker calls this method repeatedly to indicate the current progress of the bind operation, typically at reasonable intervals during a lengthy operation.

The client can use the progress notification to provide progress information to the user from the ulProgress, ulProgressMax, and szStatusText parameters, or to make programmatic decisions based on the ulStatusCode parameter.

Notes to implementers

A client can return E_UNIMPL or S_OK if it is not interested in receiving this notification.

See also BINDSTATUS


IBindStatusCallback::OnStartBinding

HRESULT OnStartBinding(
    [in] DWORD  dwReserved,
    [in] IBinding *pbinding
);

Notifies the client about the callback methods it is registered to receive. This notification is a response to the flags the client requested in the RegisterBindStatusCallback function.

  • Returns S_OK if successful, or E_INVALIDARG if the pbinding parameter is invalid.
dwReserved
Reserved for future use. Must be zero.
pbinding
Address of the IBinding interface of the current bind operation. Cannot be NULL. The client should call AddRef on this pointer to keep a reference to the binding object.

Asynchronous monikers typically call this method before the call to the IMoniker::BindToStorage or IMoniker::BindToObject method has returned.

In the call to this method, the moniker also provides the client with a pointer to the IBinding interface for the binding object associated with the current bind operation. The client can use the IBinding interface to control the progress of the bind operation.

To keep a reference to the binding object, the client must store the pointer to the IBinding interface and call AddRef on it. When the client no longer needs the reference, it must call Release on it. Note that calling Release does not cancel the bind operation; it simply frees the reference to the IBinding interface sent in the callback.

Notes to implementers

A client can return E_NOTIMPL or S_OK if it is not interested in receiving this notification.

The IBinding::Abort method will not work properly within an implementation of IBindStatusCallback::OnStartBinding. To abort the binding, IBindStatusCallback::OnStartBinding should return E_FAIL.

See also IBinding, IBindStatusCallback::OnStopBinding, RegisterBindStatusCallback


IBindStatusCallback::OnStopBinding

HRESULT OnStopBinding(
    [in] HRESULT  hrStatus,
    [in] LPCWSTR  szStatusText
);

Indicates the end of the bind operation.

hrStatus
Status code returned from the bind operation.
szStatusText
Status text. In case of error, this text describes the error. In the current implementation of URL monikers, this string is empty.

This method is always called, whether the bind operation succeeded, failed, or was aborted by a client. At this point the moniker client can use IBinding::GetBindResult to query for protocol-specific information about the outcome of the bind operation. When this method has completed, the moniker client must call IUnknown::Release on the IBinding pointer it received in IBindStatusCallback::OnStartBinding.

Because URL monikers work asynchronously, the status code returned by IBindStatusCallback::OnStopBinding and the status code returned by the binding methods (such as IMoniker::BindToStorage and IMoniker::BindToObject) may differ.

Notes to implementers

A client can return E_UNIMPL or S_OK if it is not interested in receiving this notification.

See also IBinding, IBindStatusCallback::OnStartBinding


ICodeInstall ICodeInstall *
  * Previous Topic: IBindStatusCallback
  * Next Topic: IHttpNegotiate

ICodeInstall

Obsolete. Do not use.


IHttpNegotiate::BeginningTransaction

HRESULT BeginningTransaction(
    [in] LPCWSTR  szURL,
    [in] DWORD  dwReserved,
    [in] LPCWSTR  szHeaders,
    [out] LPWSTR * pszAdditionalHeaders
);

Notifies the client of the URL being bound to at the beginning of an HTTP transaction.

  • Returns one of the following values:
    S_OK | Success, and any additional headers specified are appended.
    E_ABORT | The HTTP transaction has been terminated.
    E_INVALIDARG | A parameter is invalid.
szURL
URL for the HTTP transaction.
dwReserved
Reserved for future use.
szHeaders
Current request headers.
pszAdditionalHeaders
Optional additional headers to append to the HTTP request. If these conflict with existing values in szHeaders, the new request headers take precedence. If pszAdditionalHeaders is set to NULL, no headers are added to the HTTP request.

The URL moniker calls this method before sending an HTTP request. It notifies the client of the URL being bound to at the beginning of the HTTP transaction. It also allows the client to add additional headers, such as Accept-Language, to the request.

See also IHttpNegotiate::OnResponse


IHttpNegotiate

This interface is implemented by a client application to provide support for HTTP negotiations.
IHttpNegotiate methods | Description
BeginningTransaction | Notifies a client of a URL being bound to at the beginning of the HTTP transaction.
OnResponse | Notifies a client upon receiving a response to an HTTP request.

Urlmon.dll will use the IUnknown::QueryInterface method on your implementation of IBindStatusCallback to obtain a pointer to your IHttpNegotiate interface.

See also IWindowForBindingUI, IWinInetInfo


IHttpNegotiate::OnResponse

HRESULT OnResponse(
    [in] DWORD  dwResponseCode,
    [in] LPCWSTR  szResponseHeaders,
    [in] LPCWSTR  szRequestHeaders,
    [out] LPWSTR * pszAdditionalRequestHeaders
);

Allows the client of a bind operation to examine the response headers, optionally terminate the bind operation, and add HTTP headers to a request before resending the request.

  • Returns one of the following values:
    S_OK | The operation completed successfully. If dwResponseCode indicates an error, any szAdditionalRequestHeaders are appended and the request is sent again.
    E_ABORT | Terminate the HTTP transaction.
    E_INVALIDARG | The parameter is invalid.
dwResponseCode
HTTP response code returned in response to a previous HTTP request. For information about these codes, see the HTTP specification.
szResponseHeaders
Response headers from the HTTP server. For more information, see the HTTP specification.
szRequestHeaders
If dwResponseCode indicates an error, contains HTTP request headers that will be used when the request is sent again.
pszAdditionalRequestHeaders
If dwResponseCode indicates an error, contains optional, additional headers to add before the request is sent again. If the specified header value conflicts with existing values in szRequestHeaders, the new headers take precedence. If pszAdditionalRequestHeaders is set to NULL, no headers are added to the HTTP request.

The URL moniker calls this method when it receives a response to an HTTP request. If dwResponseCode indicates a success, the client can examine the response headers and can optionally abort the bind operation. If dwResponseCode indicates a failure, the client can add HTTP headers to the request before it is sent again.

Note that if multiple clients have registered on the bind context for a given bind operation, more than one of these clients can provide an IHttpNegotiate callback interface. Every client providing this callback receives notifications. Each one is given a chance to add HTTP headers or to abort the HTTP transaction. In such cases, the last client to receive callback notification is the client driving the download operation, and it will dictate the final decision.

See also IHttpNegotiate::BeginningTransaction


IHttpSecurity

This interface notifies a client application of authentication problems.
IHttpSecurity method | Description
OnSecurityProblem | Notifies the client application about an authentication problem.

Urlmon.dll uses the IUnknown::QueryInterface method on your implementation of IBindStatusCallback to obtain a pointer to your IHttpSecurity interface. If the application is hosting Mshtml.dll, Mshtml.dll will request a pointer to your IHttpSecurity interface by calling IUnknown::QueryInterface on your IServiceProvider interface.


IHttpSecurity::OnSecurityProblem

HRESULT OnSecurityProblem (
    [in] DWORD dwProblem
);

Notifies the client application about an authentication problem. This interface should be implemented by applications that want to handle any authentication problems themselves, instead of using the default user interface.

dwProblem
Double-word value that contains the authentication problem encountered. Can be one of the following values:
ERROR_INTERNET_SEC_CERT_DATE_INVALID
ERROR_INTERNET_SEC_CERT_CN_INVALID
ERROR_INTERNET_HTTP_TO_HTTPS_ON_REDIR
ERROR_INTERNET_HTTPS_TO_HTTP_ON_REDIR
ERROR_HTTP_REDIRECT_NEEDS_CONFIRMATION
ERROR_INTERNET_INVALID_CA
ERROR_INTERNET_CLIENT_AUTH_CERT_NEEDED


IInternetBindInfo::GetBindInfo

HRESULT GetBindInfo(
    [out] DWORD *grfBINDF,
    [in, out, unique] BINDINFO * pbindinfo
);

Gets the BINDINFO structure associated with the binding operation.

grfBINDF
Address of a value taken from the BINDF enumeration indicating whether the bind should proceed synchronously or asynchronously.
pbindinfo
Address of the BINDINFO structure, which describes how the client wants the binding to occur.

The size of the BINDINFO structure has changed with the release of Microsoft Internet Explorer 4.0. Developers must write code that checks the size of the BINDINFO structure that is passed into their implementation of this method before writing to members of the structure. See Handling BINDINFO Structures in Asynchronous and URL Monikers Overview for more information.


IInternetBindInfo::GetBindString

HRESULT GetBindString(
    [in] ULONG ulStringType,
    [in, out] LPOLESTR *ppwzStr,
    [in] ULONG cEl,
    [in, out] ULONG *pcElFetched
);

Gets the strings needed by the protocol for its operation.

ulStringType
Unsigned long integer value that indicates the type of string or strings that should be returned. Can be one of the BINDSTRING values.
ppwzStr
Address of an array of strings.
cEl
Unsigned long integer value that indicates the number of elements in the array provided.
pcElFetched
Address of an unsigned long integer that indicates the number of elements filled in the array.

This method is used if the protocol requires any additional information, such as a username or password, needed to access a URL.


IPersistMoniker::GetCurMoniker

HRESULT GetCurMoniker(
    [out] IMoniker **ppimkCur
);

Retrieves the moniker that refers to the object's persistent state.

  • Returns S_OK if a valid absolute path was successfully returned, or E_INVALIDARG if the ppimkCur parameter is invalid.
ppimkCur
Indirect pointer to the moniker that references the object's current persistent state.

Typically, this method returns the moniker last passed to the object by means of the IPersistMoniker::Load, IPersistMoniker::Save, or IPersistMoniker::SaveCompleted method.


IPersistMoniker

This interface provides methods that offer more control over the binding of persistent data.
IPersist method | Description
GetClassID | Returns the class identifier (CLSID) for the object.
IPersistMoniker methods | Description
GetCurMoniker | Retrieves the moniker that refers to the object's persistent state.
IsDirty | Checks an object for changes since it was last saved.
Load | Loads an object using a specified moniker.
Save | Saves the object, specifying a destination moniker.
SaveCompleted | Notifies the object that the save operation is complete.


IPersistMoniker::IsDirty

HRESULT IsDirty(void);

Checks an object for changes since it was last saved.

  • Returns S_OK if the object has changed since it was last saved, or S_FALSE if not.

This method checks whether an object has changed since it was last saved so you can avoid losing information in objects that have not yet been saved.

See also IPersistMoniker::Save


IPersistMoniker::Load

HRESULT Load(
    [in] BOOL fFullyAvailable,
    [in] IMoniker *pmkSrc,
    [in] IBindCtx *pbc,
    [in] DWORD grfMode
);

Loads the object from its persistent state indicated by a supplied moniker.

  • Returns S_OK if the object was successfully loaded, or E_INVALIDARG if one or more parameters are invalid.
fFullyAvailable
If TRUE, the data referred to by the moniker has already been loaded once, and subsequent binding to the moniker should be synchronous. If FALSE, an asynchronous bind operation should be launched.
pmkSrc
Address of a moniker that references the persistent state for the object to be loaded.
pbc
Address of the IBindCtx interface for the bind context to be used for any moniker binding during this method.
grfMode
Combination of values from the STGM enumeration, which indicates the access mode to use when binding to the persistent state. The IPersistMoniker::Load method can treat this value as a suggestion, adding more restrictive permissions if necessary. If grfMode is zero, the implementation should bind to the persistent state using default permissions.

Typically, the object will immediately bind to its persistent state through a call to the source moniker's IMoniker::BindToStorage method, requesting either the IStream or IStorage interface.

See also IPersistMoniker::Save, IPersistMoniker::SaveCompleted


IPersistMoniker::Save

HRESULT Save(
    [in] IMoniker *pmkDst,
    [in] IBindCtx *pbc,
    [in] BOOL fRemember
);

Requests that the object save itself to the location referred to by the pmkDst parameter.

  • Returns S_OK if the object was successfully saved, or E_INVALIDARG if one or more parameters are invalid.
pmkDst
Address of the moniker referencing the location where the object should persistently store itself.
pbc
Address of the IBindCtx interface for the bind context to be used for any moniker binding during this method.
fRemember
Indicator of whether pmkDst is to be used as the reference to the current persistent state after the save. If TRUE, pmkDst becomes the reference to the current persistent state, and the object should clear its dirty flag after the save. If FALSE, this save operation is a "Save A Copy As ..." operation. In this case, the reference to the current persistent state is unchanged, and the object should not clear its dirty flag. If pmkDst is NULL, the implementation should ignore the fRemember flag.

See also IPersistMoniker::GetCurMoniker, IPersistMoniker::Load, IPersistMoniker::SaveCompleted


IPersistMoniker::SaveCompleted

HRESULT SaveCompleted(
    [in] IMoniker *pmkNew,
    [in] IBindCtx *pbc
);

Notifies the object that it has been completely saved, and points it to its new persisted state.

  • Returns S_OK if successful, or E_INVALIDARG if one or more parameters are invalid.
pmkNew
Address of the moniker for the object's new persistent state. This parameter can be NULL if the moniker to the object's new persistent state is the same as the previous moniker to the object's persistent state. This optimization is allowed only if there was a prior call to IPersistMoniker::Save with the fRemember parameter set to TRUE, in which case the object need not rebind to pmkNew.
pbc
Address of the bind context to use for any moniker binding during this method.

See also IPersistMoniker::Load, IPersistMoniker::Save


ISoftDistExt ISoftDistExt *
  * Previous Topic: IPersistMoniker
  * Next Topic: IWindowForBindingUI

ISoftDistExt

Not currently implemented.


IWindowForBindingUI::GetWindow

HRESULT GetWindow(
    [in] GUID  guidReason,
    [out] HWND  *phwnd
);

Returns a handle to a window to present information in the user interface during a bind operation.

  • Returns S_OK if the window handle was successfully returned, or E_INVALIDARG if the phwnd parameter is invalid.
guidReason
Same value as IID_IAuthenticate or IID_IHttpSecurity.
phwnd
Address of a window handle to the parent window to use for displaying user interface information.

Notes to implementers

If you implement this interface, you can return S_FALSE for this method to indicate that no window is available for displaying user interface information.

See also IAuthenticate, IHttpNegotiate, IWinInetInfo


IWindowForBindingUI

This interface allows clients of URL monikers to display information in the client's user interface when necessary. This interface is usually implemented by OLE containers that also implement the IBindHost interface.
IWindowForBindingUI method | Description
GetWindow | Returns an HWND for displaying user interface information.


IWinInetHttpInfo

This interface checks information on HTTP requests made through the underlying Win32® Internet functions.
IWinInetHttpInfo methods | Description
QueryInfo | Queries information about an HTTP request.

Client applications can call IUnknown::QueryInterface on the IBinding interface to get a pointer to the IWinInetHttpInfo interface after your implementation of the IBindStatusCallback::OnProgress method has been called. Not all protocol schemes support this interface.


IWinInetHttpInfo::QueryInfo

HRESULT QueryInfo (
    [in] DWORD dwOption,
    [in, out] LPVOID pBuffer,
    [in, out] DWORD *pcbBuf,
    [in, out] DWORD *pdwFlags,
    [in, out] DWORD *pdw Reserved
);

Retrieves the specified information from an HTTP request.

dwOption
DWORD value that indicates the information to be queried. Can be set to WININETINFO_OPTION_LOCK_HANDLE to return the lock handle from WinInet. Can also be one of the Option Flags values used by InternetQueryOption.
pBuffer
Address of the buffer where the information will be stored.
pcbBuf
Address of a DWORD value that indicates the size of the buffer.
pdwFlags
Address of a DWORD value that contains the flags controlling the query.
pdwReserved
Reserved. Must be set to NULL.


IWinInetInfo

This interface checks information on the underlying Win32 Internet functions.
IWinInetInfo methods | Description
QueryOption | Retrieves the Win32 Internet function option indicated.

Client applications can call IUnknown::QueryInterface on the IBinding interface to get a pointer to the IWinInetInfo interface after your implementation of the IBindStatusCallback::OnProgress method has been called. Not all protocol schemes support this interface.


IWinInetInfo::QueryOption

HRESULT QueryOption (
    [in] DWORD dwOption,
    [in, out] LPVOID pBuffer,
    [in, out] DWORD *pcbBuf
);

Retrieves the Win32 Internet function option indicated.

dwOption
DWORD value that indicates the option to retrieve. Can be one of the QUERYOPTION values.
pBuffer
Address of the buffer where the information will be stored.
pcbBuf
Address of a DWORD value that contains the size of the buffer.


BINDINFO

typedef struct _tagBINDINFO {
    ULONG cbSize;
    LPWSTR szExtraInfo;
    STGMEDIUM stgmedData;
    DWORD grfBindInfoF;
    DWORD dwBindVerb;
    LPWSTR szCustomVerb;
    DWORD cbStgmedData;
    DWORD dwOptions;
    DWORD dwOptionsFlags;
    DWORD dwCodePage;
    SECURITY_ATTRIBUTES securityAttributes;
    IID iid;
    IUnknown *pUnk;
    DWORD dwReserved;
} BINDINFO;

Contains additional information on the requested binding operation. The meaning of this structure is specific to the type of asynchronous moniker.

cbSize
Size of the structure, in bytes.
szExtraInfo
Behavior of this field is moniker-specific. For URL monikers, this string is appended to the URL when the bind operation is started. Like other OLE strings, this value is a Unicode string that the client should allocate using CoTaskMemAlloc. The URL moniker frees the memory later.
stgmedData
Data to be used in a PUT or POST operation specified by the dwBindVerb member.
grfBindInfoF
Flag from the BINDINFOF enumeration that determines the use of URL encoding during the binding operation. This member is specific to URL monikers.
dwBindVerb
Value from the BINDVERB enumeration specifying an action to be performed during the bind operation.
szCustomVerb
String specifying a protocol-specific custom action to be performed during the bind operation (only if dwBindVerb is set to BINDVERB_CUSTOM).
cbStgmedData
Size of the data provided in the stgmedData member.
dwOptions
Double-word value that contains additional options.
dwOptionsFlags
Double-word value that contains the option flags.
dwCodePage
Double-word value that contains the code used to convert the URL.
securityAttributes
SECURITY_ATTRIBUTES structure that contains the descriptor for the object being bound to and specifies whether the handle retrieved by specifying this structure is inheritable.
iid
Interface identifier of the IUnknown interface referred to by pUnk.
pUnk
Address of the IUnknown interface.
dwReserved
Reserved. Must be set to zero.

The size of this structure has changed with the release of Microsoft Internet Explorer 4.0. Developers must write code that checks the size of the BINDINFO structure that is passed into their implementation of this method before writing to members of the structure. See Handling BINDINFO Structures in Asynchronous and URL Monikers Overview for more information.

See also BINDINFOF, BINDVERB, IBindStatusCallback::GetBindInfo


Structures

This section contains the structures that are exposed by Urlmon.dll.
BINDINFO
PROTOCOLDATA
PROTOCOLFILTERDATA
ZONEATTRIBUTES


Programming the Document Object Model from C/C++

This document describes the interfaces used to access the Dynamic HTML Object Model of Internet Explorer 4.0 as implemented by MSHTML.DLL (IE4/MSHTML). These interfaces may be used by applications hosting IE4/MSHTML directly, indirectly through the WebBrowser control or by controls and COM objects hosted by IE4/MSHTML.

The Dynamic HTML Object Model interfaces give C and C++ programmers access to the HTML object model of Internet Explorer 4.0. Used in ActiveX controls and applications hosting IE4/MSHTML, these interfaces give direct access to the objects, properties, methods, collections, and events described in the object model. This gives C and C++ programmers the same level of control over Dynamic HTML as script programmers.

The following sections describe the interfaces and their member functions. For a listing of the interfaces, see Interfaces and Scripting Objects.


Interfaces and Scripting Objects

The following table lists the C/C++ object model interfaces, and identifies which scripting objects most closely match these interfaces.
Interface | Object
ICSSFilter | No matching object.
ICSSFilterSite | No matching object.
IHTMLAnchorElement A
IHTMLAreaElement AREA
IHTMLAreasCollection areas
IHTMLBaseElement BASE
IHTMLBaseFontElement BASEFONT
IHTMLBGsound BGSOUND
IHTMLBlockElement | No matching object.
IHTMLBodyElement BODY
IHTMLBRElement BR
IHTMLButtonElement BUTTON
IHTMLCommentElement COMMENT
IHTMLControlElement | No matching object.
IHTMLControlRange | No matching object.
IHTMLDatabinding | No matching object.
IHTMLDDElement DD
IHTMLDialog window
IHTMLDivElement DIV
IHTMLDivPosition | No matching object.
IHTMLDListElement DL
IHTMLDocument document
IHTMLDocument2 document
IHTMLDTElement DT
IHTMLElement | All element objects.
IHTMLElementCollection elements
IHTMLEmbedElement | No matching object.
IHTMLEventObj event
IHTMLFieldSetElement FIELDSET
IHTMLFiltersCollection filters
IHTMLFontElement FONT
IHTMLFontNamesCollection | No matching object.
IHTMLFontSizesCollection | No matching object.
IHTMLFormElement FORM
IHTMLFrameBase | No matching object.
IHTMLFrameElement FRAME
IHTMLFramesCollection2 frames
IHTMLFrameSetElement FRAMESET
IHTMLHeaderElement | H1 through H6
IHTMLHRElement HR
IHTMLIFrameElement IFRAME
IHTMLImageElementFactory | No matching object.
IHTMLImgElement | Common properties of IMG and INPUT of type image
IHTMLInputButtonElement | INPUT of type reset or submit
IHTMLInputFileElement | INPUT of type file
IHTMLInputHiddenElement | INPUT of type hidden
IHTMLInputImage | INPUT of type image
IHTMLInputTextElement | INPUT of type text
IHTMLIsIndexElement ISINDEX
IHTMLLabelElement LABEL
IHTMLLegendElement LEGEND
IHTMLLIElement LI
IHTMLLinkElement LINK
IHTMLListElement | Common properties of OL and UL
IHTMLLocation location
IHTMLMapElement MAP
IHTMLMarqueeElement MARQUEE
IHTMLMetaElement META
IHTMLMimeTypesCollection | No matching object.
IHTMLNextIdElement NEXTID
IHTMLNoShowElement | No matching object.
IHTMLObjectElement OBJECT
IHTMLOListElement OL
IHTMLOpsProfile userProfile
IHTMLOptionButtonElement | INPUT of type radio
IHTMLOptionElement OPTION
IHTMLOptionElementFactory | No matching object.
IHTMLOptionsHolder | No matching object.
IHTMLParaElement P
IHTMLPhraseElement | No matching object.
IHTMLPluginsCollection EMBED
IHTMLRuleStyle style
IHTMLScreen screen
IHTMLScriptElement SCRIPT
IHTMLSelectElement SELECT
IHTMLSelectionObject selection
IHTMLSpanFlow SPAN
IHTMLStyle style
IHTMLStyleElement STYLE
IHTMLStyleSheet styleSheet
IHTMLStyleSheetRule styleSheet
IHTMLStyleSheetRulesCollection styleSheets
IHTMLStyleSheetsCollection styleSheets
IHTMLTable TABLE
IHTMLTableCaption CAPTION
IHTMLTableCell | TD and TH
IHTMLTableCol | COL and COLGROUP
IHTMLTableRow TR
IHTMLTableSection | TBODY, THEAD, and TFOOT
IHTMLTextAreaElement TEXTAREA
IHTMLTextContainer | No matching object.
IHTMLTextElement | No matching object.
IHTMLTitleElement TITLE
IHTMLTxtRange TextRange
IHTMLUListElement UL
IHTMLUnknownElement | No matching object.
IHTMLWindow2 window
IOmHistory history
IOmNavigator navigator

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


Overview

All interfaces for accessing the dynamic HTML object model are based on IDispatch and are the basis of access to the object model that is also used by scripts. It is therefore important that anyone using the interfaces to manipulate the object model also be familiar with the structure and functionality as defined in the Dynamic HTML overviews and Object Model references.

The Interfaces and Scripting Objects section shows how objects within the Dynamic HTML object model map to the interfaces. For example, using this map, you can see that the IHTMLDocument2 interface maps to the document object. Further examination of the interface shows how the properties of the document object are available through get_ and put_ methods. The object's methods map to methods available in the interface, and events can be hooked up using standard OLE Automation connection points.

Examples of how to use the object model interfaces can be seen in the following samples in the Internet Client SDK:

  • Driller
  • colbtn
  • WalkAll

Recommendations for Using the Interfaces

Usually, anything that can be done using script within the document can also be performed using the interfaces to manipulate the object model. It is therefore recommended that before writing code to use the object model interfaces, developers should prototype the functionality using script within an HTML document.

The following HTML example shows how to navigate the all collection of the document and obtain the tag name of each element in the document using script. The equivalent C++ code is demonstrated in the Driller and WalkAll samples of the Internet Client SDK using the object model interfaces.

<HTML>
<HEAD>
    <TITLE>Page Title</TITLE>
</HEAD>

<SCRIPT LANGUAGE="JavaScript">
    function Loaded()
        {
        var c = document.all.length;
        var i;
        for(i=0; i < c; i++)
            {
            spanTAGS.innerHTML = spanTAGS.innerHTML + document.all.item(i).tagName + "<BR>";
            }
        }
</SCRIPT>

<BODY onload="Loaded()">

    <SPAN id="spanTAGS"></SPAN>

</BODY>
</HTML>

Obtaining the Document Interface

To start using the object model interfaces, you need to obtain the IHTMLDocument2 interface for the document. Once you have this interface, you can access all the elements within the document. How the document interface is obtained depends upon how your application is being implemented. Each scenario listed below requires that the document interface be obtained in a different manner.

  • When hosting an MSHTML object.
  • When hosting an instance of the WebBrowser control.
  • From an ActiveX™ control contained in a page.

Obtaining the document interface when hosting MSHTML

When hosting an MSHTML object, you create the object using CoCreateInstance. Once the object is created, you can call its QueryInterface method, requesting IID_IHTMLDocument2. The WalkAll sample in the Internet Client SDK demonstrates how to do this.

Obtaining the document interface when hosting the WebBrowser control

When hosting the WebBrowser control, you perform the following steps to obtain the document pointer:

  1. Call IWebBrowser2::get_Document to obtain the document's IDispatch pointer.
  2. Call QueryInterface on the IDispatch pointer obtained in the previous step, requesting IID_IHTMLDocument2.

Obtaining the document interface from an ActiveX control

The Accessing Dynamic HTML section of the ActiveX Controls documentation details how to obtain the document interface from an ActiveX control.

Using the Document Interface

Once you have obtained the document interface, you can use any of the IHTMLDocument2 interfaces to obtain or modify the document's properties. This will most commonly involve getting some of the IHTMLElementCollection interfaces for the different element collections contained in the document.

A very common collection is the all collection. The all collection is obtained using the IHTMLDocument2::get_all method. This method returns an IHTMLElementCollection interface that contains all the elements in the document. You can then enumerate the elements using the IHTMLElementCollection::item method. The IHTMLElementCollection::item method supplies you with an IDispatch pointer that you can call QueryInterface on, requesting IID_IHTMLElement. This will give you an IHTMLElement interface pointer that you can use to obtain or set information for the individual element.

Most elements provide an interface for working with that specific element. These element-specific interface names take the format of IHTMLXXXXElement, where XXXX is the name of the element. To obtain the element-specific interface, you simply call QueryInterface on the IHTMLElement interface, requesting the element-specific interface that is desired. For example, the IMG element provides an IHTMLImgElement interface that can be used to work with the image element specifically. For a list of the element-specific interfaces that are available, see the interface listing in Programming the Document Object Model from C/C++.


AccessKey Property

*
  * Previous Topic: IHTMLAnchorElement::focus
  * Next Topic: IHTMLAnchorElement::get_hash

IHTMLAnchorElement::get_accessKey

HRESULT get_accessKey(
    BSTR *p
);

Retrieves the accelerator key for the A object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that contains the accelerator key for the element.

Up Top of Page

IHTMLAnchorElement::put_accessKey

HRESULT put_accessKey(
    BSTR v
);

Sets an accelerator key for the element. Pressing CTRL+key selects this anchor element in the user's browser.

  • Returns S_OK if successful, or an error value otherwise.
v
String value specifying the key.


IHTMLAnchorElement

Anchor elements designate the start or destination of a hypertext link. The Anchor element requires the href or the name property to be specified.

Text and/or images can be within an anchor. To represent images that are anchors, a border in the visited or not visited color is displayed.

IHTMLAnchorElement Methods
blur focus get_accessKey
get_hash get_host get_hostname
get_href get_Methods get_mimeType
get_name get_nameProp get_onblur
get_onfocus get_pathname get_port
get_protocol get_protocolLong get_rel
get_rev get_search get_tabIndex
get_target get_urn put_accessKey
put_hash put_host put_hostname
put_href put_Methods put_name
put_onblur put_onfocus put_pathname
put_port put_protocol put_rel
put_rev put_search put_tabIndex
put_target put_urn

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


IHTMLAnchorElement::blur

HRESULT blur(void);

Causes a control to lose the focus and executes the code specified for the onblur event.

  • Returns S_OK if successful, or an error value otherwise.


IHTMLAnchorElement::focus

HRESULT focus(void);

Causes the anchor element to receive the focus and executes the code specified for the onfocus event.

  • Returns S_OK if successful, or an error value otherwise.


IHTMLAnchorElement::get_mimeType

HRESULT get_mimeType(
    BSTR *p
);

Retrieves the MIME type for the file.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the MIME type.


IHTMLAnchorElement::get_nameProp

HRESULT get_nameProp(
    BSTR *p
);

Retrieves the file name from the URL that the browser uses to locate the anchor.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the file name.


IHTMLAnchorElement::get_protocolLong

HRESULT get_protocolLong(
    BSTR *p
);

Retrieves the long name of the protocol that the browser uses to locate the item associated with the anchor (for example, "Hypertext Transfer Protocol").

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the protocol name.


Hash Property

*
  * Previous Topic: IHTMLAnchorElement::get_accessKey
  * Next Topic: IHTMLAnchorElement::get_host

IHTMLAnchorElement::get_hash

HRESULT get_hash(
    BSTR *p
);

Retrieves the string associated with the hash property of the A object.

p
Address of a string variable that receives the value.

Up Top of Page

IHTMLAnchorElement::put_hash

HRESULT put_hash(
    BSTR v
);

Sets the string following the # symbol in the HREF attribute of the anchor element.

  • Returns S_OK if successful, or an error value otherwise.
v
String value specifying the hash portion of the URL.

This property is useful for moving to a bookmark within a document. Assigning an invalid value does not cause an error.


Host Property

*
  * Previous Topic: IHTMLAnchorElement::get_hash
  * Next Topic: IHTMLAnchorElement::get_hostname

IHTMLAnchorElement::get_host

HRESULT get_host(
    BSTR *p
);

Retrieves the host name and the optional port information of the location or URL.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the host name. If no host name is available, this parameter receives an empty string.

Up Top of Page

IHTMLAnchorElement::put_host

HRESULT put_host(
    BSTR v
);

Sets the host name and the optional port information of the location or URL.

  • Returns S_OK if successful, or an error value otherwise.
v
String value specifying the host name and the optional port information.


Hostname Property

*
  * Previous Topic: IHTMLAnchorElement::get_host
  * Next Topic: IHTMLAnchorElement::get_href

IHTMLAnchorElement::get_hostname

HRESULT get_hostname(
    BSTR *p
);

Retrieves the host-name portion of the location or URL.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the host name. If no host name is available, this parameter receives an empty string.

Up Top of Page

IHTMLAnchorElement::put_hostname

HRESULT put_hostname(
    BSTR v
);

Sets the host-name portion of the location or URL.

  • Returns S_OK if successful, or an error value otherwise.
v
String value specifying the host name.


Href Property

*
  * Previous Topic: IHTMLAnchorElement::get_hostname
  * Next Topic: IHTMLAnchorElement::get_Methods

IHTMLAnchorElement::get_href

HRESULT get_href(
    BSTR *p
);

Retrieves the destination URL or anchor point.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the destination URL or anchor point.

This method retrieves the href property of the A object.

Up Top of Page

IHTMLAnchorElement::put_href

HRESULT put_href(
    BSTR v
);

Sets the destination URL or anchor point.

  • Returns S_OK if successful, or an error value otherwise.
v
String value specifying the destination URL or anchor point.

The HREF attribute on the anchor is a scriptable attribute. HREFs on anchors can jump to bookmarks or any element's id attribute.


Methods Property

*
  * Previous Topic: IHTMLAnchorElement::get_href
  * Next Topic: IHTMLAnchorElement::get_mimeType

IHTMLAnchorElement::get_Methods

HRESULT get_Methods(
    BSTR *p
);

Retrieves a list of methods that the user can perform on an object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives a comma-separated list of HTTP methods supported by the object for public use.

The functions that the user can perform on an object are more accurately given by the HTTP protocol when it is used, but it might, for reasons similar to the title property, be useful to include the information in advance in the link. For example, the HTML user agent might choose a different rendering as a function of the methods allowed, and thus something that is searchable might get a different icon.

Up Top of Page

IHTMLAnchorElement::put_Methods

HRESULT put_Methods(
    BSTR v
);

Sets information about the functions that the user can perform on an object.

  • Returns S_OK if successful, or an error value otherwise.
v
String value specifying a comma-separated list of HTTP methods supported by the object for public use.

The functions that the user can perform on an object are more accurately given by the HTTP protocol when it is used, but it might, for reasons similar to the title property, be useful to include the information in advance in the link. For example, the HTML user agent might choose a different rendering as a function of the methods allowed, and thus something that is searchable might get a different icon.


Name Property

*
  * Previous Topic: IHTMLAnchorElement::get_mimeType
  * Next Topic: IHTMLAnchorElement::get_nameProp

IHTMLAnchorElement::get_name

HRESULT get_name(
    BSTR *p
);

Retrieves the name of the control, bookmark, or application.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the name.

This method is related to the name property of the A object.

Up Top of Page

IHTMLAnchorElement::put_name

HRESULT put_name(
    BSTR v
);

Sets the name of the anchor.

  • Returns S_OK if successful, or an error value otherwise.
v
String value specifying the name.

This method is related to the name property of the A object.


Onblur Property

*
  * Previous Topic: IHTMLAnchorElement::get_nameProp
  * Next Topic: IHTMLAnchorElement::get_onfocus

IHTMLAnchorElement::get_onblur

HRESULT get_onblur(
    VARIANT *p
);

Retrieves the inline script associated with the onblur event on the A object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that contains the script.

Up Top of Page

IHTMLAnchorElement::put_onblur

HRESULT put_onblur(
    VARIANT v
);

Sets the inline script associated with the onblur event on the A element.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to be set.


Onfocus Property

*
  * Previous Topic: IHTMLAnchorElement::get_onblur
  * Next Topic: IHTMLAnchorElement::get_pathname

IHTMLAnchorElement::get_onfocus

HRESULT get_onfocus(
    VARIANT *p
);

Retrieves the inline script associated with the onfocus event on the A object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that contains the script.

Up Top of Page

IHTMLAnchorElement::put_onfocus

HRESULT put_onfocus(
    VARIANT v
);

Sets the inline script associated with the onfocus event on the A element.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to be set.


Pathname Property

*
  * Previous Topic: IHTMLAnchorElement::get_onfocus
  * Next Topic: IHTMLAnchorElement::get_port

IHTMLAnchorElement::get_pathname

HRESULT get_pathname(
    BSTR *p
);

Retrieves the file or object path from the URL for the current browser location.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the path.

Up Top of Page

IHTMLAnchorElement::put_pathname

HRESULT put_pathname(
    BSTR v
);

Sets the file or object path of the URL.

  • Returns S_OK if successful, or an error value otherwise.
v
String value specifying the path.


Port Property

*
  * Previous Topic: IHTMLAnchorElement::get_pathname
  * Next Topic: IHTMLAnchorElement::get_protocol

IHTMLAnchorElement::get_port

HRESULT get_port(
    BSTR *p
);

Retrieves the port number from the URL.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the port number. If no port is specified, this parameter receives an empty string.

Up Top of Page

IHTMLAnchorElement::put_port

HRESULT put_port(
    BSTR v
);

Sets the port number in a URL.

  • Returns S_OK if successful, or an error value otherwise.
v
String value specifying the port number.


Protocol Property

*
  * Previous Topic: IHTMLAnchorElement::get_port
  * Next Topic: IHTMLAnchorElement::get_protocolLong

IHTMLAnchorElement::get_protocol

HRESULT get_protocol(
    BSTR *p
);

Retrieves the protocol portion of the URL that the browser uses to locate the item associated with the anchor. The protocol portion, which indicates the access method, includes the initial substring of the URL up to and including the first colon.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the protocol.

Up Top of Page

IHTMLAnchorElement::put_protocol

HRESULT put_protocol(
    BSTR v
);

Sets the protocol portion of the URL; that is, the initial substring up to and including the first colon. The protocol indicates the URL's access method.

  • Returns S_OK if successful, or an error value otherwise.
v
String value specifying the protocol.


Rel Property

*
  * Previous Topic: IHTMLAnchorElement::get_protocolLong
  * Next Topic: IHTMLAnchorElement::get_rev

IHTMLAnchorElement::get_rel

HRESULT get_rel(
    BSTR *p
);

Retrieves the relationship(s) described by the hypertext link from the anchor to the target.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the relationship(s). This parameter receives a comma-separated list of relationship values.

Values and their semantics will be registered by the HTML registration authority. The default relationship, if no other is given, is void. The rel property is used only when the href property is present.

Up Top of Page

IHTMLAnchorElement::put_rel

HRESULT put_rel(
    BSTR v
);

Specifies the relationship(s) described by the hypertext link from the anchor to the target.

  • Returns S_OK if successful, or an error value otherwise.
v
String value specifying the relationship(s). This parameter is a comma-separated list of relationship values.

Values and their semantics will be registered by the HTML registration authority. The default relationship, if no other is given, is void. The rel property is used only when the href property is present.


Rev Property

*
  * Previous Topic: IHTMLAnchorElement::get_rel
  * Next Topic: IHTMLAnchorElement::get_search

IHTMLAnchorElement::get_rev

HRESULT get_rev(
    BSTR *p
);

Same as the rel property, but the semantics of the link type are in the reverse direction. A link from A to B with REL="X" expresses the same relationship as a link from B to A with REV="X". An anchor can have both rel and rev properties.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the relationship(s). This parameter receives a comma-separated list of relationship values.

Up Top of Page

IHTMLAnchorElement::put_rev

HRESULT put_rev(
    BSTR v
);

Same as the rel property, but the semantics of the link type are in the reverse direction. A link from A to B with REL="X" expresses the same relationship as a link from B to A with REV="X". An anchor can have both rel and rev properties.

  • Returns S_OK if successful, or an error value otherwise.
v
String value specifying the relationship(s). This parameter is a comma-separated list of relationship values.


Search Property

*
  * Previous Topic: IHTMLAnchorElement::get_rev
  * Next Topic: IHTMLAnchorElement::get_tabIndex

IHTMLAnchorElement::get_search

HRESULT get_search(
    BSTR *p
);

Retrieves the substring that follows the ? symbol in the HREF attribute of the anchor element. This is the query string or form data.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the query string or form data.

Up Top of Page

IHTMLAnchorElement::put_search

HRESULT put_search(
    BSTR v
);

Sets the substring that follows the ? symbol in the HREF attribute of the anchor element. This is the query string or form data.

  • Returns S_OK if successful, or an error value otherwise.
v
String value specifying the query string or form data.


TabIndex Property

*
  * Previous Topic: IHTMLAnchorElement::get_search
  * Next Topic: IHTMLAnchorElement::get_target

IHTMLAnchorElement::get_tabIndex

HRESULT get_tabIndex(
    short *p
);

Retrieves the tab index of the Anchor element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a short integer variable that receives the tab index of the element.

Up Top of Page

IHTMLAnchorElement::put_tabIndex

HRESULT put_tabIndex(
    short v
);

Sets the tab index of the element.

  • Returns S_OK if successful, or an error value otherwise.
v
Short integer value that specifies the tab index to set.


Target Property

*
  * Previous Topic: IHTMLAnchorElement::get_tabIndex
  * Next Topic: IHTMLAnchorElement::get_urn

IHTMLAnchorElement::get_target

HRESULT get_target(
    BSTR *p
);

Retrieves the target window or frame.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that contains the target window or frame. Can be one of the following values:
_blank | Specifies to load the link into a new blank window. This window is not named.
_parent | Specifies to load the link into the immediate parent of the document the link is in.
_self | Specifies to load the link into the same window the link was clicked in.
_top | Specifies to load the link into the full body of the window.

The default value for the target depends upon the URL and site. If the user does not leave the site, the default is _self, but if the user exits to a new site, the default is _top.

Up Top of Page

IHTMLAnchorElement::put_target

HRESULT put_target(
    BSTR v
);

Sets the window or frame to target.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the target window or frame. Can be one of the following values:
_blank | Specifies to load the link into a new blank window. This window is not named.
_parent | Specifies to load the link into the immediate parent of the document the link is in.
_self | Specifies to load the link into the same window the link was clicked in.
_top | Specifies to load the link into the full body of the window.

If there is no frame or window that matches the specified target, a new window is opened for the link.

The default value for the target depends upon the URL and site. If the user does not leave the site, the default is _self, but if the user exits to a new site, the default is _top.


Urn Property

*
  * Previous Topic: IHTMLAnchorElement::get_target
  * Next Topic: IHTMLAnchorElement::put_accessKey

IHTMLAnchorElement::get_urn

HRESULT get_urn(
    BSTR *p
);

Retrieves a uniform resource name (URN) for a target document. The format of URNs is under discussion (1994) by various working groups of the Internet Engineering Task Force.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the uniform resource name.

Up Top of Page

IHTMLAnchorElement::put_urn

HRESULT put_urn(
    BSTR v
);

Sets a uniform resource name (URN) for a target document. The format of URNs is under discussion (1994) by various working groups of the Internet Engineering Task Force.

  • Returns S_OK if successful, or an error value otherwise.
v
String value specifying the uniform resource name.


Alt Property

*
  * Previous Topic: IHTMLAreaElement::focus
  * Next Topic: IHTMLAreaElement::get_coords

IHTMLAreaElement::get_alt

HRESULT get_alt(
    BSTR *p
);

Retrieves the optional text as an alternative to the graphic for rendering in nongraphical environments. Alternate text should be provided whenever the graphic is not rendered.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the optional text.

See also put_alt

Up Top of Page

IHTMLAreaElement::put_alt

HRESULT put_alt(
    BSTR v
);

Sets the optional text, which is used as an alternative to the graphic for rendering in nongraphical environments. Alternate text should be provided whenever the graphic is not rendered. Alternate text is mandatory for Level 0 documents.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the optional text.

See also get_alt


IHTMLAreaElement

This interface specifies the shape of a "hot spot" in a client-side image MAP.

IHTMLAreaElement Methods
blur focus get_alt
get_coords get_hash get_host
get_hostname get_href get_noHref
get_onblur get_onfocus get_pathname
get_port get_protocol get_search
get_shape get_tabIndex get_target
put_alt put_coords put_hash
put_host put_hostname put_href
put_noHref put_onblur put_onfocus
put_pathname put_port put_protocol
put_search put_shape put_tabIndex
put_target


IHTMLAreaElement::blur

HRESULT blur(void);

Causes the element to lose the focus and executes the code specified by get_onblur.

  • Returns S_OK if successful, or an error value otherwise.

See also put_onblur


Coords Property

*
  * Previous Topic: IHTMLAreaElement::get_alt
  * Next Topic: IHTMLAreaElement::get_hash

IHTMLAreaElement::get_coords

HRESULT get_coords(
    BSTR *p
);

Retrieves the coordinates that define the hot spot's shape.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the coordinates.

See also put_coords

Up Top of Page

IHTMLAreaElement::put_coords

HRESULT put_coords(
    BSTR v
);

Sets the coordinates that define the hot spot's shape.

  • Returns S_OK if successful, or an error value otherwise.
v
String value containing the coordinates.

See also get_shape


IHTMLAreaElement::focus

HRESULT focus(void);

Causes the element to receive the focus and executes the onfocus event.

  • Returns S_OK if successful, or an error value otherwise.

See also get_onfocus, put_onfocus


Hash Property

*
  * Previous Topic: IHTMLAreaElement::get_coords
  * Next Topic: IHTMLAreaElement::get_host

IHTMLAreaElement::get_hash

HRESULT get_hash(
    BSTR *p
);

Retrieves the string stored in the hash property of the AREA object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the hash portion of the URL. If the URL has no hash string, this parameter receives an empty string.

See also put_hash

Up Top of Page

IHTMLAreaElement::put_hash

HRESULT put_hash(
    BSTR v
);

Sets the string associated with the hash property of the AREA object.

  • Returns S_OK if successful, or an error value otherwise.
v
String value specifying the hash portion of the URL.

This property is useful for moving to a bookmark within a document. Assigning an invalid value does not cause an error.

See also get_hash


Host Property

*
  * Previous Topic: IHTMLAreaElement::get_hash
  * Next Topic: IHTMLAreaElement::get_hostname

IHTMLAreaElement::get_host

HRESULT get_host(
    BSTR *p
);

Retrieves the host name and the optional port information of the location or URL.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of the string variable where the host name and optional port information will be stored.

See also put_host

Up Top of Page

IHTMLAreaElement::put_host

HRESULT put_host(
    BSTR v
);

Sets the host name and the optional port information of the location or URL.

  • Returns S_OK if successful, or an error value otherwise.
v
String value specifying the host name and port information.

See also get_host


Hostname Property

*
  * Previous Topic: IHTMLAreaElement::get_host
  * Next Topic: IHTMLAreaElement::get_href

IHTMLAreaElement::get_hostname

HRESULT get_hostname(
    BSTR *p
);

Retrieves the host-name part of the location or URL.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the host name. If no host name is available, this parameter receives an empty string.

See also put_hostname

Up Top of Page

IHTMLAreaElement::put_hostname

HRESULT put_hostname(
    BSTR v
);

Sets the host-name portion of the location or URL.

  • Returns S_OK if successful, or an error value otherwise.
v
String value specifying the host name.

See also get_hostname


Href Property

*
  * Previous Topic: IHTMLAreaElement::get_hostname
  * Next Topic: IHTMLAreaElement::get_noHref

IHTMLAreaElement::get_href

HRESULT get_href(
    BSTR *p
);

Retrieves the destination URL or anchor point.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the URL.

The HREF attribute on the anchor is a scriptable attribute. HREFs on anchors can jump to bookmarks or any element's id attribute.

See also put_href

Up Top of Page

IHTMLAreaElement::put_href

HRESULT put_href(
    BSTR v
);

Sets the destination URL or anchor point.

  • Returns S_OK if successful, or an error value otherwise.
v
String value specifying the URL.

The HREF attribute on the anchor is a scriptable attribute. HREFs on anchors can jump to bookmarks or any element's id attribute.

See also get_href


NoHref Property

*
  * Previous Topic: IHTMLAreaElement::get_href
  * Next Topic: IHTMLAreaElement::get_onblur

IHTMLAreaElement::get_noHref

HRESULT get_noHref(
    VARIANT_BOOL *p
);

Determines whether clicks in this region should cause no action.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a Boolean variable that is set to TRUE if clicks cause no action, or FALSE otherwise. The default value for this property is FALSE.

See also put_noHref

Up Top of Page

IHTMLAreaElement::put_noHref

HRESULT put_noHref(
    VARIANT_BOOL v
);

Sets whether clicks in this region should cause no action.

  • Returns S_OK if successful, or an error value otherwise.
v
Boolean value that determines if an action should occur. TRUE causes no action when clicked; FALSE does. The default value for this property is FALSE.

See also get_noHref


Onblur Property

*
  * Previous Topic: IHTMLAreaElement::get_noHref
  * Next Topic: IHTMLAreaElement::get_onfocus

IHTMLAreaElement::get_onblur

HRESULT get_onblur(
    VARIANT *p
);

Retrieves the inline script associated with the onblur event on the AREA element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of VARIANT structure that contains the script.

Up Top of Page

IHTMLAreaElement::put_onblur

HRESULT put_onblur(
    VARIANT v
);

Sets the inline script associated with the onblur event for the AREA element.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to set.

See also get_onblur


Onfocus Property

*
  * Previous Topic: IHTMLAreaElement::get_onblur
  * Next Topic: IHTMLAreaElement::get_pathname

IHTMLAreaElement::get_onfocus

HRESULT get_onfocus(
    VARIANT *p
);

Retrieves the inline script associated with the onfocus event on the AREA element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that contains the script.

Up Top of Page

IHTMLAreaElement::put_onfocus

HRESULT put_onfocus(
    VARIANT v
);

Sets the inline script associated with the onfocus event for the AREA element.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to set.

See also get_onfocus


Pathname Property

*
  * Previous Topic: IHTMLAreaElement::get_onfocus
  * Next Topic: IHTMLAreaElement::get_port

IHTMLAreaElement::get_pathname

HRESULT get_pathname(
    BSTR *p
);

Retrieves the file or object path from the URL for the current browser location.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the path.

See also put_pathname

Up Top of Page

IHTMLAreaElement::put_pathname

HRESULT put_pathname(
    BSTR v
);

Sets the file or object path of the URL.

  • Returns S_OK if successful, or an error value otherwise.
v
String value specifying the path.

See also get_pathname


Port Property

*
  * Previous Topic: IHTMLAreaElement::get_pathname
  * Next Topic: IHTMLAreaElement::get_protocol

IHTMLAreaElement::get_port

HRESULT get_port(
    BSTR *p
);

Retrieves the port number from the URL.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the port number. If no port is specified, this parameter receives an empty string.

See also put_port

Up Top of Page

IHTMLAreaElement::put_port

HRESULT put_port(
    BSTR v
);

Sets the port number in a URL.

  • Returns S_OK if successful, or an error value otherwise.
v
String value specifying the port number.

See also get_port


Protocol Property

*
  * Previous Topic: IHTMLAreaElement::get_port
  * Next Topic: IHTMLAreaElement::get_search

IHTMLAreaElement::get_protocol

HRESULT get_protocol(
    BSTR *p
);

Retrieves the protocol portion of the URL. The protocol portion, which indicates the access method, includes the initial substring of the URL up to and including the first colon.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the protocol.

See also put_protocol

Up Top of Page

IHTMLAreaElement::put_protocol

HRESULT put_protocol(
    BSTR v
);

Sets the initial substring up to and including the first colon, which indicates the URL's access method.

  • Returns S_OK if successful, or an error value otherwise.
v
String value specifying the protocol substring.

See also get_protocol


Search Property

*
  * Previous Topic: IHTMLAreaElement::get_protocol
  * Next Topic: IHTMLAreaElement::get_shape

IHTMLAreaElement::get_search

HRESULT get_search(
    BSTR *p
);

Retrieves the substring that follows the ? symbol in the href property of the AREA object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the query string or form data.

See also put_search

Up Top of Page

IHTMLAreaElement::put_search

HRESULT put_search(
    BSTR v
);

Sets the substring that follows the ? symbol in the href property of the AREA object. This is the query string or form data.

  • Returns S_OK if successful, or an error value otherwise.
v
String value specifying the query string or form data.

See also get_search


Shape Property

*
  * Previous Topic: IHTMLAreaElement::get_search
  * Next Topic: IHTMLAreaElement::get_tabIndex

IHTMLAreaElement::get_shape

HRESULT get_shape(
    BSTR *p
);

Retrieves the type of shape used in the image map.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives one of the following strings:
"circ"
"circle"
"poly"
"polygon"
"rect"
"rectangle"

Each shape causes the coords property of the AREA object to take a different set of values. The relationships are as follows:
RECT | Rectangle. Takes four coordinates: x1, y1, x2, and y2.
RECTANGLE | Rectangle. Takes four coordinates: x1, y1, x2, and y2.
CIRC | Circle. Takes three coordinates: centerx, centery, and radius.
CIRCLE | Circle. Takes three coordinates: centerx, centery, and radius.
POLY | Polygon. Takes three or more pairs of coordinates denoting a polygonal region.
POLYGON | Polygon. Takes three or more pairs of coordinates denoting a polygonal region.

See also put_shape

Up Top of Page

IHTMLAreaElement::put_shape

HRESULT put_shape(
    BSTR v
);

Sets the type of shape used in the image map.

  • Returns S_OK if successful, or an error value otherwise.
v
String value specifying the shape. Can be one of these values:
"circ"
"circle"
"poly"
"polygon"
"rect"
"rectangle"

Each shape causes the coords property to take a different set of values. The relationships are described as follows:
RECT | Rectangle. Takes four coordinates: x1, y1, x2, and y2.
RECTANGLE | Rectangle. Takes four coordinates: x1, y1, x2, and y2.
CIRC | Circle. Takes three coordinates: centerx, centery, and radius.
CIRCLE | Circle. Takes three coordinates: centerx, centery, and radius.
POLY | Polygon. Takes three or more pairs of coordinates denoting a polygonal region.
POLYGON | Polygon. Takes three or more pairs of coordinates denoting a polygonal region.

See also get_shape


TabIndex Property

*
  * Previous Topic: IHTMLAreaElement::get_shape
  * Next Topic: IHTMLAreaElement::get_target

IHTMLAreaElement::get_tabIndex

HRESULT get_tabIndex(
    short *p
);

Retrieves the tab index for the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a short integer variable that receives the tab index.

Tab selection order is determined by the value of the tabIndex property as follows:

  • All elements with tabIndex > 0 are selected in increasing tabIndex order, or in source order for duplicate tabIndex values.
  • All elements with tabIndex = 0, or without tabIndex set, are selected next, in source order if more than one.
  • Elements with tabIndex = -1 are omitted from tab selection.

See also put_tabIndex

Up Top of Page

IHTMLAreaElement::put_tabIndex

HRESULT put_tabIndex(
    short v
);

Sets the tab index for the object.

  • Returns S_OK if successful, or an error value otherwise.
v
Short integer value specifying the tab index.

Tab selection order is determined by the value of the tabIndex property as follows:

  • All elements with tabIndex > 0 are selected in increasing tabIndex order, or in source order for duplicate tabIndex values.
  • All elements with tabIndex = 0, or without tabIndex set, are selected next, in source order if more than one.
  • Elements with tabIndex = -1 are omitted from tab selection.

See also get_tabIndex


Target Property

*
  * Previous Topic: IHTMLAreaElement::get_tabIndex
  * Next Topic: IHTMLAreaElement::put_alt

IHTMLAreaElement::get_target

HRESULT get_target(
    BSTR *p
);

Retrieves the target window or frame.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the target window or frame. Can be one of the following values:
_blank | Specifies to load the link into a new blank window. This window is not named.
_parent | Specifies to load the link into the immediate parent of the document the link is in.
_self | Specifies to load the link into the same window the link was clicked in.
_top | Specifies to load the link into the full body of the window.

If there is no frame or window that matches the specified target, a new window is opened for the link.

The default value for the target depends upon the URL and site. If the user does not leave the site, the default is _self, but if the user exits to a new site, the default is _top.

Up Top of Page

IHTMLAreaElement::put_target

HRESULT put_target(
    BSTR v
);

Sets the target window or frame.

  • Returns S_OK if successful, or an error value otherwise.
v
String value specifying the target window or frame. Can be one of the following special values:
_blank | Specifies to load the link into a new blank window. This window is not named.
_parent | Specifies to load the link into the immediate parent of the document the link is in.
_self | Specifies to load the link into the same window the link was clicked in.
_top | Specifies to load the link into the full body of the window.

If there is no frame or window that matches the specified target, a new window is opened for the link.

The default value for the target depends upon the URL and site. If the user does not leave the site, the default is _self, but if the user exits to a new site, the default is _top.

See also get_target


IHTMLAreasCollection::add

HRESULT add(
    IHTMLElement *element,
    VARIANT before
);

Adds an element to the collection.

  • Returns S_OK if successful, or an error value otherwise.
element
Address of the IHTMLElement interface of the element to add.
before
VARIANT structure containing the number specifying the position within the collection to place the element. If no value is given, the method places the element at the end of the collection.

See also IHTMLElement, remove


IHTMLAreasCollection

This interface is a collection of areas that make up the image map.

Areas can be added or removed from the collection. This collection is indexed first by name, then by ID. If duplicate names are found, a collection of those named items is returned. The resulting collection can only be referenced by ordinal position.

This is a collection of AREA tags.

IHTMLAreasCollection Methods
add get_length get_newEnum
item put_length remove
tags


IHTMLAreasCollection::get__newEnum

HRESULT get__newEnum(
    IUnknown **p
);

Retrieves an enumerator interface which can be used to iterate through the areas collection of the AREA element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a pointer to a variable of IUnknown type.


IHTMLAreasCollection::item

HRESULT item(
    VARIANT name,
    VARIANT index,
    Rob

);

Retrieves an element or a collection from the given collection. The index parameter determines which action to take.

  • Returns S_OK if successful, or an error value otherwise.
name
VARIANT structure that contains the number or string specifying the element or collection to retrieve. If this parameter is a number, the method returns the element in the collection at the given position, where the first element has value 0, the second has 1, and so on. If this parameter contains a string, the method returns a collection of elements, where the value of the name or id property for each element is equal to the string.
index
VARIANT structure that contains the number specifying the position of an element to retrieve. This parameter is used when name is a string. The method uses the string to construct a collection of all elements that have a name or id equal to the string, then retrieves from this collection the element at the position specified by index.
pdisp
Address of a pointer to an IDispatch interface.


Length Property

*
  * Previous Topic: IHTMLAreasCollection::add
  * Next Topic: IHTMLAreasCollection::get__newEnum

IHTMLAreasCollection::get_length

HRESULT get_length(
    long *p
);

Retrieves the number of elements in a collection.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a long integer variable that receives the number of elements.

See also put_length

Up Top of Page

IHTMLAreasCollection::put_length

HRESULT put_length(
    long v
);

Sets the number of elements in a collection.

  • Returns S_OK if successful, or an error value otherwise.
v
Long integer value that specifies the number of elements.

See also get_length


IHTMLAreasCollection::remove

HRESULT remove(
    long index
);

Removes an element from the collection.

  • Returns S_OK if successful, or an error value otherwise.
index
Long integer value that specifies the element to remove. The method removes the element at the given position in the collection, where 0 is the first position, 1 the second, and so on.

See also add


IHTMLAreasCollection::tags

HRESULT tags(
    VARIANT tagName,
    IDispatch **pdisp
);

Retrieves a collection of all elements in the given collection that have the given HTML tag name.

  • Returns S_OK if successful, or an error value otherwise.
tagName
VARIANT structure containing the name of elements to retrieve.
pdisp
Address of a pointer to an IDispatch interface.

This method returns an empty collection if no elements having the given name are found. Use the length property on the collection to determine the number of elements it contains.


IHTMLBaseElement

This interface specifies the document's base URL. The base URL is used to ensure that your document is not reviewed out of context.

This element can be used only within the HEAD tag.

IHTMLBaseElement Methods


Href Property

*
  * Previous Topic: IHTMLBaseElement
  * Next Topic: IHTMLBaseElement::get_target

IHTMLBaseElement::get_href

HRESULT get_href(
    BSTR *p
);

Retrieves the document's full URL in case the document gets read out of context and the reader wants to refer to the original.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the base URL.

See also put_href

Up Top of Page

IHTMLBaseElement::put_href

HRESULT put_href(
    BSTR v
);

Sets the document's full URL in case the document gets read out of context and the reader wants to refer to the original.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the base URL.

See also get_href


Target Property

*
  * Previous Topic: IHTMLBaseElement::get_href
  * Next Topic: IHTMLBaseElement::put_href

IHTMLBaseElement::get_target

HRESULT get_target(
    BSTR *p
);

Retrieves the window or frame at which to target the contents.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the target, or one of these values:
_blank | Specifies to load the link into a new blank window. This window is not named.
_parent | Specifies to load the link into the immediate parent of the document the link is in.
_self | Specifies to load the link into the same window the link was clicked in.
_top | Specifies to load the link into the full body of the window.

If there is no frame or window that matches the specified target, a new window is opened for the link.

The default value for the target depends upon the URL and site. If the user does not leave the site, the default is _self, but if the user exits to a new site, the default is _top.

See also put_target

Up Top of Page

IHTMLBaseElement::put_target

HRESULT put_target(
    BSTR v
);

Sets the window or frame at which to target the contents.

  • Returns S_OK if successful, or an error value otherwise.
v
String value that specifies the target. Can be one of these values:
_blank | Specifies to load the link into a new blank window. This window is not named.
_parent | Specifies to load the link into the immediate parent of the document the link is in.
_self | Specifies to load the link into the same window the link was clicked in.
_top | Specifies to load the link into the full body of the window.

If there is no frame or window that matches the specified target, a new window is opened for the link.

The default value for the target depends upon the URL and site. If the user does not leave the site, the default is _self, but if the user exits to a new site, the default is _top.

See also get_target


IHTMLBaseFontElement

This interface sets a base font value to be used as the default font when rendering text.

This element can be used only within the HEAD tag.

IHTMLBaseFontElement Methods


Color Property

*
  * Previous Topic: IHTMLBaseFontElement
  * Next Topic: IHTMLBaseFontElement::get_face

IHTMLBaseFontElement::get_color

HRESULT get_color(
    VARIANT *p
);

Retrieves the color used by the font.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the color. It can be one of the color names or values given in the Color Table reference documentation.

See also put_color

Up Top of Page

IHTMLBaseFontElement::put_color

HRESULT put_color(
    VARIANT v
);

Sets the color to be used by the font.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains either a string or numeric value specifying the color. It can be one of the color names or values given in the Color Table reference documentation.

See also get_color


Face Property

*
  * Previous Topic: IHTMLBaseFontElement::get_color
  * Next Topic: IHTMLBaseFontElement::get_size

IHTMLBaseFontElement::get_face

HRESULT get_face(
    BSTR *p
);

Retrieves the name of the typeface for the base font.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the name of the typeface.

See also put_face

Up Top of Page

IHTMLBaseFontElement::put_face

HRESULT put_face(
    BSTR v
);

Sets the typeface to use for the text of the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String value that specifies the font.

See also get_face


Size Property

*
  * Previous Topic: IHTMLBaseFontElement::get_face
  * Next Topic: IHTMLBaseFontElement::put_color

IHTMLBaseFontElement::get_size

HRESULT get_size(
    long *p
);

Retrieves the font size used for the text of the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a long integer variable that receives the size. It can be an integer value in the range 1 through 7, with 7 representing the largest font.

See also put_size

Up Top of Page

IHTMLBaseFontElement::put_size

HRESULT put_size(
    long v
);

Sets the font size for the text of the element.

  • Returns S_OK if successful, or an error value otherwise.
v
Long integer value specifying the font size. This property takes an integer value in the range 1 through 7, with 7 representing the largest font.

See also get_size


Balance Property

*
  * Previous Topic: IHTMLBGsound
  * Next Topic: IHTMLBGsound::get_loop

IHTMLBGsound::get_balance

HRESULT get_balance(
    VARIANT *p
);

Retrieves the balance value of the background sound. The value specifies how the sound is divided between left and right speakers.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that contains the balance.

See also put_balance

Up Top of Page

IHTMLBGsound::put_balance

HRESULT put_balance(
    VARIANT v
);

Sets the balance value of the background sound. The value specifies how the sound is divided between left and right speakers.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the balance value to set.

See also get_balance


IHTMLBGsound

This interface provides the methods for controlling background sound elements. These methods include the src, volume, balance, and loop properties for the sound element.

The BGSOUND tag enables you to create pages with background sounds or "sound tracks".

This element can be used only within the HEAD tag.

IHTMLBGsound Methods
get_balance get_loop get_src
get_volume put_balance put_loop
put_src put_volume

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


Loop Property

*
  * Previous Topic: IHTMLBGsound::get_balance
  * Next Topic: IHTMLBGsound::get_src

IHTMLBGsound::get_loop

HRESULT get_loop(
    VARIANT *p
);

Retrieves the number of times the sound will loop when activated.

  • Returns S_OK if successful, or an error value otherwise.
p
VARIANT structure containing a numeric value that specifies the number of times to loop. If this parameter receives -1 (infinite), the video will loop continuously.

Following are descriptions on how the loop works for some boundary cases.
<BGSOUND src="file:///c:\win95\system\msremind.wav"> | once
<BGSOUND src="file:///c:\win95\system\msremind.wav" LOOP> | once
<BGSOUND src="file:///c:\win95\system\msremind.wav" LOOP=> | zero times
<BGSOUND src="file:///c:\win95\system\msremind.wav" LOOP=-1> | infinitely
<BGSOUND src="file:///c:\win95\system\msremind.wav" LOOP=0> | once

See also put_loop

Up Top of Page

IHTMLBGsound::put_loop

HRESULT put_loop(
    VARIANT v
);

Sets the number of times the sound will loop when activated.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure containing the value that specifies the number of times to loop. If this parameter is -1 (infinite), the sound will loop continuously.

Following are descriptions on how loop works for some boundary cases.
<BGSOUND src="file:///c:\win95\system\msremind.wav"> | once
<BGSOUND src="file:///c:\win95\system\msremind.wav" LOOP> | once
<BGSOUND src="file:///c:\win95\system\msremind.wav" LOOP=> | zero times
<BGSOUND src="file:///c:\win95\system\msremind.wav" LOOP=-1> | infinitely
<BGSOUND src="file:///c:\win95\system\msremind.wav" LOOP=0> | once

See also get_loop


Src Property

*
  * Previous Topic: IHTMLBGsound::get_loop
  * Next Topic: IHTMLBGsound::get_volume

IHTMLBGsound::get_src

HRESULT get_src(
    BSTR *p
);

Retrieves the URL of the sound to be played.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the URL.

See also put_src

Up Top of Page

IHTMLBGsound::put_src

HRESULT put_src(
    BSTR v
);

Sets the URL of a sound to be played.

  • Returns S_OK if successful, or an error value otherwise.
v
String value that specifies the URL.

See also get_src


Volume Property

*
  * Previous Topic: IHTMLBGsound::get_src
  * Next Topic: IHTMLBGsound::put_balance

IHTMLBGsound::get_volume

HRESULT get_volume(
    VARIANT *p
);

Retrieves the volume setting for the sound. The higher the setting, the louder the sound.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the volume setting.

See also put_volume

Up Top of Page

IHTMLBGsound::put_volume

HRESULT put_volume(
    VARIANT v
);

Sets the volume setting for the sound. The higher the setting, the louder the sound.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains a string or numeric value specifying the volume setting.

See also get_volume


IHTMLBlockElement

This interface provides access to properties and methods available to most block elements.

IHTMLBlockElement Methods


Clear Property

*
  * Previous Topic: IHTMLBlockElement
  * Next Topic: IHTMLBlockElement::put_clear

IHTMLBlockElement::get_clear

HRESULT get_clear(
    BSTR *p
);

Retrieves the clear value, specifying whether the element allows floating elements on its left and/or right sides.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives one of these values:
none | No floating elements allowed.
left | Floating elements allowed on the left side.
right | Floating elements allowed on the right side.
both | Floating elements allowed on both sides.

See also put_clear

Up Top of Page

IHTMLBlockElement::put_clear

HRESULT put_clear(
    BSTR v
);

Sets the clear value, specifying whether the element allows floating elements on its left and/or right sides.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the clear value. Can be one of these values:
none | No floating elements allowed.
left | Floating elements allowed on the left side.
right | Floating elements allowed on the right side.
both | Floating elements allowed on both sides.

See also get_clear


ALink Property

*
  * Previous Topic: IHTMLBodyElement::put_aLink
  * Next Topic: IHTMLBodyElement::put_onload

IHTMLBodyElement::get_aLink

HRESULT get_aLink(
    VARIANT *p
);

Retrieves the color used for the active link.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the color. Can be one of the color names or values given in the Color Table reference documentation.

See also put_aLink

Up Top of Page

IHTMLBodyElement::put_aLink

HRESULT put_aLink(
    VARIANT v
);

Sets the color for the active link.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure containing either a string or value specifying the color. Can be one of the color names or values given in the Color Table reference documentation.

See also get_aLink


Background Property

*
  * Previous Topic: IHTMLBodyElement::put_background
  * Next Topic: IHTMLBodyElement::put_bgProperties

IHTMLBodyElement::get_background

HRESULT get_background(
    BSTR *p
);

Retrieves the URL of the background picture, if any. The picture is tiled behind the text and graphics on the page.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the URL of the background picture.

See also put_background

Up Top of Page

IHTMLBodyElement::put_background

HRESULT put_background(
    BSTR v
);

Sets a background picture. The picture is tiled behind the text and graphics on the page.

  • Returns S_OK if successful, or an error value otherwise.
v
String value specifying the URL of the background picture.

See also get_background


BgColor Property

*
  * Previous Topic: IHTMLBodyElement::put_bgColor
  * Next Topic: IHTMLBodyElement::put_text

IHTMLBodyElement::get_bgColor

HRESULT get_bgColor(
    VARIANT *p
);

Retrieves the background color of the page.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the color. The color can be one of the color names or values given in the Color Table reference documentation.

JScript supports the entire set of valid property colors both as strings and their numerical equivalents as a string. JScript always returns the property as the numeric equivalent as a string regardless of the format to which the value was set.

See also put_bgColor

Up Top of Page

IHTMLBodyElement::put_bgColor

HRESULT put_bgColor(
    VARIANT v
);

Sets the background color of the page.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure containing a string or value specifying the color. The color can be one of the color names or values given in the Color Table reference documentation.

JScript supports the entire set of valid property colors both as strings and their numerical equivalents as a string. JScript always returns the property as the numeric equivalent as a string regardless of the format to which the value was set.

See also get_bgColor


BgProperties Property

*
  * Previous Topic: IHTMLBodyElement::put_bgProperties
  * Next Topic: IHTMLBodyElement::put_leftMargin

IHTMLBodyElement::get_bgProperties

HRESULT get_bgProperties(
    BSTR *p
);

Retrieves the properties for the background picture; for example, whether the picture is a fixed watermark or scrolls with the page

  • Returns S_OK if successful, or an error value otherwise.
v
Address of a string variable that receives the background properties. This parameter receives "fixed" if the background picture is fixed and does not scroll with the page, or an empty string ("") if the background picture scrolls.

See also put_bgProperties

Up Top of Page

IHTMLBodyElement::put_bgProperties

HRESULT put_bgProperties(
    BSTR v
);

Sets the properties for the background picture. For example, specifies whether the picture is a fixed watermark or scrolls with the page

  • Returns S_OK if successful, or an error value otherwise.
v
String value specifying the background properties. If this parameter is "fixed", the background picture is fixed and does not scroll with the page. If set to an empty string (""), the background picture scrolls.

See also get_bgProperties


IHTMLBodyElement

This interface provides access to the BODY object. The methods that act on the IHTMLBodyElement allow you to control the behavior and characteristics of the BODY element.

This interface specifies the beginning and end of the document body.

Use the IHTMLDocument2::get_body method to retrieve a pointer to the IHTMLBodyElement interface for a document's BODY object.

The BODY element is a block element.

IHTMLBodyElement Methods
put_background get_background put_bgProperties
get_bgProperties put_leftMargin get_leftMargin
put_topMargin get_topMargin put_rightMargin
get_rightMargin put_bottomMargin get_bottomMargin
put_noWrap get_noWrap put_bgColor
get_bgColor put_text get_text
put_link get_link put_vLink
get_vLink put_aLink get_aLink
put_onload get_onload put_onunload
get_onunload put_scroll get_scroll
put_onselect get_onselect put_onbeforeunload
get_onbeforeunload createTextRange

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


BottomMargin Property

*
  * Previous Topic: IHTMLBodyElement::put_bottomMargin
  * Next Topic: IHTMLBodyElement::put_noWrap

IHTMLBodyElement::get_bottomMargin

HRESULT get_bottomMargin(
    VARIANT *p
);

Retrieves the margin for the bottom of the page and overrides the default margin.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the bottom margin. This property receives "" if the margin is exactly on the bottom edge.

See also put_bottomMargin

Up Top of Page

IHTMLBodyElement::put_bottomMargin

HRESULT put_bottomMargin(
    VARIANT v
);

Sets the margin for the bottom of the page and overrides the default margin.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure containing either a string or value specifying the bottom margin. If set to "", the margin will be exactly on the bottom edge.

See also get_bottomMargin


IHTMLBodyElement::createTextRange

HRESULT createTextRange(
    IHTMLTxtRange **range
);

Creates a text range object for the BODY object. You use a text range to examine and modify the text within the element.

  • Returns S_OK if successful, or an error value otherwise.
range
Address of a pointer to the IHTMLTxtRange interface that is created.


LeftMargin Property

*
  * Previous Topic: IHTMLBodyElement::put_leftMargin
  * Next Topic: IHTMLBodyElement::put_topMargin

IHTMLBodyElement::get_leftMargin

HRESULT get_leftMargin(
    VARIANT *p
);

Retrieves the left margin for the entire body of the page. This property overrides the default margin.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the left margin. This property receives "" if the margin is exactly on the left edge.

See also put_leftMargin

Up Top of Page

IHTMLBodyElement::put_leftMargin

HRESULT put_leftMargin(
    VARIANT v
);

Sets the left margin for the entire body of the page and overrides the default margin.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure containing a string or value specifying the left margin. If set to "", the margin will be exactly on the left edge.

See also get_leftMargin


Link Property

*
  * Previous Topic: IHTMLBodyElement::put_link
  * Next Topic: IHTMLBodyElement::put_vLink

IHTMLBodyElement::get_link

HRESULT get_link(
    VARIANT *p
);

Retrieves the color used for links that have not yet been visited.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the color. Can be one of the color names or values given in the Color Table reference documentation.

See also put_link

Up Top of Page

IHTMLBodyElement::put_link

HRESULT put_link(
    VARIANT v
);

Sets the color of links that have not yet been visited.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure containing either a string or value specifying the color. Can be one of the color names or values given in the Color Table reference documentation.

See also get_link


NoWrap Property

*
  * Previous Topic: IHTMLBodyElement::put_noWrap
  * Next Topic: IHTMLBodyElement::put_bgColor

IHTMLBodyElement::get_noWrap

HRESULT get_noWrap(
    VARIANT_BOOL *p
);

Determines whether automatic word wrapping is enabled or disabled for the document.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a Boolean variable that receives TRUE if automatic word-wrapping is enabled for the document, or FALSE otherwise. The default value for this property is FALSE.

See also put_noWrap

Up Top of Page

IHTMLBodyElement::put_noWrap

HRESULT put_noWrap(
    VARIANT_BOOL v
);

Enables or disables automatic word wrapping for the document.

  • Returns S_OK if successful, or an error value otherwise.
v
Boolean value that contains the word-wrap flag. If TRUE, the browser performs automatic word wrapping for the document. If FALSE, it doesn't. The default value for this property is FALSE.

See also get_noWrap


Onbeforeunload Property

*
  * Previous Topic: IHTMLBodyElement::put_onbeforeunload
  * Next Topic: IHTMLBodyElement::createTextRange

IHTMLBodyElement::get_onbeforeunload

HRESULT get_onbeforeunload(
    VARIANT *p
);

Retrieves the inline script associated with the onbeforeunload event on the BODY element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script.

The handler for this event should return NULL if doing the unload is safe, or a text string to prompt the user to decide to cancel or continue with the unload operation. Only the user's response to the warning can stop the new navigation causing the unload; the event handler itself cannot unilaterally block the operation. If the handler returns a non-NULL string, a modal dialog box appears that displays the explanatory string. The dialog box shows three buttons with the message for user action:

  • Continue—the unload operation proceeds.
  • Cancel—the navigation causing the unload is immediately canceled.
  • Help—(strongly recommended)—displays additional explanatory text, such as "This operation may cause existing content information to be lost. Choose Continue if this is OK, or Cancel to retain the information."

In the case of frames, the full sequence of onbeforeunload events is fired on each frame in the same order, depth-first, that onunload events are about to be fired. A dialog box is presented for each event handler that returns a non-NULL string. The first Cancel response stops the potential navigation, in which case no unload occurs. If there is no Cancel response, the unload proceeds and onunload events fire.

See also put_onbeforeunload

Up Top of Page

IHTMLBodyElement::put_onbeforeunload

HRESULT put_onbeforeunload(
    VARIANT v
);

Sets the inline script associated with the onbeforeunload event on the BODY element.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure containing the script.

The handler for this event should return NULL if doing the unload is safe, or a text string to prompt the user to decide to cancel or continue with the unload operation. Only the user's response to the warning can stop the new navigation causing the unload; the event handler itself cannot unilaterally block the operation. If the handler returns a non-NULL string, a modal dialog box appears that displays the explanatory string. The dialog box shows three buttons with the message for user action:

  • Continue—the unload operation proceeds.
  • Cancel—the navigation causing the unload is immediately canceled.
  • Help—(strongly recommended)—displays additional explanatory text, such as "This operation may cause existing content information to be lost. Choose Continue if this is OK, or Cancel to retain the information."

In the case of frames, the full sequence of onbeforeunload events is fired on each frame in the same order, depth-first, that onunload events are about to be fired. A dialog box is presented for each event handler that returns a non-NULL string. The first Cancel response stops the potential navigation, in which case no unload occurs. If there is no Cancel response, the unload proceeds and onunload events fire.

See also get_onbeforeunload


Onload Property

*
  * Previous Topic: IHTMLBodyElement::put_onload
  * Next Topic: IHTMLBodyElement::put_onunload

IHTMLBodyElement::get_onload

HRESULT get_onload(
    VARIANT *p
);

Retrieves the inline script associated with the onload event on the BODY element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that will hold the script.

See also put_onload

Up Top of Page

IHTMLBodyElement::put_onload

HRESULT put_onload(
    VARIANT v
);

Sets the inline script associated with the onload event on the BODY element. Occurs immediately after the browser loads the given object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script.

See also get_onload


Onselect Property

*
  * Previous Topic: IHTMLBodyElement::put_onselect
  * Next Topic: IHTMLBodyElement::put_onbeforeunload

IHTMLBodyElement::get_onselect

HRESULT get_onselect(
    VARIANT *p
);

Retrieves the inline script associated with the onselect event on the BODY element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script.

See also put_onselect

Up Top of Page

IHTMLBodyElement::put_onselect

HRESULT put_onselect(
    VARIANT v
);

Sets the inline script associated with the onselect event on the BODY element.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script.

See also get_onselect


Onunload Property

*
  * Previous Topic: IHTMLBodyElement::put_onunload
  * Next Topic: IHTMLBodyElement::put_scroll

IHTMLBodyElement::get_onunload

HRESULT get_onunload(
    VARIANT *p
);

Retrieves the inline script associated with the onunload event on the BODY element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script.

See also put_onunload

Up Top of Page

IHTMLBodyElement::put_onunload

HRESULT put_onunload(
    VARIANT v
);

Sets the inline script associated with the onunload event on the BODY element.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure containing the script.

See also get_onunload


RightMargin Property

*
  * Previous Topic: IHTMLBodyElement::put_rightMargin
  * Next Topic: IHTMLBodyElement::put_bottomMargin

IHTMLBodyElement::get_rightMargin

HRESULT get_rightMargin(
    VARIANT *p
);

Retrieves the right margin for the entire body of the page and overrides the default margin.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the right margin. This property receives "" if the margin is exactly on the right edge.

See also put_rightMargin

Up Top of Page

IHTMLBodyElement::put_rightMargin

HRESULT put_rightMargin(
    VARIANT v
);

Sets the right margin for the entire body of the page and overrides the default margin.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure containing a string or value specifying the right margin. If set to "", the margin will be exactly on the right edge.

See also get_rightMargin


Scroll Property

*
  * Previous Topic: IHTMLBodyElement::put_scroll
  * Next Topic: IHTMLBodyElement::put_onselect

IHTMLBodyElement::get_scroll

HRESULT get_scroll(
    BSTR *p
);

Determines whether the scroll bars are on or off.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives "yes" if the scroll bars are on, or "no" if they are off.

See also put_scroll

Up Top of Page

IHTMLBodyElement::put_scroll

HRESULT put_scroll(
    BSTR v
);

Turns the scroll bars on or off.

  • Returns S_OK if successful, or an error value otherwise.
v
String value specifying whether to turn the scroll bars on or off. Specify "yes" to turn on the scroll bars, or "no" to turn them off.

See also get_scroll


Text Property

*
  * Previous Topic: IHTMLBodyElement::put_text
  * Next Topic: IHTMLBodyElement::put_link

IHTMLBodyElement::get_text

HRESULT get_text(
    VARIANT *p
);

Retrieves the current text (foreground) color of the document body.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the color. The color can be one of the color names or values given in the Color Table reference documentation.

The text is formatted within the current context of the document.

See also put_text

Up Top of Page

IHTMLBodyElement::put_text

HRESULT put_text(
    VARIANT v
);

Sets the text (foreground) color for the document body.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains either a string or value specifying the color. The color can be one of the color names or values given in the Color Table reference documentation.

The text is formatted within the current context of the document.

See also get_text


TopMargin Property

*
  * Previous Topic: IHTMLBodyElement::put_topMargin
  * Next Topic: IHTMLBodyElement::put_rightMargin

IHTMLBodyElement::get_topMargin

HRESULT get_topMargin(
    VARIANT *p
);

Retrieves the margin for the top of the page and overrides the default margin.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the top margin. This property receives "" if the margin is exactly on the top edge.

See also put_topMargin

Up Top of Page

IHTMLBodyElement::put_topMargin

HRESULT put_topMargin(
    VARIANT v
);

Sets the margin for the top of the page and overrides the default margin.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains either a string or numeric value specifying the top margin. If set to "", the margin will be exactly on the top edge.

See also get_topMargin


VLink Property

*
  * Previous Topic: IHTMLBodyElement::put_vLink
  * Next Topic: IHTMLBodyElement::put_aLink

IHTMLBodyElement::get_vLink

HRESULT get_vLink(
    VARIANT *p
);

Retrieves the color used for links that have been visited.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the color. Can be one of the color names or values given in the Color Table reference documentation.

See also put_vLink

Up Top of Page

IHTMLBodyElement::put_vLink

HRESULT put_vLink(
    VARIANT v
);

Sets the color of links that have been visited.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains either a string or value specifying the color. Can be one of the color names or values given in the Color Table reference documentation.

See also get_vLink


IHTMLBRElement IHTMLBRElement *
  * Previous Topic: IHTMLBodyElement::createTextRange
  * Next Topic: IHTMLBRElement::get_clear

IHTMLBRElement

This interface inserts a line break.

IHTMLBRElement Methods


Clear Property

*
  * Previous Topic: IHTMLBRElement
  * Next Topic: IHTMLBRElement::put_clear

IHTMLBRElement::get_clear

HRESULT get_clear(
    BSTR *p
);

Determines whether vertical space is inserted so that the next text displayed is past left- or right-aligned floating images.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives one of the following values:
all | Place text after all images.
left | Place text past left-aligned images.
right | Place text past right-aligned images.

See also put_clear

Up Top of Page

IHTMLBRElement::put_clear

HRESULT put_clear(
    BSTR v
);

Inserts vertical space so that the next text displayed will be past left- and/or right-aligned floating images.

  • Returns S_OK if successful, or an error value otherwise.
v
String value specifying one of the following values:
all | Place text after all images.
left | Place text past left-aligned images.
right | Place text past right-aligned images.

See also get_clear


IHTMLButtonElement

This interface renders content as an HTML button.

This element is a block element.

IHTMLButtonElement Methods
get_type put_value get_value
put_name get_name put_status
get_status put_disabled get_disabled
get_form createTextRange

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


IHTMLButtonElement::createTextRange

HRESULT createTextRange(
    IHTMLTxtRange **range
);

Creates a text range object for the BUTTON object. You use a text range to examine and modify the text within the element.

  • Returns S_OK if successful, or an error value otherwise.
range
Address of a pointer to the IHTMLTxtRange interface of the text range created.


Disabled Property

*
  * Previous Topic: IHTMLButtonElement::put_disabled
  * Next Topic: IHTMLButtonElement::get_form

IHTMLButtonElement::get_disabled

HRESULT get_disabled(
    VARIANT_BOOL *p
);

Determines whether the control is enabled or disabled.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a Boolean variable that receives TRUE if the control is disabled, or FALSE otherwise.

The default value for this property is FALSE.

See also put_disabled

Up Top of Page

IHTMLButtonElement::put_disabled

HRESULT put_disabled(
    VARIANT_BOOL v
);

Enables or disables the control. A disabled control appears greyed and does not respond to user input.

  • Returns S_OK if successful, or an error value otherwise.
v
Boolean value specifying whether to disable the control. If TRUE, the control is disabled; otherwise, it is enabled.

The default value for this property is FALSE.

See also get_disabled


IHTMLButtonElement::get_form

HRESULT get_form(
    IHTMLFormElement **p
);

Retrieves a reference to the form the element is embedded on.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a pointer to the IHTMLFormElement interface of the form element. This parameter receives NULL if the element is not on a form.

See also IHTMLFormElement


IHTMLButtonElement::get_type

HRESULT get_type(
    BSTR *p
);

Retrieves the visual appearance and default behavior of the button.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives one of these strings:
button | Creates a command button. This is the default value for this property.
reset | Creates a reset button. If in a form, this button resets the fields in the form to their initial values.
submit | Creates a submit button. If in a form, this button submits the form.


Name Property

*
  * Previous Topic: IHTMLButtonElement::put_name
  * Next Topic: IHTMLButtonElement::put_status

IHTMLButtonElement::get_name

HRESULT get_name(
    BSTR *p
);

Retrieves the name of the button control.

  • Returns S_OK if successful, or an error value otherwise.
v
Address of a string variable that receives the name.

This method is related to the name property of the BUTTON object.

See also put_name

Up Top of Page

IHTMLButtonElement::put_name

HRESULT put_name(
    BSTR v
);

Sets the name of the button control.

  • Returns S_OK if successful, or an error value otherwise.
v
String value specifying the name.

This method is related to the name property of the BUTTON object.

See also get_name


Status Property

*
  * Previous Topic: IHTMLButtonElement::put_status
  * Next Topic: IHTMLButtonElement::put_disabled

IHTMLButtonElement::get_status

HRESULT get_status(
    VARIANT *p
);

Retrieves the status of the button control.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the status. Can be TRUE, FALSE, or NULL.

See also put_status

Up Top of Page

IHTMLButtonElement::put_status

HRESULT put_status(
    VARIANT v
);

Sets the status of the button control.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure specifying the status. Can be TRUE, FALSE, or NULL.

See also get_status


Value Property

*
  * Previous Topic: IHTMLButtonElement::put_value
  * Next Topic: IHTMLButtonElement::put_name

IHTMLButtonElement::get_value

HRESULT get_value(
    BSTR *p
);

Retrieves the value of the button control. The value is submitted to the server as a name/value pair.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the value.

See also put_value

Up Top of Page

IHTMLButtonElement::put_value

HRESULT put_value(
    BSTR v
);

Sets the value of the button control. The value is submitted to the server as a name/value pair.

  • Returns S_OK if successful, or an error value otherwise.
v
String value specifying the value.

See also get_value


IHTMLCommentElement IHTMLCommentElement *
  * Previous Topic: IHTMLButtonElement::createTextRange
  * Next Topic: IHTMLCommentElement::put_text

IHTMLCommentElement

This interface indicates a comment that will not be displayed.

IHTMLCommentElement Methods


Text Property

*
  * Previous Topic: IHTMLCommentElement::put_text
  * Next Topic: IHTMLControlElement

IHTMLCommentElement::get_text

HRESULT get_text(
    BSTR *p
);

Retrieves the text contained within the COMMENT object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the text.

The text is formatted within the current context of the document.

See also put_text

Up Top of Page

IHTMLCommentElement::put_text

HRESULT put_text(
    BSTR v
);

Sets the text contained within the COMMENT object.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the text.

See also get_text


AccessKey Property

*
  * Previous Topic: IHTMLControlElement::put_accessKey
  * Next Topic: IHTMLControlElement::put_onblur

IHTMLControlElement::get_accessKey

HRESULT get_accessKey(
    BSTR *p
);

Retrieves an accelerator for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the accelerator key.

See also put_accessKey

Up Top of Page

IHTMLControlElement::put_accessKey

HRESULT put_accessKey(
    BSTR v
);

Sets an accelerator for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the accelerator.

See also get_accessKey


IHTMLControlElement::addFilter

HRESULT addFilter(
    IUnknown *pUnk
);

Adds the specified filter to the list of filters influencing this element.

  • Returns S_OK if successful, or an error value otherwise.
pUnk
Address of the IUnknown interface of the filter to be added.

See also removeFilter


IHTMLControlElement::blur

HRESULT blur(void);

Causes a control to lose focus and fires the onblur event.

  • Returns S_OK if successful, or an error value otherwise.

See also focus


IHTMLControlElement

This interface is a base interface for control type elements such as IHTMLImgElement.

IHTMLControlElement Methods
put_tabIndex get_tabIndex focus
put_accessKey get_accessKey put_onblur
get_onblur put_onfocus get_onfocus
put_onresize get_onresize blur
addFilter removeFilter get_clientWidth
get_clientHeight get_clientTop get_clientLeft

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


IHTMLControlElement::focus

HRESULT focus(void);

Causes a control to receive the focus and executes the code specified by onfocus.

  • Returns S_OK if successful, or an error value otherwise.

See also blur


IHTMLControlElement::get_clientHeight

HRESULT get_clientHeight(
    long *p
);

Retrieves the height of the element, in pixels. This height does not take into account any margin, border, scroll bar, or padding that might have been applied to the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the height of the element.


IHTMLControlElement::get_clientLeft

HRESULT get_clientLeft(
    long *p
);

Retrieves the left coordinates of the client area inside this element's borders.

p
Long integer value containing the coordinates for the left corner of the client area inside this element's borders.

Up Top of Page


IHTMLControlElement::get_clientTop

HRESULT get_clientTop(
    long *p
);

Retrieves the top coordinates of the client area inside this element's borders.

p
Long integer value containing the coordinates for the top corner of the client area inside this element's borders.

Up Top of Page


IHTMLControlElement::get_clientWidth

HRESULT get_clientWidth(
    long *p
);

Retrieves the width of the element, in pixels. This width does not take into account any margin, border, scroll bar, or padding that might have been applied to the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the width of the element.

Up Top of Page


Onblur Property

*
  * Previous Topic: IHTMLControlElement::put_onblur
  * Next Topic: IHTMLControlElement::put_onfocus

IHTMLControlElement::get_onblur

HRESULT get_onblur(
    VARIANT *p
);

Retrieves the inline script associated with the onblur event on the control element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script.

See also put_onblur

Up Top of Page

IHTMLControlElement::put_onblur

HRESULT put_onblur(
    VARIANT v
);

Sets the inline script associated with the onblur event on the control element.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure containing the script to set.

See also get_onblur


Onfocus Property

*
  * Previous Topic: IHTMLControlElement::put_onfocus
  * Next Topic: IHTMLControlElement::put_onresize

IHTMLControlElement::get_onfocus

HRESULT get_onfocus(
    VARIANT *p
);

Retrieves the inline script associated with the onfocus event on the control element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script.

See also put_onfocus

Up Top of Page

IHTMLControlElement::put_onfocus

HRESULT put_onfocus(
    VARIANT v
);

Sets the inline script associated with the onfocus event on the control element.

  • Returns S_OK if successful, or an error value otherwise.
v
Variable of VARIANT type.

See also get_onfocus


Onresize Property

*
  * Previous Topic: IHTMLControlElement::put_onresize
  * Next Topic: IHTMLControlElement::blur

IHTMLControlElement::get_onresize

HRESULT get_onresize(
    VARIANT *p
);

Retrieves the inline script associated with the onresize event on the control element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script.

See also put_onresize

Up Top of Page

IHTMLControlElement::put_onresize

HRESULT put_onresize(
    VARIANT v
);

Sets the inline script associated with the onresize event on the control element.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure containing the script.

See also get_onresize


IHTMLControlElement::removeFilter

HRESULT removeFilter(
    IUnknown *pUnk
);

Removes the specified filter from the list of filters influencing this element.

  • Returns S_OK if successful, or an error value otherwise.
pUnk
Address of a variable of IUnknown type.

See also addFilter


TabIndex Property

*
  * Previous Topic: IHTMLControlElement::put_tabIndex
  * Next Topic: IHTMLControlElement::focus

IHTMLControlElement::get_tabIndex

HRESULT get_tabIndex(
    short *p
);

Retrieves the tab index for the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a short integer variable that receives the tab index.

Tab selection order is determined by the value of the tabIndex property as follows:

  • All elements with tabIndex > 0 are selected in increasing tabIndex order, or in source order for duplicate tabIndex values.
  • All elements with tabIndex = 0, or without tabIndex set, are selected next, in source order if more than one.
  • Elements with tabIndex = -1 are omitted from tab selection.

See also put_tabIndex

Up Top of Page

IHTMLControlElement::put_tabIndex

HRESULT put_tabIndex(
    short v
);

Sets the tab index for the object. The tab index determines the tab selection order.

  • Returns S_OK if successful, or an error value otherwise.
v
Short integer value specifying the tab index.

Tab selection order is determined by the value of the tabIndex property as follows:

  • All elements with tabIndex > 0 are selected in increasing tabIndex order, or in source order for duplicate tabIndex values.
  • All elements with tabIndex = 0, or without tabIndex set, are selected next, in source order if more than one.
  • Elements with tabIndex = -1 are omitted from tab selection.

See also get_tabIndex


IHTMLControlRange::add

HRESULT add(
    IHTMLControlElement *item
);

Adds an element to the collection.

  • Returns S_OK if successful, or an error value otherwise.
item
Address of the IHTMLControlElement interface to add.


IHTMLControlRange::commonParentElement

HRESULT commonParentElement(
    IHTMLElement **Parent
);

Retrieves the interface to the first parent element that contains all the controls that are currently stored in this range and within its scope.

  • Returns S_OK if successful, or an error value otherwise.
Parent
Address of a pointer to the IHTMLElement interface of the element.


IHTMLControlRange

The IHTMLControlRange interface contains a range of control type elements. This interface is used for control selection and represents an array of controls that can be operated on as a group.

IHTMLControlRange Methods
select add remove
item scrollIntoView queryCommandSupported
queryCommandEnabled queryCommandState queryCommandIndeterm
queryCommandText queryCommandValue execCommand
execCommandShowHelp commonParentElement get_length

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


IHTMLControlRange::execCommand

HRESULT execCommand(
    BSTR cmdID,
    VARIANT_BOOL showUI,
    VARIANT value,
    VARIANT_BOOL *pfRet
);

Executes the given command over the current selection or text range.

  • Returns S_OK if successful, or an error value otherwise.
cmdID
String identifier of a command. Can be any command identifier given in the list of Command Identifiers.
showUI
Boolean value specifying whether to display a user interface if the command supports one. If TRUE, the command displays a user interface, if applicable; otherwise, it doesn't.
value
VARIANT structure containing a value to pass to the command. Possible values depend on the value of cmdID.
pfRet
Address of a Boolean variable that receives TRUE if the function is successful, or FALSE otherwise.


IHTMLControlRange::execCommandShowHelp

HRESULT execCommandShowHelp(
    BSTR cmdID,
    VARIANT_BOOL *pfRet
);

Displays help information for the given command identifier.

  • Returns S_OK if successful, or an error value otherwise.
cmdID
String identifier of a command. Can be any command identifier given in the list of Command Identifiers.
pfRet
Address of a Boolean variable that receives TRUE if successful, or FALSE otherwise.


IHTMLControlRange::get_length

HRESULT get_length(
    long *p
);

Retrieves the number of elements in the collection.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a long integer variable that receives the number of elements.


IHTMLControlRange::item

HRESULT item(
    long index,
    IHTMLElement **pdisp
);

Retrieves an element or a collection from the given collection. The index parameter determines which action to take.

  • Returns S_OK if successful, or an error value otherwise.
index
Long integer value containing the zero-based index of the item to retrieve.
pdisp
Address of a pointer to the IHTMLElement interface for the element or collection.

Up Top of Page


IHTMLControlRange::queryCommandEnabled

HRESULT queryCommandEnabled(
    BSTR cmdID,
    VARIANT_BOOL *pfRet
);

Determines whether the given command is currently available.

  • Returns S_OK if successful, or an error value otherwise.
cmdID
String containing an identifier of a command. Can be any command identifier given in the list of Command Identifiers.
pfRet
Address of a Boolean variable that receives TRUE if the command is available, or FALSE otherwise.


IHTMLControlRange::queryCommandIndeterm

HRESULT queryCommandIndeterm(
    BSTR cmdID,
    VARIANT_BOOL *pfRet
);

Determines whether the given command is in the indeterminate state.

  • Returns S_OK if successful, or an error value otherwise.
cmdID
String value containing an identifier of a command. Can be any command identifier given in the list of Command Identifiers.
pfRet
Address of a Boolean variable that receives TRUE if the given command is in the indeterminate state, or FALSE otherwise.


IHTMLControlRange::queryCommandState

HRESULT queryCommandState(
    BSTR cmdID,
    VARIANT_BOOL *pfRet
);

Retrieves the current status of the given command. The status indicates whether the command has been carried out on the object.

  • Returns S_OK if successful, or an error value otherwise.
cmdID
String value containing an identifier of a command. Can be any command identifier given in the list of Command Identifiers.
pfRet
Address of a Boolean variable that receives TRUE if the given command has been carried out, FALSE if it has not, or NULL if the function cannot determine the status of the command.


IHTMLControlRange::queryCommandSupported

HRESULT queryCommandSupported(
    BSTR cmdID,
    VARIANT_BOOL *pfRet
);

Determines whether the given command is supported.

  • Returns S_OK if successful, or an error value otherwise.
cmdID
String value containing the identifier of a command. Can be any command identifier given in the list of Command Identifiers.
pfRet
Address of a Boolean variable that receives TRUE if the command is supported, or FALSE otherwise.


IHTMLControlRange::queryCommandText

HRESULT queryCommandText(
    BSTR cmdID,
    BSTR *pcmdText
);

Retrieves the string associated with the given command.

  • Returns S_OK if successful, or an error value otherwise.
cmdID
String value containing an identifier of a command. Can be any command identifier given in the list of Command Identifiers.
pcmdText
Address of a Boolean variable that receives the command string.


IHTMLControlRange::queryCommandValue

HRESULT queryCommandValue(
    BSTR cmdID,
    VARIANT *pcmdValue
);

Retrieves the current value of the given command.

  • Returns S_OK if successful, or an error value otherwise.
cmdID
String identifier of a command. Can be any command identifier given in the list of Command Identifiers.
pcmdValue
Address of a Boolean variable that receives a string representing the command value. If the command is not supported, this variable receives NULL.


IHTMLControlRange::remove

HRESULT remove(
    long index
);

Removes an element from the collection.

  • Returns S_OK if successful, or an error value otherwise.
index
Long integer value containing the index of the element to remove.

See also add


IHTMLControlRange::scrollIntoView

HRESULT scrollIntoView(
    VARIANT varargStart
);

Scrolls the object into view, aligning it at either the top or bottom of the window.

  • Returns S_OK if successful, or an error value otherwise.
varargStart
Boolean value specifying whether to place the object at the top of the window or at the bottom. If TRUE, the method scrolls the object so that its top is visible at the top of the window. If FALSE, the bottom of the object is visible at the bottom of the window. If no value is given, the object scrolls to the top by default.

Depending on the size of the given object and the current window, this method may not be able to put the item at the very top or very bottom, but will position the object as close to the requested position as possible.


IHTMLControlRange::select

HRESULT select(void);

Highlights the input area of a form element.

  • Returns S_OK if successful, or an error value otherwise.


IHTMLDatabinding

This interface encapsulates the databinding methods that an IHTMLElement interface can support. To access these methods, a control should query IHTMLElement for this interface.

IHTMLDatabinding Methods


DataFld Property

*
  * Previous Topic: IHTMLDatabinding::put_dataFld
  * Next Topic: IHTMLDatabinding::put_dataSrc

IHTMLDatabinding::get_dataFld

HRESULT get_dataFld(
    BSTR *p
);

Retrieves the field of a given data source (as specified by the dataFld property) to bind to the given element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the field.

See also put_dataFld

Up Top of Page

IHTMLDatabinding::put_dataFld

HRESULT put_dataFld(
    BSTR v
);

Sets the field of a given data source (as specified by the dataFld property) to bind to the given element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the field.

See also get_dataFld


DataFormatAs Property

*
  * Previous Topic: IHTMLDatabinding::put_dataFormatAs
  * Next Topic: IHTMLDDElement

IHTMLDatabinding::get_dataFormatAs

HRESULT get_dataFormatAs(
    BSTR *p
);

Retrieves the type of the data to bind to the given element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the type of data.

See also put_dataFormatAs

Up Top of Page

IHTMLDatabinding::put_dataFormatAs

HRESULT put_dataFormatAs(
    BSTR v
);

Sets the type of the data to bind to the given element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the type of data.

See also get_dataFormatAs


DataSrc Property

*
  * Previous Topic: IHTMLDatabinding::put_dataSrc
  * Next Topic: IHTMLDatabinding::put_dataFormatAs

IHTMLDatabinding::get_dataSrc

HRESULT get_dataSrc(
    BSTR *p
);

Retrieves the identifier of the data source object that supplies the data that is bound to this element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the identifier of the data source object.

See also put_dataSrc

Up Top of Page

IHTMLDatabinding::put_dataSrc

HRESULT put_dataSrc(
    BSTR v
);

Sets the identifier of the data source object that supplies the data that is bound to this element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the identifier of the data source object.

See also get_dataSrc


IHTMLDDElement IHTMLDDElement *
  * Previous Topic: IHTMLDatabinding::get_dataFormatAs
  * Next Topic: IHTMLDDElement::put_noWrap

IHTMLDDElement

This interface provides access to the DD object.

IHTMLDDElement Methods


NoWrap Property

*
  * Previous Topic: IHTMLDDElement::put_noWrap
  * Next Topic: IHTMLDialog

IHTMLDDElement::get_noWrap

HRESULT get_noWrap(
    VARIANT_BOOL *p
);

Determines whether automatic word wrapping is enabled or disabled for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a Boolean variable that receives TRUE if automatic word-wrapping is enabled for the element, or FALSE otherwise. The default value for this property is FALSE.

See also put_noWrap

Up Top of Page

IHTMLDDElement::put_noWrap

HRESULT put_noWrap(
    VARIANT_BOOL v
);

Enables or disables automatic word wrapping for the text of the element.

  • Returns S_OK if successful, or an error value otherwise.
v
Boolean value containing the word-wrap flag. If TRUE, the browser performs automatic word wrapping on the element text. If FALSE, it doesn't. The default value for this property is FALSE.

See also get_noWrap


IHTMLDialog::close IHTMLDialog::close *
  * Previous Topic: IHTMLDialog::get_returnValue
  * Next Topic: IHTMLDialog::toString

IHTMLDialog::close

HRESULT close(void);

Closes the dialog box.

  • Returns S_OK if successful, or an error value otherwise.


IHTMLDialog

This interface provides access to information about an HTML dialog box.

The dialog object is the special window object created by the IHTMLWindow2::showModalDialog method. From within the dialog window, scripts reference the dialog object as the top-level window property. There is no such dialog property in the dialog.

IHTMLDialog Methods
put_dialogTop get_dialogTop put_dialogLeft
get_dialogLeft put_dialogWidth get_dialogWidth
put_dialogHeight get_dialogHeight get_dialogArguments
put_returnValue get_returnValue close
toString


DialogHeight Property

*
  * Previous Topic: IHTMLDialog::put_dialogHeight
  * Next Topic: IHTMLDialog::get_dialogArguments

IHTMLDialog::get_dialogHeight

HRESULT get_dialogHeight(
    VARIANT *p
);

Retrieves the height of the dialog box.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the height.

This property applies only to windows created using the showModalDialog method.

See also put_dialogHeight

Up Top of Page

IHTMLDialog::put_dialogHeight

HRESULT put_dialogHeight(
    VARIANT v
);

Sets the height of the dialog box.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains a string or value specifying the height.

This property applies only to windows created using the showModalDialog method.

See also get_dialogHeight


DialogLeft Property

*
  * Previous Topic: IHTMLDialog::put_dialogLeft
  * Next Topic: IHTMLDialog::put_dialogWidth

IHTMLDialog::get_dialogLeft

HRESULT get_dialogLeft(
    VARIANT *p
);

Retrieves the left coordinate of the dialog box.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the left coordinate.

This property applies only to windows created using the showModalDialog method.

See also put_dialogLeft

Up Top of Page

IHTMLDialog::put_dialogLeft

HRESULT put_dialogLeft(
    VARIANT v
);

Sets the left coordinate of the dialog box.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure containing a string or value specifying the left coordinate.

This property applies only to windows created using the showModalDialog method.

See also get_dialogLeft


DialogTop Property

*
  * Previous Topic: IHTMLDialog::put_dialogTop
  * Next Topic: IHTMLDialog::put_dialogLeft

IHTMLDialog::get_dialogTop

HRESULT get_dialogTop(
    VARIANT *p
);

Retrieves the top coordinate of the dialog box.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the top coordinate.

This property applies only to windows created using the showModalDialog method.

See also put_dialogTop

Up Top of Page

IHTMLDialog::put_dialogTop

HRESULT put_dialogTop(
    VARIANT v
);

Sets the top coordinate of the dialog box.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure containing either a string or value specifying the top coordinate.

This property applies only to windows created using the showModalDialog method.

See also get_dialogTop


DialogWidth Property

*
  * Previous Topic: IHTMLDialog::put_dialogWidth
  * Next Topic: IHTMLDialog::put_dialogHeight

IHTMLDialog::get_dialogWidth

HRESULT get_dialogWidth(
    VARIANT *p
);

Retrieves the width of the dialog box.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the width.

This property applies only to windows created using the showModalDialog method.

See also put_dialogWidth

Up Top of Page

IHTMLDialog::put_dialogWidth

HRESULT put_dialogWidth(
    VARIANT v
);

Sets the width of the dialog box.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains a string or value specifying the width.

This property applies only to windows created using the showModalDialog method.

See also get_dialogWidth


IHTMLDialog::get_dialogArguments

HRESULT get_dialogArguments(
    VARIANT *p
);

Retrieves the variable or array of variables passed into the modal dialog window.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the variables.

This property applies only to windows created using the showModalDialog method.


ReturnValue Property

*
  * Previous Topic: IHTMLDialog::put_returnValue
  * Next Topic: IHTMLDialog::close

IHTMLDialog::get_returnValue

HRESULT get_returnValue(
    VARIANT *p
);

Retrieves the return value of the dialog box.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the return value, which can be either TRUE or FALSE.

For event handler functions, the value of this property takes precedence over values returned by the function, such as through a return statement.

See also put_returnValue

Up Top of Page

IHTMLDialog::put_returnValue

HRESULT put_returnValue(
    VARIANT v
);

Sets the return value of the dialog box.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains a string or value specifying the return value, which can be either TRUE or FALSE.

For event handler functions, the value of this property takes precedence over values returned by the function, such as through a return statement.

See also get_returnValue


IHTMLDialog::toString

HRESULT toString(
    BSTR *String
);

Retrieves a string representation of the dialog object.

  • Returns S_OK if successful, or an error value otherwise.
String
Address of a string variable that receives the string representation.


Align Property

*
  * Previous Topic: IHTMLDivElement::put_align
  * Next Topic: IHTMLDivElement::put_noWrap

IHTMLDivElement::get_align

HRESULT get_align(
    BSTR *p
);

Retrieves the alignment of the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives one of these values:
center | Align to the center.
left | Align to the left edge.
right | Align to the right edge.

See also put_align

Up Top of Page

IHTMLDivElement::put_align

HRESULT put_align(
    BSTR v
);

Sets the alignment of the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the alignment. Can be one of these values:
center | Align to the center.
left | Align to the left edge.
right | Align to the right edge.

See also get_align


IHTMLDivElement

The DIV element is used with the className property to represent different kinds of containers.

This element is a block element.

IHTMLDivElement Methods


NoWrap Property

*
  * Previous Topic: IHTMLDivElement::put_noWrap
  * Next Topic: IHTMLDivPosition

IHTMLDivElement::get_noWrap

HRESULT get_noWrap(
    VARIANT_BOOL *p
);

Determines whether automatic word wrapping is enabled or disabled for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a Boolean variable that receives TRUE if automatic word wrapping is enabled for the element, or FALSE otherwise. The default value for this property is FALSE.

See also put_noWrap

Up Top of Page

IHTMLDivElement::put_noWrap

HRESULT put_noWrap(
    VARIANT_BOOL v
);

Enables or disables automatic word wrapping for the text in the division.

  • Returns S_OK if successful, or an error value otherwise.
v
Boolean value that contains the word-wrap flag. If TRUE, the browser performs automatic word wrapping on the division contents. If FALSE, it doesn't. The default value for this property is FALSE.

See also get_noWrap


Align Property

*
  * Previous Topic: IHTMLDivPosition::put_align
  * Next Topic: IHTMLDListElement

IHTMLDivPosition::get_align

HRESULT get_align(
    BSTR *p
);

Retrieves how the element is aligned with adjacent text.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the alignment. Can be one of these values:
absbottom | Aligns the bottom of the element with the absolute bottom of the surrounding text. The absolute bottom is equal to the baseline of the text minus the height of the largest descender in the text.
absmiddle | Aligns the middle of the element with the middle of the surrounding text. The absolute middle is the midpoint between the absolute bottom and texttop of the surrounding text.
baseline | Aligns the bottom of the element with the baseline of the surrounding text.
bottom | Aligns the bottom of the element with the bottom of the surrounding text. The bottom is equal to the baseline minus the standard height of a descender in the text.
left | Aligns the element to the left of the surrounding text. All preceding and subsequent text flows to the right of the element. This is the default value.
middle | Aligns the middle of the element with the surrounding text.
right | Aligns the element to the right of the surrounding text. All subsequent text flows to the left of the element.
texttop | Aligns the top of the element with the absolute top of the surrounding text. The absolute top is the baseline plus the height of the largest ascender in the text.
top | Aligns the top of the element with the top of the text. The top of the text is the baseline plus the standard height of an ascender in the text.

For the INPUT element, this attribute applies only to the image input type. It is undefined for all other types.

See also put_align

Up Top of Page

IHTMLDivPosition::put_align

HRESULT put_align(
    BSTR v
);

Sets how the element is aligned with adjacent text.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the alignment. Can be one of these values:
absbottom | Aligns the bottom of the element with the absolute bottom of the surrounding text. The absolute bottom is equal to the baseline of the text minus the height of the largest descender in the text.
absmiddle | Aligns the middle of the element with the middle of the surrounding text. The absolute middle is the midpoint between the absolute bottom and texttop of the surrounding text.
baseline | Aligns the bottom of the element with the baseline of the surrounding text.
bottom | Aligns the bottom of the element with the bottom of the surrounding text. The bottom is equal to the baseline minus the standard height of a descender in the text.
left | Aligns the element to the left of the surrounding text. All preceding and subsequent text flows to the right of the element. This is the default value.
middle | Aligns the middle of the element with the surrounding text.
right | Aligns the element to the right of the surrounding text. All subsequent text flows to the left of the element.
texttop | Aligns the top of the element with the absolute top of the surrounding text. The absolute top is the baseline plus the height of the largest ascender in the text.
top | Aligns the top of the element with the top of the text. The top of the text is the baseline plus the standard height of an ascender in the text.

For the INPUT element, this attribute applies only to the image input type. It is undefined for all other types.

See also get_align


IHTMLDivPosition

This interface enables you to specify how adjacent text is aligned with respect to a DIV object.

IHTMLDivPosition Methods


Compact Property

*
  * Previous Topic: IHTMLDListElement::put_compact
  * Next Topic: IHTMLDocument

IHTMLDListElement::get_compact

HRESULT get_compact(
    VARIANT_BOOL *p
);

Determines whether the list is being compacted to remove extra space between list elements.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a Boolean variable that receives TRUE if the list is being compacted, or FALSE otherwise.

The default value for this property is FALSE.

See also put_compact

Up Top of Page

IHTMLDListElement::put_compact

HRESULT put_compact(
    VARIANT_BOOL v
);

Specifies that the list should be compacted to remove extra space between list elements.

  • Returns S_OK if successful, or an error value otherwise.
v
Boolean value that contains the compact flag. If TRUE, the list is compacted; if FALSE, it is not.

The default value for this property is FALSE.

See also get_compact


IHTMLDListElement IHTMLDListElement *
  * Previous Topic: IHTMLDivPosition::get_align
  * Next Topic: IHTMLDListElement::put_compact

IHTMLDListElement

This interface denotes a definition list.

This element is a block element.

IHTMLDListElement Methods


IHTMLDocument

A document object represents the HTML document in a given browser window. You use the document object to retrieve information about the document, to examine and modify the HTML elements and text within the document, and to process events.

Typically, every window object has a corresponding document object that you can retrieve by calling the QueryInterface function with the IID_IHTMLDocument or IID_IHTMLDocument2 interface identifier. Windows that contain HTML documents always have valid document objects, but windows that contain documents in other formats may not. In general, before attempting to retrieve the document object for a window that is not the current window, make sure that the source file associated with that window is an HTML document file or a file that can be represented as an HTML document (for example, a text file).

IHTMLDocument Methods
get_Script


IHTMLDocument::get_Script

HRESULT get_Script(
    IDispatch **p
);

Retrieves an interface pointer that provides access to the scripting object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a pointer to an IDispatch interface to the scripting object.


AlinkColor Property

*
  * Previous Topic: IHTMLDocument2::put_alinkColor
  * Next Topic: IHTMLDocument2::put_bgColor

IHTMLDocument2::get_alinkColor

HRESULT get_alinkColor(
    VARIANT *p
);

Retrieves the color that the browser uses to indicate the active link.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the color. It can be one of the color names or values given in the Color Table reference documentation.

See also put_alinkColor

Up Top of Page

IHTMLDocument2::put_alinkColor

HRESULT put_alinkColor(
    VARIANT v
);

Sets the color that the browser uses to indicate the active link.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure containing a string or value specifying the color. It can be one of the color names or values given in the Color Table reference documentation.

See also get_alinkColor


BgColor Property

*
  * Previous Topic: IHTMLDocument2::put_bgColor
  * Next Topic: IHTMLDocument2::put_fgColor

IHTMLDocument2::get_bgColor

HRESULT get_bgColor(
    VARIANT *p
);

Retrieves the background color of the page.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the color. The color can be one of the color names or values given in the Color Table reference documentation.

See also put_bgColor

Up Top of Page

IHTMLDocument2::put_bgColor

HRESULT put_bgColor(
    VARIANT v
);

Sets the background color of the page.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure containing a string or value specifying the color. The color can be one of the color names or values given in the Color Table reference documentation.

See also get_bgColor


Charset Property

*
  * Previous Topic: IHTMLDocument2::put_charset
  * Next Topic: IHTMLDocument2::put_defaultCharset

IHTMLDocument2::get_charset

HRESULT get_charset(
    BSTR *p
);

Retrieves the character set used to encode the document.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the current character set.

See also put_charset

Up Top of Page

IHTMLDocument2::put_charset

HRESULT put_charset(
    BSTR v
);

Specifies the character set used to encode the document.

  • Returns S_OK if successful, or an error value otherwise.
v
String value specifying the character set.

See also get_charset


IHTMLDocument2::clear IHTMLDocument2::clear *
  * Previous Topic: IHTMLDocument2::close
  * Next Topic: IHTMLDocument2::queryCommandSupported

IHTMLDocument2::clear

HRESULT clear(void);

This is a no-op.

  • Returns S_OK.


IHTMLDocument2::close

HRESULT close(void);

Closes an output stream and forces data sent to layout to display.

  • Returns S_OK if successful, or an error value otherwise.

See also open


Cookie Property

*
  * Previous Topic: IHTMLDocument2::put_cookie
  * Next Topic: IHTMLDocument2::put_expando

IHTMLDocument2::get_cookie

HRESULT get_cookie(
    BSTR *p
);

Retrieves the string value of a cookie, which is a small piece of information stored by the browser.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the cookie.

See also put_cookie

Up Top of Page

IHTMLDocument2::put_cookie

HRESULT put_cookie(
    BSTR v
);

Sets the string value of a cookie, which is a small piece of information stored by the browser.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the cookie.

See also get_cookie


IHTMLDocument2::createElement

HRESULT createElement(
    BSTR eTag,
    IHTMLElement **newElem
);

Creates an instance of the element object for the specified tag. Only new IMG and OPTION objects can be created. Before they can be used, new objects must be explicitly added to their respective collections.

  • Returns S_OK if successful, or an error value otherwise.
eTag
String value specifiying the type of element to create.
newElem
Address of a pointer to the IHTMLElement interface of the new element.


DefaultCharset Property

*
  * Previous Topic: IHTMLDocument2::put_defaultCharset
  * Next Topic: IHTMLDocument2::get_mimeType

IHTMLDocument2::get_defaultCharset

HRESULT get_defaultCharset(
    BSTR *p
);

Retrieves the default character set of the document.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the name of the default character set.

See also put_defaultCharset

Up Top of Page

IHTMLDocument2::put_defaultCharset

HRESULT put_defaultCharset(
    BSTR v
);

Specifies the default character set of the document.

  • Returns S_OK if successful, or an error value otherwise.
v
String value specifying the default character set.

See also get_defaultCharset


IHTMLDocument2

A document object represents the HTML document in a given browser window. You use the document object to retrieve information about the document, to examine and modify the HTML elements and text within the document, and to process events.

Typically, every window object has a corresponding document object that you can retrieve by calling the IUnknown::QueryInterface method with the IID_IHTMLDocument or IID_IHTMLDocument2 interface identifier. Windows that contain HTML documents always have valid document objects, but windows that contain documents in other formats might not. In general, before attempting to retrieve the document object for a window that is not the current window, make sure that the source file associated with that window is an HTML document file or a file that can be represented as an HTML document (for example, a text file).

IHTMLDocument2 Methods
get_all get_body get_activeElement
get_images get_applets get_links
get_forms get_anchors put_title
get_title get_scripts get_selection
get_readyState get_frames get_embeds
get_plugins put_alinkColor get_alinkColor
put_bgColor get_bgColor put_fgColor
get_fgColor put_linkColor get_linkColor
put_vlinkColor get_vlinkColor get_referrer
get_location get_lastModified put_URL
get_URL put_domain get_domain
put_cookie get_cookie put_expando
get_expando put_charset get_charset
put_defaultCharset get_defaultCharset get_mimeType
get_fileSize get_fileCreatedDate get_fileModifiedDate
get_fileUpdatedDate get_security get_protocol
get_nameProp write writeln
open close clear
queryCommandSupported queryCommandEnabled queryCommandState
queryCommandIndeterm queryCommandText queryCommandValue
execCommand execCommandShowHelp createElement
put_onhelp get_onhelp put_onclick
get_onclick put_ondblclick get_ondblclick
put_onkeyup get_onkeyup put_onkeydown
get_onkeydown put_onkeypress get_onkeypress
put_onmouseup get_onmouseup put_onmousedown
get_onmousedown put_onmousemove get_onmousemove
put_onmouseout get_onmouseout put_onmouseover
get_onmouseover put_onreadystatechange get_onreadystatechange
put_onafterupdate get_onafterupdate put_onrowexit
get_onrowexit put_onrowenter get_onrowenter
put_ondragstart get_ondragstart put_onselectstart
get_onselectstart elementFromPoint get_parentWindow
get_styleSheets put_onbeforeupdate get_onbeforeupdate
put_onerrorupdate get_onerrorupdate toString

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


Domain Property

*
  * Previous Topic: IHTMLDocument2::put_domain
  * Next Topic: IHTMLDocument2::put_cookie

IHTMLDocument2::get_domain

HRESULT get_domain(
    BSTR *p
);

Retrieves or the security domain of the document.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the security domain.

The domain property initially returns the hostname of the server that the page is from. This property can be assigned the domain suffix to allow sharing of pages across frames. For example, a page in one frame from home.microsoft.com and a page from www.microsoft.com would initially not be able to communicate with each other. However, by setting the domain property of both pages to the suffix, microsoft.com, both pages would be considered secure and now code can access between the pages.

See also put_domain

Up Top of Page

IHTMLDocument2::put_domain

HRESULT put_domain(
    BSTR v
);

Sets or returns the security domain of the document.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the security domain.

The domain property initially returns the host name of the server the page is from. This property can be assigned the domain suffix to allow sharing of pages across frames. For example, a page in one frame from home.microsoft.com and a page from www.microsoft.com would initially not be able to communicate with each other. However, by setting the domain property of both pages to the suffix, microsoft.com, both pages would be considered secure and now code can be shared between the pages.

See also get_domain


IHTMLDocument2::elementFromPoint

HRESULT elementFromPoint(
    long x,
    long y,
    IHTMLElement **elementHit
);

Retrieves the element at the specified x and y coordinates.

  • Returns S_OK if successful, or an error value otherwise.
x
Long integer value specifying the horizontal coordinate, in window coordinates.
y
Long integer value specifying the vertical coordinate, in window coordinates.
elementHit
Address of a pointer to the IHTMLElement interface for the element at the given coordinates.

Window coordinates are relative to the top-left corner of the window, which is at coordinates 0,0.


IHTMLDocument2::execCommand

HRESULT execCommand(
    BSTR cmdID,
    VARIANT_BOOL showUI,
    VARIANT value,
    VARIANT_BOOL *pfRet
);

Executes the given command over the current selection or text range.

  • Returns S_OK if successful, or an error value otherwise.
cmdID
String value containing the identifier of a command. Can be any command identifier given in the list of Command Identifiers.
showUI
Boolean value specifying whether to display a user interface if the command supports one. If TRUE, the command displays a user interface, if applicable; otherwise, it doesn't.
value
VARIANT structure to pass to the command. Possible values depend on the value of cmdID.
pfRet
Address of a Boolean variable that receives TRUE if the function is successful, or FALSE otherwise.


IHTMLDocument2::execCommandShowHelp

HRESULT execCommandShowHelp(
    BSTR cmdID,
    VARIANT_BOOL *pfRet
);

Displays help information for the given command identifier.

  • Returns S_OK if successful, or an error value otherwise.
cmdID
String value that contains the identifier of a command. Can be any command identifier given in the list of Command Identifiers.
pfRet
Address of a Boolean variable that receives TRUE if successful, or FALSE otherwise.


Expando Property

*
  * Previous Topic: IHTMLDocument2::put_expando
  * Next Topic: IHTMLDocument2::put_charset

IHTMLDocument2::get_expando

HRESULT get_expando(
    VARIANT_BOOL *p
);

Determines whether the document supports the use of expando properties.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a Boolean variable that receives TRUE if the document supports expando properties, or FALSE otherwise.

See also put_expando

Up Top of Page

IHTMLDocument2::put_expando

HRESULT put_expando(
    VARIANT_BOOL v
);

Specifies whether the document supports the use of expando properties.

  • Returns S_OK if successful, or an error value otherwise.
v
Boolean value. If TRUE, the document supports expando properties; if FALSE, it does not.

See also get_expando


FgColor Property

*
  * Previous Topic: IHTMLDocument2::put_fgColor
  * Next Topic: IHTMLDocument2::put_linkColor

IHTMLDocument2::get_fgColor

HRESULT get_fgColor(
    VARIANT *p
);

Retrieves the color of the document foreground text.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the color. The color can be one of the color names or values given in the Color Table reference documentation.

Changing this property after the document is rendered does not change the displayed color.

JScript supports the entire set of valid property colors both as strings and their numerical equivalents as a string. JScript always returns the property as the numeric equivalent as a string regardless of the format to which the value was set.

The default foreground color is UA-specific.

See also put_fgColor

Up Top of Page

IHTMLDocument2::put_fgColor

HRESULT put_fgColor(
    VARIANT v
);

Sets the color of the document foreground text.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure containing a string or value specifying the color. The color can be one of the color names or values given in the Color Table reference documentation.

Changing this property after the document is rendered does not change the displayed color.

The default foreground color is browser specific.

See also get_fgColor


IHTMLDocument2::get_activeElement

HRESULT get_activeElement(
    IHTMLElement **p
);

Retrieves a pointer to the interface of the element that has the focus, which is determined by the activeElement property.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a pointer to the IHTMLElement interface of the element that currently has the focus.


IHTMLDocument2::get_all

HRESULT get_all(
    IHTMLElementCollection **p
);

Retrieves an interface pointer to a zero-based collection of all the elements in an HTML document.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a pointer to the IHTMLElementCollection interface of the collection of elements.

The collection includes one element object for each valid HTML tag. If a valid tag has a matching end tag, both tags are represented by the same element object. The collection always includes one element object for each of the HTML, HEAD, and BODY tags regardless of whether the tags are present in the document. If the document contains invalid or unknown tags, the collection includes one element object for each. Unlike valid end tags, unknown end tags are represented by their own element objects. The order of the element objects in the collection is the same as the order of corresponding tags in the document. Although the collection indicates the order of tags, it does not indicate which tags contain others.

You can use the length property to determine the number of element objects in the collection, and the item or tags function to retrieve individual objects or collections of objects from the collection. You can retrieve individual objects by specifying the object's index or by using its name property. Index values can be either numbers or names. Number values are zero-based, that is, 0 for the first element object, 1 for the next, and so on. A name is valid only if it is defined by a name or ID property for at least one of the elements in the collection. If the name is defined by more than one element, you can use it to retrieve a collection of all element objects that define that name.

See also get_body


IHTMLDocument2::get_anchors

HRESULT get_anchors(
    IHTMLElementCollection **p
);

Retrieves an interface pointer to a zero-based collection of all the A objects in an HTML document. The elements are in the same order as they appear in the document.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a pointer to the IHTMLElementCollection interface of the collection containing all the A objects in the HTML document.

The collection is indexed first by name, then by ID. If duplicate names are found, a collection of those named items is returned. The resulting collection can be only referenced by ordinal position.


IHTMLDocument2::get_applets

HRESULT get_applets(
    IHTMLElementCollection **p
);

Retrieves an interface pointer to a zero-based collection of all the APPLET objects in an HTML document. The objects are in the same order as they appear in the document.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a pointer to the IHTMLElementCollection interface of the applet collection.

The collection is indexed first by name, then by ID. If duplicate names are found, a collection of those named items is returned. The resulting collection can be referenced only by ordinal position.


IHTMLDocument2::get_body

HRESULT get_body(
    IHTMLElement **p
);

Retrieves an interface pointer to the document's BODY object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a pointer to the IHTMLElement interface of the BODY object.

See also get_all


IHTMLDocument2::get_embeds

HRESULT get_embeds(
    IHTMLElementCollection **p
);

Retrieves an interface pointer to a zero-based collection of all the EMBED objects in an HTML document. The objects are in the same order as they appear in the document.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a pointer to the IHTMLElementCollection interface of the collection.

The collection is indexed first by name, then by ID. If duplicate names are found, a collection of those named items is returned. The resulting collection can only be referenced by ordinal position.


IHTMLDocument2::get_fileCreatedDate

HRESULT get_fileCreatedDate(
    BSTR *p
);

Retrieves the date when the document file was created.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the creation date. The date consists of the weekday, month, date, and year.


IHTMLDocument2::get_fileModifiedDate

HRESULT get_fileModifiedDate(
    BSTR *p
);

Retrieves the date when the document file was most recently modified.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the modification date. The date consists of the weekday, month, date, and year.

See also get_fileUpdatedDate


IHTMLDocument2::get_fileSize

HRESULT get_fileSize(
    BSTR *p
);

Retrieves the size, in bytes, of the document file.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the size of the document file.


IHTMLDocument2::get_fileUpdatedDate

HRESULT get_fileUpdatedDate(
    BSTR *p
);

Retrieves the date when the document file was last updated.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the date. The date consists of the weekday, month, date, and year.

See also get_fileModifiedDate


IHTMLDocument2::get_forms

HRESULT get_forms(
    IHTMLElementCollection **p
);

Retrieves an interface pointer to a zero-based collection of all the FORM objects in an HTML document. The objects are in the same order as they appear in the document.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a pointer to the IHTMLElementCollection of the collection containing all the FORM objects in an HTML document.

The collection is indexed first by name, then by ID. If duplicate names are found, a collection of those named items is returned. The resulting collection can be only referenced by ordinal position.


IHTMLDocument2::get_frames

HRESULT get_frames(
    IHTMLFramesCollection2 **p
);

Retrieves an interface pointer to a zero-based collection of all the FRAME objects in an HTML document, if the document contains the FRAMESET object. If the document contains the BODY object, this is a collection of all IFRAME objects in the document. In either case, the objects are in the same order as they appear in the document.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a pointer to the IHTMLFramesCollection2 interface of the collection.

The collection is indexed first by name, then by ID. If duplicate names are found, a collection of those named items is returned. The resulting collection can only be referenced by ordinal position.


IHTMLDocument2::get_images

HRESULT get_images(
    IHTMLElementCollection **p
);

Retrieves a pointer to the IHTMLElementCollection interface of the zero-based collection of all the images in an HTML document. The images are in the same order as they appear in the document.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a pointer to the IHTMLElementCollection interface of the images collection.


IHTMLDocument2::get_lastModified

HRESULT get_lastModified(
    BSTR *p
);

Retrieves a string containing the last-modified date of the page (if the page provides one).

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the last-modified date.


IHTMLDocument2::get_links

HRESULT get_links(
    IHTMLElementCollection **p
);

Retrieves an interface pointer to a zero-based collection of all the LINK and AREA objects in an HTML document. The objects are in the same order as they appear in the document.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a pointer to the IHTMLElementCollection interface of the collection containing all the LINK and AREA elements.

The collection is indexed first by name, then by ID. If duplicate names are found, a collection of those named items is returned. The resulting collection can be only referenced by ordinal position.


IHTMLDocument2::get_location

HRESULT get_location(
    IHTMLLocation **p
);

Retrieves an interface pointer to a location object. The object contains information about the current location (full URL) of the document.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a pointer to the IHTMLLocation interface of the location object.


IHTMLDocument2::get_mimeType

HRESULT get_mimeType(
    BSTR *p
);

Retrieves the MIME type for the document file.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the MIME type.


IHTMLDocument2::get_nameProp

HRESULT get_nameProp(
    BSTR *p
);

Retrieves the file name from the URL that the browser uses to locate the document file.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the file name.


IHTMLDocument2::get_parentWindow

HRESULT get_parentWindow(
    IHTMLWindow2 **p
);

Retrieves an interface pointer to the window object for the document.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a pointer to the IHTMLWindow2 interface associated with the parent window.


IHTMLDocument2::get_plugins

HRESULT get_plugins(
    IHTMLElementCollection **p
);

Retrieves an interface pointer to a zero-based collection of all the EMBED objects in an HTML document. The objects are in the same order as they appear in the document.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a pointer to the IHTMLElementCollection interface of the collection.

The collection is indexed first by name, then by ID. If duplicate names are found, a collection of those named items is returned. The resulting collection can only be referenced by ordinal position.


IHTMLDocument2::get_protocol

HRESULT get_protocol(
    BSTR *p
);

Retrieves the protocol portion of the URL that the browser uses to locate the document file. The protocol portion, which indicates the access method, includes the initial substring of the URL up to and including the first colon.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the protocol.


IHTMLDocument2::get_readyState

HRESULT get_readyState(
    BSTR *p
);

Retrieves the current status of an object being downloaded.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the download status of the object. Can be one of these strings:
complete | The object is completely loaded.
interactive | The object can be interacted with even though it is not fully loaded.
loading | The object is currently being loaded.
unitialized | The object is not created. Usually when the object is being downloaded.

Each object can independently determine which of the three states they expose.


IHTMLDocument2::get_referrer

HRESULT get_referrer(
    BSTR *p
);

Retrieves the URL of the previous location.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the URL.


IHTMLDocument2::get_scripts

HRESULT get_scripts(
    IHTMLElementCollection **p
);

Retrieves an interface pointer to a zero-based collection of all the SCRIPT objects in an HTML document. The objects are in the same order as they appear in the document.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a pointer to the IHTMLElementCollection interface of the collection that contains all the SCRIPT objects.

The collection is indexed first by name, then by ID. If duplicate names are found, a collection of those named items is returned. The resulting collection can only be referenced by ordinal position.


IHTMLDocument2::get_security

HRESULT get_security(
    BSTR *p
);

Retrieves security information for the document.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the security information.


IHTMLDocument2::get_selection

HRESULT get_selection(
    IHTMLSelectionObject **p
);

Retrieves an interface pointer to an object representing the active selection. The active selection can be an insertion point, or a highlighted block of text or other elements in the document upon which the user or a script can carry out an action.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a pointer to an IHTMLSelectionObject interface of the object representing the active selection.

You typically use the selection object as input from the user identifying the portion of the document to act on, or as output to the user showing the results of an action.

The user, a script, or an object can create a selection. The user creates a selection by dragging the mouse over a portion of the document. A script or object creates a selection by calling the select method on a text range or similar object.

To carry out work on a selection, you can create a text range object from the selection by using the createRange method.

A document can have only one selection at a time. The selection has a type that determines whether it is empty or contains a contiguous block of consecutive text and/or elements. Although an empty selection contains nothing, it is useful for marking a position in the document.


IHTMLDocument2::get_styleSheets

HRESULT get_styleSheets(
    IHTMLStyleSheetsCollection **p
);

Retrieves an interface pointer to a zero-based collection of the style sheet objects exposed from the document object. Each style sheet object represents an individual style sheet that is defined for the document.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a pointer to the IHTMLStyleSheetsCollection interface of the collection.


LinkColor Property

*
  * Previous Topic: IHTMLDocument2::put_linkColor
  * Next Topic: IHTMLDocument2::put_vlinkColor

IHTMLDocument2::get_linkColor

HRESULT get_linkColor(
    VARIANT *p
);

Retrieves the color of the document links.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the color. The color can be one of the color names or values given in the Color Table reference documentation.

See also put_linkColor

Up Top of Page

IHTMLDocument2::put_linkColor

HRESULT put_linkColor(
    VARIANT v
);

Sets the color of the document links.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains a string or value specifying the color. The color can be one of the color names or values given in the Color Table reference documentation.

See also get_linkColor


Onafterupdate Property

*
  * Previous Topic: IHTMLDocument2::put_onafterupdate
  * Next Topic: IHTMLDocument2::put_onrowexit

IHTMLDocument2::get_onafterupdate

HRESULT get_onafterupdate(
    VARIANT *p
);

Retrieves the inline script associated with the onafterupdate event on the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script.

See also put_onafterupdate

Up Top of Page

IHTMLDocument2::put_onafterupdate

HRESULT put_onafterupdate(
    VARIANT v
);

Sets the inline script associated with the onafterupdate event on the object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure containing the script to set.

See also get_onafterupdate


Onbeforeupdate Property

*
  * Previous Topic: IHTMLDocument2::put_onbeforeupdate
  * Next Topic: IHTMLDocument2::put_onerrorupdate

IHTMLDocument2::get_onbeforeupdate

HRESULT get_onbeforeupdate(
    VARIANT *p
);

Retrieves the inline script associated with the onbeforeupdate event on the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script.

See also put_onbeforeupdate

Up Top of Page

IHTMLDocument2::put_onbeforeupdate

HRESULT put_onbeforeupdate(
    VARIANT v
);

Sets the inline script associated with the onbeforeupdate event on the object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to set.

See also get_onbeforeupdate


Onclick Property

*
  * Previous Topic: IHTMLDocument2::put_onclick
  * Next Topic: IHTMLDocument2::put_ondblclick

IHTMLDocument2::get_onclick

HRESULT get_onclick(
    VARIANT *p
);

Retrieves the inline script associated with the onclick event on the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script.

See also put_onclick

Up Top of Page

IHTMLDocument2::put_onclick

HRESULT put_onclick(
    VARIANT v
);

Sets the inline script associated with the onclick event on the object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the inline script.

See also get_onclick


Ondblclick Property

*
  * Previous Topic: IHTMLDocument2::put_ondblclick
  * Next Topic: IHTMLDocument2::put_onkeyup

IHTMLDocument2::get_ondblclick

HRESULT get_ondblclick(
    VARIANT *p
);

Retrieves the inline script associated with the ondblclick event on the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script.

See also put_ondblclick

Up Top of Page

IHTMLDocument2::put_ondblclick

HRESULT put_ondblclick(
    VARIANT v
);

Sets the inline script associated with the ondblclick event on the object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script.

See also get_ondblclick


Ondragstart Property

*
  * Previous Topic: IHTMLDocument2::put_ondragstart
  * Next Topic: IHTMLDocument2::put_onselectstart

IHTMLDocument2::get_ondragstart

HRESULT get_ondragstart(
    VARIANT *p
);

Retrieves the inline script associated with the ondragstart event on the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script.

See also put_ondragstart

Up Top of Page

IHTMLDocument2::put_ondragstart

HRESULT put_ondragstart(
    VARIANT v
);

Sets the inline script associated with the ondragstart event on the object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure containing the script to set.

See also get_ondragstart


Onerrorupdate Property

*
  * Previous Topic: IHTMLDocument2::put_onerrorupdate
  * Next Topic: IHTMLDocument2::toString

IHTMLDocument2::get_onerrorupdate

HRESULT get_onerrorupdate(
    VARIANT *p
);

Retrieves the inline script associated with the onerrorupdate event on the object.

p
Address of a VARIANT structure to store the script.

See also put_onerrorupdate

Up Top of Page

IHTMLDocument2::put_onerrorupdate

HRESULT put_onerrorupdate(
    VARIANT v
);

Sets the inline script associated with the onerrorupdate event on the object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure containing the script to set.

See also get_onerrorupdate


Onhelp Property

*
  * Previous Topic: IHTMLDocument2::put_onhelp
  * Next Topic: IHTMLDocument2::put_onclick

IHTMLDocument2::get_onhelp

HRESULT get_onhelp(
    VARIANT *p
);

Retrieves the inline script associated with the onhelp event on the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script.

See also put_onhelp

Up Top of Page

IHTMLDocument2::put_onhelp

HRESULT put_onhelp(
    VARIANT v
);

Sets the inline script associated with the onhelp event on the object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure containing the inline script.

See also get_onhelp


Onkeydown Property

*
  * Previous Topic: IHTMLDocument2::put_onkeydown
  * Next Topic: IHTMLDocument2::put_onkeypress

IHTMLDocument2::get_onkeydown

HRESULT get_onkeydown(
    VARIANT *p
);

Retrieves the inline script associated with the onkeydown event on the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script.

See also put_onkeydown

Up Top of Page

IHTMLDocument2::put_onkeydown

HRESULT put_onkeydown(
    VARIANT v
);

Sets the inline script associated with the onkeydown event on the object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure containing the script to set.

See also get_onkeydown


Onkeypress Property

*
  * Previous Topic: IHTMLDocument2::put_onkeypress
  * Next Topic: IHTMLDocument2::put_onmouseup

IHTMLDocument2::get_onkeypress

HRESULT get_onkeypress(
    VARIANT *p
);

Retrieves the inline script associated with the onkeypress event on the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script.

See also put_onkeypress

Up Top of Page

IHTMLDocument2::put_onkeypress

HRESULT put_onkeypress(
    VARIANT v
);

Sets the inline script associated with the onkeypress event on the object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to set.

See also get_onkeypress


Onkeyup Property

*
  * Previous Topic: IHTMLDocument2::put_onkeyup
  * Next Topic: IHTMLDocument2::put_onkeydown

IHTMLDocument2::get_onkeyup

HRESULT get_onkeyup(
    VARIANT *p
);

Retrieves the inline script associated with the onkeyup event on the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script.

See also put_onkeyup

Up Top of Page

IHTMLDocument2::put_onkeyup

HRESULT put_onkeyup(
    VARIANT v
);

Sets the inline script associated with the onkeyup event on the object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure containing the script to set.

See also get_onkeyup


Onmousedown Property

*
  * Previous Topic: IHTMLDocument2::put_onmousedown
  * Next Topic: IHTMLDocument2::put_onmousemove

IHTMLDocument2::get_onmousedown

HRESULT get_onmousedown(
    VARIANT *p
);

Retrieves the inline script associated with the onmousedown event on the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script.

See also put_onmousedown

Up Top of Page

IHTMLDocument2::put_onmousedown

HRESULT put_onmousedown(
    VARIANT v
);

Sets the inline script associated with the onmousedown event on the object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to be set.

See also get_onmousedown


Onmousemove Property

*
  * Previous Topic: IHTMLDocument2::put_onmousemove
  * Next Topic: IHTMLDocument2::put_onmouseout

IHTMLDocument2::get_onmousemove

HRESULT get_onmousemove(
    VARIANT *p
);

Retrieves the inline script associated with the onmousemove event on the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script.

See also put_onmousemove

Up Top of Page

IHTMLDocument2::put_onmousemove

HRESULT put_onmousemove(
    VARIANT v
);

Sets the inline script associated with the onmousemove event on the object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure containing the script to set.

See also get_onmousemove


Onmouseout Property

*
  * Previous Topic: IHTMLDocument2::put_onmouseout
  * Next Topic: IHTMLDocument2::put_onmouseover

IHTMLDocument2::get_onmouseout

HRESULT get_onmouseout(
    VARIANT *p
);

Retrieves the inline script associated with the onmouseout event on the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script.

See also put_onmouseout

Up Top of Page

IHTMLDocument2::put_onmouseout

HRESULT put_onmouseout(
    VARIANT v
);

Sets the inline script associated with the onmouseout event on the object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to set.

See also get_onmouseout


Onmouseover Property

*
  * Previous Topic: IHTMLDocument2::put_onmouseover
  * Next Topic: IHTMLDocument2::put_onreadystatechange

IHTMLDocument2::get_onmouseover

HRESULT get_onmouseover(
    VARIANT *p
);

Retrieves the inline script associated with the onmouseover event on the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the data.

See also put_onmouseover

Up Top of Page

IHTMLDocument2::put_onmouseover

HRESULT put_onmouseover(
    VARIANT v
);

Sets the inline script associated with the onmouseover event on the object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure containing the script to set.

See also get_onmouseover


Onmouseup Property

*
  * Previous Topic: IHTMLDocument2::put_onmouseup
  * Next Topic: IHTMLDocument2::put_onmousedown

IHTMLDocument2::get_onmouseup

HRESULT get_onmouseup(
    VARIANT *p
);

Retrieves the inline script associated with the onmouseup event on the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script.

See also put_onmouseup

Up Top of Page

IHTMLDocument2::put_onmouseup

HRESULT put_onmouseup(
    VARIANT v
);

Sets the inline script associated with the onmouseup event on the object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure containing the script to set.

See also get_onmouseup


Onreadystatechange Property

*
  * Previous Topic: IHTMLDocument2::put_onreadystatechange
  * Next Topic: IHTMLDocument2::put_onafterupdate

IHTMLDocument2::get_onreadystatechange

HRESULT get_onreadystatechange(
    VARIANT *p
);

Retrieves the inline script associated with the onreadystatechange event on the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script.

See also put_onreadystatechange

Up Top of Page

IHTMLDocument2::put_onreadystatechange

HRESULT put_onreadystatechange(
    VARIANT v
);

Sets the inline script associated with the onreadystatechange event on the object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to set.

See also get_onreadystatechange


Onrowenter Property

*
  * Previous Topic: IHTMLDocument2::put_onrowenter
  * Next Topic: IHTMLDocument2::put_ondragstart

IHTMLDocument2::get_onrowenter

HRESULT get_onrowenter(
    VARIANT *p
);

Retrieves the inline script associated with the onrowenter event on the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script.

See also put_onrowenter

Up Top of Page

IHTMLDocument2::put_onrowenter

HRESULT put_onrowenter(
    VARIANT v
);

Sets the inline script associated with the onrowenter event on the object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to set.

See also get_onrowenter


Onrowexit Property

*
  * Previous Topic: IHTMLDocument2::put_onrowexit
  * Next Topic: IHTMLDocument2::put_onrowenter

IHTMLDocument2::get_onrowexit

HRESULT get_onrowexit(
    VARIANT *p
);

Retrieves the inline script associated with the onrowexit event on the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script.

See also put_onrowexit

Up Top of Page

IHTMLDocument2::put_onrowexit

HRESULT put_onrowexit(
    VARIANT v
);

Sets the inline script associated with the onrowexit event on the object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure containing the script to set.

See also get_onrowexit


Onselectstart Property

*
  * Previous Topic: IHTMLDocument2::put_onselectstart
  * Next Topic: IHTMLDocument2::elementFromPoint

IHTMLDocument2::get_onselectstart

HRESULT get_onselectstart(
    VARIANT *p
);

Retrieves the inline script associated with the onselect event on the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script.

See also put_onselectstart

Up Top of Page

IHTMLDocument2::put_onselectstart

HRESULT put_onselectstart(
    VARIANT v
);

Sets the inline script associated with the onselect event on the object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure containing the script to set.

See also get_onselectstart


IHTMLDocument2::open

HRESULT open(
    BSTR url,
    VARIANT name,
    VARIANT features,
    VARIANT replace ,
    IDispatch **pomWindowResult
);

Opens a stream to collect the output of the write or writeln method.

  • Returns S_OK if successful, or an error value otherwise.
url
String value containing the URL of the resource.
name
VARIANT structure that contains the name.
features
VARIANT structure that contains the features.
replace
VARIANT structure.
pomWindowResult
Address of a pointer to the IDispatch interface.

See also close


IHTMLDocument2::queryCommandEnabled

HRESULT queryCommandEnabled(
    BSTR cmdID,
    VARIANT_BOOL *pfRet
);

Determines whether the given command is currently available.

  • Returns S_OK if successful, or an error value otherwise.
cmdID
String value containing the identifier of a command. Can be any command identifier given in the list of Command Identifiers.
pfRet
Address of a Boolean variable that receives TRUE if the command is available, or FALSE otherwise.


IHTMLDocument2::queryCommandIndeterm

HRESULT queryCommandIndeterm(
    BSTR cmdID,
    VARIANT_BOOL *pfRet
);

Determines whether the given command is in the indeterminate state.

  • Returns S_OK if successful, or an error value otherwise.
cmdID
String value that contains the identifier of a command. Can be any command identifier given in the list of Command Identifiers.
pfRet
Address of a Boolean variable that receives TRUE if the given command is in the indeterminate state, or FALSE otherwise.


IHTMLDocument2::queryCommandState

HRESULT queryCommandState(
    BSTR cmdID,
    VARIANT_BOOL *pfRet
);

Retrieves the current status of the given command. The status indicates whether the command has been carried out on the object.

  • Returns S_OK if successful, or an error value otherwise.
cmdID
String value that contains the identifier of a command. Can be any command identifier given in the list of Command Identifiers.
pfRet
Address of a Boolean variable that receives TRUE if the given command has been carried out, FALSE if it has not, or NULL if the function cannot determine the status of the command.


IHTMLDocument2::queryCommandSupported

HRESULT queryCommandSupported(
    BSTR cmdID,
    VARIANT_BOOL *pfRet
);

Determines whether the given command is supported.

  • Returns S_OK if successful, or an error value otherwise.
cmdID
String value containing the identifier of a command.
pfRet
Address of a Boolean variable that receives TRUE if the command is supported, or FALSE otherwise.


IHTMLDocument2::queryCommandText

HRESULT queryCommandText(
    BSTR cmdID,
    BSTR *pcmdText
);

Returns the string associated with a command.

  • Returns S_OK if successful, or an error value otherwise.
cmdID
String value that contains the identifier of a command. Can be any command identifier given in the list of Command Identifiers.
pcmdText
Address of a string variable where the text associated with the command will be stored.


IHTMLDocument2::queryCommandValue

HRESULT queryCommandValue(
    BSTR cmdID,
    VARIANT *pcmdValue
);

Retrieves the current value of the given command.

  • Returns S_OK if successful, or an error value otherwise.
cmdID
String value that contains the identifier of a command. Can be any command identifier given in the list of Command Identifiers.
pcmdValue
Address of a VARIANT structure that receives a string representing the command value. If the command is not supported, this variable receives NULL.


Title Property

*
  * Previous Topic: IHTMLDocument2::put_title
  * Next Topic: IHTMLDocument2::get_scripts

IHTMLDocument2::get_title

HRESULT get_title(
    BSTR *p
);

Retrieves the title of the document. The title identifies the contents of the document and is displayed in the header bar of the document window.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the title.

This function retrieves the TITLE object in the document header (defined by the HEAD object).

See also put_title

Up Top of Page

IHTMLDocument2::put_title

HRESULT put_title(
    BSTR v
);

Sets the title of the document. The title identifies the contents of the document and is displayed in the header bar of the document window.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the document title.

This function sets the TITLE object in the document header (defined by the HEAD object).

See also get_title


IHTMLDocument2::toString

HRESULT toString(
    BSTR *String
);

Retrieves a string representation of the document object.

  • Returns S_OK if successful, or an error value otherwise.
String
Address of a string variable that receives the string representation.


URL Property

*
  * Previous Topic: IHTMLDocument2::put_URL
  * Next Topic: IHTMLDocument2::put_domain

IHTMLDocument2::get_URL

HRESULT get_URL(
    BSTR *p
);

Retrieves the URL for the current document.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the URL.

This function performs the same action as the IHTMLLocation::get_href function.

See also put_URL

Up Top of Page

IHTMLDocument2::put_URL

HRESULT put_URL(
    BSTR v
);

Sets the URL for the current document. This function causes the browser to browse to the location specified by the URL.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the URL.

This function performs the same action as the IHTMLLocation::put_href function.

See also get_URL


VlinkColor Property

*
  * Previous Topic: IHTMLDocument2::put_vlinkColor
  * Next Topic: IHTMLDocument2::get_referrer

IHTMLDocument2::get_vlinkColor

HRESULT get_vlinkColor(
    VARIANT *p
);

Retrieves the color of links that have already been visited.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the color. The color can be one of the color names or values given in the Color Table reference documentation.

See also put_vlinkColor

Up Top of Page

IHTMLDocument2::put_vlinkColor

HRESULT put_vlinkColor(
    VARIANT v
);

Sets the color of links that have already been visited.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains a string or value specifying the color. The color can be one of the color names or values given in the Color Table reference documentation.

See also get_vlinkColor


IHTMLDocument2::write

HRESULT write(
    SAFEARRAY *psarray
);

Writes one or more HTML expressions to a document in the specified window.

  • Returns S_OK if successful, or an error value otherwise.
psarray
Address of a safe array containing the text and HTML tags to write.

See also writeln


IHTMLDocument2::writeln

HRESULT writeln(
    SAFEARRAY *psarray
);

Writes one or more HTML expressions to a document in the specified window, followed by a carriage return.

  • Returns S_OK if successful, or an error value otherwise.
psarray
Address of a safe array containing the text and HTML tags to write.

In HTML, the carriage return is ignored unless within preformatted text.

See also write


IHTMLDTElement

This interface provides access for controlling the text wrapping characteristics for the IHTMLDTElement object.

IHTMLDTElement Methods


NoWrap Property

*
  * Previous Topic: IHTMLDTElement::put_noWrap
  * Next Topic: IHTMLElement

IHTMLDTElement::get_noWrap

HRESULT get_noWrap(
    VARIANT_BOOL *p
);

Determines whether automatic word wrapping is enabled or disabled for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a Boolean variable that receives TRUE if automatic word-wrapping is enabled for the element, or FALSE otherwise. The default value is FALSE.

See also put_noWrap

Up Top of Page

IHTMLDTElement::put_noWrap

HRESULT put_noWrap(
    VARIANT_BOOL v
);

Enables or disables automatic word wrapping for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
Boolean value that contains the word-wrap setting. If TRUE, the browser performs automatic word wrapping on the element. If FALSE, it doesn't. The default value is FALSE.

See also get_noWrap


IHTMLElementCollection

This interface provides access to a collection of element objects.

This collection is indexed first by name, then by id. If duplicate names are found, a collection of those named items is returned. Collections of duplicate names must subsequently be referenced by ordinal position.

A zero-based collection, in source order, of all elements in a given form. This collection can contain any combination of INPUT, SELECT, and TEXTAREA elements.

IHTMLElementCollection Methods


IHTMLElementCollection::get__newEnum

HRESULT get__newEnum(
    IUnknown **p
);

Retrieves an enumerator for the collection.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a pointer to the IUnknown interface of the enumerator.


IHTMLElementCollection::item

HRESULT item(
    VARIANT name,
    VARIANT index,
    IDispatch **pdisp
);

Retrieves an object or a collection from the given collection. The name determines which action to take.

  • Returns S_OK if successful, or an error value otherwise.
name
VARIANT structure containing a string or value specifying the object or collection to retrieve. If this parameter is a number, the method returns the object in the collection at the given position, where the first object has value 0, the second has 1, and so on. If this parameter contains a string, the method returns a collection of objects, where the value of the name or id property for each object is equal to the string.
index
VARIANT structure containing a value specifying the position of an object to retrieve. This parameter is used when name is a string. The method uses the string to construct a collection of all objects that have a name or id equal to the string, then retrieves from this collection the element at the position specified by index.
pdisp
Address of the IDispatch interface of the collection or object.


Length Property

*
  * Previous Topic: IHTMLElementCollection::put_length
  * Next Topic: IHTMLElementCollection::get__newEnum

IHTMLElementCollection::get_length

HRESULT get_length(
    long *p
);

Retrieves the number of objects in the collection.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a long integer variable that receives the number of elements.

See also put_length

Up Top of Page

IHTMLElementCollection::put_length

HRESULT put_length(
    long v
);

Sets the size, in objects, of the collection.

  • Returns S_OK if successful, or an error value otherwise.
v
Long integer value specifying the number of elements.

See also get_length


IHTMLElementCollection::tags

HRESULT tags(
    VARIANT tagName,
    IDispatch **pdisp
);

Retrieves a collection of all objects in the given collection that have the given HTML tag name.

  • Returns S_OK if successful, or an error value otherwise.
tagName
VARIANT structure containing a string specifying the HTML tag name of the objects to retrieve.
pdisp
Address of the IDispatch interface of the collection.

This method returns an empty collection if no objects having the given name are found. Use the length property on the collection to determine the number of objects it contains.


IHTMLElementCollection::toString

HRESULT toString(
    BSTR *String
);

Retrieves a string representation of the element collection object.

  • Returns S_OK if successful, or an error value otherwise.
String
Address of a string variable that receives the string representation.


IHTMLEmbedElement

This interface provides access to the EMBED object.

IHTMLEmbedElement Methods
put_hidden get_hidden get_palette
get_pluginspage put_src get_src
put_units get_units put_name
get_name put_width get_width
put_height get_height

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


IHTMLEmbedElement::get_palette

HRESULT get_palette(
    BSTR *p
);

Retrieves the palette used for the embedded document.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the palette.


IHTMLEmbedElement::get_pluginspage

HRESULT get_pluginspage(
    BSTR *p
);

Retrieves the plug-ins supporting this embedded document.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the plug-ins.


Height Property

*
  * Previous Topic: IHTMLEmbedElement::put_height
  * Next Topic: IHTMLEventObj

IHTMLEmbedElement::get_height

HRESULT get_height(
    VARIANT *p
);

Retrieves the calculated height of the element, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the height.

If the value of the corresponding HTML attribute was set using a percentage, this property specifies the height in pixels represented by that percentage.

See also put_height

Up Top of Page

IHTMLEmbedElement::put_height

HRESULT put_height(
    VARIANT v
);

Sets the calculated height of the element, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the value specifying the height.

If the value of the corresponding HTML attribute was set using a percentage, this property specifies the height in pixels represented by that percentage.

See also get_height


Hidden Property

*
  * Previous Topic: IHTMLEmbedElement::put_hidden
  * Next Topic: IHTMLEmbedElement::get_palette

IHTMLEmbedElement::get_hidden

HRESULT get_hidden(
    BSTR *p
);

Determines whether the embedded element is currently hidden or shown.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the status.

See also put_hidden

Up Top of Page

IHTMLEmbedElement::put_hidden

HRESULT put_hidden(
    BSTR v
);

Hides or shows the embedded element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying if the embedded element is hidden. TRUE hides the embedded element, and FALSE shows it.

See also get_hidden


Name Property

*
  * Previous Topic: IHTMLEmbedElement::put_name
  * Next Topic: IHTMLEmbedElement::put_width

IHTMLEmbedElement::get_name

HRESULT get_name(
    BSTR *p
);

Retrieves the name of the frame so it can be targeted from links in other documents.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the window or frame name, or one of these values:
window_name | String that specifies a frame.
_blank | Loads the link into a new, unnamed window.
_parent | Loads the link over the parent. If the frame has no parent, this refers to _self.
_self | Replaces the page with the specified link.
_top | Loads the link at the top-most level.

The name property on the window comes from the FRAME definition. There is no other way to persist a window name in HTML.

See also put_name

Up Top of Page

IHTMLEmbedElement::put_name

HRESULT put_name(
    BSTR v
);

Sets the name of the frame so it can be targeted from links in other documents.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the name. It can be the name of a window or frame, or one of the following values:
window_name | String that specifies a frame.
_blank | Loads the link into a new, unnamed window.
_parent | Loads the link over the parent. If the frame has no parent, this refers to _self.
_self | Replaces the page with the specified link.
_top | Loads the link at the top-most level.

The name property on the window comes from the FRAME definition. There is no other way to persist a window name in HTML.

See also get_name


Src Property

*
  * Previous Topic: IHTMLEmbedElement::put_src
  * Next Topic: IHTMLEmbedElement::put_units

IHTMLEmbedElement::get_src

HRESULT get_src(
    BSTR *p
);

Retrieves the URL of the embedded document.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the URL.

See also put_src

Up Top of Page

IHTMLEmbedElement::put_src

HRESULT put_src(
    BSTR v
);

Sets the URL of the embedded document.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the URL.

See also get_src


Units Property

*
  * Previous Topic: IHTMLEmbedElement::put_units
  * Next Topic: IHTMLEmbedElement::put_name

IHTMLEmbedElement::get_units

HRESULT get_units(
    BSTR *p
);

Retrieves the current units used to caculate the height and width.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that contains the unit type. Can be either "pixels" or "ems".

See also put_units

Up Top of Page

IHTMLEmbedElement::put_units

HRESULT put_units(
    BSTR v
);

Sets the units that the height and width are calculated in.

  • Returns S_OK if successful, or an error value otherwise.
v
String value that contains the units. Can be either "pixels" or "ems".

See also get_units


Width Property

*
  * Previous Topic: IHTMLEmbedElement::put_width
  * Next Topic: IHTMLEmbedElement::put_height

IHTMLEmbedElement::get_width

HRESULT get_width(
    VARIANT *p
);

Retrieves the calculated width of the element, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the width.

This property is an integer value. Although an HTML author can specify the width as a percentage, this property always specifies the width in pixels.

See also put_width

Up Top of Page

IHTMLEmbedElement::put_width

HRESULT put_width(
    VARIANT v
);

Sets the calculated width of the element, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains a value specifying the width.

This property is an integer value. Although an HTML author can specify the width as a percentage, this property always specifies the width in pixels.

See also get_width


CancelBubble Property

*
  * Previous Topic: IHTMLEventObj::put_cancelBubble
  * Next Topic: IHTMLEventObj::get_fromElement

IHTMLEventObj::get_cancelBubble

HRESULT get_cancelBubble(
    VARIANT_BOOL *p
);

Retrieves whether the current event should bubble up the hierarchy of event handlers.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a Boolean variable that receives TRUE if bubbling has been canceled, or FALSE otherwise.

Using this property to cancel bubbling for an event does not affect subsequent events.

See also put_cancelBubble

Up Top of Page

IHTMLEventObj::put_cancelBubble

HRESULT put_cancelBubble(
    VARIANT_BOOL v
);

Sets whether the current event should bubble up the hierarchy of event handlers.

  • Returns S_OK if successful, or an error value otherwise.
v
Boolean value that contains the cancel-bubble flag. TRUE cancels bubbling for this event, preventing the next event handler in the hierarchy from receiving the event. FALSE enables bubbling; this is the default value.

Using this property to cancel bubbling for an event does not affect subsequent events.

See also get_cancelBubble


IHTMLEventObj

This interface provides access to the event processes, such as the element in which the event occurred, the state of the keyboard keys, the location of the mouse, and the state of the mouse buttons.

The event object is only available during an event, that is, you can use it in event handlers but not in other code. You retrieve the event object by calling the IHTMLWindow2::get_event method.

Although all event properties are available to all event objects, some properties might not have meaningful values during some events. For example, the values retrieved by the get_fromElement and the get_toElement methods are meaningful only when processing the onmouseover and onmouseout events.

IHTMLEventObj Methods
get_srcElement get_altKey get_ctrlKey
get_shiftKey put_returnValue get_returnValue
put_cancelBubble get_cancelBubble get_fromElement
get_toElement put_keyCode get_keyCode
get_button get_type get_qualifier
get_reason get_x get_y
get_clientX get_clientY get_offsetX
get_offsetY get_screenX get_screenY
get_srcFilter


IHTMLEventObj::get_altKey

HRESULT get_altKey(
    VARIANT_BOOL *p
);

Retrieves the state of the ALT key.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a Boolen variable that receives TRUE if the key is down, or FALSE otherwise.


IHTMLEventObj::get_button

HRESULT get_button(
    long *p
);

Retrieves which mouse button, if any, is pressed.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a long integer variable that receives one of these values:
0 | No button.
1 | Left button is pressed.
2 | Right button is pressed.
4 | Middle button is pressed.

This property is intended to be used with the onmousedown, onmouseup, and onmousemove events. For other events, it typically is 0 regardless of the state of the mouse buttons.


IHTMLEventObj::get_clientX

HRESULT get_clientX(
    long *p
);

Retrieves the horizontal position of the mouse hit relative to the top of the client area of the window. This does not include window decorations or scroll bars.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a long integer variable that receives the position.

See also get_clientY


IHTMLEventObj::get_clientY

HRESULT get_clientY(
    long *p
);

Retrieves the vertical position of the mouse hit relative to side of the client area of the window. This does not include window decorations or scroll bars.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a long integer variable that receives the position.

See also get_clientX


IHTMLEventObj::get_ctrlKey

HRESULT get_ctrlKey(
    VARIANT_BOOL *p
);

Retrieves the state of the CTRL key.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a Boolen variable that receives TRUE if the key is down, or FALSE otherwise.


IHTMLEventObj::get_fromElement

HRESULT get_fromElement(
    IHTMLElement **p
);

Retrieves the object being moved from for the onmouseover and onmouseout events.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a pointer to the IHTMLElement interface of the object.

Up Top of Page


IHTMLEventObj::get_offsetX

HRESULT get_offsetX(
    long *p
);

Returns container-relative positions. These match the offsetLeft and offsetTop properties of the object. Use offsetParent to find the container object that defines this coordinate system.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a long integer variable that receives the positions.

See also get_offsetY


IHTMLEventObj::get_offsetY

HRESULT get_offsetY(
    long *p
);

Returns container-relative positions. These match the offsetLeft and offsetTop properties of the object. Use offsetParent to find the container object that defines this coordinate system.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a long integer variable that receives the positions.

See also get_offsetX


IHTMLEventObj::get_qualifier

HRESULT get_qualifier(
    BSTR *p
);

Specifies the event qualifier.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the event qualifier. In Internet Explorer 4.0, it is always set to "".


IHTMLEventObj::get_reason

HRESULT get_reason(
    long *p
);

Retrieves the disposition of data transfer for a data source object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a long integer variable that receives an integer value specifying the reason for completion. Can be one of these values:
0 | Data transmitted successfully.
1 | Data transfer aborted.
2 | Data transfer in error.


IHTMLEventObj::get_screenX

HRESULT get_screenX(
    long *p
);

Returns coordinates relative to the physical screen size.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a long integer variable that receives the screen coordinates.

See also get_screenY


IHTMLEventObj::get_screenY

HRESULT get_screenY(
    long *p
);

Returns coordinates relative to the physical screen size.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a long integer variable that receives the screen coordinates.

See also get_screenX


IHTMLEventObj::get_shiftKey

HRESULT get_shiftKey(
    VARIANT_BOOL *p
);

Retrieves the state of the SHIFT key.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a Boolean variable that receives TRUE if the key is down, or FALSE otherwise.


IHTMLEventObj::get_srcElement

HRESULT get_srcElement(
    IHTMLElement **p
);

Retrieves an interface pointer for the object in which the event occurred.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a pointer to the IHTMLElement interface of the object.

Up Top of Page


IHTMLEventObj::get_srcFilter

HRESULT get_srcFilter(
    BSTR *p
);

Specifies the filter object that caused the onfilterchange event.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the filter object.


IHTMLEventObj::get_toElement

HRESULT get_toElement(
    IHTMLElement **p
);

Retrieves the object being moved to for the onmouseover and onmouseout events.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a pointer to the IHTMLElement interface of the object.

Up Top of Page


IHTMLEventObj::get_type

HRESULT get_type(
    BSTR *p
);

Retrieves the event name as a string.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the event name.

Events are returned without the "on" prefix. For example, the "onclick" event is returned as "click".


IHTMLEventObj::get_x

HRESULT get_x(
    long *p
);

Retrieves the position of the mouse hit relative to the object in the parent heirarchy that is positioned using the CSS positioning attribute. If no object in the heirarchy has been positioned, the BODY is the default.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a long integer variable that receives the position of the mouse hit.

If the mouse is outside the window when the event is called, this property returns -1.

See also get_y


IHTMLEventObj::get_y

HRESULT get_y(
    long *p
);

Retrieves the position of the mouse hit relative to the object in the parent heirarchy that is positioned using the CSS positioning attribute. If no object in the heirarchy has been positioned, the BODY is the default.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a long integer variable that receives the position of the mouse hit.

If the mouse is outside the window at the time the event fires, this property returns -1.

See also get_x


KeyCode Property

*
  * Previous Topic: IHTMLEventObj::put_keyCode
  * Next Topic: IHTMLEventObj::get_button

IHTMLEventObj::get_keyCode

HRESULT get_keyCode(
    long *p
);

Retrieves the Unicode key code associated with the key that caused the event.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a long integer variable that receives the Unicode key code. It can be any key code in the range 1 to 255. It is zero if no key caused the event.

If you set this property, the given key code replaces the existing value. Subsequent event handlers receive the new value rather than the original.

This property is intended to be used with the onkeydown, onkeyup, and onkeypress events.

See also put_keyCode

Up Top of Page

IHTMLEventObj::put_keyCode

HRESULT put_keyCode(
    long v
);

Sets the Unicode key code associated with the key that caused the event.

  • Returns S_OK if successful, or an error value otherwise.
v
Long integer value specifying any Unicode key code in the range 1 to 255. It is zero if no key caused the event.

If you set this property, the given key code replaces the existing value. Subsequent event handlers receive the new value rather than the original.

This property is intended to be used with the onkeydown, onkeyup, and onkeypress events.

See also get_keyCode


ReturnValue Property

*
  * Previous Topic: IHTMLEventObj::put_returnValue
  * Next Topic: IHTMLEventObj::put_cancelBubble

IHTMLEventObj::get_returnValue

HRESULT get_returnValue(
    VARIANT *p
);

Retrieves the return value of the event or dialog.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the return value. It can be either TRUE or FALSE.

For event handler functions, the value of this property takes precedence over values returned by the function, such as through a return statement.

See also put_returnValue

Up Top of Page

IHTMLEventObj::put_returnValue

HRESULT put_returnValue(
    VARIANT v
);

Sets the return value of the event.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the return value. It can be either TRUE of FALSE.

For event handler functions, the value of this property takes precedence over values returned by the function, such as through a return statement.

See also get_returnValue


Align Property

*
  * Previous Topic: IHTMLFieldSetElement::put_align
  * Next Topic: IHTMLFiltersCollection

IHTMLFieldSetElement::get_align

HRESULT get_align(
    BSTR *p
);

Retrieves how the element is aligned with adjacent text.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the alignment. Can be one of these values:
absbottom | Aligns the bottom of the element with the absolute bottom of the surrounding text. The absolute bottom is equal to the baseline of the text minus the height of the largest descender in the text.
absmiddle | Aligns the middle of the element with the middle of the surrounding text. The absolute middle is the midpoint between the absolute bottom and texttop of the surrounding text.
baseline | Aligns the bottom of the element with the baseline of the surrounding text.
bottom | Aligns the bottom of the element with the bottom of the surrounding text. The bottom is equal to the baseline minus the standard height of a descender in the text.
left | Aligns the element to the left of the surrounding text. All preceding and subsequent text flows to the right of the element. This is the default value.
middle | Aligns the middle of the element with the surrounding text.
right | Aligns the element to the right of the surrounding text. All subsequent text flows to the left of the element.
texttop | Aligns the top of the element with the absolute top of the surrounding text. The absolute top is the baseline plus the height of the largest ascender in the text.
top | Aligns the top of the element with the top of the text. The top of the text is the baseline plus the standard height of an ascender in the text.

For the INPUT element, this attribute applies only to the image type. It is undefined for all other types.

See also put_align

Up Top of Page

IHTMLFieldSetElement::put_align

HRESULT put_align(
    BSTR v
);

Sets how the element is aligned with adjacent text.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the alignment. This can be one of the following values:
absbottom | Aligns the bottom of the element with the absolute bottom of the surrounding text. The absolute bottom is equal to the baseline of the text, minus the height of the largest descender in the text.
absmiddle | Aligns the middle of the element with the middle of the surrounding text. The absolute middle is the midpoint between the absolute bottom and texttop of the surrounding text.
baseline | Aligns the bottom of the element with the baseline of the surrounding text.
bottom | Aligns the bottom of the element with the bottom of the surrounding text. The bottom is equal to the baseline minus the standard height of a descender in the text.
left | Aligns the element to the left of the surrounding text. All preceding and subsequent text flows to the right of the element. This is the default value.
middle | Aligns the middle of the element with the surrounding text.
right | Aligns the element to the right of the surrounding text. All subsequent text flows to the left of the element.
texttop | Aligns the top of the element with the absolute top of the surrounding text. The absolute top is the baseline plus the height of the largest ascender in the text.
top | Aligns the top of the element with the top of the text. The top of the text is the baseline plus the standard height of an ascender in the text.

For the INPUT element, this attribute applies only to the image type. It is undefined for all other types.

See also get_align


IHTMLFieldSetElement

This interface draws a box around the text and other elements it contains. This element is useful for grouping elements in a form and for distinctively marking text in a document.

IHTMLFieldSetElement Methods


IHTMLFiltersCollection

This interface provides the ability to access the collection of filters for the object. This is a zero-based collection of filters that is exposed from the document object. The methods for this interface allow for obtaining the number of filters in the collection, enumerating over the collection, or requesting a single filter from the collection.

IHTMLFiltersCollection Methods


IHTMLFiltersCollection::get__newEnum

HRESULT get__newEnum (
    IUnknown **p
);

Retrieves an OLE enumeration interface. This will enumerate over the filters in this collection.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a pointer to an IUnknown interface.


IHTMLFiltersCollection::get_length

HRESULT get_length (
    long *p
);

Retrieves the number of elements in a collection.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a long integer variable that receives the length.


IHTMLFiltersCollection::item

HRESULT item (
    VARIANT *pvarIndex,
    VARIANT *pvarResult
);

Retrieves a collection of filters, or a single item from the collection. The pvarIndex parameter determines which action to take.

  • Returns S_OK if successful, or an error value otherwise.
pvarIndex
Address of a VARIANT structure specifying the element or collection to retrieve. If this parameter is a number, the method returns the element in the collection at the given position, where the first element has value 0, the second has 1, and so on. If this parameter is a string, the method returns a collection of elements, where the value of the name or ID property for each element is equal to the string.
pvarResult
Address of a VARIANT structure that receives an element object or a collection of element objects if successful, or NULL otherwise.


Color Property

*
  * Previous Topic: IHTMLFontElement::put_color
  * Next Topic: IHTMLFontElement::put_face

IHTMLFontElement::get_color

HRESULT get_color(
    VARIANT *p
);

Retrieves the color used by the font.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the color. It can be one of the color names or values given in the Color Table reference documentation.

See also put_color

Up Top of Page

IHTMLFontElement::put_color

HRESULT put_color(
    VARIANT v
);

Sets the color to be used by the font.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the color. It can be one of the color names or values given in the Color Table reference documentation.

See also get_color


Face Property

*
  * Previous Topic: IHTMLFontElement::put_face
  * Next Topic: IHTMLFontElement::put_size

IHTMLFontElement::get_face

HRESULT get_face(
    BSTR *p
);

Retrieves the current font's typeface.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the font's typeface.

See also put_face

Up Top of Page

IHTMLFontElement::put_face

HRESULT put_face(
    BSTR v
);

Sets the typeface to use for the text of the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the font.

See also get_face


IHTMLFontElement

This interface specifies a new font face, size, and color to be used for rendering the enclosed text.

IHTMLFontElement Methods


Size Property

*
  * Previous Topic: IHTMLFontElement::put_size
  * Next Topic: IHTMLFontNamesCollection

IHTMLFontElement::get_size

HRESULT get_size(
    VARIANT *p
);

Retrieves the current font size for the text of the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the font size. This property is an integer value in the range 1 through 7, with 7 representing the largest font.

See also put_size

Up Top of Page

IHTMLFontElement::put_size

HRESULT put_size(
    VARIANT v
);

Sets the font size for the text of the element.

  • Returns S_OK if successful, or an error value otherwise.
v
Integer value specifying the font size. This property takes an integer value in the range 1 through 7, with 7 representing the largest font.

See also get_size


IHTMLFontNamesCollection

This interface is for the collection of all the font names supported by the system, created by using the system font enumeration calls. The collection is maintained by the IHTMLOptionsHolder object, which returns this interface for collection access.

IHTMLFontNamesCollection Methods


IHTMLFontNamesCollection::get__newEnum

HRESULT get__newEnum(
    IUnknown **p
);

Returns an OLE enumeration interface. This will enumerate over the names in this collection.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the IUnknown interface pointer.


IHTMLFontNamesCollection::get_length

HRESULT get_length(
    long *p
);

Retrieves the number of elements in a collection.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the number of elements.


IHTMLFontNamesCollection::item

HRESULT item(
    long index,
    BSTR *pBstr
);

Retrieves an element or a collection from the collection. The index determines which action to take.

  • Returns S_OK if successful, or an error value otherwise.
index
Address of a variable specifying the element or collection to retrieve. If this parameter is a number, the method returns the element in the collection at the given position, where the first element has value 0, the second has 1, and so on. If this parameter is a string, the method returns a collection of elements, where the value of the name or id property for each element is equal to the string.
pBstr
Address of a variable that receives an element object or a collection of element objects if successful, or null otherwise.


IHTMLFontSizesCollection::get__newEnum

HRESULT get__newEnum(
    IUnknown **p
);

Returns an OLE enumeration interface. This will enumerate over the sizes in this collection.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the IUnknown interface pointer.


IHTMLFontSizesCollection::get_forFont

HRESULT get_forFont(
    BSTR *p
);

Returns a string of the font name that this collection of font sizes applies to.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the font name.


IHTMLFontSizesCollection::get_length

HRESULT get_length(
    long *p
);

Retrieves the number of elements in a collection.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a long integer that receives the number of font sizes in the collection.

This property is read-write on the areas and the options collection for image maps and select boxes, respectively. This allows a developer to shrink the collection.


IHTMLFontSizesCollection::item

HRESULT item(
    long index,
    long *plSize
);

Retrieves a single element or a collection from the collection. The index parameter determines which action to take.

  • Returns S_OK if successful, or an error value otherwise.
index
Address of a variable specifying the element or collection to retrieve. If this parameter is a number, the method returns the element in the collection at the given position, where the first element has value 0, the second has 1, and so on. If this parameter is a string, the method returns a collection of elements, where the value of the name or id property for each element is equal to the string.
plSize
Address of a variable that receives an element object or a collection of element objects if successful, or null otherwise.


IHTMLFontSizesCollection

This interface is for the collection of all the font sizes available for a font on the system. The collection of fonts and sizes that this is built from is maintained in the IHTMLOptionsHolder object. This interface is returned when that collection is accessed.

IHTMLFontSizesCollection Methods


Action Property

*
  * Previous Topic: IHTMLFormElement::put_action
  * Next Topic: IHTMLFormElement::put_dir

IHTMLFormElement::get_action

HRESULT get_action(
    BSTR *p
);

Retrieves the address to be used to carry out the action of the form. If none is specified, the base URL of the document is used.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the address.

The way the data is submitted depends upon the value of the method and encoding properties.

See also put_action

Up Top of Page

IHTMLFormElement::put_action

HRESULT put_action(
    BSTR v
);

Sets the address to be used to carry out the action of the form. If none is specified, the base URL of the document is used.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the address.

The way the data is submitted depends upon the value of the method and encoding properties.

See also get_action


Dir Property

*
  * Previous Topic: IHTMLFormElement::put_dir
  * Next Topic: IHTMLFormElement::put_encoding

IHTMLFormElement::get_dir

HRESULT get_dir(
    BSTR *p
);

Retrieves the direction value for the form. The direction represents the direction of the text on the form.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives one of the following strings:
"leftToRight" | The direction is from left to right.
"rightToLeft" | The direction is from right to left.

See also put_dir

Up Top of Page

IHTMLFormElement::put_dir

HRESULT put_dir(
    BSTR v
);

Sets the form's direction property. The direction represents the direction of the text on the form.

  • Returns S_OK if successful, or an error value otherwise.
v
String variable that contains one of the following strings:
"leftToRight" | The direction is from left to right.
"rightToLeft" | The direction is from right to left.

See also get_dir


Encoding Property

*
  * Previous Topic: IHTMLFormElement::put_encoding
  * Next Topic: IHTMLFormElement::put_method

IHTMLFormElement::get_encoding

HRESULT get_encoding(
    BSTR *p
);

Retrieves the mime-encoding for the form. This property corresponds to the HTML ENCTYPE= attribute.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the mime-encoding. The default is "application/x-www-form-urlencoded". Internet Explorer 4.0 also recognizes "multipart/form-data", which with a POST method is required to submit a file upload to the server

See also put_encoding

Up Top of Page

IHTMLFormElement::put_encoding

HRESULT put_encoding(
    BSTR v
);

Sets the mime encoding for the form. This property corresponds to the HTML ENCTYPE= attribute.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the mime encoding. The default is "application/x-www-form-urlencoded". Internet Explorer 4.0 also recognizes "multipart/form-data", which with a POST method is required to submit a file upload to the server

See also get_encoding


IHTMLFormElement

This interface specifies that the contained controls take part in a form.

When programming the form, all control-like elements are added to the form as named items. In addition, these items are exposed through the IHTMLFormElement::item method.

When the focus is on a control in a form, pressing the ESC key once causes the value of the control to revert back to the last value, and pressing the ESC key again resets the form.

If one and only one text box is on a form, pressing ENTER fires the onsubmit event. If the form has a submit button, the button appears with a dark border, indicating that pressing ENTER submits the form.

This element is a block element.

IHTMLFormElement Methods
put_action get_action put_dir
get_dir put_encoding get_encoding
put_method get_method get_elements
put_target get_target put_name
get_name put_onsubmit get_onsubmit
put_onreset get_onreset submit
reset put_length get_length
get__newEnum item tags

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


IHTMLFormElement::get__newEnum

HRESULT get__newEnum(
     IUnknown **p
);

Retrieves an enumerator interface which can be used to iterate through the form element collection.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the IUnknown interface pointer.


IHTMLFormElement::get_elements

HRESULT get_elements(
    IDispatch **p
);

Retrieves an interface pointer to a zero-based collection of the elements in the form. The pointer provides access to the properties and methods of the elements. The order of the elements in the collection is determined by the HTML source.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the interface pointer.


IHTMLFormElement::item

HRESULT item(
    VARIANT name,
    VARIANT index,
    IDispatch **pdisp
);

Retrieves an element or a collection from the given collection. The index determines which action to take.

  • Returns S_OK if successful, or an error value otherwise.
name
Number or string specifying the element or collection to retrieve. If this parameter is a number, the method returns the element in the collection at the given position, where the first element has value 0, the second has 1, and so on. If this parameter contains a string, the method returns a collection of elements, where the value of the NAME or ID= property for each element is equal to the string.
index
Number specifying the position of an element to retrieve. This parameter is used when name is a string. The method uses the string to construct a collection of all elements that have a NAME or ID= equal to the string, then retrieves from this collection the element at the position specified by index.
pdisp
Address of a variable that receives an interface pointer to the element object.


Length Property

*
  * Previous Topic: IHTMLFormElement::put_length
  * Next Topic: IHTMLFormElement::get__newEnum

IHTMLFormElement::get_length

HRESULT get_length(
    long *p
);

Retrieves the number of elements in a collection.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the length.

This property is read-write on the areas and the options collection for image maps and select boxes, respectively. This allows a developer to shrink the collection.

See also put_length

Up Top of Page

IHTMLFormElement::put_length

HRESULT put_length(
    long v
);

Sets the number of elements in a collection.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the length.

This property is read-write on the areas and the options collection for image maps and select boxes, respectively. This allows a developer to shrink the collection.

See also get_length


Method Property

*
  * Previous Topic: IHTMLFormElement::put_method
  * Next Topic: IHTMLFormElement::get_elements

IHTMLFormElement::get_method

HRESULT get_method(
    BSTR *p
);

Retrieves how the form data should be sent to the server, either as GET or POST.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that reeives the send method. Can be one of these values:
get | Append the arguments to the action URL and open it as if it were an anchor.
post | Send the data through an HTTP POST transaction.

See also put_method

Up Top of Page

IHTMLFormElement::put_method

HRESULT put_method(
    BSTR v
);

Specifies how the form data should be sent to the server, either as GET or POST.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying how to send the data. Can be one of these values:
get | Append the arguments to the action URL and open it as if it were an anchor.
post | Send the data through an HTTP POST transaction.

See also get_method


Name Property

*
  * Previous Topic: IHTMLFormElement::put_name
  * Next Topic: IHTMLFormElement::put_onsubmit

IHTMLFormElement::get_name

HRESULT get_name(
    BSTR *p
);

Retrieves the name of the control, bookmark, or application.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the name.

The name is used to bind the value of the control when submitting a form. The NAME is not the value that is displayed for the button, reset, and submit objects. Submitting the form submits the internally stored value, not the one displayed.

JScript allows the name to be changed at run time. This does not change the name in the programming model, in the collection of elements, but does change the name used for submitting elements.

See also put_name

Up Top of Page

IHTMLFormElement::put_name

HRESULT put_name(
    BSTR v
);

Sets the name of the control, bookmark, or application.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the name.

The name is used to bind the value of the control when submitting a form. The NAME is not the value that is displayed for the button, reset, and submit objects. Submitting the form submits the internally stored value, not the one displayed.

JScript allows the name to be changed at run time. This does change the name in the programming model, in the collection of elements, but does change the name used for submitting elements.

See also get_name


Onreset Property

*
  * Previous Topic: IHTMLFormElement::put_onreset
  * Next Topic: IHTMLFormElement::submit

IHTMLFormElement::get_onreset

HRESULT get_onreset(
    VARIANT *p
);

Retrieves the inline script associated with the onreset event for a FORM element. A reset event occurs when a user resets a form (clicks a Reset button).

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the script.

See also put_onreset

Up Top of Page

IHTMLFormElement::put_onreset

HRESULT put_onreset(
    VARIANT v
);

Sets the inline script associated with the onreset event for a FORM element. A reset event occurs when a user resets a form (clicks a Reset button).

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the new script.

See also get_onreset


Onsubmit Property

*
  * Previous Topic: IHTMLFormElement::put_onsubmit
  * Next Topic: IHTMLFormElement::put_onreset

IHTMLFormElement::get_onsubmit

HRESULT get_onsubmit(
    VARIANT *p
);

Retrieves the inline script associated with the onsubmit event for a FORM element. A submit event occurs when a user submits a form (clicks a Submit button).

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the script.

See also put_onsubmit

Up Top of Page

IHTMLFormElement::put_onsubmit

HRESULT put_onsubmit(
    VARIANT v
);

Sets the inline script associated with the onsubmit event for a FORM element. A submit event occurs when a user submits a form (clicks a Submit button).

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to be set.

See also get_onsubmit


IHTMLFormElement::reset

HRESULT reset(
    void
);

Simulates a mouse click on a reset button for the calling form.

  • Returns S_OK if successful, or an error value otherwise.


IHTMLFormElement::submit

HRESULT submit(
    void
);

Submits the form and fires the onsubmit event.

  • Returns S_OK if successful, or an error value otherwise.


IHTMLFormElement::tags

HRESULT tags(
    VARIANT tagName,
    IDispatch **pdisp
);

Retrieves a collection of all elements in the given collection that have the given HTML tag name.

  • Returns S_OK if successful, or an error value otherwise.
tagName
String specifying the name of a tag.
pdisp
Address of a variable that receives an interface pointer to the element collection.

This method returns an empty collection if no elements having the given name are found. Use the length property on the collection to determine the number of elements it contains.


Target Property

*
  * Previous Topic: IHTMLFormElement::put_target
  * Next Topic: IHTMLFormElement::put_name

IHTMLFormElement::get_target

HRESULT get_target(
    BSTR *p
);

Retrieves the window or frame to target the contents at.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the name of the target window or frame, or one of the following special values:
_blank | Specifies to load the link into a new blank window. This window is not named.
_parent | Specifies to load the link into the immediate parent of the document the link is in.
_self | Specifies to load the link into the same window the link was clicked in.
_top | Specifies to load the link into the full body of the window.

If there is no frame or window that matches the specified target, a new window is opened for the link.

The default value for the target depends upon the URL and site. If the user does not leave the site, the default is _self, but if the user exits to a new site, the default is _top.

See also put_target

Up Top of Page

IHTMLFormElement::put_target

HRESULT put_target(
    BSTR v
);

Sets the window or frame to target the contents at.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the name of the target window or frame. Can also be one of the following special values:
_blank | Specifies to load the link into a new blank window. This window is not named.
_parent | Specifies to load the link into the immediate parent of the document the link is in.
_self | Specifies to load the link into the same window the link was clicked in.
_top | Specifies to load the link into the full body of the window.

If there is no frame or window that matches the specified target, a new window is opened for the link.

The default value for the target depends upon the URL and site. If the user does not leave the site, the default is _self, but if the user exits to a new site, the default is _top.

See also get_target


Border Property

*
  * Previous Topic: IHTMLFrameBase::put_border
  * Next Topic: IHTMLFrameBase::put_frameBorder

IHTMLFrameBase::get_border

HRESULT get_border(
    VARIANT *p
);

Retrieves the thickness of the border.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the thickness.

Setting a border to zero or omitting the attribute causes no border to be displayed. Supplying the border attribute without a value defaults to a single border.

See also put_border

Up Top of Page

IHTMLFrameBase::put_border

HRESULT put_border(
    VARIANT v
);

Specifies the thickness of the border.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the thickness.

Setting a border to zero or omitting the attribute causes no border to be displayed. Supplying the border attribute without a value defaults to a single border.

See also get_border


IHTMLFrameBase

This interface provides access to properties and methods that are common to FRAME and IFRAME elements.

IHTMLFrameBase Methods
put_src get_src put_name
get_name put_border get_border
put_frameBorder get_frameBorder put_frameSpacing
get_frameSpacing put_marginWidth get_marginWidth
put_marginHeight get_marginHeight put_noResize
get_noResize put_scrolling get_scrolling

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


FrameBorder Property

*
  * Previous Topic: IHTMLFrameBase::put_frameBorder
  * Next Topic: IHTMLFrameBase::put_frameSpacing

IHTMLFrameBase::get_frameBorder

HRESULT get_frameBorder(
    BSTR *p
);

Determines whether a border is currently being displayed for the frame.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives "Yes" if the frame has an inset border, or "No" if it has no border.

See also put_frameBorder

Up Top of Page

IHTMLFrameBase::put_frameBorder

HRESULT put_frameBorder(
    BSTR v
);

Specifies whether to display a border for the frame.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying whether to display a border. If this parameter is "Yes", the frame will have an inset border. If it is "No", the frame will have no border. Any other value turns on the borders.

See also get_frameBorder


FrameSpacing Property

*
  * Previous Topic: IHTMLFrameBase::put_frameSpacing
  * Next Topic: IHTMLFrameBase::put_marginWidth

IHTMLFrameBase::get_frameSpacing

HRESULT get_frameSpacing(
    VARIANT *p
);

Retrieves the amount of additional space between the frames, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the amount of additional space. The default spacing is 2 pixels.

The amount defined for frameSpacing does not include the width of the frameBorder. frameSpacing can be set on one or more FRAMESETs, and applies to the contained FRAMESET unless the contained FRAMESET defines a different frameSpacing.

See also put_frameSpacing

Up Top of Page

IHTMLFrameBase::put_frameSpacing

HRESULT put_frameSpacing(
    VARIANT v
);

Creates additional space between the frames, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the amount of additional space. The default spacing is 2 pixels.

The amount defined for frameSpacing does not include the width of the frameBorder. frameSpacing can be set on one or more FRAMESETs, and applies to the contained FRAMESET unless the contained FRAMESET defines a different frameSpacing.

See also get_frameSpacing


MarginHeight Property

*
  * Previous Topic: IHTMLFrameBase::put_marginHeight
  * Next Topic: IHTMLFrameBase::put_noResize

IHTMLFrameBase::get_marginHeight

HRESULT get_marginHeight(
    VARIANT *p
);

Retrieves the width, in pixels, of the top and bottom margins for the text in a frame.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the width.

Margins cannot be less than 1 nor so large that the text cannot be displayed.

See also put_marginHeight

Up Top of Page

IHTMLFrameBase::put_marginHeight

HRESULT put_marginHeight(
    VARIANT v
);

Sets the width, in pixels, of the top and bottom margins for the text in a frame.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying margin widths.

Margins cannot be less than 1 nor so large that the text cannot be displayed.

See also get_marginHeight


MarginWidth Property

*
  * Previous Topic: IHTMLFrameBase::put_marginWidth
  * Next Topic: IHTMLFrameBase::put_marginHeight

IHTMLFrameBase::get_marginWidth

HRESULT get_marginWidth(
    VARIANT *p
);

Retrieves the width, in pixels, of the left and right margins for the text in a frame.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the width.

Margins cannot be less than 1 nor so large that the text cannot be displayed.

See also put_marginWidth

Up Top of Page

IHTMLFrameBase::put_marginWidth

HRESULT put_marginWidth(
    VARIANT v
);

Sets the width, in pixels, of the left and right margins for the text in a frame.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying margin widths.

Margins cannot be less than 1 nor too large that the text cannot be displayed.

See also get_marginWidth


Name Property

*
  * Previous Topic: IHTMLFrameBase::put_name
  * Next Topic: IHTMLFrameBase::put_border

IHTMLFrameBase::get_name

HRESULT get_name(
    BSTR *p
);

Retrieves the name of the frame so it can be targeted from links in other documents.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the window or frame name, or one of these values:
window_name | String that specifies a frame.
_blank | Loads the link into a new, unnamed window.
_parent | Loads the link over the parent. If the frame has no parent, this refers to _self.
_self | Replaces the page with the specified link.
_top | Loads the link at the topmost level.

The name property on the window comes from the FRAME definition. There is no other way to persist a window name in HTML.

See also put_name

Up Top of Page

IHTMLFrameBase::put_name

HRESULT put_name(
    BSTR v
);

Sets the name of the frame so it can be targeted from links in other documents.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the name. It can be the name of a window or frame, or one of the following values:
window_name | String that specifies a frame.
_blank | Loads the link into a new, unnamed window.
_parent | Loads the link over the parent. If the frame has no parent, this refers to _self.
_self | Replaces the page with the specified link.
_top | Loads the link at the topmost level.

The name property on the window comes from the FRAME definition. There is no other way to persist a window name in HTML.

See also get_name


NoResize Property

*
  * Previous Topic: IHTMLFrameBase::put_noResize
  * Next Topic: IHTMLFrameBase::put_scrolling

IHTMLFrameBase::get_noResize

HRESULT get_noResize(
    VARIANT_BOOL *p
);

Retrieves whether the user can resize the frame.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives TRUE if the frame is not resizeable, or FALSE if it is.

See also put_noResize

Up Top of Page

IHTMLFrameBase::put_noResize

HRESULT put_noResize(
    VARIANT_BOOL v
);

Specifies whether the user can resize the frame.

  • Returns S_OK if successful, or an error value otherwise.
v
Resize flag. TRUE means the size is fixed; the user cannot resize the frame. FALSE means the user can resize the frame. This is the default value for the property.

See also get_noResize


Scrolling Property

*
  * Previous Topic: IHTMLFrameBase::put_scrolling
  * Next Topic: IHTMLFrameElement

IHTMLFrameBase::get_scrolling

HRESULT get_scrolling(
    BSTR *p
);

Retrieves a value indicating whether the frame can be scrolled.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives one of these values:
auto | The browser determines if the scroll bars are necessary. This is the default value.
no | The frame cannot be scrolled.
yes | The frame can be scrolled.

See also put_scrolling

Up Top of Page

IHTMLFrameBase::put_scrolling

HRESULT put_scrolling(
    BSTR v
);

Specifies whether the frame can be scrolled.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying one of these values:
auto | The browser determines if the scroll bars are necessary. This is the default value.
no | The frame cannot be scrolled.
yes | The frame can be scrolled.

See also get_scrolling


Src Property

*
  * Previous Topic: IHTMLFrameBase::put_src
  * Next Topic: IHTMLFrameBase::put_name

IHTMLFrameBase::get_src

HRESULT get_src(
    BSTR *p
);

Retrieves the URL of the associated file.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the URL.

See also put_src

Up Top of Page

IHTMLFrameBase::put_src

HRESULT put_src(
    BSTR v
);

Sets the URL of the associated file.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the URL.

See also get_src


BorderColor Property

*
  * Previous Topic: IHTMLFrameElement::put_borderColor
  * Next Topic: IHTMLFramesCollection2

IHTMLFrameElement::get_borderColor

HRESULT get_borderColor(
    VARIANT *p
);

Retrieves the border color.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the color. The color can be one of the color names or values given in the Color Table reference documentation.

See also put_borderColor

Up Top of Page

IHTMLFrameElement::put_borderColor

HRESULT put_borderColor(
    VARIANT v
);

Sets the border color and must be used with the border property.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the color. The color can be one of the color names or values given in the Color Table reference documentation.

See also get_borderColor


IHTMLFrameElement

This interface specifies an individual frame within a FRAMESET.

This element is a block element.

IHTMLFrameElement Methods


IHTMLFramesCollection2

This is a zero-based collection of all FRAME elements if the document contains the FRAMESET element. If the document contains the BODY element, this is a collection of all IFRAME elements in the document. In either case, the order of frames is determined by the HTML source.

This collection is indexed first by name, then by ID. If duplicate names are found, a collection of those named items is returned. The resulting collection can only be referenced by ordinal position.

This is a collection of FRAME tags.

IHTMLFramesCollection2 Methods


IHTMLFramesCollection2::get_length

HRESULT get_length(
    long *p
);

Retrieves the number of elements in the frames collection.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the number of elements.


IHTMLFramesCollection2::item

HRESULT item(
    VARIANT *pvarIndex,
    VARIANT *pvarResult
);

Retrieves an element or a collection from the frames collection. The index determines which action to take.

  • Returns S_OK if successful, or an error value otherwise.
pvarIndex
Address of a variable specifying the element or collection to retrieve. If this parameter is a number, the method returns the element in the collection at the given position, where the first element has value 0, the second has 1, and so on. If this parameter is a string, the method returns a collection of elements, where the value of the name or id property for each element is equal to the string.
pvarResult
Address of a variable that receives an element object or a collection of element objects if successful, or null otherwise.


Border Property

*
  * Previous Topic: IHTMLFrameSetElement::put_border
  * Next Topic: IHTMLFrameSetElement::put_borderColor

IHTMLFrameSetElement::get_border

HRESULT get_border(
    VARIANT *p
);

Retrieves the border color and must be used with the border property, except for frames.

  • Returns S_OK if successful, or an error value otherwise.
v
Addres of a variable that receives a string or value specifying the color. It can be one of the color names or values given in the Color Table reference documentation.

See also put_border

Up Top of Page

IHTMLFrameSetElement::put_border

HRESULT put_border(
    VARIANT v
);

Sets the border color and must be used with the border property, except for frames.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the color. It can be one of the color names or values given in the Color Table reference documentation.

See also get_border


BorderColor Property

*
  * Previous Topic: IHTMLFrameSetElement::put_borderColor
  * Next Topic: IHTMLFrameSetElement::put_frameBorder

IHTMLFrameSetElement::get_borderColor

HRESULT get_borderColor(
    VARIANT *p
);

Retrieves the border color.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the color. The color can be one of the color names or values given in the Color Table reference documentation.

See also put_borderColor

Up Top of Page

IHTMLFrameSetElement::put_borderColor

HRESULT put_borderColor(
    VARIANT v
);

Sets the border color.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the color. The color can be one of the color names or values given in the Color Table reference documentation.

See also get_borderColor


Cols Property

*
  * Previous Topic: IHTMLFrameSetElement::put_cols
  * Next Topic: IHTMLFrameSetElement::put_border

IHTMLFrameSetElement::get_cols

HRESULT get_cols(
    BSTR *p
);

Retrieves a comma-delimited list of frames to create. Each item in the list contains the initial size of the column.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the comma-delimited list.

See also put_cols

Up Top of Page

IHTMLFrameSetElement::put_cols

HRESULT put_cols(
    BSTR v
);

Specifies a comma-delimited list of frames to create. Each item in the list contains the initial size of the column.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying a comma-delimited list of frames.

See also get_cols


FrameBorder Property

*
  * Previous Topic: IHTMLFrameSetElement::put_frameBorder
  * Next Topic: IHTMLFrameSetElement::put_frameSpacing

IHTMLFrameSetElement::get_frameBorder

HRESULT get_frameBorder(
    BSTR *p
);

Determines whether a border is currently being displayed for the frame.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives "Yes" if the frame has an inset border, or "No" if it has no border.

See also put_frameBorder

Up Top of Page

IHTMLFrameSetElement::put_frameBorder

HRESULT put_frameBorder(
    BSTR v
);

Specifies whether to display a border for the frame.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying whether to display a border. If this parameter is "Yes", the frame will have an inset border. If it is "No", the frame will have no border. Any other value turns on the borders.

See also get_frameBorder


IHTMLFrameSetElement

This interface specifies a frameset. Framesets are used to organize multiple frames and nested framesets. A frameset organizes multiple frames on the screen. Only FRAME, nested FRAMESET, and the NOFRAMES tags are valid within a frameset.

This element is a block element.

IHTMLFrameSetElement Methods
put_rows get_rows put_cols
get_cols put_border get_border
put_borderColor get_borderColor put_frameBorder
get_frameBorder put_frameSpacing get_frameSpacing
put_name get_name put_onload
get_onload put_onunload get_onunload
put_onbeforeunload get_onbeforeunload

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


FrameSpacing Property

*
  * Previous Topic: IHTMLFrameSetElement::put_frameSpacing
  * Next Topic: IHTMLFrameSetElement::put_name

IHTMLFrameSetElement::get_frameSpacing

HRESULT get_frameSpacing(
    VARIANT *p
);

Retrieves the amount of additional space between the frames, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the amount of additional space. The default spacing is 2 pixels.

The amount defined for frameSpacing does not include the width of the frameBorder. frameSpacing can be set on one or more FRAMESETs, and applies to the contained FRAMESET unless the contained FRAMESET defines a different frameSpacing.

See also put_frameSpacing

Up Top of Page

IHTMLFrameSetElement::put_frameSpacing

HRESULT put_frameSpacing(
    VARIANT v
);

Creates additional space between the frames, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the amount of additional space. The default spacing is 2 pixels.

The amount defined for frameSpacing does not include the width of the frameBorder. frameSpacing can be set on one or more FRAMESETs, and applies to the contained FRAMESET unless the contained FRAMESET defines a different frameSpacing.

See also get_frameSpacing


Name Property

*
  * Previous Topic: IHTMLFrameSetElement::put_name
  * Next Topic: IHTMLFrameSetElement::put_onload

IHTMLFrameSetElement::get_name

HRESULT get_name(
    BSTR *p
);

Retrieves the name of the frame so it can be targeted from links in other documents.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the window or frame name, or one of these values:
window_name | String that specifies a frame.
_blank | Loads the link into a new, unnamed window.
_parent | Loads the link over the parent. If the frame has no parent, this refers to _self.
_self | Replaces the page with the specified link.
_top | Loads the link at the topmost level.

The name property on the window comes from the FRAME definition. There is no other way to persist a window name in HTML.

See also put_name

Up Top of Page

IHTMLFrameSetElement::put_name

HRESULT put_name(
    BSTR v
);

Sets the name of the frame so it can be targeted from links in other documents.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the name. It can be the name of a window or frame, or one of the following values:
window_name | String that specifies a frame.
_blank | Loads the link into a new, unnamed window.
_parent | Loads the link over the parent. If the frame has no parent, this refers to _self.
_self | Replaces the page with the specified link.
_top | Loads the link at the topmost level.

The name property on the window comes from the FRAME definition. There is no other way to persist a window name in HTML.

See also get_name


Onbeforeunload Property

*
  * Previous Topic: IHTMLFrameSetElement::put_onbeforeunload
  * Next Topic: IHTMLHeaderElement

IHTMLFrameSetElement::get_onbeforeunload

HRESULT get_onbeforeunload(
    VARIANT *p
);

Retrieves the inline script associated with the onbeforeunload event before a FRAME element is unloaded.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the script.

This event is fired before the onunload event. It provides an opportunity to warn the user if the window is currently in an unsaved state and the information will be lost.

See also put_onbeforeunload

Up Top of Page

IHTMLFrameSetElement::put_onbeforeunload

HRESULT put_onbeforeunload(
    VARIANT v
);

Sets the inline script associated with the onbeforeunload event before a FRAME element is unloaded.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to be set.

This event is fired before the onunload event. It provides an opportunity to warn the user if the window is currently in an unsaved state and the information will be lost.

See also get_onbeforeunload


Onload Property

*
  * Previous Topic: IHTMLFrameSetElement::put_onload
  * Next Topic: IHTMLFrameSetElement::put_onunload

ITMLFrameSetElement::get_onload

HRESULT get_onload(
    VARIANT *p
);

Retrieves the inline script associated with the onload event before a FRAME element is loaded.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the script.

See also put_onload

Up Top of Page

IHTMLFrameSetElement::put_onload

HRESULT put_onload(
    VARIANT v
);

Sets the inline script associated with the onload event before a FRAME element is loaded.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to be set.

See also get_onload


Onunload Property

*
  * Previous Topic: IHTMLFrameSetElement::put_onunload
  * Next Topic: IHTMLFrameSetElement::put_onbeforeunload

IHTMLFrameSetElement::get_onunload

HRESULT get_onunload(
    VARIANT *p
);

Retrieves the inline script associated with the onunload event before a FRAME element is unloaded.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the script.

See also put_onunload

Up Top of Page

IHTMLFrameSetElement::put_onunload

HRESULT put_onunload(
    VARIANT v
);

Sets the inline script associated with the onunload event before a FRAME element is unloaded.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to be set.

See also get_onunload


Rows Property

*
  * Previous Topic: IHTMLFrameSetElement::put_rows
  * Next Topic: IHTMLFrameSetElement::put_cols

IHTMLFrameSetElement::get_rows

HRESULT get_rows(
    BSTR *p
);

Retrieves a comma-delimited list of frames to create. Each item in the list contains the initial size of the row.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the comma-delimited list.

See also put_rows

Up Top of Page

IHTMLFrameSetElement::put_rows

HRESULT put_rows(
    BSTR v
);

Specifies a comma-delimited list of frames to create. Each item in the list contains the initial size of the row.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying a comma-delimited list of frames.

See also get_rows


Align Property

*
  * Previous Topic: IHTMLHeaderElement::put_align
  * Next Topic: IHTMLHRElement

IHTMLHeaderElement::get_align

HRESULT get_align(
    BSTR *p
);

Displays the element left flush, right flush, or centered relative to the display or table.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives one of these values:
center | Align to the center.
left | Align to the left edge.
right | Align to the right edge.

See also put_align

Up Top of Page

IHTMLHeaderElement::put_align

HRESULT put_align(
    BSTR v
);

Displays the element left flush, right flush, or centered relative to the display or table.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the alignment. Can be one of these values:
center | Align to the center.
left | Align to the left edge.
right | Align to the right edge.

See also get_align


IHTMLHeaderElement IHTMLHeaderElement *
  * Previous Topic: IHTMLFrameSetElement::get_onbeforeunload
  * Next Topic: IHTMLHeaderElement::put_align

IHTMLHeaderElement

This interface renders text as a heading style.

This element is a block element.

IHTMLHeaderElement Methods


Align Property

*
  * Previous Topic: IHTMLHRElement::put_align
  * Next Topic: IHTMLHRElement::put_color

IHTMLHRElement::get_align

HRESULT get_align(
    BSTR *p
);

Displays the element left flush, right flush, or centered relative to the display or table.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives one of these values:
center | Align to the center.
left | Align to the left edge.
right | Align to the right edge.

See also put_align

Up Top of Page

IHTMLHRElement::put_align

HRESULT put_align(
    BSTR v
);

Displays the element left flush, right flush, or centered relative to the display or table.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the alignment. Can be one of these values:
center | Align to the center.
left | Align to the left edge.
right | Align to the right edge.

See also get_align


Color Property

*
  * Previous Topic: IHTMLHRElement::put_color
  * Next Topic: IHTMLHRElement::put_noShade

IHTMLHRElement::get_color

HRESULT get_color(
    VARIANT *p
);

Retrieves the color to be used by the horizontal rule.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the color. It can be one of the color names or values given in the Color Table reference documentation.

See also put_color

Up Top of Page

IHTMLHRElement::put_color

HRESULT put_color(
    VARIANT v
);

Sets the color to be used by the horizontal rule.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the color. It can be one of the color names or values given in the Color Table reference documentation.

See also get_color


IHTMLHRElement

This interface draws a horizontal rule.

This element is a block element.

IHTMLHRElement Methods
put_align get_align put_color
get_color put_noShade get_noShade
put_width get_width put_size
get_size


NoShade Property

*
  * Previous Topic: IHTMLHRElement::put_noShade
  * Next Topic: IHTMLHRElement::put_width

IHTMLHRElement::get_noShade

HRESULT get_noShade(
    VARIANT_BOOL *p
);

Determines whether the horizontal rule is drawn with 3-D shading.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives TRUE if 3-D shading is used, or FALSE if not.

The default value for this property is FALSE.

See also put_noShade

Up Top of Page

IHTMLHRElement::put_noShade

HRESULT put_noShade(
    VARIANT_BOOL v
);

Specifies whether to draw the horizontal rule with 3-D shading.

  • Returns S_OK if successful, or an error value otherwise.
v
Shading flag. If TRUE, the rule is 3-D shaded; if FALSE, it is not.

The default value for this property is FALSE.

See also get_noShade


Size Property

*
  * Previous Topic: IHTMLHRElement::put_size
  * Next Topic: IHTMLIFrameElement

IHTMLHRElement::get_size

HRESULT get_size(
    VARIANT *p
);

Retrieves the height of the horizontal rule, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the height.

See also put_size

Up Top of Page

IHTMLHRElement::put_size

HRESULT put_size(
    VARIANT v
);

Sets the height of the horizontal rule, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the height.

See also get_size


Width Property

*
  * Previous Topic: IHTMLHRElement::put_width
  * Next Topic: IHTMLHRElement::put_size

IHTMLHRElement::get_width

HRESULT get_width(
    VARIANT *p
);

Retrieves the calculated width of the horizontal rule, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the width.

This property is an integer value. Although an HTML author can specify the width as a percentage, this property always specifies the width in pixels.

See also put_width

Up Top of Page

IHTMLHRElement::put_width

HRESULT put_width(
    VARIANT v
);

Sets the calculated width of the horizontal rule, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the width.

This property is an integer value. Although an HTML author can specify the width as a percentage, this property always specifies the width in pixels.

See also get_width


ICSSFilter ICSSFilter *
  * Previous Topic: Overview
  * Next Topic: ICSSFilter::OnAmbientPropertyChange

ICSSFilter

This interface is implemented by a control that is being used as a filter.

ICSSFilter Methods


ICSSFilter::OnAmbientPropertyChange

HRESULT OnAmbientPropertyChange(
    LONG dispid
);

Notifies the filter of an ambient property change in the element.

  • Returns S_OK if successful, or an error value otherwise.
dispid
Long integer value that contains the DISPID of the property.


ICSSFilter::SetSite

HRESULT SetSite(
    ICSSFilterSite *pSink
);

Initializes the site being filtered.

  • Returns S_OK if successful, or an error value otherwise.
pSink
Address of an ICSSFilterSite interface of the site that will be filtered.


ICSSFilterSite::FireOnFilterChangeEvent

HRESULT FireOnFilterChangeEvent(void);

Fires the onfilterchange method for the specified object.

  • Returns S_OK if successful, or an error value otherwise.


ICSSFilterSite::GetElement

HRESULT GetElement(
    IHTMLElement **ppElem
);

Retrieves the interface to the element the filter is influencing.

  • Returns S_OK if successful, or an error value otherwise.
ppElem
Address of a pointer to the IHTMLElement interface of the element.


ICSSFilterSite ICSSFilterSite *
  * Previous Topic: ICSSFilter::SetSite
  * Next Topic: ICSSFilterSite::FireOnFilterChangeEvent

ICSSFilterSite

This interface provides a filter control with access to elements.

ICSSFilterSite Methods


Align Property

*
  * Previous Topic: IHTMLIFrameElement::put_align
  * Next Topic: IHTMLImageElementFactory

IHTMLIFrameElement::get_align

HRESULT get_align(
    BSTR *p
);

Retrieves how the element is aligned with adjacent text.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the alignment. Can be one of these values:
absbottom | Aligns the bottom of the element with the absolute bottom of the surrounding text. The absolute bottom is equal to the baseline of the text minus the height of the largest descender in the text.
absmiddle | Aligns the middle of the element with the middle of the surrounding text. The absolute middle is the midpoint between the absolute bottom and texttop of the surrounding text.
baseline | Aligns the bottom of the element with the baseline of the surrounding text.
bottom | Aligns the bottom of the element with the bottom of the surrounding text. The bottom is equal to the baseline minus the standard height of a descender in the text.
left | Aligns the element to the left of the surrounding text. All preceding and subsequent text flows to the right of the element. This is the default value.
middle | Aligns the middle of the element with the surrounding text.
right | Aligns the element to the right of the surrounding text. All subsequent text flows to the left of the element.
texttop | Aligns the top of the element with the absolute top of the surrounding text. The absolute top is the baseline plus the height of the largest ascender in the text.
top | Aligns the top of the element with the top of the text. The top of the text is the baseline plus the standard height of an ascender in the text.

For the INPUT element, this attribute applies only to the image type. It is undefined for all other types.

See also put_align

Up Top of Page

IHTMLIFrameElement::put_align

HRESULT put_align(
    BSTR v
);

Sets how the element is aligned with adjacent text.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the alignment. Can be one of these values:
absbottom | Aligns the bottom of the element with the absolute bottom of the surrounding text. The absolute bottom is equal to the baseline of the text minus the height of the largest descender in the text.
absmiddle | Aligns the middle of the element with the middle of the surrounding text. The absolute middle is the midpoint between the absolute bottom and texttop of the surrounding text.
baseline | Aligns the bottom of the element with the baseline of the surrounding text.
bottom | Aligns the bottom of the element with the bottom of the surrounding text. The bottom is equal to the baseline minus the standard height of a descender in the text.
left | Aligns the element to the left of the surrounding text. All preceding and subsequent text flows to the right of the element. This is the default value.
middle | Aligns the middle of the element with the surrounding text.
right | Aligns the element to the right of the surrounding text. All subsequent text flows to the left of the element.
texttop | Aligns the top of the element with the absolute top of the surrounding text. The absolute top is the baseline plus the height of the largest ascender in the text.
top | Aligns the top of the element with the top of the text. The top of the text is the baseline plus the standard height of an ascender in the text.

For the INPUT element, this attribute applies only to the image type. It is undefined for all other types.

See also get_align


Hspace Property

*
  * Previous Topic: IHTMLIFrameElement::put_hspace
  * Next Topic: IHTMLIFrameElement::put_align

IHTMLIFrameElement::get_hspace

HRESULT get_hspace(
    long *p
);

Retrieves the horizontal margins for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the horizontal margins.

Similar to border, except the margins are not painted with color when the element is a link.

See also put_hspace

Up Top of Page

IHTMLIFrameElement::put_hspace

HRESULT put_hspace(
    long v
);

Sets the horizontal margins for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the horizontal margins.

Similar to border, except the margins are not painted with color when the element is a link.

See also get_hspace


IHTMLIFrameElement IHTMLIFrameElement *
  * Previous Topic: IHTMLHRElement::get_size
  * Next Topic: IHTMLIFrameElement::put_vspace

IHTMLIFrameElement

This interface creates inline floating frames.

This element is a block element.

IHTMLIFrameElement Methods


Vspace Property

*
  * Previous Topic: IHTMLIFrameElement::put_vspace
  * Next Topic: IHTMLIFrameElement::put_hspace

IHTMLIFrameElement::get_vspace

HRESULT get_vspace(
    long *p
);

Retrieves the width of the vertical margins for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the width of the vertical margins.

Similar to border, except the margins are not painted with color when the element is a link.

See also put_vspace

Up Top of Page

IHTMLIFrameElement::put_vspace

HRESULT put_vspace(
    long v
);

Sets the vertical margins for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the width of the vertical margins.

Similar to border, except the margins are not painted with color when the element is a link.

See also get_vspace


ClassName Property

*
  * Previous Topic: IHTMLElement::put_className
  * Next Topic: IHTMLElement::put_id

IHTMLElement::get_className

HRESULT get_className(
    BSTR *p
);

Retrieves the value of the className property of the given object. The property is typically used to associate a particular style rule in a style sheet with the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the value of the property, which can be any valid string.

By default, the value is equal to the string assigned to the className property of the given object, or is an empty string if the property is not explicitly assigned.

See also put_className

Up Top of Page

IHTMLElement::put_className

HRESULT put_className(
    BSTR v
);

Sets the value of the className property of the object. The property is typically used to associate a particular style rule in a style sheet with the object.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the value of the attribute. Can be any valid string.

By default, the property is equal to the string assigned to the className property of the given object, or is an empty string if the attribute is not explicitly assigned.

See also get_className


IHTMLElement::click

HRESULT click(void);

Simulates a click by causing the onclick event to fire.

  • Returns S_OK if successful, or an error value otherwise.


IHTMLElement::contains

HRESULT contains(
    IHTMLElement *pChild,
    VARIANT_BOOL *pfResult
);

Determines whether the given object is contained within the current object.

  • Returns S_OK if successful, or an error value otherwise.
pChild
Address of the IHTMLElement interface of the element object to check.
pfResult
Address of a Boolean variable that receives TRUE if the pChild element is contained, or FALSE otherwise.


IHTMLElement

The element object interface provides the ability to programmatically access the properties and methods that are common to all element objects.

IHTMLElement Methods
setAttribute getAttribute removeAttribute
put_className get_className put_id
get_id get_tagName get_parentElement
get_style put_onhelp get_onhelp
put_onclick get_onclick put_ondblclick
get_ondblclick put_onkeydown get_onkeydown
put_onkeyup get_onkeyup put_onkeypress
get_onkeypress put_onmouseout get_onmouseout
put_onmouseover get_onmouseover put_onmousemove
get_onmousemove put_onmousedown get_onmousedown
put_onmouseup get_onmouseup get_document
put_title get_title put_language
get_language put_onselectstart get_onselectstart
scrollIntoView contains get_sourceIndex
get_recordNumber put_lang get_lang
get_offsetLeft get_offsetTop get_offsetWidth
get_offsetHeight get_offsetParent put_innerHTML
get_innerHTML put_innerText get_innerText
put_outerHTML get_outerHTML put_outerText
get_outerText insertAdjacentHTML insertAdjacentText
get_parentTextEdit get_isTextEdit click
get_filters put_ondragstart get_ondragstart
toString put_onbeforeupdate get_onbeforeupdate
put_onafterupdate get_onafterupdate put_onerrorupdate
get_onerrorupdate put_onrowexit get_onrowexit
put_onrowenter get_onrowenter put_ondatasetchanged
get_ondatasetchanged put_ondataavailable get_ondataavailable
put_ondatasetcomplete get_ondatasetcomplete put_onfilterchange
get_onfilterchange get_children get_all

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


IHTMLElement::get_all

HRESULT get_all(
    IDispatch **p
);

Retrieves the collection of all the objects in the HTML that are within the scope of this object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a pointer to the IDispatch interface of the collection.


IHTMLElement::get_children

HRESULT get_children(
    IDispatch **p
);

Retrieves the collection that contains all the immediate children of this object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a pointer to the IDispatch interface of the collection.


IHTMLElement::get_document

HRESULT get_document(
    IDispatch **p
);

Retrieves an interface pointer that provides access to the document object's properties and methods.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a pointer to the IDispatch interface for the document object. The variable receives NULL if the current object is the top-most object.

See also IHTMLDocument2


IHTMLElement::get_filters

HRESULT get_filters(
    IHTMLFiltersCollection **p
);

Retrieves a collection of filter objects for an element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a pointer to the IHTMLFiltersCollection interface of the collection.

Up Top of Page


IHTMLElement::get_isTextEdit

HRESULT get_isTextEdit(
    VARIANT_BOOL *p
);

Retrieves whether a text range object can be created using the given object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a Boolean variable that receives TRUE if a text range can be created, and FALSE otherwise.

Only the BODY, BUTTON, and TEXTAREA objects and an INPUT object having text input type can be used to create a text range object.


IHTMLElement::get_offsetHeight

HRESULT get_offsetHeight(
    long *p
);

Retrieves the height of the element, relative to the parent coordinate system.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a long integer variable that receives the height, in pixels.


IHTMLElement::get_offsetLeft

HRESULT get_offsetLeft(
    long *p
);

Retrieves the calculated left position of the element, relative to the window.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a long integer variable that receives the left position, in pixels.


IHTMLElement::get_offsetParent

HRESULT get_offsetParent(
    IHTMLElement **p
);

Retrieves the container element object that defines the top and left offsets.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a pointer to the IHTMLElement interface for the container element object.

Up Top of Page


IHTMLElement::get_offsetTop

HRESULT get_offsetTop(
    long *p
);

Retrieves the calculated top position of the element, relative to the element's parent.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a long integer variable that receives the top position, in pixels.


IHTMLElement::get_offsetWidth

HRESULT get_offsetWidth(
    long *p
);

Retrieves the width of the element relative to the document's top-left corner.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a long integer variable that receives the width, in pixels.


IHTMLElement::get_parentElement

HRESULT get_parentElement(
    IHTMLElement **p
);

Retrieves an interface pointer that provides access to the parent object's properties and methods.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a pointer to the IHTMLElement interface of the parent object. The variable receives NULL if the current object is the top-most object.

Up Top of Page


IHTMLElement::get_parentTextEdit

HRESULT get_parentTextEdit(
    IHTMLElement **p
);

Retrieves an object that can be used to create a text range that contains the original object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a pointer to the IHTMLElement interface for the new parent object. This parameter receives NULL if no suitable parent object exists.

Up Top of Page


IHTMLElement::get_recordNumber

HRESULT get_recordNumber(
    VARIANT *p
);

Retrieves the ordinal record from the data set that generated the element. Applies to a bound, repeated table.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the ordinal record.

This property can be used in conjunction with the ADO recordset available from every data source object through the object's recordset property.


IHTMLElement::get_sourceIndex

HRESULT get_sourceIndex(
    long *p
);

Retrieves the ordinal position of the element in the source order.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a long integer variable that receives the element's ordinal position.


IHTMLElement::get_style

HRESULT get_style(
    IHTMLStyle **p
);

Retrieves an inline style sheet for the tag.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a pointer to the IHTMLStyle interface for the style sheet.

Up Top of Page


IHTMLElement::get_tagName

HRESULT get_tagName(
    BSTR *p
);

Retrieves the name of the current object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the name.


IHTMLElement::getAttribute

HRESULT getAttribute(
    BSTR strAttributeName,
    LONG fFlags,
    VARIANT *AttributeValue
);

Retrieves the value of the given attribute.

  • Returns S_OK if successful, or an error value otherwise.
strAttributeName
String specifying the name of the attribute to retrieve.
fFlags
Long integer value that contains the flags for this method.
AttributeValue
Address of a VARIANT structure that receives a string, number, or Boolean value as defined by the attribute. If the attribute is not present, this method returns NULL.

If two or more attributes have the same name (differing only in uppercase and lowercase letters) and fFlags is FALSE, this method retrieves values only for the last attribute (the last to be created with this name). All other attributes of the same name are ignored.

See also setAttribute


Id Property

*
  * Previous Topic: IHTMLElement::put_id
  * Next Topic: IHTMLElement::get_tagName

IHTMLElement::get_id

HRESULT get_id(
    BSTR *p
);

Retrieves the value of the id property for the object. The property is an SGML identifier used as the target for hypertext links or for naming particular objects in associated style sheets.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the value of the id property. For scripting, this can be any alphanumeric string that begins with a letter, and can include the underbar (_) character.

The value of the id property should be unique throughout the scope of the current document. If there is more than one object with the same identifier, a collection of those named items is created that can only be referenced by ordinal position.

See also put_id

Up Top of Page

IHTMLElement::put_id

HRESULT put_id(
    BSTR v
);

Sets the value of the id property for the object. The property is an SGML identifier used as the target for hypertext links or for naming particular objects in associated style sheets.

  • Returns S_OK if successful, or an error value otherwise.
v
String containing the ID. For scripting, this can be any alphanumeric string that begins with a letter, and can include the underbar (_) character.

The value of the id property should be unique throughout the scope of the current document. If there is more than one object with the same identifier, a collection of those named items is created that can only be referenced by ordinal position.

See also get_id


InnerHTML Property

*
  * Previous Topic: IHTMLElement::put_innerHTML
  * Next Topic: IHTMLElement::put_innerText

IHTMLElement::get_innerHTML

HRESULT get_innerHTML(
    BSTR *p
);

Retrieves the HTML between the start and end tags of the current element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the HTML. This can be any valid string containing any combination of text and HTML tags.

When setting this property, the given string completely replaces the existing content of the element. If the string contains HTML tags, the string is parsed and formatted as it is placed into the document.

You cannot set this property while the document is loading. Wait for the onload event before attempting to set it.

See also put_innerHTML

Up Top of Page

IHTMLElement::put_innerHTML

HRESULT put_innerHTML(
    BSTR v
);

Sets the HTML between the start and end tags of the current element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying any combination of text and HTML tags.

When setting this property, the given string completely replaces the existing content of the element. If the string contains HTML tags, the string is parsed and formatted as it is placed into the document.

You cannot set this property while the document is loading. Wait for the onload event before attempting to set it.

See also get_innerHTML


InnerText Property

*
  * Previous Topic: IHTMLElement::put_innerText
  * Next Topic: IHTMLElement::put_outerHTML

IHTMLElement::get_innerText

HRESULT get_innerText(
    BSTR *p
);

Retrieves the text between the start and end tags of the current element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the text. It can be any valid string.

When setting this property, the given string completely replaces the existing content of the element.

You cannot set this property while the document is loading. Wait for the onload event before attempting to set it.

See also put_innerText

Up Top of Page

IHTMLElement::put_innerText

HRESULT put_innerText(
    BSTR v
);

Sets the text between the start and end tags of the current element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the text. It can be any valid string.

When setting this property, the given string completely replaces the existing content of the element.

You cannot set this property while the document is loading. Wait for the onload event before attempting to set it.

See also get_innerText


IHTMLElement::insertAdjacentHTML

HRESULT insertAdjacentHTML(
    BSTR where,
    BSTR html
);

Inserts the given HTML text into the element object at the given location. If the text contains HTML tags, the method parses and formats the text as it inserts.

  • Returns S_OK if successful, or an error value otherwise.
where
String specifying where to insert the HTML text. Can be one of these strings:
BeforeBegin | Inserts the text immediately before the element.
AfterBegin | Inserts the text after the start of the element but before all other content in the element.
BeforeEnd | Inserts the text immediately before the end of the element but after all other content in the element.
AfterEnd | Inserts the text immediately after the end of the element.
html
String specifying the HTML text to insert.

You cannot insert text while the document is loading. Wait for the onload event before attempting to call this method.


IHTMLElement::insertAdjacentText

HRESULT insertAdjacentText(
    BSTR where,
    BSTR text
);

Inserts the given text into the element object at the given place. The method inserts the text as plain text.

  • Returns S_OK if successful, or an error value otherwise.
where
String specifying where to insert the text. Can be one of these strings:
BeforeBegin | Inserts the text immediately before the element.
AfterBegin | Inserts the text after the start of the element but before all other content in the element.
BeforeEnd | Inserts the text immediately before the end of the element but after all other content in the element.
AfterEnd | Inserts the text immediately after the end of the element.
text
String specifying the text to insert.

You cannot insert text while the document is loading. Wait for the onload event before attempting to call this method.


Lang Property

*
  * Previous Topic: IHTMLElement::put_lang
  * Next Topic: IHTMLElement::get_offsetLeft

IHTMLElement::get_lang

HRESULT get_lang(
    BSTR *p
);

Retrieves the current language.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the an ISO standard language abbreviation of the current language.

The parser can use this property to determine how to display language-specific choices for quotations, numbers, and so on.

See also put_lang

Up Top of Page

IHTMLElement::put_lang

HRESULT put_lang(
    BSTR v
);

Sets the language to use.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying an ISO standard language abbreviation.

The parser can use this property to determine how to display language-specific choices for quotations, numbers, and so on.

See also get_lang


Language Property

*
  * Previous Topic: IHTMLElement::put_language
  * Next Topic: IHTMLElement::put_onselectstart

IHTMLElement::get_language

HRESULT get_language(
    BSTR *p
);

Retrieves the language that the current script is written in.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the language. Can be one of these values:
JScript | Specifies that the script is written in JScript.
Jscript | Specifies the language as JScript.
vbs | Specifies the language is VBScript.
vbscript | Specifies that the script is written in VBScript.

See also put_language

Up Top of Page

IHTMLElement::put_language

HRESULT put_language(
    BSTR v
);

Sets the language that the current script is written in.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the language. Can be one of the following values;
JScript | Specifies that the script is written in JScript.
Jscript | Specifies the language as JScript.
vbs | Specifies the language is VBScript.
vbscript | Specifies that the script is written in VBScript.

See also get_language


Onafterupdate Property

*
  * Previous Topic: IHTMLElement::put_onafterupdate
  * Next Topic: IHTMLElement::put_onerrorupdate

IHTMLElement::get_onafterupdate

HRESULT get_onafterupdate(
    VARIANT *p
);

Retrieves the inline script associated with the onafterupdate event on the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script.

See also put_onafterupdate

Up Top of Page

IHTMLElement::put_onafterupdate

HRESULT put_onafterupdate(
    VARIANT v
);

Sets the inline script associated with the onafterupdate event on the object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to set.

See also get_onafterupdate


Onbeforeupdate Property

*
  * Previous Topic: IHTMLElement::put_onbeforeupdate
  * Next Topic: IHTMLElement::put_onafterupdate

IHTMLElement::get_onbeforeupdate

HRESULT get_onbeforeupdate(
    VARIANT *p
);

Retrieves the inline script associated with the onbeforeupdate event on the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script.

See also put_onbeforeupdate

Up Top of Page

IHTMLElement::put_onbeforeupdate

HRESULT put_onbeforeupdate(
    VARIANT v
);

Sets the inline script associated with the onbeforeupdate event on the object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to set.

See also get_onbeforeupdate


Onclick Property

*
  * Previous Topic: IHTMLElement::put_onclick
  * Next Topic: IHTMLElement::put_ondblclick

IHTMLElement::get_onclick

HRESULT get_onclick(
    VARIANT *p
);

Retrieves the inline script associated with the onclick event on the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script.

See also put_onclick

Up Top of Page

IHTMLElement::put_onclick

HRESULT put_onclick(
    VARIANT v
);

Sets the inline script associated with the onclick event on the object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the inline script.

See also get_onclick


Ondataavailable Property

*
  * Previous Topic: IHTMLElement::put_ondataavailable
  * Next Topic: IHTMLElement::put_ondatasetcomplete

IHTMLElement::get_ondataavailable

HRESULT get_ondataavailable(
    VARIANT *p
);

Retrieves the inline script associated with the ondataavailable event on the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script.

See also put_ondataavailable

Up Top of Page

IHTMLElement::put_ondataavailable

HRESULT put_ondataavailable(
    VARIANT v
);

Sets the inline script associated with the ondataavailable event on the object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to set.

See also get_ondataavailable


Ondatasetchanged Property

*
  * Previous Topic: IHTMLElement::put_ondatasetchanged
  * Next Topic: IHTMLElement::put_ondataavailable

IHTMLElement::get_ondatasetchanged

HRESULT get_ondatasetchanged(
    VARIANT *p
);

Retrieves the inline script associated with the ondatasetchanged event on the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script.

See also put_ondatasetchanged

Up Top of Page

IHTMLElement::put_ondatasetchanged

HRESULT put_ondatasetchanged(
    VARIANT v
);

Sets the inline script associated with the ondatasetchanged event on the object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to set.

See also get_ondatasetchanged


Ondatasetcomplete Property

*
  * Previous Topic: IHTMLElement::put_ondatasetcomplete
  * Next Topic: IHTMLElement::put_onfilterchange

IHTMLElement::get_ondatasetcomplete

HRESULT get_ondatasetcomplete(
    VARIANT *p
);

Retrieves the inline script associated with the ondatasetcomplete event on the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script.

See also put_ondatasetcomplete

Up Top of Page

IHTMLElement::put_ondatasetcomplete

HRESULT put_ondatasetcomplete(
    VARIANT v
);

Sets the inline script associated with the ondatasetcomplete event on the object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to set.

See also get_ondatasetcomplete


Ondblclick Property

*
  * Previous Topic: IHTMLElement::put_ondblclick
  * Next Topic: IHTMLElement::put_onkeydown

IHTMLElement::get_ondblclick

HRESULT get_ondblclick(
    VARIANT *p
);

Retrieves the inline script associated with the ondblclick event on the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script.

See also put_ondblclick

Up Top of Page

IHTMLElement::put_ondblclick

HRESULT put_ondblclick(
    VARIANT v
);

Sets the inline script associated with the ondblclick event on the object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script.

See also get_ondblclick


Ondragstart Property

*
  * Previous Topic: IHTMLElement::put_ondragstart
  * Next Topic: IHTMLElement::toString

IHTMLElement::get_ondragstart

HRESULT get_ondragstart(
    VARIANT *p
);

Retrieves the inline script associated with the ondragstart event on the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script.

See also put_ondragstart

Up Top of Page

IHTMLElement::put_ondragstart

HRESULT put_ondragstart(
    VARIANT v
);

Sets the inline script associated with the ondragstart event on the object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to set.

See also get_ondragstart


Onerrorupdate Property

*
  * Previous Topic: IHTMLElement::put_onerrorupdate
  * Next Topic: IHTMLElement::put_onrowexit

IHTMLElement::get_onerrorupdate

HRESULT get_onerrorupdate(
    VARIANT *p
);

Retrieves the inline script associated with the onerrorupdate event on the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script.

See also put_onerrorupdate

Up Top of Page

IHTMLElement::put_onerrorupdate

HRESULT put_onerrorupdate(
    VARIANT v
);

Sets the inline script associated with the onerrorupdate event on the object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to set.

See also get_onerrorupdate


Onfilterchange Property

*
  * Previous Topic: IHTMLElement::put_onfilterchange
  * Next Topic: IHTMLElement::get_children

IHTMLElement::get_onfilterchange

HRESULT get_onfilterchange(
    VARIANT *p
);

Retrieves the inline script associated with the onfilterchange event on the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script.

See also put_onfilterchange

Up Top of Page

IHTMLElement::put_onfilterchange

HRESULT put_onfilterchange(
    VARIANT v
);

Sets the inline script associated with the onfilterchange event on the object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to set.

See also get_onfilterchange


Onhelp Property

*
  * Previous Topic: IHTMLElement::put_onhelp
  * Next Topic: IHTMLElement::put_onclick

IHTMLElement::get_onhelp

HRESULT get_onhelp(
    VARIANT *p);

Retrieves the inline script associated with the onhelp event on the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script.

See also put_onhelp

Up Top of Page

IHTMLElement::put_onhelp

HRESULT put_onhelp(
    VARIANT v
);

Sets the inline script associated with the onhelp event on the object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure containing the inline script.

See also get_onhelp


Onkeydown Property

*
  * Previous Topic: IHTMLElement::put_onkeydown
  * Next Topic: IHTMLElement::put_onkeyup

IHTMLElement::get_onkeydown

HRESULT get_onkeydown(
    VARIANT *p
);

Retrieves the inline script associated with the onkeydown event on the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script.

See also put_onkeydown

Up Top of Page

IHTMLElement::put_onkeydown

HRESULT put_onkeydown(
    VARIANT v
);

Sets the inline script associated with the onkeydown event on the object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to set.

See also get_onkeydown


Onkeypress Property

*
  * Previous Topic: IHTMLElement::put_onkeypress
  * Next Topic: IHTMLElement::put_onmouseout

IHTMLElement::get_onkeypress

HRESULT get_onkeypress(
    VARIANT *p
);

Retrieves the inline script associated with the onkeypress event on the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script.

See also put_onkeypress

Up Top of Page

IHTMLElement::put_onkeypress

HRESULT put_onkeypress(
    VARIANT v
);

Sets the inline script associated with the onkeypress event on the object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to set.

See also get_onkeypress


Onkeyup Property

*
  * Previous Topic: IHTMLElement::put_onkeyup
  * Next Topic: IHTMLElement::put_onkeypress

IHTMLElement::get_onkeyup

HRESULT get_onkeyup(
    VARIANT *p
);

Retrieves the inline script associated with the onkeyup event on the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script.

See also put_onkeyup

Up Top of Page

IHTMLElement::put_onkeyup

HRESULT put_onkeyup(
    VARIANT v
);

Sets the inline script associated with the onkeyup event on the object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to set.

See also get_onkeyup


Onmousedown Property

*
  * Previous Topic: IHTMLElement::put_onmousedown
  * Next Topic: IHTMLElement::put_onmouseup

IHTMLElement::get_onmousedown

HRESULT get_onmousedown(
    VARIANT *p
);

Retrieves the inline script associated with the onmousedown event on the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script.

See also put_onmousedown

Up Top of Page

IHTMLElement::put_onmousedown

HRESULT put_onmousedown(
    VARIANT v
);

Sets the inline script associated with the onmousedown event on the object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to set.

See also get_onmousedown


Onmousemove Property

*
  * Previous Topic: IHTMLElement::put_onmousemove
  * Next Topic: IHTMLElement::put_onmousedown

IHTMLElement::get_onmousemove

HRESULT get_onmousemove(
    VARIANT *p
);

Retrieves the inline script associated with the onmousemove event on the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script.

See also put_onmousemove

Up Top of Page

IHTMLElement::put_onmousemove

HRESULT put_onmousemove(
    VARIANT v
);

Sets the inline script associated with the onmousemove event on the object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to set.

See also get_onmousemove


Onmouseout Property

*
  * Previous Topic: IHTMLElement::put_onmouseout
  * Next Topic: IHTMLElement::put_onmouseover

IHTMLElement::get_onmouseout

HRESULT get_onmouseout(
    VARIANT *p
);

Retrieves the inline script associated with the onmouseout event on the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script in.

See also put_onmouseout

Up Top of Page

IHTMLElement::put_onmouseout

HRESULT put_onmouseout(
    VARIANT v
);

Sets the inline script associated with the onmouseout event on the object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to set.

See also get_onmouseout


Onmouseover Property

*
  * Previous Topic: IHTMLElement::put_onmouseover
  * Next Topic: IHTMLElement::put_onmousemove

IHTMLElement::get_onmouseover

HRESULT get_onmouseover(
    VARIANT *p
);

Retrieves the inline script associated with the onkeyup event on the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script.

See also put_onmouseover

Up Top of Page

IHTMLElement::put_onmouseover

HRESULT put_onmouseover(
    VARIANT v
);

Sets the inline script associated with the onmouseover event on the object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to set.

See also get_onmouseover


Onmouseup Property

*
  * Previous Topic: IHTMLElement::put_onmouseup
  * Next Topic: IHTMLElement::get_document

IHTMLElement::get_onmouseup

HRESULT get_onmouseup(
    VARIANT *p
);

Retrieves the inline script associated with the onmouseup event on the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script.

See also put_onmouseup

Up Top of Page

IHTMLElement::put_onmouseup

HRESULT put_onmouseup(
    VARIANT v
);

Sets the inline script associated with the onmouseup event on the object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to set.

See also get_onmouseup


Onrowenter Property

*
  * Previous Topic: IHTMLElement::put_onrowenter
  * Next Topic: IHTMLElement::put_ondatasetchanged

IHTMLElement::get_onrowenter

HRESULT get_onrowenter(
    VARIANT *p
);

Retrieves the inline script associated with the onrowenter event on the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script.

See also put_onrowenter

Up Top of Page

IHTMLElement::put_onrowenter

HRESULT put_onrowenter(
    VARIANT v
);

Sets the inline script associated with the onrowenter event on the object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to set.

See also get_onrowenter


Onrowexit Property

*
  * Previous Topic: IHTMLElement::put_onrowexit
  * Next Topic: IHTMLElement::put_onrowenter

IHTMLElement::get_onrowexit

HRESULT get_onrowexit(
    VARIANT *p
);

Retrieves the inline script associated with the onrowexit event on the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script.

See also put_onrowexit

Up Top of Page

IHTMLElement::put_onrowexit

HRESULT put_onrowexit(
    VARIANT v
);

Sets the inline script associated with the onrowexit event on the object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to set.

See also get_onrowexit


Onselectstart Property

*
  * Previous Topic: IHTMLElement::put_onselectstart
  * Next Topic: IHTMLElement::scrollIntoView

IHTMLElement::get_onselectstart

HRESULT get_onselectstart(
    VARIANT *p
);

Retrieves the inline script associated with the onselect event on the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure to store the script.

See also put_onselectstart

Up Top of Page

IHTMLElement::put_onselectstart

HRESULT put_onselectstart(
    VARIANT v
);

Sets the inline script associated with the onselect event on the object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to set.

See also get_onselectstart


OuterHTML Property

*
  * Previous Topic: IHTMLElement::put_outerHTML
  * Next Topic: IHTMLElement::put_outerText

IHTMLElement::get_outerHTML

HRESULT get_outerHTML(
    BSTR *p
);

Retrieves the current element object and its content in HTML.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the current element object, including its start and end tags, and the element's content in HTML. It can be any valid string containing any combination of text and HTML tags.

You cannot set this property while the document is loading. Wait for the onload event before attempting to set it.

See also put_outerHTML

Up Top of Page

IHTMLElement::put_outerHTML

HRESULT put_outerHTML(
    BSTR v
);

Replaces the current element object and its content with the given HTML.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the replacement HTML. It can be any valid string containing any combination of text and HTML tags.

When setting this property, the given string completely replaces the current element, including its start and end tags. If the string contains HTML tags, the string is parsed and formatted as it is placed into the document.

You cannot set this property while the document is loading. Wait for the onload event before attempting to set it.

See also get_outerHTML


OuterText Property

*
  * Previous Topic: IHTMLElement::put_outerText
  * Next Topic: IHTMLElement::insertAdjacentHTML

IHTMLElement::get_outerText

HRESULT get_outerText(
    BSTR *p
);

Retrieves the outerText property of the current element object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the text of the current element object. It can be any valid string.

You cannot set this property while the document is loading. Wait for the onload event before attempting to set it.

See also put_outerText

Up Top of Page

IHTMLElement::put_outerText

HRESULT put_outerText(
    BSTR v
);

Sets the outerText property of the current element object.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the new text for the current element object. It can be any valid string.

You cannot set this property while the document is loading. Wait for the onload event before attempting to set it.

See also get_outerText


IHTMLElement::removeAttribute

HRESULT removeAttribute(
    BSTR strAttributeName,
    VARIANT_BOOL fCaseSensitive,
    VARIANT_BOOL *pfSuccess
);

Removes the given attribute from the element.

  • Returns S_OK if successful, or an error value otherwise.
strAttributeName
String specifying the name of the attribute to remove.
fCaseSensitive
Boolean value specifying whether to use a case-sensitive search to locate the attribute. If TRUE, the uppercase and lowercase letters in strAttributeName must match exactly those in the attribute name.
pfSuccess
Address of a variable that receives TRUE if the function succeeds, or FALSE otherwise.

If two or more attributes have the same name (differing only in uppercase and lowercase letters) and fCaseSensitive is FALSE, this method removes only the last attribute (the last to be created with this name). All other attributes of the same name are ignored.


IHTMLElement::scrollIntoView

HRESULT scrollIntoView(
    VARIANT varargStart
);

Scrolls the object into view, aligning it at either the top or bottom of the window.

  • Returns S_OK if successful, or an error value otherwise.
varargStart
VARIANT structure containing a Boolean value specifying whether to place the object at the top of the window or at the bottom. If TRUE, the method scrolls the object so that its top is visible at the top of the window. If FALSE, the bottom of the object is visible at the bottom of the window. If no value is given, the object scrolls to the top by default.

Depending on the size of the given object and the current window, this method might not be able to put the item at the very top or very bottom, but will always position the object as close to the requested position as possible.


IHTMLElement::setAttribute

HRESULT setAttribute(
    BSTR strAttributeName,
    VARIANT AttributeValue,
    VARIANT_BOOL fCaseSensitive
);

Sets the value of the given attribute. If the attribute is not already present, the method adds the attribute to the element and sets the value.

  • Returns S_OK if successful, or an error value otherwise.
strAttributeName
String specifying the name of the attribute to set.
AttributeValue
VARIANT structure containing a string, number, or Boolean value to assign to the attribute.
fCaseSensitive
Boolean value specifying whether to use a case-sensitive search to locate the attribute. If TRUE, the uppercase and lowercase letters in strAttributeName must match exactly those in the attribute name.

Be careful when spelling attribute names. If fCaseSensitive is TRUE and strAttributeName does not have the same uppercase and lowercase letters as the attribute, this method creates a new attribute.

If two or more attributes have the same name (differing only in uppercase and lowercase letters) and fCaseSensitive is FALSE, this method assigns values only to the first attribute (the first to be created with this name). All other attributes of the same name are ignored.

See also getAttribute


Title Property

*
  * Previous Topic: IHTMLElement::put_title
  * Next Topic: IHTMLElement::put_language

IHTMLElement::get_title

HRESULT get_title(
    BSTR *p
);

Retrieves the title of the style sheet.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the title. It is FALSE for style sheets that do not specify a title, and that title is not currently selected.

The application of individual style sheets can be turned on and off dynamically. Note that the value of this property is also controlled by whether titled style sheets are applied.

See also put_title

Up Top of Page

IHTMLElement::put_title

HRESULT put_title(
    BSTR v
);

Sets the title of the style sheet.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the title. It is FALSE for style sheets that do not specify a title, and that title is not currently selected.

The application of individual style sheets can be turned on and off dynamically. Note that the value of this property is also controlled by whether titled style sheets are applied.

See also get_title


IHTMLElement::toString

HRESULT toString(
    BSTR *String
);

Retrieves a string representation of the element object.

  • Returns S_OK if successful, or an error value otherwise.
String
Address of a string variable that receives the string representation.


IHTMLImageElementFactory::create

HRESULT create(
    VARIANT width,
    VARIANT height,
    IHTMLImgElement **ppImgElement
);

Creates a new IMG element of the specified width and height.

  • Returns S_OK if successful, or an error value otherwise.
width
Width, in pixels, of the new IMG element.
height
Height, in pixels, of the new IMG element.
ppImgElement
Address of a variable that receives an interface pointer to the new IMG element.

See also IHTMLImgElement


IHTMLImageElementFactory IHTMLImageElementFactory *
  * Previous Topic: IHTMLIFrameElement::get_align
  * Next Topic: IHTMLImageElementFactory::create

IHTMLImageElementFactory

This interface is used to create new instances of the OPTION element.

IHTMLImageElementFactory Methods
create


Align Property

*
  * Previous Topic: IHTMLImgElement::put_align
  * Next Topic: IHTMLImgElement::put_onload

IHTMLImgElement::get_align

HRESULT get_align(
    BSTR *p
);

Retrieves how the element is aligned with adjacent text.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the alignment. Can be one of these values:
absbottom | Aligns the bottom of the element with the absolute bottom of the surrounding text. The absolute bottom is equal to the baseline of the text minus the height of the largest descender in the text.
absmiddle | Aligns the middle of the element with the middle of the surrounding text. The absolute middle is the midpoint between the absolute bottom and texttop of the surrounding text.
baseline | Aligns the bottom of the element with the baseline of the surrounding text.
bottom | Aligns the bottom of the element with the bottom of the surrounding text. The bottom is equal to the baseline minus the standard height of a descender in the text.
left | Aligns the element to the left of the surrounding text. All preceding and subsequent text flows to the right of the element. This is the default value.
middle | Aligns the middle of the element with the surrounding text.
right | Aligns the element to the right of the surrounding text. All subsequent text flows to the left of the element.
texttop | Aligns the top of the element with the absolute top of the surrounding text. The absolute top is the baseline plus the height of the largest ascender in the text.
top | Aligns the top of the element with the top of the text. The top of the text is the baseline plus the standard height of an ascender in the text.

For the INPUT element, this attribute applies only to the image type. It is undefined for all other types.

See also put_align

Up Top of Page

IHTMLImgElement::put_align

HRESULT put_align(
    BSTR v
);

Sets how the element is aligned with adjacent text.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the alignment. Can be one of these values:
absbottom | Aligns the bottom of the element with the absolute bottom of the surrounding text. The absolute bottom is equal to the baseline of the text minus the height of the largest descender in the text.
absmiddle | Aligns the middle of the element with the middle of the surrounding text. The absolute middle is the midpoint between the absolute bottom and texttop of the surrounding text.
baseline | Aligns the bottom of the element with the baseline of the surrounding text.
bottom | Aligns the bottom of the element with the bottom of the surrounding text. The bottom is equal to the baseline minus the standard height of a descender in the text.
left | Aligns the element to the left of the surrounding text. All preceding and subsequent text flows to the right of the element. This is the default value.
middle | Aligns the middle of the element with the surrounding text.
right | Aligns the element to the right of the surrounding text. All subsequent text flows to the left of the element.
texttop | Aligns the top of the element with the absolute top of the surrounding text. The absolute top is the baseline plus the height of the largest ascender in the text.
top | Aligns the top of the element with the top of the text. The top of the text is the baseline plus the standard height of an ascender in the text.

For the INPUT element, this attribute applies only to the image type. It is undefined for all other types.

See also get_align


Alt Property

*
  * Previous Topic: IHTMLImgElement::put_alt
  * Next Topic: IHTMLImgElement::put_src

IHTMLImgElement::get_alt

HRESULT get_alt(
    BSTR *p
);

Retrieves the optional text as an alternative to the graphic for rendering in nongraphical environments. Alternate text should be provided whenever the graphic is not rendered. Alternate text is mandatory for Level 0 documents.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the optional text.

See also put_alt

Up Top of Page

IHTMLImgElement::put_alt

HRESULT put_alt(
    BSTR v
);

Indicates optional text as an alternative to the graphic for rendering in nongraphical environments. Alternate text should be provided whenever the graphic is not rendered. Alternate text is mandatory for Level 0 documents.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the optional text.

See also get_alt


Border Property

*
  * Previous Topic: IHTMLImgElement::put_border
  * Next Topic: IHTMLImgElement::put_vspace

IHTMLImgElement::get_border

HRESULT get_border(
    VARIANT *p
);

Retrieves the current thickness of the border around the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the border thickness.

See also put_border

Up Top of Page

IHTMLImgElement::put_border

HRESULT put_border(
    VARIANT v
);

Sets the thickness of the border around the element.

  • Returns S_OK if successful, or an error value otherwise.
v
A string or value specifying the border thickness.

See also get_border


Dynsrc Property

*
  * Previous Topic: IHTMLImgElement::put_dynsrc
  * Next Topic: IHTMLImgElement::get_readyState

IHTMLImgElement::get_dynsrc

HRESULT get_dynsrc(
    BSTR *p
);

Retrieves the address of a video clip or VRML world to be displayed in the window. Stands for Dynamic Source.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the address.

See also put_dynsrc

Up Top of Page

IHTMLImgElement::put_dynsrc

HRESULT put_dynsrc(
    BSTR v
);

Sets the address of a video clip or VRML world to be displayed in the window. Stands for Dynamic Source.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the address.

See also get_dynsrc


IHTMLImgElement::get_complete

HRESULT get_complete(
    VARIANT_BOOL *p
);

Retrieves whether the specified element is fully loaded.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives TRUE if the element is fully loaded, or FALSE otherwise.


IHTMLImgElement::get_fileCreatedDate

HRESULT get_fileCreatedDate(
    BSTR *p
);

Retrieves the creation date of the image file associated with the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the creation date. The date consists of the weekday, month, date, and year.


IHTMLImgElement::get_fileModifiedDate

HRESULT get_fileModifiedDate(
    BSTR *p
);

Retrieves the date when the image file associated with the element was most recently modified.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the modification date. The date consists of the weekday, month, date, and year.


IHTMLImgElement::get_fileSize

HRESULT get_fileSize(
    BSTR *p
);

Retrieves the size, in bytes, of the image file associated with the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the file size.


IHTMLImgElement::get_fileUpdatedDate

HRESULT get_fileUpdatedDate(
    BSTR *p
);

Retrieves the date when the image file associated with the element was last updated.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the date. The date consists of the weekday, month, date, and year.


IHTMLImgElement::get_href

HRESULT get_href(
    BSTR *p
);

Retrieves the entire URL that the browser uses to locate the image or video clip associated with the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the URL.


IHTMLImgElement::get_mimeType

HRESULT get_mimeType(
    BSTR *p
);

Retrieves the MIME type for the file.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the MIME type. This parameter receives "text/html" for HTML files.


IHTMLImgElement::get_nameProp

HRESULT get_nameProp(
    BSTR *p
);

Retrieves the file name from the URL that the browser uses to locate the image or video clip associated with the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the file name.


IHTMLImgElement::get_protocol

HRESULT get_protocol(
    BSTR *p
);

Retrieves the protocol portion of the URL that the browser uses to locate the image or video clip associated with the element. The protocol portion, which indicates the access method, includes the initial substring of the URL up to and including the first colon.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the protocol.


IHTMLImgElement::get_readyState

HRESULT get_readyState(
    BSTR *p
);

Retrieves the current state of an object being downloaded.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the state. Can be one of these values:
complete | The object is completely loaded.
interactive | The object can be interacted with even though it is not fully loaded.
loading | The object is currently being loaded.
unitialized | The object is not created. Usually when the object is being downloaded.

Each object can independently determine which of the states they expose.


Height Property

*
  * Previous Topic: IHTMLImgElement::put_height
  * Next Topic: IHTMLImgElement::put_start

IHTMLImgElement::get_height

HRESULT get_height(
    long *p
);

Retrieves the calculated height of the element, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the height.

If the value of the corresponding HTML attribute was set using a percentage, this property specifies the height in pixels represented by that percentage.

See also put_height

Up Top of Page

IHTMLImgElement::put_height

HRESULT put_height(
    long v
);

Sets the calculated height of the element, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the height.

If the value of the corresponding HTML attribute was set using a percentage, this property specifies the height in pixels represented by that percentage.

See also get_height


Hspace Property

*
  * Previous Topic: IHTMLImgElement::put_hspace
  * Next Topic: IHTMLImgElement::put_alt

IHTMLImgElement::get_hspace

HRESULT get_hspace(
    long *p
);

Retrieves the horizontal margins for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the horizontal margins.

Similar to border, except the margins are not painted with color when the element is a link.

See also put_hspace

Up Top of Page

IHTMLImgElement::put_hspace

HRESULT put_hspace(
    long v
);

Sets the horizontal margins for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the horizontal margins.

Similar to border, except the margins are not painted with color when the element is a link.

See also get_hspace


IHTMLImgElement

This interface provides access to some of the properties and methods supported by the IMG element and the INPUT element of the image type. The other properties and methods are accessible through the IHTMLImgElement interface.

The IMG element embeds an image or a video clip in a document. It supports the onfocus event and can receive the input focus only if it has been associated with a MAP element.

IHTMLImgElement Methods
put_isMap get_isMap put_useMap
get_useMap get_mimeType get_fileSize
get_fileCreatedDate get_fileModifiedDate get_fileUpdatedDate
get_protocol get_href get_nameProp
put_border get_border put_vspace
get_vspace put_hspace get_hspace
put_alt get_alt put_src
get_src put_lowsrc get_lowsrc
put_vrml get_vrml get_dynsrc
get_readyState get_complete put_loop
get_loop put_align get_align
put_onload get_onload put_onerror
get_onerror put_onabort get_onabort
put_name get_name put_width
get_width put_height get_height
put_start get_start

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


IsMap Property

*
  * Previous Topic: IHTMLImgElement::put_isMap
  * Next Topic: IHTMLImgElement::put_useMap

IHTMLImgElement::get_isMap

HRESULT get_isMap(
    VARIANT_BOOL *p
);

Determines whether the picture is a server-side image map.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives TRUE if the picture is a server-side image map, or FALSE if not.

See also put_isMap

Up Top of Page

IHTMLImgElement::put_isMap

HRESULT put_isMap(
    VARIANT_BOOL v
);

Specifies whether the picture is a server-side image map.

  • Returns S_OK if successful, or an error value otherwise.
v
Boolean value that, if TRUE, specifies that the picture is a server-side image map.

See also get_isMap


Loop Property

*
  * Previous Topic: IHTMLImgElement::put_loop
  * Next Topic: IHTMLImgElement::put_align

IHTMLImgElement::get_loop

HRESULT get_loop(
    VARIANT *p
);

Retrieves the number of times a video loops when activated.

  • Returns S_OK if successful, or an error value otherwise.
p
Value specifying the number of times to loop. If this parameter receives -1 (infinite), the video will loop continuously.

Below are descriptions on how loop works for some boundary cases.
<BGSOUND src="file:///c:\win95\system\msremind.wav"> | once
<BGSOUND src="file:///c:\win95\system\msremind.wav" LOOP> | once
<BGSOUND src="file:///c:\win95\system\msremind.wav" LOOP=> | zero times
<BGSOUND src="file:///c:\win95\system\msremind.wav" LOOP=-1> | infinitely
<BGSOUND src="file:///c:\win95\system\msremind.wav" LOOP=0> | once

See also put_loop

Up Top of Page

IHTMLImgElement::put_loop

HRESULT put_loop(
    VARIANT v
);

Sets the number of times a video will loop when activated.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the number of times to loop. If this parameter is -1 (infinite), the video will loop continuously.

Below are descriptions on how loop works for some boundary cases.
<BGSOUND src="file:///c:\win95\system\msremind.wav"> | once
<BGSOUND src="file:///c:\win95\system\msremind.wav" LOOP> | once
<BGSOUND src="file:///c:\win95\system\msremind.wav" LOOP=> | zero times
<BGSOUND src="file:///c:\win95\system\msremind.wav" LOOP=-1> | infinitely
<BGSOUND src="file:///c:\win95\system\msremind.wav" LOOP=0> | once

See also get_loop


Lowsrc Property

*
  * Previous Topic: IHTMLImgElement::put_lowsrc
  * Next Topic: IHTMLImgElement::put_vrml

IHTMLImgElement::get_lowsrc

HRESULT get_lowsrc(
    BSTR *p
);

Retrieves the URL of a lower-resolution image to display.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the URL.

Setting the SRC= attribute in code has the side-effect of actually starting to load the new URL into the image area (and aborting the transfer of any image data that is already loading into the same area). Therefore, you should alter the lowsrc property before setting the src property. If the URL in the src property refers to an image that is not the same size as the image cell it is loaded into, the source image is scaled to fit.

See also put_lowsrc

Up Top of Page

IHTMLImgElement::put_lowsrc

HRESULT put_lowsrc(
    BSTR v
);

Specifies the URL of a lower-resolution image to display.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the URL.

Setting the SRC= attribute in code has the side-effect of actually starting to load the new URL into the image area (and aborting the transfer of any image data that is already loading into the same area). Therefore, you should alter the lowsrc property before setting the src property. If the URL in the src property refers to an image that is not the same size as the image cell it is loaded into, the source image is scaled to fit.

See also get_lowsrc


Name Property

*
  * Previous Topic: IHTMLImgElement::put_name
  * Next Topic: IHTMLImgElement::put_width

IHTMLImgElement::get_name

HRESULT get_name(
    BSTR *p
);

Retrieves the name of the control.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the name.

The name is used to bind the value of the control when submitting a form. The NAME is not the value that is displayed for the button, reset, and submit objects. Submitting the form submits the internally stored value, not the one displayed.

JScript allows the name to be changed at run time. This does not change the name in the programming model, in the collection of elements, but does change the name used for submitting elements.

See also put_name

Up Top of Page

IHTMLImgElement::put_name

HRESULT put_name(
    BSTR v
);

Sets the name of the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the name.

The name is used to bind the value of the control when submitting a form. The NAME is not the value that is displayed for the button, reset, and submit objects. Submitting the form submits the internally stored value, not the one displayed.

JScript allows the name to be changed at run time. This does not change the name in the programming model, in the collection of elements, but does change the name used for submitting elements.

See also get_name


Onabort Property

*
  * Previous Topic: IHTMLImgElement::put_onabort
  * Next Topic: IHTMLImgElement::put_name

IHTMLImgElement::get_onabort

HRESULT get_onabort(
    VARIANT *p
);

Retrieves the inline script associated with the onabort event for an IMG element. The onabort event occurs when the user aborts the download of the image.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the script.

See also put_onabort

Up Top of Page

IHTMLImgElement::put_onabort

HRESULT put_onabort(
    VARIANT v
);

Sets the inline script associated with the onabort event for an IMG element. The onabort event occurs when the user aborts the download of the image.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the new script.

See also get_onabort


Onerror Property

*
  * Previous Topic: IHTMLImgElement::put_onerror
  * Next Topic: IHTMLImgElement::put_onabort

IHTMLImgElement::get_onerror

HRESULT get_onerror(
    VARIANT *p
);

Retrieves the inline script associated with the onerror event for an IMG element. The onerror event occurs when the loading of a document or image causes an error.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the script.

See also put_onerror

Up Top of Page

IHTMLImgElement::put_onerror

HRESULT put_onerror(
    VARIANT v
);

Sets the inline script associated with the onerror event for an IMG element. The onerror event occurs when the loading of a document or image causes an error.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the new script.

See also get_onerror


Onload Property

*
  * Previous Topic: IHTMLImgElement::put_onload
  * Next Topic: IHTMLImgElement::put_onerror

IHTMLImgElement::get_onload

HRESULT get_onload(
    VARIANT *p
);

Retrieves the inline script associated with the onload event for an IMG element. The onload event occurs immediately after the browser loads the given object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the script.

See also put_onload

Up Top of Page

IHTMLImgElement::put_onload

HRESULT put_onload(
    VARIANT v
);

Sets the inline script associated with the onload event for an IMG element. The onload event occurs immediately after the browser loads the given object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the new script.

See also get_onload


Src Property

*
  * Previous Topic: IHTMLImgElement::put_src
  * Next Topic: IHTMLImgElement::put_lowsrc

IHTMLImgElement::get_src

HRESULT get_src(
    BSTR *p
);

Retrieves the URL of a sound to be played.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the URL.

See also put_src

Up Top of Page

IHTMLImgElement::put_src

HRESULT put_src(
    BSTR v
);

Sets the URL of an image to be shown.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the URL.

See also get_src


Start Property

*
  * Previous Topic: IHTMLImgElement::put_start
  * Next Topic: IHTMLInputButtonElement

IHTMLImgElement::get_start

HRESULT get_start(
    BSTR *p
);

Retrieves when a video clip should start playing.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives one of these values:
fileopen | The video starts as soon as it is finished loading.
mouseover | The video starts when the mouse goes over the animation.

See also put_start

Up Top of Page

IHTMLImgElement::put_start

HRESULT put_start(
    BSTR v
);

Specifies when a video clip file should start playing.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying when to start the video. Can be one of these values:
fileopen | The video starts as soon as it is finished loading.
mouseover | The video starts when the mouse goes over the animation.

See also get_start


UseMap Property

*
  * Previous Topic: IHTMLImgElement::put_useMap
  * Next Topic: IHTMLImgElement::get_mimeType

IHTMLImgElement::get_useMap

HRESULT get_useMap(
    BSTR *p
);

Retrieves the URL used as a client-side image map. The URL includes the bookmark extension (#name), if any.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the URL.

See also put_useMap

Up Top of Page

IHTMLImgElement::put_useMap

HRESULT put_useMap(
    BSTR v
);

Identifies a URL, often with a bookmark extension (#name), to use as a client-side image map.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the URL.

See also get_useMap


Vrml Property

*
  * Previous Topic: IHTMLImgElement::put_vrml
  * Next Topic: IHTMLImgElement::put_dynsrc

IHTMLImgElement::get_vrml

HRESULT get_vrml(
    BSTR *p
);

Retrieves the URL of the VRML world to be displayed in the window.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the URL.

See also put_vrml

Up Top of Page

IHTMLImgElement::put_vrml

HRESULT put_vrml(
    BSTR v
);

Specifies the URL of a VRML world to be displayed in the window.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the URL.

See also get_vrml


Vspace Property

*
  * Previous Topic: IHTMLImgElement::put_vspace
  * Next Topic: IHTMLImgElement::put_hspace

IHTMLImgElement::get_vspace

HRESULT get_vspace(
    long *p
);

Retrieves the vertical margins for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the vertical margins.

Similar to border, except the margins are not painted with color when the element is a link.

See also put_vspace

Up Top of Page

IHTMLImgElement::put_vspace

HRESULT put_vspace(
    long v
);

Sets the vertical margins for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the margins.

Similar to border, except the margins are not painted with color when the element is a link.

See also get_vspace


Width Property

*
  * Previous Topic: IHTMLImgElement::put_width
  * Next Topic: IHTMLImgElement::put_height

IHTMLImgElement::get_width

HRESULT get_width(
    long *p
);

Retrieves the calculated width of the element, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the width.

This property is an integer value. Although an HTML author can specify the width as a percentage, this property always specifies the width in pixels.

See also put_width

Up Top of Page

IHTMLImgElement::put_width

HRESULT put_width(
    long v
);

Sets the calculated width of the element, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the width.

This property is an integer value. Although an HTML author can specify the width as a percentage, this property always specifies the width in pixels.

See also get_width


Disabled Property

*
  * Previous Topic: IHTMLInputButtonElement::put_disabled
  * Next Topic: IHTMLInputButtonElement::get_form

IHTMLInputButtonElement::get_disabled

HRESULT get_disabled(
    VARIANT_BOOL *p
);

Determines whether the INPUT button control is enabled or disabled.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives TRUE if the control is disabled, or FALSE otherwise.

The default value for this property is FALSE.

See also put_disabled

Up Top of Page

IHTMLInputButtonElement::put_disabled

HRESULT put_disabled(
    VARIANT_BOOL v
);

Enables or disables the INPUT button control. A disabled control appears dimmed and does not respond to user input.

  • Returns S_OK if successful, or an error value otherwise.
v
Boolean value specifying whether to disable the control. If TRUE, the control is disabled; otherwise, it is enabled.

The default value for this property is FALSE.

See also get_disabled


IHTMLInputButtonElement::get_form

HRESULT get_form(
     IHTMLFormElement **p
);

Retrieves a reference to the form on which the INPUT button control is embedded.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives an interface pointer to the form element. This parameter receives NULL if the element is not on a form.

See also IHTMLFormElement


IHTMLInputButtonElement::get_type

HRESULT get_type(
    BSTR *p
);

Retrieves the type of intrinsic control represented by the given element object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the control type. The possible values depend on the element as listed in the following table.

Element | Possible value | Description
INPUT | checkbox | Used for simple Boolean attributes or for attributes that can take multiple values at the same time. It is represented by a number of check box fields, each of which has the same name. Each selected check box generates a separate name/value pair in the submitted data, even if this results in duplicate names. The default value for check boxes is on.
file | A file upload element.
hidden | No field is presented to the user, but the content of the field is sent with the submitted form. This value can be used to transmit state information about client/server interaction.
image | An image field that you can click, causing the form to be immediately submitted. The coordinates of the selected point are measured in pixel units from the upper-left corner of the image, and are returned (along with the other contents of the form) in two name/value pairs. The x-coordinate is submitted under the name of the field with .x appended, and the y-coordinate is submitted under the name of the field with .y appended. Any value property is ignored. The image itself is specified by the SRC attribute, exactly as for the Image element.
password | Same as the TEXT attribute, except that text is not displayed as the user enters it.
radio | Used for attributes that accept a single value from a set of alternatives. Each radio-button field in the group should be given the same name. Only the selected radio button in the group generates a name/value pair in the submitted data. Radio buttons require an explicit value property.
reset | reset is a button that when clicked resets the form's fields to their specified initial values. The label to be displayed on the button can be specified just as for the submit button.
submit | submit is a button that when clicked submits the form. You can use the value attribute to provide a non-editable label to be displayed on the button. The default label is application-specific. If a submit button is clicked to submit the form, and that button has a name attribute specified, that button contributes a name/value pair to the submitted data. Otherwise, a submit button makes no contribution to the submitted data.
text | Used for a single-line text-entry field. Use in conjunction with the size and maxLength properties.
SELECT | select-multiple | Specifies a multiple-select list box.
select-one | Specifies a single-select list box.
TEXTAREA | textarea | Used for multiple-line text-entry fields. Use in conjunction with the size and maxLength properties.


IHTMLInputButtonElement

This interface specifies a form input control.

IHTMLInputButtonElement Methods
get_type put_value get_value
put_name get_name put_status
get_status put_disabled get_disabled
get_form


Name Property

*
  * Previous Topic: IHTMLInputButtonElement::put_name
  * Next Topic: IHTMLInputButtonElement::put_status

IHTMLInputButtonElement::get_name

HRESULT get_name(
    BSTR *p
);

Retrieves the name of the INPUT button control.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the name.

The name is used to bind the value of the control when submitting a form. The NAME is not the value that is displayed for the button, reset, and submit objects. Submitting the form submits the internally stored value, not the one displayed.

JScript allows the name to be changed at run time. This does not change the name in the programming model, in the collection of elements, but does change the name used for submitting elements.

See also put_name

Up Top of Page

IHTMLInputButtonElement::put_name

HRESULT put_name(
    BSTR v
);

Sets the name of the INPUT button control.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the name.

The name is used to bind the value of the control when submitting a form. The NAME is not the value that is displayed for the button, reset, and submit objects. Submitting the form submits the internally stored value, not the one displayed.

JScript allows the name to be changed at run time. This does not change the name in the programming model, in the collection of elements, but does change the name used for submitting elements.

See also get_name


Status Property

*
  * Previous Topic: IHTMLInputButtonElement::put_status
  * Next Topic: IHTMLInputButtonElement::put_disabled

IHTMLInputButtonElement::get_status

HRESULT get_status(
    VARIANT *p
);

Retrieves the status of the INPUT button control.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the status. Can be TRUE, FALSE, or NULL.

See also put_status

Up Top of Page

IHTMLInputButtonElement::put_status

HRESULT put_status(
    VARIANT v
);

Sets the status of the INPUT control.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the status. Can be TRUE, FALSE, or NULL.

See also get_status


Value Property

*
  * Previous Topic: IHTMLInputButtonElement::put_value
  * Next Topic: IHTMLInputButtonElement::put_name

IHTMLInputButtonElement::get_value

HRESULT get_value(
    BSTR *p
);

Retrieves the default or "selected" value of the given control.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value. The purpose of the string depends on the type of control as described in the following table.

Control Type | Description
checkbox | The "selected" value. The control submits this value only if the user has selected the control. Otherwise, the control submits no value.
file | The value, a file name, typed by the user into the control. Unlike other controls, this value is read-only.
hidden | The control submits this value when the form is submitted.
OPTION | The "selected" value. The containing list box control submits this value only if the user has selected the option.
password | The default value. The control displays this value when it is first created and when the user clicks the reset button.
radio | The "selected" value. The control submits this value only if the user has selected the control. Otherwise, the control submits no value.
reset | The button label. If not set, the label defaults to "Reset".
submit | The button label. If not set, the label defaults to "Submit".
text | The default value. The control displays this value when it is first created and when the user clicks the reset button.

See also put_value

Up Top of Page

IHTMLInputButtonElement::put_value

HRESULT put_value(
    BSTR v
);

Sets the default or "selected" value of the given control.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the value. The purpose of the value depends on the type of control as described in the following table.

Control type | Description
checkbox | The "selected" value. The control submits this value only if the user has selected the control. Otherwise, the control submits no value.
file | The value, a file name, typed by the user into the control. Unlike other controls, this value is read-only.
hidden | The control submits this value when the form is submitted.
OPTION | The "selected" value. The containing list box control submits this value only if the user has selected the option.
password | The default value. The control displays this value when it is first created and when the user clicks the reset button.
radio | The "selected" value. The control submits this value only if the user has selected the control. Otherwise, the control submits no value.
reset | The button label. If not set, the label defaults to "Reset".
submit | The button label. If not set, the label defaults to "Submit".
text | The default value. The control displays this value when it is first created and when the user clicks the reset button.

See also get_value


Disabled Property

*
  * Previous Topic: IHTMLInputFileElement::put_disabled
  * Next Topic: IHTMLInputFileElement::get_form

IHTMLInputFileElement::get_disabled

HRESULT get_disabled(
    VARIANT_BOOL *p
);

Determines whether the INPUT file control is enabled or disabled.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives TRUE if the control is disabled, or FALSE otherwise.

The default value for this property is FALSE.

See also put_disabled

Up Top of Page

IHTMLInputFileElement::put_disabled

HRESULT put_disabled(
    VARIANT_BOOL v
);

Enables or disables the INPUT file control. A disabled control appears dimmed and does not respond to user input.

  • Returns S_OK if successful, or an error value otherwise.
v
Boolean value specifying whether to disable the control. If TRUE, the control is disabled; otherwise, it is enabled.

The default value for this property is FALSE.

See also get_disabled


IHTMLInputFileElement::get_form

HRESULT get_form(
    IHTMLFormElement **p
);

Retrieves a reference to the form the element is embedded on.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives an interface pointer to the form element. This parameter receives NULL if the element is not on a form.

See also IHTMLFormElement


IHTMLInputFileElement::get_type

HRESULT get_type(
    BSTR *p
);

Retrieves the type of intrinsic control represented by the given element object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the intrinsic-control type. The possible values depend on the element as listed in the following table.

Element | Possible value | Description
INPUT | checkbox | Used for simple Boolean attributes or for attributes that can take multiple values at the same time. It is represented by a number of check box fields, each of which has the same name. Each selected check box generates a separate name/value pair in the submitted data, even if this results in duplicate names. The default value for check boxes is on.
file | A file upload element.
hidden | No field is presented to the user, but the content of the field is sent with the submitted form. This value can be used to transmit state information about client/server interaction.
image | An image field that you can click, causing the form to be immediately submitted. The coordinates of the selected point are measured in pixel units from the upper-left corner of the image, and are returned (along with the other contents of the form) in two name/value pairs. The x-coordinate is submitted under the name of the field with .x appended, and the y-coordinate is submitted under the name of the field with .y appended. Any value property is ignored. The image itself is specified by the SRC attribute, exactly as for the Image element.
password | Same as the TEXT attribute, except that text is not displayed as the user enters it.
radio | Used for attributes that accept a single value from a set of alternatives. Each radio-button field in the group should be given the same name. Only the selected radio button in the group generates a name/value pair in the submitted data. Radio buttons require an explicit value property.
reset | reset is a button that when clicked resets the form's fields to their specified initial values. The label to be displayed on the button can be specified just as for the submit button.
submit | submit is a button that when clicked submits the form. You can use the value attribute to provide a non-editable label to be displayed on the button. The default label is application-specific. If a submit button is clicked to submit the form, and that button has a name attribute specified, that button contributes a name/value pair to the submitted data. Otherwise, a submit button makes no contribution to the submitted data.
text | Used for a single-line text-entry field. Use in conjunction with the size and maxLength properties.
SELECT | select-multiple | Specifies a multiple-select list box.
select-one | Specifies a single-select list box.
TEXTAREA | textarea | Used for multiple-line text-entry fields. Use in conjunction with the size and maxLength properties.


IHTMLInputFileElement

This interface specifies a form input control.

IHTMLInputFileElement Methods
get_type put_name get_name
put_status get_status put_disabled
get_disabled get_form put_size
get_size put_maxLength get_maxLength
select put_onchange get_onchange
put_onselect get_onselect put_value
get_value


MaxLength Property

*
  * Previous Topic: IHTMLInputFileElement::put_maxLength
  * Next Topic: IHTMLInputFileElement::select

IHTMLInputFileElement::get_maxLength

HRESULT get_maxLength(
    long *p
);

Retrieves the maximum number of characters that can be entered into the control.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the maximum number of characters.

This can be larger than the size of the textbox. When this occurs, the textbox should scroll accordingly as the user types. The default is there is no limit.

See also put_maxLength

Up Top of Page

IHTMLInputFileElement::put_maxLength

HRESULT put_maxLength(
    long v
);

Sets the maximum number of characters that can be entered into the control.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the length.

This can be larger than the size of the control. When this occurs, the control scrolls accordingly as the user types. The default is there is no limit.

See also get_maxLength


Name Property

*
  * Previous Topic: IHTMLInputFileElement::put_name
  * Next Topic: IHTMLInputFileElement::put_status

IHTMLInputFileElement::get_name

HRESULT get_name(
    BSTR *p
);

Retrieves the name of the control, bookmark, or application.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the name.

The name is used to bind the value of the control when submitting a form. The NAME is not the value that is displayed for the button, reset, and submit objects. Submitting the form submits the internally stored value, not the one displayed.

JScript allows the name to be changed at run time. This does not change the name in the programming model, in the collection of elements, but does change the name used for submitting elements.

See also put_name

Up Top of Page

IHTMLInputFileElement::put_name

HRESULT put_name(
    BSTR v
);

Sets the name of the control, bookmark, or application.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the name.

The name is used to bind the value of the control when submitting a form. The NAME is not the value that is displayed for the button, reset, and submit objects. Submitting the form submits the internally stored value, not the one displayed.

JScript allows the name to be changed at run time. This does not change the name in the programming model, in the collection of elements, but does change the name used for submitting elements.

See also get_name


Onchange Property

*
  * Previous Topic: IHTMLInputFileElement::put_onchange
  * Next Topic: IHTMLInputFileElement::put_onselect

IHTMLInputFileElement::get_onchange

HRESULT get_onchange(
    VARIANT *p
);

Retrieves the inline script associated with the onchange event for an INPUT type=file element. An onchange event occurs when the content of the object has changed.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the script.

See also put_onchange

Up Top of Page

IHTMLInputFileElement::put_onchange

HRESULT put_onchange(
    VARIANT v
);

Sets the inline script associated with the onchange event for an INPUT type=file element. An onchange event occurs when the content of the object has changed.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the new script.

See also get_onchange


Onselect Property

*
  * Previous Topic: IHTMLInputFileElement::put_onselect
  * Next Topic: IHTMLInputFileElement::put_value

IHTMLInputFileElement::get_onselect

HRESULT get_onselect(
    VARIANT *p
);

Retrieves the inline script associated with the onselect event for an INPUT type=file element. An onselect event occurs at the beginning of a user-initiated select. This event can be canceled, and it participates in the bubbling model.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the script.

See also put_onselect

Up Top of Page

IHTMLInputFileElement::put_onselect

HRESULT put_onselect(
    VARIANT v
);

Sets the inline script associated with the onselect event for an INPUT type=file element. An onselect event occurs at the beginning of a user-initiated select. This event can be canceled, and it participates in the bubbling model.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the new script.

See also get_onselect


IHTMLInputFileElement::select

HRESULT select(
    void
);

Highlights the input area of the INPUT file control.

  • Returns S_OK if successful, or an error value otherwise.

You can use the select method with the focus method to highlight a field and position the cursor for a user response.


Size Property

*
  * Previous Topic: IHTMLInputFileElement::put_size
  * Next Topic: IHTMLInputFileElement::put_maxLength

IHTMLInputFileElement::get_size

HRESULT get_size(
    long *p
);

Retrieves the size of the control.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the size, in characters.

See also put_size

Up Top of Page

IHTMLInputFileElement::put_size

HRESULT put_size(
    long v
);

Sets the size of the control.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the size, in characters.

See also get_size


Status Property

*
  * Previous Topic: IHTMLInputFileElement::put_status
  * Next Topic: IHTMLInputFileElement::put_disabled

IHTMLInputFileElement::get_status

HRESULT get_status(
    VARIANT *p
);

Retrieves the status of the INPUT file control.

  • Returns S_OK if successful, or an error value otherwise.
v
Address of a variable that receives the status.

See also put_status

Up Top of Page

IHTMLInputFileElement::put_status

HRESULT put_status(
    VARIANT v
);

Sets the status of the INPUT file control.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the status.

See also get_status


Value Property

*
  * Previous Topic: IHTMLInputFileElement::put_value
  * Next Topic: IHTMLInputHiddenElement

IHTMLInputFileElement::get_value

HRESULT get_value(
    BSTR *p
);

Retrieves the value of the INPUT file control.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value.

See also put_value

Up Top of Page

IHTMLInputFileElement::put_value

HRESULT put_value(
    BSTR v
);

Sets the value of the INPUT file control.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the value.

See also get_value


IHTMLInputHiddenElement::createTextRange

HRESULT createTextRange(
    IHTMLTxtRange **range
);

Creates a text range object for the element. You use a text range to examine and modify the text within the element.

  • Returns S_OK if successful, or an error value otherwise.
range
Address of a variable that receives an interface pointer to the text range.

See also IHTMLTxtRange


Disabled Property

*
  * Previous Topic: IHTMLInputHiddenElement::put_disabled
  * Next Topic: IHTMLInputHiddenElement::get_form

IHTMLInputHiddenElement::get_disabled

HRESULT get_disabled(
    VARIANT_BOOL *p
);

Determines whether the control is enabled or disabled.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives TRUE if the control is disabled, or FALSE otherwise.

The default value for this property is FALSE.

See also put_disabled

Up Top of Page

IHTMLInputHiddenElement::put_disabled

HRESULT put_disabled(
    VARIANT_BOOL v
);

Enables or disables the control. A disabled control appears dimmed and does not respond to user input.

  • Returns S_OK if successful, or an error value otherwise.
v
Boolean value specifying whether to disable the control. If TRUE, the control is disabled; otherwise, it is enabled.

The default value for this property is FALSE.

See also get_disabled


IHTMLInputHiddenElement::get_form

HRESULT get_form(
    IHTMLFormElement **p
);

Retrieves a reference to the form the element is embedded on.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives an interface pointer to the form.

Returns NULL if the element is not on a form.

See also IHTMLFormElement


IHTMLInputHiddenElement::get_type

HRESULT get_type(
    BSTR *p
);

Retrieves the type of intrinsic control represented by the given element object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the type. The possible values depend on the element as listed in the following table.

Element | Possible Value | Description
INPUT | checkbox | Used for simple Boolean attributes or for attributes that can take multiple values at the same time. It is represented by a number of check box fields, each of which has the same name. Each selected check box generates a separate name/value pair in the submitted data, even if this results in duplicate names. The default value for check boxes is on.
file | A file upload element.
hidden | No field is presented to the user, but the content of the field is sent with the submitted form. This value can be used to transmit state information about client/server interaction.
image | An image field which you can click, causing the form to be immediately submitted. The coordinates of the selected point are measured in pixel units from the upper-left corner of the image, and are returned (along with the other contents of the form) in two name/value pairs. The x-coordinate is submitted under the name of the field with .x appended, and the y-coordinate is submitted under the name of the field with .y appended. Any value property is ignored. The image itself is specified by the SRC attribute, exactly as for the Image element.
password | The same as the TEXT attribute, except that text is not displayed as the user enters it.
radio | Used for attributes that accept a single value from a set of alternatives. Each radio-button field in the group should be given the same name. Only the selected radio button in the group generates a name/value pair in the submitted data. Radio buttons require an explicit value property.
reset | reset is a button that when clicked resets the form's fields to their specified initial values. The label to be displayed on the button can be specified just as for the submit button.
submit | submit is a button that when clicked submits the form. You can use the value attribute to provide a non-editable label to be displayed on the button. The default label is application-specific. If a submit button is clicked to submit the form, and that button has a name attribute specified, then that button contributes a name/value pair to the submitted data. Otherwise, a submit button makes no contribution to the submitted data.
text | Used for a single-line text-entry field. Use in conjunction with the size and maxLength property.
SELECT | select-multiple | Specifies a multiple-select list box.
select-one | Specifies a single-select list box.
TEXTAREA | textarea | Used for multiple-line text-entry fields. Use in conjunction with the size and maxLength properties.


IHTMLInputHiddenElement

This interface specifies a form input control.

IHTMLInputHiddenElement Methods
get_type put_value get_value
put_name get_name put_status
get_status put_disabled get_disabled
get_form createTextRange

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


Name Property

*
  * Previous Topic: IHTMLInputHiddenElement::put_name
  * Next Topic: IHTMLInputHiddenElement::put_status

IHTMLInputHiddenElement::get_name

HRESULT get_name(
    BSTR *p
);

Retrieves the name of the control, bookmark, or application.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the name.

The name is used to bind the value of the control when submitting a form. The NAME is not the value that is displayed for the button, reset, and submit objects. Submitting the form submits the internally stored value, not the one displayed.

JScript allows the name to be changed at run time. This does not change the name in the programming model, in the collection of elements, but does change the name used for submitting elements.

See also put_name

Up Top of Page

IHTMLInputHiddenElement::put_name

HRESULT put_name(
    BSTR v
);

Sets the name of the control, bookmark, or application.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the name.

The name is used to bind the value of the control when submitting a form. The NAME is not the value that is displayed for the button, reset, and submit objects. Submitting the form submits the internally stored value, not the one displayed.

JScript allows the name to be changed at run time. This does not change the name in the programming model, in the collection of elements, but does change the name used for submitting elements.

See also get_name


Status Property

*
  * Previous Topic: IHTMLInputHiddenElement::put_status
  * Next Topic: IHTMLInputHiddenElement::put_disabled

IHTMLInputHiddenElement::get_status

HRESULT get_status(
    VARIANT *p
);

Retrieves the value of a check box or radio button. This property is equivalent to the value property for check boxes and radio buttons.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value.

See also put_status

Up Top of Page

IHTMLInputHiddenElement::put_status

HRESULT put_status(
    VARIANT v
);

Sets the value of a check box or radio button. This property is equivalent to the value property for check boxes and radio buttons.

  • Returns S_OK if successful, or an error value otherwise.
v
Value of the check box or radio button.

See also get_status


Value Property

*
  * Previous Topic: IHTMLInputHiddenElement::put_value
  * Next Topic: IHTMLInputHiddenElement::put_name

IHTMLInputHiddenElement::get_value

HRESULT get_value(
    BSTR *p
);

Retrieves the default or "selected" value of the given control.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value. It can be any valid string. The purpose of the string depends on the type of control as described in the following table.

Control type | Description
checkbox | The "selected" value. The control submits this value only if the user has selected the control. Otherwise, the control submits no value.
file | The value, a file name, typed by the user into the control. Unlike other controls, this value is read-only.
hidden | The control submits this value when the form is submitted.
OPTION | The "selected" value. The containing list box control submits this value only if the user has selected the option.
password | The default value. The control displays this value when it is first created and when the user clicks the reset button.
radio | The "selected" value. The control submits this value only if the user has selected the control. Otherwise, the control submits no value.
reset | The button label. If not set, the label defaults to "Reset".
submit | The button label. If not set, the label defaults to "Submit".
text | The default value. The control displays this value when it is first created and when the user clicks the reset button.

See also put_value

Up Top of Page

IHTMLInputHiddenElement::put_value

HRESULT put_value(
    BSTR v
);

Sets the default or "selected" value of the given control.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the value. It can be any valid string. The purpose of the string depends on the type of control as described in the following table.

Control type | Description
checkbox | The "selected" value. The control submits this value only if the user has selected the control. Otherwise, the control submits no value.
file | The value, a file name, typed by the user into the control. Unlike other controls, this value is read-only.
hidden | The control submits this value when the form is submitted.
OPTION | The "selected" value. The containing list box control submits this value only if the user has selected the option.
password | The default value. The control displays this value when it is first created and when the user clicks the reset button.
radio | The "selected" value. The control submits this value only if the user has selected the control. Otherwise, the control submits no value.
reset | The button label. If not set, the label defaults to "Reset".
submit | The button label. If not set, the label defaults to "Submit".
text | The default value. The control displays this value when it is first created and when the user clicks the reset button.

See also get_value


Align Property

*
  * Previous Topic: IHTMLInputImage::put_align
  * Next Topic: IHTMLInputImage::put_onload

IHTMLInputImage::get_align

HRESULT get_align(
    BSTR *p
);

Retrieves how the element is aligned with adjacent text.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the alignment. Can be one of these values:
absbottom | Aligns the bottom of the element with the absolute bottom of the surrounding text. The absolute bottom is equal to the baseline of the text minus the height of the largest descender in the text.
absmiddle | Aligns the middle of the element with the middle of the surrounding text. The absolute middle is the midpoint between the absolute bottom and texttop of the surrounding text.
baseline | Aligns the bottom of the element with the baseline of the surrounding text.
bottom | Aligns the bottom of the element with the bottom of the surrounding text. The bottom is equal to the baseline minus the standard height of a descender in the text.
left | Aligns the element to the left of the surrounding text. All preceding and subsequent text flows to the right of the element. This is the default value.
middle | Aligns the middle of the element with the surrounding text.
right | Aligns the element to the right of the surrounding text. All subsequent text flows to the left of the element.
texttop | Aligns the top of the element with the absolute top of the surrounding text. The absolute top is the baseline plus the height of the largest ascender in the text.
top | Aligns the top of the element with the top of the text. The top of the text is the baseline plus the standard height of an ascender in the text.

For the INPUT element, this attribute applies only to the image type. It is undefined for all other types.

See also put_align

Up Top of Page

IHTMLInputImage::put_align

HRESULT put_align(
    BSTR v
);

Sets how the element is aligned with adjacent text.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the alignment. Can be one of these values:
absbottom | Aligns the bottom of the element with the absolute bottom of the surrounding text. The absolute bottom is equal to the baseline of the text minus the height of the largest descender in the text.
absmiddle | Aligns the middle of the element with the middle of the surrounding text. The absolute middle is the midpoint between the absolute bottom and texttop of the surrounding text.
baseline | Aligns the bottom of the element with the baseline of the surrounding text.
bottom | Aligns the bottom of the element with the bottom of the surrounding text. The bottom is equal to the baseline minus the standard height of a descender in the text.
left | Aligns the element to the left of the surrounding text. All preceding and subsequent text flows to the right of the element. This is the default value.
middle | Aligns the middle of the element with the surrounding text.
right | Aligns the element to the right of the surrounding text. All subsequent text flows to the left of the element.
texttop | Aligns the top of the element with the absolute top of the surrounding text. The absolute top is the baseline plus the height of the largest ascender in the text.
top | Aligns the top of the element with the top of the text. The top of the text is the baseline plus the standard height of an ascender in the text.

For the INPUT element, this attribute applies only to the image type. It is undefined for all other types.

See also get_align


Alt Property

*
  * Previous Topic: IHTMLInputImage::put_alt
  * Next Topic: IHTMLInputImage::put_src

IHTMLInputImage::get_alt

HRESULT get_alt(
    BSTR *p
);

Retrieves the optional text as an alternative to the graphic for rendering in nongraphical environments. Alternate text should be provided whenever the graphic is not rendered. Alternate text is mandatory for Level 0 documents.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the optional text.

See also put_alt

Up Top of Page

IHTMLInputImage::put_alt

HRESULT put_alt(
    BSTR v
);

Indicates optional text as an alternative to the graphic for rendering in nongraphical environments. Alternate text should be provided whenever the graphic is not rendered. Alternate text is mandatory for Level 0 documents.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the optional text.

See also get_alt


Border Property

*
  * Previous Topic: IHTMLInputImage::put_border
  * Next Topic: IHTMLInputImage::put_vspace

IHTMLInputImage::get_border

HRESULT get_border(
    VARIANT *p
);

Retrieves the current thickness of the border around the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the border thickness.

See also put_border

Up Top of Page

IHTMLInputImage::put_border

HRESULT put_border(
    VARIANT v
);

Sets the thickness of the border around the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the border thickness.

See also get_border


Disabled Property

*
  * Previous Topic: IHTMLInputImage::put_disabled
  * Next Topic: IHTMLInputImage::put_border

IHTMLInputImage::get_disabled

HRESULT get_disabled(
    VARIANT_BOOL *p
);

Determines whether the control is enabled or disabled.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives TRUE if the control is disabled, or FALSE otherwise.

The default value for this property is FALSE.

See also put_disabled

Up Top of Page

IHTMLInputImage::put_disabled

HRESULT put_disabled(
    VARIANT_BOOL v
);

Enables or disables the control. A disabled control appears dimmed and does not respond to user input.

  • Returns S_OK if successful, or an error value otherwise.
v
Boolean value specifying whether to disable the control. If TRUE, the control is disabled; otherwise, it is enabled.

The default value for this property is FALSE.

See also get_disabled


Dynsrc Property

*
  * Previous Topic: IHTMLInputImage::put_dynsrc
  * Next Topic: IHTMLInputImage::get_readyState

IHTMLInputImage::get_dynsrc

HRESULT get_dynsrc(
    BSTR *p
);

Retrieves the address of a video clip or VRML world to be displayed in the window.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the address.

See also put_dynsrc

Up Top of Page

IHTMLInputImage::put_dynsrc

HRESULT put_dynsrc(
    BSTR v
);

Sets the address of a video clip or VRML world to be displayed in the window.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the address.

See also get_dynsrc


IHTMLInputImage::get_complete

HRESULT get_complete(
    VARIANT_BOOL *p
);

Retrieves whether the specified element is fully loaded.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives TRUE if the element is fully loaded, or FALSE otherwise.


IHTMLInputImage::get_readyState

HRESULT get_readyState(
    BSTR *p
);

Retrieves the current state of an object being downloaded.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the state. Can be one of these values:
complete | The object is completely loaded.
interactive | The object can be interacted with even though it is not fully loaded.
loading | The object is currently being loaded.
unitialized | The object is not created. Usually when the object is being downloaded.

Each object can independently determine which of the states it exposes.


IHTMLInputImage::get_type

HRESULT get_type(
    BSTR *p
);

Retrieves the type of intrinsic control represented by the given element object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the type, which can be one of these values:

Element | Possible value | Description
INPUT | checkbox | Used for simple Boolean attributes or for attributes that can take multiple values at the same time. It is represented by a number of check box fields, each of which has the same name. Each selected check box generates a separate name/value pair in the submitted data, even if this results in duplicate names. The default value for check boxes is on.
file | A file upload element.
hidden | No field is presented to the user, but the content of the field is sent with the submitted form. This value can be used to transmit state information about client/server interaction.
image | An image field which you can click, causing the form to be immediately submitted. The coordinates of the selected point are measured in pixel units from the upper-left corner of the image, and are returned (along with the other contents of the form) in two name/value pairs. The x-coordinate is submitted under the name of the field with .x appended, and the y-coordinate is submitted under the name of the field with .y appended. Any value property is ignored. The image itself is specified by the SRC attribute, exactly as for the Image element.
password | The same as the TEXT attribute, except that text is not displayed as the user enters it.
radio | Used for attributes that accept a single value from a set of alternatives. Each radio-button field in the group should be given the same name. Only the selected radio button in the group generates a name/value pair in the submitted data. Radio buttons require an explicit value property.
reset | reset is a button that when clicked resets the form's fields to their specified initial values. The label to be displayed on the button can be specified just as for the submit button.
submit | submit is a button that when clicked submits the form. You can use the value attribute to provide a non-editable label to be displayed on the button. The default label is application-specific. If a submit button is clicked to submit the form, and that button has a name attribute specified, then that button contributes a name/value pair to the submitted data. Otherwise, a submit button makes no contribution to the submitted data.
text | Used for a single-line text-entry field. Use in conjunction with the size and maxLength property.
SELECT | select-multiple | Specifies a multiple-select list box.
select-one | Specifies a single-select list box.
TEXTAREA | textarea | Used for multiple-line text-entry fields. Use in conjunction with the size and maxLength properties.


Height Property

*
  * Previous Topic: IHTMLInputImage::put_height
  * Next Topic: IHTMLInputImage::put_start

IHTMLInputImage::get_height

HRESULT get_height(
    long *p
);

Retrieves the calculated height of the element, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the height.

If the value of the corresponding HTML attribute was set using a percentage, this property specifies the height in pixels represented by that percentage.

See also put_height

Up Top of Page

IHTMLInputImage::put_height

HRESULT put_height(
    long v
);

Sets the calculated height of the element, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the height.

If the value of the corresponding HTML attribute was set using a percentage, this property specifies the height in pixels represented by that percentage.

See also get_height


Hspace Property

*
  * Previous Topic: IHTMLInputImage::put_hspace
  * Next Topic: IHTMLInputImage::put_alt

IHTMLInputImage::get_hspace

HRESULT get_hspace(
    long *p
);

Retrieves the horizontal margins for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the horizontal margins.

Similar to border, except the margins are not painted with color when the element is a link.

See also put_hspace

Up Top of Page

IHTMLInputImage::put_hspace

HRESULT put_hspace(
    long v
);

Sets the horizontal margins for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the horizontal margins.

Similar to border, except the margins are not painted with color when the element is a link.

See also get_hspace


IHTMLInputImage

This interface specifies a form input control.

IHTMLInputImage Methods
get_type put_disabled get_disabled
put_border get_border put_vspace
get_vspace put_hspace get_hspace
put_alt get_alt put_src
get_src put_lowsrc get_lowsrc
get_vrml put_dynsrc get_dynsrc
get_readyState get_complete put_loop
get_loop put_align get_align
put_onload get_onload put_onerror
get_onerror put_onabort get_onabort
put_name get_name put_width
get_width put_height get_height
put_start get_start

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


Loop Property

*
  * Previous Topic: IHTMLInputImage::put_loop
  * Next Topic: IHTMLInputImage::put_align

IHTMLInputImage::get_loop

HRESULT get_loop(
    VARIANT *p
);

Retrieves the number of times a video loops when activated.

  • Returns S_OK if successful, or an error value otherwise.
p
Value specifying the number of times to loop. If this parameter receives -1 (infinite), the video will loop continuously.

Below are descriptions on how loop works for some boundary cases.
<BGSOUND src="file:///c:\win95\system\msremind.wav"> | once
<BGSOUND src="file:///c:\win95\system\msremind.wav" LOOP> | once
<BGSOUND src="file:///c:\win95\system\msremind.wav" LOOP=> | zero times
<BGSOUND src="file:///c:\win95\system\msremind.wav" LOOP=-1> | infinitely
<BGSOUND src="file:///c:\win95\system\msremind.wav" LOOP=0> | once

See also put_loop

Up Top of Page

IHTMLInputImage::put_loop

HRESULT put_loop(
    VARIANT v
);

Sets the number of times a video will loop when activated.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the number of times to loop. If this parameter is -1 (infinite), the video will loop continuously.

Below are descriptions on how loop works for some boundary cases.
<BGSOUND src="file:///c:\win95\system\msremind.wav"> | once
<BGSOUND src="file:///c:\win95\system\msremind.wav" LOOP> | once
<BGSOUND src="file:///c:\win95\system\msremind.wav" LOOP=> | zero times
<BGSOUND src="file:///c:\win95\system\msremind.wav" LOOP=-1> | infinitely
<BGSOUND src="file:///c:\win95\system\msremind.wav" LOOP=0> | once

See also get_loop


Lowsrc Property

*
  * Previous Topic: IHTMLInputImage::put_lowsrc
  * Next Topic: IHTMLInputImage::put_vrml

IHTMLInputImage::get_lowsrc

HRESULT get_lowsrc(
    BSTR *p
);

Retrieves the URL of a lower-resolution image to display.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the URL.

Setting the SRC= attribute in code has the side-effect of actually starting to load the new URL into the image area (and aborting the transfer of any image data that is already loading into the same area). Therefore, you should alter the lowsrc property before setting the src property. If the URL in the src property refers to an image that is not the same size as the image cell it is loaded into, the source image is scaled to fit.

See also put_lowsrc

Up Top of Page

IHTMLInputImage::put_lowsrc

HRESULT put_lowsrc(
    BSTR v
);

Specifies the URL of a lower-resolution image to display.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the URL.

Setting the SRC= attribute in code has the side-effect of actually starting to load the new URL into the image area (and aborting the transfer of any image data that is already loading into the same area). Therefore, you should alter the lowsrc property before setting the src property. If the URL in the src property refers to an image that is not the same size as the image cell it is loaded into, the source image is scaled to fit.

See also get_lowsrc


Name Property

*
  * Previous Topic: IHTMLInputImage::put_name
  * Next Topic: IHTMLInputImage::put_width

IHTMLInputImage::get_name

HRESULT get_name(
    BSTR *p
);

Retrieves the name of the frame so it can be targeted from links in other documents.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the window or frame name, or one of these values:
window_name | String that specifies a frame.
_blank | Loads the link into a new, unnamed window.
_parent | Loads the link over the parent. If the frame has no parent, this refers to _self.
_self | Replaces the page with the specified link.
_top | Loads the link at the topmost level.

The name property on the window comes from the FRAME definition. There is no other way to persist a window name in HTML.

See also put_name

Up Top of Page

IHTMLInputImage::put_name

HRESULT put_name(
    BSTR v
);

Sets the name of the frame so it can be targeted from links in other documents.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the name. Either a window name or frame can be specified, or one of the following values:
window_name | String that specifies a frame.
_blank | Loads the link into a new, unnamed window.
_parent | Loads the link over the parent. If the frame has no parent, this refers to _self.
_self | Replaces the page with the specified link.
_top | Loads the link at the topmost level.

The name property on the window comes from the FRAME definition. There is no other way to persist a window name in HTML.

See also get_name


Onabort Property

*
  * Previous Topic: IHTMLInputImage::put_onabort
  * Next Topic: IHTMLInputImage::put_name

IHTMLInputImage::get_onabort

HRESULT get_onabort(
    VARIANT *p
);

Retrieves the inline script associated with the onabort event for an INPUT type=image element. An onabort event occurs when the loading of a document or image causes an error.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the script.

See also put_onabort

Up Top of Page

IHTMLInputImage::put_onabort

HRESULT put_onabort(
    VARIANT v
);

Sets the inline script associated with the onabort event for an INPUT type=image element. An onabort event occurs when the loading of a document or image causes an error.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the new script.

See also get_onabort


Onerror Property

*
  * Previous Topic: IHTMLInputImage::put_onerror
  * Next Topic: IHTMLInputImage::put_onabort

IHTMLInputImage::get_onerror

HRESULT get_onerror(
    VARIANT *p
);

Retrieves the inline script associated with the onerror event for an INPUT type=image element. An onerror event occurs when the loading of a document or image causes an error.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the script.

See also put_onerror

Up Top of Page

IHTMLInputImage::put_onerror

HRESULT put_onerror(
    VARIANT v
);

Sets the inline script associated with the onerror event for an INPUT type=image element. An onerror event occurs when the loading of a document or image causes an error.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the new script.

See also get_onerror


Onload Property

*
  * Previous Topic: IHTMLInputImage::put_onload
  * Next Topic: IHTMLInputImage::put_onerror

IHTMLInputImage::get_onload

HRESULT get_onload(
    VARIANT *p
);

Retrieves the inline script associated with the onload event for an INPUT type=image element. An onload event occurs immediately after the browser loads the given object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the script.

See also put_onload

Up Top of Page

IHTMLInputImage::put_onload

HRESULT put_onload(
    VARIANT v
);

Sets the inline script associated with the onload event for an INPUT type=image element. An onload event occurs immediately after the browser loads the given object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the new script.

See also get_onload


Src Property

*
  * Previous Topic: IHTMLInputImage::put_src
  * Next Topic: IHTMLInputImage::put_lowsrc

IHTMLnputImage::get_src

HRESULT get_src(
    BSTR *p
);

Retrieves the URL of the image.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the URL.

See also put_src

Up Top of Page

IHTMLInputImage::put_src

HRESULT put_src(
    BSTR v
);

Sets the URL of an image to be shown.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the URL.

See also get_src


Start Property

*
  * Previous Topic: IHTMLInputImage::put_start
  * Next Topic: IHTMLInputTextElement

IHTMLInputImage::get_start

HRESULT get_start(
    BSTR *p
);

Retrieves when a video clip should start playing.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives one of these values:
fileopen | The video starts as soon as it is finished loading.
mouseover | The video starts when the mouse goes over the animation.

See also put_start

Up Top of Page

IHTMLInputImage::put_start

HRESULT put_start(
    BSTR v
);

Specifies when a video clip file should start playing.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying when to start the video. Can be one of these values:
fileopen | The video starts as soon as it is finished loading.
mouseover | The video starts when the mouse goes over the animation.

See also get_start


Vrml Property

*
  * Previous Topic: IHTMLInputImage::put_vrml
  * Next Topic: IHTMLInputImage::put_dynsrc

IHTMLInputImage::get_vrml

HRESULT get_vrml(
    BSTR *p
);

Retrieves the URL of the VRML world to be displayed in the window.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the URL.

Up Top of Page

IHTMLInputImage::put_vrml

HRESULT put_vrml(
    BSTR v
);

Specifies the URL of a VRML world to be displayed in the window.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the URL.


Vspace Property

*
  * Previous Topic: IHTMLInputImage::put_vspace
  * Next Topic: IHTMLInputImage::put_hspace

IHTMLInputImage::get_vspace

HRESULT get_vspace(
    long *p
);

Retrieves the vertical margins for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the vertical margins.

Similar to border, except the margins are not painted with color when the element is a link.

See also put_vspace

Up Top of Page

IHTMLInputImage::put_vspace

HRESULT put_vspace(
    long v
);

Sets the vertical margins for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the margins.

Similar to border, except the margins are not painted with color when the element is a link.

See also get_vspace


Width Property

*
  * Previous Topic: IHTMLInputImage::put_width
  * Next Topic: IHTMLInputImage::put_height

IHTMLInputImage::get_width

HRESULT get_width(
    long *p
);

Retrieves the calculated width of the element, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the width.

This property is an integer value. Although an HTML author can specify the width as a percentage, this property always specifies the width in pixels.

See also put_width

Up Top of Page

IHTMLInputImage::put_width

HRESULT put_width(
    long v
);

Sets the calculated width of the element, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the width.

This property is an integer value. Although an HTML author can specify the width as a percentage, this property always specifies the width in pixels.

See also get_width


IHTMLInputTextElement::createTextRange

HRESULT createTextRange(
    IHTMLTxtRange **range
);

Creates a text range object for the element. You use a text range to examine and modify the text within the element.

  • Returns S_OK if successful, or an error value otherwise.
range
Address of a variable that receives an interface pointer to the text range.

See also IHTMLTxtRange


DefaultValue Property

*
  * Previous Topic: IHTMLInputTextElement::put_defaultValue
  * Next Topic: IHTMLInputTextElement::put_size

IHTMLInputTextElement::get_defaultValue

HRESULT get_defaultValue(
    BSTR *p
);

Retrieves the initial contents of a password or text control or the TEXTAREA element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the initial contents.

This value can be changed programmatically but has no effect on the appearance, or on how forms are submitted.

See also put_defaultValue

Up Top of Page

IHTMLInputTextElement::put_defaultValue

HRESULT put_defaultValue(
    BSTR v
);

Sets the initial contents of a password or text control or the TEXTAREA element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the initial contents.

This value can be changed programmatically but has no effect on the appearance, or on how forms are submitted.

See also get_defaultValue


Disabled Property

*
  * Previous Topic: IHTMLInputTextElement::put_disabled
  * Next Topic: IHTMLInputTextElement::get_form

IHTMLInputTextElement::get_disabled

HRESULT get_disabled(
    VARIANT_BOOL *p
);

Determines whether the control is enabled or disabled.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives TRUE if the control is disabled, or FALSE otherwise.

The default value for this property is FALSE.

See also put_disabled

Up Top of Page

IHTMLInputTextElement::put_disabled

HRESULT put_disabled(
    VARIANT_BOOL v
);

Enables or disables the control. A disabled control appears dimmed and does not respond to user input.

  • Returns S_OK if successful, or an error value otherwise.
v
Boolean value specifying whether to disable the control. If TRUE, the control is disabled; otherwise, it is enabled.

The default value for this property is FALSE.

See also get_disabled


IHTMLInputTextElement::get_form

HRESULT get_form(
    IHTMLFormElement **p
);

Retrieves a reference to the form the element is embedded on.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives an interface pointer to the form element. This parameter receives NULL if the element is not on a form.

See also IHTMLFormElement


IHTMLInputTextElement::get_type

HRESULT get_type(
    BSTR *p
);

Retrieves the type of intrinsic control represented by the given element object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the type. The possible values depend on the element as listed in the following table.

Element | Possible value | Description
INPUT | checkbox | Used for simple Boolean attributes or for attributes that can take multiple values at the same time. It is represented by a number of check box fields, each of which has the same name. Each selected check box generates a separate name/value pair in the submitted data, even if this results in duplicate names. The default value for check boxes is on.
file | A file upload element.
hidden | No field is presented to the user, but the content of the field is sent with the submitted form. This value can be used to transmit state information about client/server interaction.
image | An image field that you can click, causing the form to be immediately submitted. The coordinates of the selected point are measured in pixel units from the upper-left corner of the image, and are returned (along with the other contents of the form) in two name/value pairs. The x-coordinate is submitted under the name of the field with .x appended, and the y-coordinate is submitted under the name of the field with .y appended. Any value property is ignored. The image itself is specified by the SRC attribute, exactly as for the Image element.
password | Same as the TEXT attribute, except that text is not displayed as the user enters it.
radio | Used for attributes that accept a single value from a set of alternatives. Each radio-button field in the group should be given the same name. Only the selected radio button in the group generates a name/value pair in the submitted data. Radio buttons require an explicit value property.
reset | reset is a button that when clicked resets the form's fields to their specified initial values. The label to be displayed on the button can be specified just as for the submit button.
submit | submit is a button that when clicked submits the form. You can use the value attribute to provide a non-editable label to be displayed on the button. The default label is application-specific. If a submit button is clicked to submit the form, and that button has a name attribute specified, that button contributes a name/value pair to the submitted data. Otherwise, a submit button makes no contribution to the submitted data.
text | Used for a single-line text-entry field. Use in conjunction with the size and maxLength properties.
SELECT | select-multiple | Specifies a multiple-select list box.
select-one | Specifies a single-select list box.
TEXTAREA | textarea | Used for multiple-line text-entry fields. Use in conjunction with the size and maxLength properties.


IHTMLInputTextElement

This interface specifies a form input control.

IHTMLInputTextElement Methods
get_type put_value get_value
put_name get_name put_status
get_status put_disabled get_disabled
get_form put_defaultValue get_defaultValue
put_size get_size put_maxLength
get_maxLength select put_onchange
get_onchange put_onselect get_onselect
put_readOnly get_readOnly createTextRange

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


MaxLength Property

*
  * Previous Topic: IHTMLInputTextElement::put_maxLength
  * Next Topic: IHTMLInputTextElement::select

IHTMLInputTextElement::get_maxLength

HRESULT get_maxLength(
    long *p
);

Retrieves the maximum number of characters that can be entered into a text control.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the maximum number of characters.

This can be larger than the size of the text box. When this occurs, the text box should scroll accordingly as the user types. The default is there is no limit.

See also put_maxLength

Up Top of Page

IHTMLInputTextElement::put_maxLength

HRESULT put_maxLength(
    long v
);

Sets the maximum number of characters that can be entered into a text control.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the maximum number of characters.

This can be larger than the size of the text box. When this occurs, the text box should scroll accordingly as the user types. The default is there is no limit.

See also get_maxLength


Name Property

*
  * Previous Topic: IHTMLInputTextElement::put_name
  * Next Topic: IHTMLInputTextElement::put_status

IHTMLInputTextElement::get_name

HRESULT get_name(
    BSTR *p
);

Retrieves the name of the control, bookmark, or application.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the name.

The name is used to bind the value of the control when submitting a form. The NAME is not the value that is displayed for the button, reset, and submit objects. Submitting the form submits the internally stored value, not the one displayed.

JScript allows the name to be changed at run time. This does not change the name in the programming model, in the collection of elements, but does change the name used for submitting elements.

See also put_name

Up Top of Page

IHTMLInputTextElement::put_name

HRESULT put_name(
    BSTR v
);

Sets the name of the control, bookmark, or application.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the name.

The name is used to bind the value of the control when submitting a form. The NAME is not the value that is displayed for the button, reset, and submit objects. Submitting the form submits the internally stored value, not the one displayed.

JScript allows the name to be changed at run time. This does not change the name in the programming model, in the collection of elements, but does change the name used for submitting elements.

See also get_name


Onchange Property

*
  * Previous Topic: IHTMLInputTextElement::put_onchange
  * Next Topic: IHTMLInputTextElement::put_onselect

IHTMLInputTextElement::get_onchange

HRESULT get_onchange(
    VARIANT *p
);

Retrieves the inline script associated with the onchange event on the INPUT text element. This occurs when the contents of the object have changed.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that contains the script.

For more information on inline script, see Attaching an Event Handler in the Understanding the Event Model documentation.

See also put_onchange

Up Top of Page

IHTMLInputTextElement::put_onchange

HRESULT put_onchange(
    VARIANT v
);

Sets the inline script associated with the onchange event on the INPUT text element. This occurs when the contents of the object have changed.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to be set.

For more information on inline script, see Attaching an Event Handler in the Understanding the Event Model documentation.

See also get_onchange


Onselect Property

*
  * Previous Topic: IHTMLInputTextElement::put_onselect
  * Next Topic: IHTMLInputTextElement::put_readOnly

IHTMLInputTextElement::get_onselect

HRESULT get_onselect(
    VARIANT *
);

Retrieves the inline script associated with the onselect event on the INPUT text element. This event fires at the beginning of a user-initiated select. This event can be canceled, and it participates in the bubbling model.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that contains the script.

For more information on inline script, see Attaching an Event Handler in the Understanding the Event Model documentation.

See also put_onselect

Up Top of Page

IHTMLInputTextElement::put_onselect

HRESULT put_onselect(
    VARIANT v
);

Sets the inline script associated with the onselect event on the INPUT text element. This event fires at the beginning of a user-initiated select. This event can be canceled, and it participates in the bubbling model.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to be set.

For more information on inline script, see Attaching an Event Handler in the Understanding the Event Model documentation.

See also get_onselect


ReadOnly Property

*
  * Previous Topic: IHTMLInputTextElement::put_readOnly
  * Next Topic: IHTMLInputTextElement::createTextRange

IHTMLInputTextElement::get_readOnly

HRESULT get_readOnly(
    VARIANT_BOOL *p
);

Determines whether the element's contents are read-only, meaning that the user cannot enter or edit text in the control.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives TRUE if the element is read-only, or FALSE if not.

This is different than disabled. Read-only still allows the element to receive the focus, while disabled does not allow the element to receive the focus.

The default value for this property is FALSE.

See also put_readOnly

Up Top of Page

IHTMLInputTextElement::put_readOnly

HRESULT put_readOnly(
    VARIANT_BOOL v
);

Specifies whether the element's contents are read-only, meaning that the user cannot enter or edit text in the control.

  • Returns S_OK if successful, or an error value otherwise.
v
Read-only flag. TRUE sets the element to read-only; FALSE does not.

This is different than disabled. Read-only still allows the element to receive the focus, while disabled does not allow the element to receive the focus.

The default value for this property is FALSE.

See also get_readOnly


IHTMLInputTextElement::select

HRESULT select(
    void
);

Highlights the input area of a form element.

  • Returns S_OK if successful, or an error value otherwise.

You can use the select method with the focus method to highlight a field and position the cursor for a user response.


Size Property

*
  * Previous Topic: IHTMLInputTextElement::put_size
  * Next Topic: IHTMLInputTextElement::put_maxLength

IHTMLInputTextElement::get_size

HRESULT get_size(
    long *p
);

Retrieves the size of the control.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the size, in characters.

See also put_size

Up Top of Page

IHTMLInputTextElement::put_size

HRESULT put_size(
    long v
);

Sets the size of the control.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the size, in characters.

See also get_size


Status Property

*
  * Previous Topic: IHTMLInputTextElement::put_status
  * Next Topic: IHTMLInputTextElement::put_disabled

IHTMLInputTextElement::get_status

HRESULT get_status(
    VARIANT *p
);

Retrieves the value of a checkbox or radio button. This property is equivalent to the value property for check boxes and radio buttons.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value.

See also put_status

Up Top of Page

IHTMLInputTextElement::put_status

HRESULT put_status(
    VARIANT v
);

Sets the value of a checkbox or radio button. This property is equivalent to the value property for check boxes and radio buttons.

  • Returns S_OK if successful, or an error value otherwise.
v
Value of the check box or radio button.

See also get_status


Value Property

*
  * Previous Topic: IHTMLInputTextElement::put_value
  * Next Topic: IHTMLInputTextElement::put_name

IHTMLInputTextElement::get_value

HRESULT get_value(
    BSTR *p
);

Retrieves the default or "selected" value of the given control.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value. It can be any valid string. The purpose of the string depends on the type of control, as described in the following table.
Control type | Description
checkbox | The "selected" value. The control submits this value only if the user has selected the control. Otherwise, the control submits no value.
file | The value, a file name, typed by the user into the control. Unlike other controls, this value is read-only.
hidden | The control submits this value when the form is submitted.
OPTION | The "selected" value. The containing list box control submits this value only if the user has selected the option.
password | The default value. The control displays this value when it is first created and when the user clicks the reset button.
radio | The "selected" value. The control submits this value only if the user has selected the control. Otherwise, the control submits no value.
reset | The button label. If not set, the label defaults to "Reset".
submit | The button label. If not set, the label defaults to "Submit".
text | The default value. The control displays this value when it is first created and when the user clicks the reset button.

See also put_value

Up Top of Page

IHTMLInputTextElement::put_value

HRESULT put_value(
    BSTR v
);

Sets the default or "selected" value of the given control.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the value. It can be any valid string. The purpose of the string depends on the type of control, as described in the following table.
Control type | Description
checkbox | The "selected" value. The control submits this value only if the user has selected the control. Otherwise, the control submits no value.
file | The value, a file name, typed by the user into the control. Unlike other controls, this value is read-only.
hidden | The control submits this value when the form is submitted.
OPTION | The "selected" value. The containing list box control submits this value only if the user has selected the option.
password | The default value. The control displays this value when it is first created and when the user clicks the reset button.
radio | The "selected" value. The control submits this value only if the user has selected the control. Otherwise, the control submits no value.
reset | The button label. If not set, the label defaults to "Reset".
submit | The button label. If not set, the label defaults to "Submit".
text | The default value. The control displays this value when it is first created and when the user clicks the reset button.

See also get_value


IOmHistory::back

HRESULT back(
    VARIANT *pvargdistance
);

Loads the previous URL in the History list.

  • Returns S_OK if successful, or an error value otherwise.
pvargdistance
Address of a VARIANT structure that contains the script.

This method performs the same action as a user clicking the Back button in the browser. Trying to go past the beginning of the history does not generate an error. Instead, the browser remains at the current page.

See also forward


IOmHistory::forward

HRESULT forward(
    VARIANT *pvargdistance
);

Loads the next URL in the History list.

  • Returns S_OK if successful, or an error value otherwise.
pvargdistance
Address of a VARIANT structure that contains the script.

This method performs the same action as a user clicking the Forward button in the browser. Trying to go past the end of the history does not generate an error. Instead, the browser remains at the current page.

See also back


IOmHistory::get_length

HRESULT get_length(
    short *p
);

Retrieves the number of elements in the History list.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the number of items.


IOmHistory::go

HRESULT go(
    VARIANT *pvargdistance
);

Loads a URL in the History list.

  • Returns S_OK if successful, or an error value otherwise.
pvargdistance
Address of a VARIANT structure that contains the script.

Trying to go past the beginning or end of the history does not generate an error. Instead, the browser remains at the current page.


IOmHistory

This interface provides the ability to access the history object for the client. The history object contains information on the URLs that the client has visited.

IOmHistory Methods


IOmNavigator::get_appCodeName

HRESULT get_appCodeName(
    BSTR *p
);

Retrieves the code name of the browser.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the code name.


IOmNavigator::get_appMinorVersion

HRESULT get_appMinorVersion(
    BSTR *p
);

Returns a string of the minor version number of the browser.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the minor version number.


IOmNavigator::get_appName

HRESULT get_appName(
    BSTR *p
);

Retrieves the application name of the browser.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the application name.


IOmNavigator::get_appVersion

HRESULT get_appVersion(
    BSTR *p
);

Retrieves the version of the browser.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the version information.


IOmNavigator::get_browserLanguage

HRESULT get_browserLanguage(
    BSTR *p
);

Currently not implemented.


*
  * Previous Topic: IOmNavigator::get_browserLanguage
  * Next Topic: IOmNavigator::get_cookieEnabled

IOmNavigator::get_connectionSpeed

HRESULT get_connectionSpeed(
    long *p
);

Currently not implemented.


IOmNavigator::get_cookieEnabled

HRESULT get_cookieEnabled(
    VARIANT_BOOL *p
);

Determines whether client-side cookies are enabled in the browser.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives TRUE if client-side cookies are enabled, or FALSE otherwise.


IOmNavigator::get_cpuClass

HRESULT get_cpuClass(
    BSTR *p
);

Returns a string of the CPU class (for example, "x86", "Alpha", "Other").

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the cpuClass value.


IOmNavigator::get_mimeTypes

HRESULT get_mimeTypes(
    IHTMLMimeTypesCollection **p
);

Retrieves an empty collection for Internet Explorer 4.0. This property exists for compatibility with other browsers.

  • Returns S_OK if successful, or an error value otherwise.
enabled
Address of a variable that receives an interface pointer for the collection.

See also IHTMLMimeTypesCollection


IOmNavigator::get_onLine

HRESULT get_onLine(
    VARIANT_BOOL *p
);

Returns a Boolean indicating whether the browser is running online or offline.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives TRUE if the browser is running online, or FALSE otherwise.


IOmNavigator::get_opsProfile

HRESULT get_opsProfile(
    IHTMLOpsProfile **p
);

Returns an IHTMLOpsProfile interface pointer.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives an interface pointer to the IHTMLOpsProfile object.

The IHTMLOpsProfile element is a profile object that stores various types of information about the user. This information is taken from the Address Book.


IOmNavigator::get_platform

HRESULT get_platform(
    BSTR *p
);

Returns a string indicating which platform the browser is currently running on (for example, "Win32", "Win16", "WinCE", and so on).

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the operating platform type.


IOmNavigator::get_plugins

HRESULT get_plugins(
    IHTMLPluginsCollection **p
);

Retrieves an interface pointer to a zero-based collection of all the EMBED elements in an HTML document. The elements are in the same order as they appear in the document.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the interface pointer.

The collection is indexed first by name, then by ID. If duplicate names are found, a collection of those named items is returned. The resulting collection can be referenced only by ordinal position.

See also IHTMLPluginsCollection


IOmNavigator::get_systemLanguage

HRESULT get_systemLanguage(
    BSTR *p
);

Returns a string of the default language the system is running with.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the system language information.


IOmNavigator::get_userAgent

HRESULT get_userAgent(
    BSTR *p
);

Retrieves a string that represents the user-agent header sent in the HTTP protocol from the client to the server.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the user-agent header.


IOmNavigator::get_userLanguage

HRESULT get_userLanguage(
    BSTR *p
);

Returns a string indicating the language that the user is running by default.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the user language.


IOmNavigator::get_userProfile

HRESULT get_userProfile(
    IHTMLOpsProfile **p
);

Alias for the IHTMLOpsProfile interface.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a pointer to the IHTMLOpsProfile interface element.

The IHTMLOpsProfile element is a profile object that stores various types of information about the user. This information is taken from the Address Book.


IOmNavigator

This interface provides access to an object that contains information about the browser.

IOmNavigator Methods
get_appCodeName get_appName get_appVersion
get_userAgent javaEnabled taintEnabled
get_mimeTypes get_plugins get_cookieEnabled
get_opsProfile toString get_cpuClass
get_systemLanguage get_browserLanguage get_userLanguage
get_platform get_appMinorVersion get_connectionSpeed
get_onLine get_userProfile

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


IOmNavigator::javaEnabled

HRESULT javaEnabled(
    VARIANT_BOOL *enabled
);

Returns whether Java is enabled.

  • Returns S_OK if successful, or an error value otherwise.
enabled
Address of a variable that receives TRUE if Java is enabled, or FALSE otherwise.


IOmNavigator::taintEnabled

HRESULT taintEnabled(
    VARIANT_BOOL *enabled
);

Determines whether data tainting is enabled.

  • Returns S_OK if successful, or an error value otherwise.
enabled
Address of a variable that receives TRUE if data tainting is enabled, or FALSE otherwise.

This method always returns FALSE for Internet Explorer 4.0. Data tainting is not supported.


IOmNavigator::toString

HRESULT toString(
    BSTR *string
);

Returns a string representation of the navigation object.

  • Returns S_OK if successful, or an error value otherwise.
string
Address of a string variable that represents the navigation object.


Action Property

*
  * Previous Topic: IHTMLIsIndexElement::put_action
  * Next Topic: IHTMLLabelElement

IHTMLIsIndexElement::get_action

HRESULT get_action(
    BSTR *p
);

Retrieves the gateway program to which the string in the text box should be passed.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the gateway program.

See also put_action

Up Top of Page

IHTMLIsIndexElement::put_action

HRESULT put_action(
    BSTR v
);

Sets the gateway program to which the string in the text box should be passed.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the gateway program.

See also get_action


IHTMLIsIndexElement

This interface indicates the document contains a searchable index.

To use the ISINDEX tag, the server must provide a search engine that supports this tag. The script to be executed on the server can be specified by the action property on this tag.

This element can be used only within the HEAD tag.

IHTMLIsIndexElement Methods


Prompt Property

*
  * Previous Topic: IHTMLIsIndexElement::put_prompt
  * Next Topic: IHTMLIsIndexElement::put_action

IHTMLIsIndexElement::get_prompt

HRESULT get_prompt(
    BSTR *p
);

Retrieves a prompt to be used instead of the ACTION.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the prompt.

See also put_prompt

Up Top of Page

IHTMLIsIndexElement::put_prompt

HRESULT put_prompt(
    BSTR v
);

Sets a prompt to be used instead of the ACTION.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the prompt.

See also get_prompt


AccessKey Property

*
  * Previous Topic: IHTMLLabelElement::put_accessKey
  * Next Topic: IHTMLLegendElement

IHTMLLabelElement::get_accessKey

HRESULT get_accessKey(
    BSTR *p
);

Retrieves the accelerator key for the element. Pressing CTRL+key selects this anchor element in the user's browser.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the key.

See also put_accessKey

Up Top of Page

IHTMLLabelElement::put_accessKey

HRESULT put_accessKey(
    BSTR v
);

Sets an accelerator key for the element. Pressing CTRL+key selects this anchor element in the user's browser.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the key.

See also get_accessKey


HtmlFor Property

*
  * Previous Topic: IHTMLLabelElement::put_htmlFor
  * Next Topic: IHTMLLabelElement::put_accessKey

IHTMLLabelElement::get_htmlFor

HRESULT get_htmlFor(
    BSTR *p
);

Retrieves which control-like element to assign the given label element to. This property corresponds to the FOR= attribute in HTML.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the control-like element.

The FOR= attribute references the ID of another element. The FOR= attribute is optional when the label is implicitly defined. This is done by wrapping the label around the control the label is specified for.

See also put_htmlFor

Up Top of Page

IHTMLLabelElement::put_htmlFor

HRESULT put_htmlFor(
    BSTR v
);

Sets which control-like element to assign the given label element to. This property corresponds to the FOR= attribute in HTML.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the control-like element.

The FOR= attribute references the ID of another element. The FOR= attribute is optional when the label is implicitly defined. This is done by wrapping the label around the control the label is specified for.

See also get_htmlFor


IHTMLLabelElement IHTMLLabelElement *
  * Previous Topic: IHTMLIsIndexElement::get_action
  * Next Topic: IHTMLLabelElement::put_htmlFor

IHTMLLabelElement

This interface specifies a label for a control-like element.

Labels cannot be nested.

IHTMLLabelElement Methods


Align Property

*
  * Previous Topic: IHTMLLegendElement::put_align
  * Next Topic: IHTMLLIElement

IHTMLLegendElement::get_align

HRESULT get_align(
    BSTR *p
);

Retrieves how the element is aligned with adjacent text.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the alignment. Can be one of these values:
absbottom | Aligns the bottom of the element with the absolute bottom of the surrounding text. The absolute bottom is equal to the baseline of the text minus the height of the largest descender in the text.
absmiddle | Aligns the middle of the element with the middle of the surrounding text. The absolute middle is the midpoint between the absolute bottom and texttop of the surrounding text.
baseline | Aligns the bottom of the element with the baseline of the surrounding text.
bottom | Aligns the bottom of the element with the bottom of the surrounding text. The bottom is equal to the baseline minus the standard height of a descender in the text.
left | Aligns the element to the left of the surrounding text. All preceding and subsequent text flows to the right of the element. This is the default value.
middle | Aligns the middle of the element with the surrounding text.
right | Aligns the element to the right of the surrounding text. All subsequent text flows to the left of the element.
texttop | Aligns the top of the element with the absolute top of the surrounding text. The absolute top is the baseline plus the height of the largest ascender in the text.
top | Aligns the top of the element with the top of the text. The top of the text is the baseline plus the standard height of an ascender in the text.

For the INPUT element, this attribute applies only to the image type. It is undefined for all other types.

See also put_align

Up Top of Page

IHTMLLegendElement::put_align

HRESULT put_align(
    BSTR v
);

Sets how the element is aligned with adjacent text.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the alignment. Can be one of these values:
absbottom | Aligns the bottom of the element with the absolute bottom of the surrounding text. The absolute bottom is equal to the baseline of the text minus the height of the largest descender in the text.
absmiddle | Aligns the middle of the element with the middle of the surrounding text. The absolute middle is the midpoint between the absolute bottom and texttop of the surrounding text.
baseline | Aligns the bottom of the element with the baseline of the surrounding text.
bottom | Aligns the bottom of the element with the bottom of the surrounding text. The bottom is equal to the baseline minus the standard height of a descender in the text.
left | Aligns the element to the left of the surrounding text. All preceding and subsequent text flows to the right of the element. This is the default value.
middle | Aligns the middle of the element with the surrounding text.
right | Aligns the element to the right of the surrounding text. All subsequent text flows to the left of the element.
texttop | Aligns the top of the element with the absolute top of the surrounding text. The absolute top is the baseline plus the height of the largest ascender in the text.
top | Aligns the top of the element with the top of the text. The top of the text is the baseline plus the standard height of an ascender in the text.

For the INPUT element, this attribute applies only to the image type. It is undefined for all other types.

See also get_align


IHTMLLegendElement

This interface inserts a caption into the box drawn by the FIELDSET element. If given, this element must be the first element in FIELDSET.

This element is a block element.

IHTMLLegendElement Methods


IHTMLLIElement IHTMLLIElement *
  * Previous Topic: IHTMLLegendElement::get_align
  * Next Topic: IHTMLLIElement::put_type

IHTMLLIElement

This interface denotes one item of a list.

This element is a block element.

IHTMLLIElement Methods


Type Property

*
  * Previous Topic: IHTMLLIElement::put_type
  * Next Topic: IHTMLLIElement::put_value

IHTMLLIElement::get_type

HRESULT get_type(
    BSTR *p
);

Retrieves the current style of the list.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives one of these style values:
1 | Use numbers. This is the default value.
a | Use small letters.
A | Use large letters.
i | Use small roman numerals.
I | Use large roman numerals.

See also put_type

Up Top of Page

IHTMLLIElement::put_type

HRESULT put_type(
    BSTR v
);

Changes the style of the list.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the style. Can be one of these values:
1 | Use numbers. This is the default value.
a | Use small letters.
A | Use large letters.
i | Use small roman numerals.
I | Use large roman numerals.

See also get_type


Value Property

*
  * Previous Topic: IHTMLLIElement::put_value
  * Next Topic: IHTMLLinkElement

IHTMLLIElement::get_value

HRESULT get_value(
    long *p
);

Retrieves the value of a list item. In an ordered list, the value is the number that precedes the list item. This property has no visual effect on an unordered list item.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the item.

See also put_value

Up Top of Page

IHTMLLIElement::put_value

HRESULT put_value(
    long v
);

Sets the value of a list item. In an ordered list, the value is the number that precedes the list item. This property has no visual effect on an unordered list item.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the item number.

See also get_value


Disabled Property

*
  * Previous Topic: IHTMLLinkElement::put_disabled
  * Next Topic: IHTMLLinkElement::put_media

IHTMLLinkElement::get_disabled

HRESULT get_disabled(
    VARIANT_BOOL *p
);

Returns a Boolean value indicating whether this link has been disabled.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives TRUE if the element is read-only, or FALSE if not.

See also put_disabled

Up Top of Page

IHTMLLinkElement::put_disabled

HRESULT put_disabled(
    VARIANT_BOOL v
);

Sets the value of the link as being disabled or not.

  • Returns S_OK if successful, or an error value otherwise.
v
Disabled flag. TRUE sets the element to disabled; FALSE does not.

See also get_disabled


IHTMLLinkElement::get_readyState

HRESULT get_readyState(
    BSTR *p
);

Retrieves the current state of an object being downloaded.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the ready state. Can be one of these values:
complete | The object is completely loaded.
interactive | The object can be interacted with even though it is not fully loaded.
loading | The object is currently being loaded.
unitialized | The object is not created. Usually when the object is being downloaded.

Each object can independently determine which of the states it exposes.


IHTMLLinkElement::get_styleSheet

HRESULT get_styleSheet(
    IHTMLStyleSheet **p
);

Retrieves an interface pointer that provides access to the style sheet object's properties and methods.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the interface pointer. See IHTMLStyleSheet for details.


Href Property

*
  * Previous Topic: IHTMLLinkElement::put_href
  * Next Topic: IHTMLLinkElement::put_rel

IHTMLLinkElement::get_href

HRESULT get_href(
    BSTR *p
);

Retrieves the destination URL or anchor point.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the destination URL or anchor point.

The HREF attribute on the anchor is a scriptable attribute. HREFs on anchors can jump to bookmarks or any element's ID attribute.

See also put_href

Up Top of Page

IHTMLLinkElement::put_href

HRESULT put_href(
    BSTR v
);

Sets the destination URL or anchor point.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the URL or anchor point.

The HREF attribute on the anchor is a scriptable attribute. HREFs on anchors can jump to bookmarks or any element's ID attribute.

See also get_href


IHTMLLinkElement

This interface is used to specify a typed link between the document and some other resource.

This element can be used only within the HEAD tag.

IHTMLLinkElement Methods
put_href get_href put_rel
get_rel put_rev get_rev
put_type get_type get_readyState
put_onreadystatechange get_onreadystatechange put_onload
get_onload put_onerror get_onerror
get_styleSheet put_disabled get_disabled
put_media get_media

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


Media Property

*
  * Previous Topic: IHTMLLinkElement::put_media
  * Next Topic: IHTMLListElement

IHTMLLinkElement::get_media

HRESULT get_media(
    BSTR *p
);

Retrieves the inline script that indicates which media this LINK element applies to.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the media type.

See also put_media

Up Top of Page

IHTMLLinkElement::put_media

HRESULT put_media(
    BSTR v
);

Sets the inline script that indicates which media this LINK element applies to.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the media type.

See also get_media


Onerror Property

*
  * Previous Topic: IHTMLLinkElement::put_onerror
  * Next Topic: IHTMLLinkElement::get_styleSheet

IHTMLLinkElement::get_onerror

HRESULT get_onerror(
    VARIANT *p
);

Retrieves the inline script associated with the onerror event on the LINK element. An error event occurs when the loading of a document or image causes an error.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that contains the script.

For more information on inline script, see Attaching an Event Handler in the Understanding the Event Model documentation.

See also put_onerror

Up Top of Page

IHTMLLinkElement::put_onerror

HRESULT put_onerror(
    VARIANT v
);

Sets the inline script associated with the onerror event on the LINK element. An error event occurs when the loading of a document or image causes an error.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to be set.

For more information on inline script, see Attaching an Event Handler in the Understanding the Event Model documentation.

See also get_onerror


Onload Property

*
  * Previous Topic: IHTMLLinkElement::put_onload
  * Next Topic: IHTMLLinkElement::put_onerror

IHTMLLinkElement::get_onload

HRESULT get_onload(
    VARIANT *p
);

Retrieves the inline script associated with the onload event on the LINK element. This event occurs immediately after the browser loads the given object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that contains the script.

For more information on inline script, see Attaching an Event Handler in the Understanding the Event Model documentation.

See also put_onload

Up Top of Page

IHTMLLinkElement::put_onload

HRESULT put_onload(
    VARIANT v
);

Sets the inline script associated with the onload event on the LINK element. This event occurs immediately after the browser loads the given object.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to be set.

For more information on inline script, see Attaching an Event Handler in the Understanding the Event Model documentation.

See also get_onload


Onreadystatechange Property

*
  * Previous Topic: IHTMLLinkElement::put_onreadystatechange
  * Next Topic: IHTMLLinkElement::put_onload

IHTMLLinkElement::get_onreadystatechange

HRESULT get_onreadystatechange(
    VARIANT *p
);

Retrieves the inline script associated with the onreadystatechange event on the LINK element. This event occurs whenever the readyState for the object has changed.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that contains the script.

For more information on inline script, see Attaching an Event Handler in the Understanding the Event Model documentation.

See also put_onreadystatechange

Up Top of Page

IHTMLLinkElement::put_onreadystatechange

HRESULT put_onreadystatechange(
    VARIANT v
);

Sets the inline script associated with the onreadystatechange event on the LINK element. This event occurs whenever the readyState for the object has changed.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to be set.

For more information on inline script, see Attaching an Event Handler in the Understanding the Event Model documentation.

See also get_onreadystatechange


Rel Property

*
  * Previous Topic: IHTMLLinkElement::put_rel
  * Next Topic: IHTMLLinkElement::put_rev

IHTMLLinkElement::get_rel

HRESULT get_rel(
    BSTR *p
);

Retrieves the relationship(s) described by the hypertext link from the anchor to the target.

  • Returns S_OK if successful, or an error value otherwise.
v
Address of a variable that receives the relationship(s). This parameter receives a comma-separated list of relationship values.

Values and their semantics will be registered by the HTML registration authority. The default relationship, if none other is given, is void. The rel property is used only when the href property is present.

See also put_rel

Up Top of Page

IHTMLLinkElement::put_rel

HRESULT put_rel(
    BSTR v
);

Specifies the relationship(s) described by the hypertext link from the anchor to the target.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the relationship(s). This parameter is a comma-separated list of relationship values.

Values and their semantics will be registered by the HTML registration authority. The default relationship, if none other is given, is void. The rel property is used only when the href property is present.

See also get_rel


Rev Property

*
  * Previous Topic: IHTMLLinkElement::put_rev
  * Next Topic: IHTMLLinkElement::put_type

IHTMLLinkElement::get_rev

HRESULT get_rev(
     BSTR *p
);

Same as the rel property, but the semantics of the link type are in the reverse direction. A link from A to B with REL="X" expresses the same relationship as a link from B to A with REV="X". An anchor can have both rel and rev properties.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the relationship(s). This parameter receives a comma-separated list of relationship values.

See also put_rev

Up Top of Page

IHTMLLinkElement::put_rev

HRESULT put_rev(
    BSTR v
);

Same as the rel property, but the semantics of the link type are in the reverse direction. A link from A to B with REL="X" expresses the same relationship as a link from B to A with REV="X". An anchor can have both rel and rev properties.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the relationship(s). This parameter is a comma-separated list of relationship values.

See also get_rev


Type Property

*
  * Previous Topic: IHTMLLinkElement::put_type
  * Next Topic: IHTMLLinkElement::get_readyState

IHTMLLinkElement::get_type

HRESULT get_type(
    BSTR *p
);

Retrieves the current style of the list.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the list style. Can be one of these values:
1 | Use numbers. This is the default value.
a | Use small letters.
A | Use large letters.
i | Use small roman numerals.
I | Use large roman numerals.

See also put_type

Up Top of Page

IHTMLLinkElement::put_type

HRESULT put_type(
    BSTR v
);

Changes the style of the list.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the list style. Can be one of these values:
1 | Use numbers. This is the default value.
a | Use small letters.
A | Use large letters.
i | Use small roman numerals.
I | Use large roman numerals.

See also get_type


IHTMLListElement

This interface provides access to the properties and methods that are common to the OL and UL elements, and is equivalent to the IHTMLElement interface. For more information and a listing of the available methods, see the reference section for the IHTMLElement interface.


IHTMLLocation::assign

HRESULT assign(
    BSTR bstr
);

Sets the current location to the given URL. This method loads the given document specified by the URL if it exists.

  • Returns S_OK if successful, or an error value otherwise.
bstr
String specifying the URL of the document to assign.


Hash Property

*
  * Previous Topic: IHTMLLocation::put_hash
  * Next Topic: IHTMLLocation::reload

IHTMLLocation::get_hash

HRESULT get_hash(
    BSTR *p
);

Retrieves the string following the # symbol in the current URL.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the hash portion of the URL. If the URL has no hash sting, this parameter receives and empty string.

This property is useful for moving to a bookmark within a document. Assigning an invalid value does not cause an error.

See also put_hash

Up Top of Page

IHTMLLocation::put_hash

HRESULT put_hash(
    BSTR v
);

Sets the string following the # symbol in the URL.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the hash portion of the URL.

This property is useful for moving to a bookmark within a document. Assigning an invalid value does not cause an error.

See also get_hash


Host Property

*
  * Previous Topic: IHTMLLocation::put_host
  * Next Topic: IHTMLLocation::put_hostname

IHTMLLocation::get_host

HRESULT get_host(
    BSTR *p
);

Retrieves the hostname part of the location or URL.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the host name. If no host name is available, this parameter receives an empty string.

See also put_host

Up Top of Page

IHTMLLocation::put_host

HRESULT put_host(
    BSTR v
);

Sets the hostname portion of the location or URL.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the host name.

See also get_host


Hostname Property

*
  * Previous Topic: IHTMLLocation::put_hostname
  * Next Topic: IHTMLLocation::put_port

IHTMLLocation::get_hostname

HRESULT get_hostname(
    BSTR *p
);

Retrieves the hostname part of the location or URL.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the host name. If no host name is available, this parameter receives an empty string.

See also put_hostname

Up Top of Page

IHTMLLocation::put_hostname

HRESULT put_hostname(
    BSTR v
);

Sets the hostname portion of the location or URL.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the host name.

See also get_hostname


Href Property

*
  * Previous Topic: IHTMLLocation::put_href
  * Next Topic: IHTMLLocation::put_protocol

IHTMLLocation::get_href

HRESULT get_href(
    BSTR *p
);

Retrieves the URL of the current browser location.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the URL.

See also put_href

Up Top of Page

IHTMLLocation::put_href

HRESULT put_href(
    BSTR v
);

Sets the entire URL for the browser. Setting this property causes the browser to navigate to the location specified by the URL.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the URL.

See also get_href


IHTMLLocation

This interface contains information about the current URL.

IHTMLLocation Methods
put_href get_href put_protocol
get_protocol put_host get_host
put_hostname get_hostname put_port
get_port put_pathname get_pathname
put_search get_search put_hash
get_hash reload replace
assign toString

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


Pathname Property

*
  * Previous Topic: IHTMLLocation::put_pathname
  * Next Topic: IHTMLLocation::put_search

IHTMLLocation::get_pathname

HRESULT get_pathname(
    BSTR *p
);

Retrieves the file or object path from the URL for the current browser location.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the path.

See also put_pathname

Up Top of Page

IHTMLLocation::put_pathname

HRESULT put_pathname(
    BSTR v
);

Sets the file or object path of the URL.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the path.

See also get_pathname


Port Property

*
  * Previous Topic: IHTMLLocation::put_port
  * Next Topic: IHTMLLocation::put_pathname

IHTMLLocation::get_port

HRESULT get_port(
    BSTR *p
);

Retrieves the port number from the URL.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the port number. If no port is specified, this parameter receives an empty string.

See also put_port

Up Top of Page

IHTMLLocation::put_port

HRESULT put_port(
    BSTR v
);

Sets the port number in a URL.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the port number.

See also get_port


Protocol Property

*
  * Previous Topic: IHTMLLocation::put_protocol
  * Next Topic: IHTMLLocation::put_host

IHTMLLocation::get_protocol

HRESULT get_protocol(
    BSTR *p
);

Retrieves the protocol portion of the URL that the browser uses to locate the item. The protocol portion, which indicates the access method, includes the initial substring of the URL up to and including the first colon.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the protocol.

See also put_protocol

Up Top of Page

IHTMLLocation::put_protocol

HRESULT put_protocol(
    BSTR v
);

Sets the protocol portion of the URL that the browser uses to locate the item. The protocol portion, which indicates the access method, includes the initial substring of the URL up to and including the first colon.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the protocol.

See also get_protocol


IHTMLLocation::reload

HRESULT reload(
     VARIANT_BOOL flag
);

Reloads the current page.

  • Returns S_OK if successful, or an error value otherwise.
flag
A Boolean value. TRUE sets the flag to reload the page, FALSE indicates not to reload the page.


IHTMLLocation::replace

HRESULT replace(
    BSTR bstr
);

Replaces the current document by loading the document at the given URL. This method also removes the current document from the browser's session history.

  • Returns S_OK if successful, or an error value otherwise.
bstr
String specifying the URL to insert into the session history.

Replacing a document causes it to no longer be accessible through the history object.

See also IOmHistory


Search Property

*
  * Previous Topic: IHTMLLocation::put_search
  * Next Topic: IHTMLLocation::put_hash

IHTMLLocation::get_search

HRESULT get_search(
    BSTR *p
);

Retrieves the substring that follows the ? symbol in the current URL. This is the query string or form data.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the query string or form data.

See also put_search

Up Top of Page

IHTMLLocation::put_search

HRESULT put_search(
    BSTR v
);

Sets the substring that follows the ? symbol in the current URL. This is the query string or form data.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the query string or form data.

See also get_search


IHTMLLocation::toString

HRESULT toString(
    BSTR *string
);

Retrieves a string representation of the location object that is the href of the current browser location.

  • Returns S_OK if successful, or an error value otherwise.
string
Address of a string variable that receives the href.


IHTMLMapElement::get_areas

HRESULT get_areas(
    IHTMLAreasCollection **p
);

Retrieves a collection of the AREA elements defined for the given MAP element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives an interface pointer to the collection object.

See also IHTMLAreasCollection


IHTMLMapElement IHTMLMapElement *
  * Previous Topic: IHTMLLocation::toString
  * Next Topic: IHTMLMapElement::get_areas

IHTMLMapElement

Ths interface specifies a collection of hot spots for a client-side image map

IHTMLMapElement Methods


Name Property

*
  * Previous Topic: IHTMLMapElement::put_name
  * Next Topic: IHTMLMarqueeElement

IHTMLMapElement::get_name

HRESULT get_name(
    BSTR *p
);

Retrieves the name of the control, bookmark, or application.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the name.

The name is used to bind the value of the control when submitting a form. The NAME is not the value that is displayed for the button, reset, and submit objects. Submitting the form submits the internally stored value, not the one displayed.

JScript allows the name to be changed at run time. This does not change the name in the programming model, in the collection of elements, but does change the name used for submitting elements.

See also put_name

Up Top of Page

IHTMLMapElement::put_name

HRESULT put_name(
    BSTR v
);

Sets the name of the control, bookmark, or application.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the name.

The name is used to bind the value of the control when submitting a form. The NAME is not the value that is displayed for the button, reset, and submit objects. Submitting the form submits the internally stored value, not the one displayed.

JScript allows the name to be changed at run time. This does not change the name in the programming model, in the collection of elements, but does change the name used for submitting elements.

See also get_name


Behavior Property

*
  * Previous Topic: IHTMLMarqueeElement::put_behavior
  * Next Topic: IHTMLMarqueeElement::put_scrollAmount

IHTMLMarqueeElement::get_behavior

HRESULT get_behavior(
    BSTR *p
);

Retrieves how the text scrolls in the marquee.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives one of these strings:
alternate | The marquee alternates left and right.
scroll | The marquee is a scrolling marquee in the direction specified by the direction attribute. The text scrolls off the end and starts over.
slide | The marquee is a scrolling marquee in the direction specified by the direction attribute. The text scrolls to the end and stops.

See also put_behavior

Up Top of Page

IHTMLMarqueeElement::put_behavior

HRESULT put_behavior(
    BSTR v
);

Sets how the text scrolls in the MARQUEE.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the scrolling behavior. Can be one of these values:
alternate | The marquee alternates left and right.
scroll | The marquee is a scrolling marquee in the direction specified by the direction attribute. The text scrolls off the end and starts over.
slide | The marquee is a scrolling marquee in the direction specified by the direction attribute. The text scrolls to the end and stops.

See also get_behavior


BgColor Property

*
  * Previous Topic: IHTMLMarqueeElement::put_bgColor
  * Next Topic: IHTMLMarqueeElement::put_scrollDelay

IHTMLMarqueeElement::get_bgColor

HRESULT get_bgColor(
    VARIANT *p
);

Retrieves the background color behind the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the color value for the background color. The color can be one of the color names or values given in the Color Table reference documentation.

See also put_bgColor

Up Top of Page

IHTMLMarqueeElement::put_bgColor

HRESULT put_bgColor(
    VARIANT v
);

Sets the background color behind the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the color, which can be one of the color names or values given in the Color Table reference documentation.

See also get_bgColor


Direction Property

*
  * Previous Topic: IHTMLMarqueeElement::put_direction
  * Next Topic: IHTMLMarqueeElement::put_behavior

IHTMLMarqueeElement::get_direction

HRESULT get_direction(
    BSTR *p
);

Retrieves the current direction in which the text scrolls.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the scroll direction. Can be one of these values:
down | The marquee scrolls down.
left | The marquee scrolls left. This is the default value.
right | The marquee scrolls right.
up | The marquee scrolls up.

See also put_direction

Up Top of Page

IHTMLMarqueeElement::put_direction

HRESULT put_direction(
    BSTR v
);

Sets the direction in which the text scrolls.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the scroll direction. Can be one of these values:
down | The marquee scrolls down.
left | The marquee scrolls left. This is the default value.
right | The marquee scrolls right.
up | The marquee scrolls up.

See also get_direction


Height Property

*
  * Previous Topic: IHTMLMarqueeElement::put_height
  * Next Topic: IHTMLMarqueeElement::put_trueSpeed

IHTMLMarqueeElement::get_height

HRESULT get_height(
    VARIANT *p
);

Retrieves the calculated height of the element, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the height.

If the value of the corresponding HTML attribute was set using a percentage, this property specifies the height in pixels represented by that percentage.

See also put_height

Up Top of Page

IHTMLMarqueeElement::put_height

HRESULT put_height(
    VARIANT v
);

Sets the calculated height of the element, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the height.

If the value of the corresponding HTML attribute was set using a percentage, this property specifies the height in pixels represented by that percentage.

See also get_height


Hspace Property

*
  * Previous Topic: IHTMLMarqueeElement::put_hspace
  * Next Topic: IHTMLMarqueeElement::put_onfinish

IHTMLMarqueeElement::get_hspace

HRESULT get_hspace(
    long *p
);

Retrieves the horizontal margins for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the horizontal margins.

Similar to border, except the margins are not painted with color when the element is a link.

See also put_hspace

Up Top of Page

IHTMLMarqueeElement::put_hspace

HRESULT put_hspace(
    long v
);

Sets the horizontal margins for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the horizontal margins.

Similar to border, except the margins are not painted with color when the element is a link.

See also get_hspace


Loop Property

*
  * Previous Topic: IHTMLMarqueeElement::put_loop
  * Next Topic: IHTMLMarqueeElement::put_vspace

IHTMLMarqueeElement::get_loop

HRESULT get_loop(
    long *p
);

Retrieves the number of times the MARQUEE will loop.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the number of times to loop. This parameter receives -1 if the marquee is set to loop continuously.

Below are descriptions on how loop works for some boundary cases.
<BGSOUND src="file:///c:\win95\system\msremind.wav"> | once
<BGSOUND src="file:///c:\win95\system\msremind.wav" LOOP> | once
<BGSOUND src="file:///c:\win95\system\msremind.wav" LOOP=> | zero times
<BGSOUND src="file:///c:\win95\system\msremind.wav" LOOP=-1> | infinitely
<BGSOUND src="file:///c:\win95\system\msremind.wav" LOOP=0> | once

See also put_loop

Up Top of Page

IHTMLMarqueeElement::put_loop

HRESULT put_loop(
    long v
);

Sets the number of times the MARQUEE should loop.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the number of times to loop. If this parameter is -1 (infinite), the marquee will loop continuously.

Below are descriptions on how loop works for some boundary cases.
<BGSOUND src="file:///c:\win95\system\msremind.wav"> | once
<BGSOUND src="file:///c:\win95\system\msremind.wav" LOOP> | once
<BGSOUND src="file:///c:\win95\system\msremind.wav" LOOP=> | zero times
<BGSOUND src="file:///c:\win95\system\msremind.wav" LOOP=-1> | infinitely
<BGSOUND src="file:///c:\win95\system\msremind.wav" LOOP=0> | once

See also get_loop


IHTMLMarqueeElement

This interface is used to specify a MARQUEE element. The MARQUEE tag enables you to create a scrolling text marquee, and control its content.

IHTMLMarqueeElement Methods
put_bgColor get_bgColor put_scrollDelay
get_scrollDelay put_direction get_direction
put_behavior get_behavior put_scrollAmount
get_scrollAmount put_loop get_loop
put_vspace get_vspace put_hspace
get_hspace put_onfinish get_onfinish
put_onstart get_onstart put_onbounce
get_onbounce put_width get_width
put_height get_height put_trueSpeed
get_trueSpeed start stop

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


Onbounce Property

*
  * Previous Topic: IHTMLMarqueeElement::put_onbounce
  * Next Topic: IHTMLMarqueeElement::put_width

IHTMLMarqueeElement::get_onbounce

HRESULT get_onbounce(
    VARIANT *p
);

Retrieves the inline script associated with the onbounce event on the MARQUEE element. This event is fired when the behavior property of the MARQUEE element is set to "alternate", and the content of the marquee reaches the specified side.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that contains the script to be set.

For more information on inline script, see Attaching an Event Handler in the Understanding the Event Model documentation.

See also put_onbounce

Up Top of Page

IHTMLMarqueeElement::put_onbounce

HRESULT put_onbounce(
    VARIANT v
);

Sets the inline script associated with the onbounce event on the MARQUEE element. This event is fired when the behavior property of the MARQUEE element is set to "alternate", and the content of the marquee reaches the specified side.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to be set.

For more information on inline script, see Attaching an Event Handler in the Understanding the Event Model documentation.

See also get_onbounce


Onfinish Property

*
  * Previous Topic: IHTMLMarqueeElement::put_onfinish
  * Next Topic: IHTMLMarqueeElement::put_onstart

IHTMLMarqueeElement::get_onfinish

HRESULT get_onfinish(
    VARIANT *p
);

Retrieves the inline script associated with the onfinish event on the MARQUEE element. This event is fired when the looping is complete.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that contains the script.

For more information on inline script, see Attaching an Event Handler in the Understanding the Event Model documentation.

See also put_onfinish

Up Top of Page

IHTMLMarqueeElement::put_onfinish

HRESULT put_onfinish(
    VARIANT v
);

Sets the inline script associated with the onfinish event on the MARQUEE element. This event is fired when the looping is complete.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to be set.

For more information on inline script, see Attaching an Event Handler in the Understanding the Event Model documentation.

See also get_onfinish


Onstart Property

*
  * Previous Topic: IHTMLMarqueeElement::put_onstart
  * Next Topic: IHTMLMarqueeElement::put_onbounce

IHTMLMarqueeElement::get_onstart

HRESULT get_onstart(
    VARIANT *p
);

Retrieves the inline script associated with the onstart event on the MARQUEE element. This event is fired when a loop begins, and when a bounce cycle begins for alternate behavior.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that contains the script.

For more information on inline script, see Attaching an Event Handler in the Understanding the Event Model documentation.

See also put_onstart

Up Top of Page

IHTMLMarqueeElement::put_onstart

HRESULT put_onstart(
    VARIANT v
);

Sets the inline script associated with the onstart event on the MARQUEE element. This event is fired when a loop begins, and when a bounce cycle begins for alternate behavior.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to be set.

For more information on inline script, see Attaching an Event Handler in the Understanding the Event Model documentation.

See also get_onstart


ScrollAmount Property

*
  * Previous Topic: IHTMLMarqueeElement::put_scrollAmount
  * Next Topic: IHTMLMarqueeElement::put_loop

IHTMLMarqueeElement::get_scrollAmount

HRESULT get_scrollAmount(
    long *p
);

Retrieves the number of pixels the text scrolls between each subsequent drawing of the MARQUEE.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the number of pixels.

See also put_scrollAmount

Up Top of Page

IHTMLMarqueeElement::put_scrollAmount

HRESULT put_scrollAmount(
    long v
);

Sets the number of pixels the text scrolls between each subsequent drawing of the MARQUEE.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the number of pixels.

See also get_scrollAmount


ScrollDelay Property

*
  * Previous Topic: IHTMLMarqueeElement::put_scrollDelay
  * Next Topic: IHTMLMarqueeElement::put_direction

IHTMLMarqueeElement::get_scrollDelay

HRESULT get_scrollDelay(
    long *p
);

Retrieves the speed at which the MARQUEE scrolls.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the scroll delay, in milliseconds.

See also put_scrollDelay

Up Top of Page

IHTMLMarqueeElement::put_scrollDelay

HRESULT put_scrollDelay(
    long v
);

Sets the speed at which the MARQUEE scrolls.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the scroll delay, in milliseconds.

See also get_scrollDelay


IHTMLMarqueeElement::start

HRESULT start(
    void
);

Begins scrolling the marquee.

  • Returns S_OK if successful, or an error value otherwise.

See also stop


IHTMLMarqueeElement::stop

HRESULT stop(
    void
);

Stops scrolling the marquee.

  • Returns S_OK if successful, or an error value otherwise.

See also start


TrueSpeed Property

*
  * Previous Topic: IHTMLMarqueeElement::put_trueSpeed
  * Next Topic: IHTMLMarqueeElement::start

IHTMLMarqueeElement::get_trueSpeed

HRESULT get_trueSpeed(
    VARIANT_BOOL *p
);

Retrieves whether the position of the marquee is calculated using the scrollDelay and scrollAmount properties, and the actual time elapsed from the last clock tick.

  • Returns S_OK if successful, or an error value otherwise.
v
Address of a boolean value that has one of the following meanings:
TRUE | The marquee advances the pixel value of scrollAmount per the number of milliseconds (ms) set for scrollDelay. For example, the marquee advances 10 pixels for every 6ms if scrollDelay is 6 and scrollAmount is 10.
FALSE | The marquee computes movement based on 60ms ticks of the clock. This means every scrollDelay value under 60 is essentially ignored, and the marquee advances the amount of scrollAmount each 60ms. For example, if scrollDelay is 6 and scrollAmount is 10, the marquee advances 10 pixels every 60ms.

By default, this property is FALSE.

See also put_trueSpeed

Up Top of Page

IHTMLMarqueeElement::put_trueSpeed

HRESULT put_trueSpeed(
    VARIANT_BOOL v
);

Sets whether the position of the marquee is calculated using the scrollDelay and scrollAmount properties, and the actual time elapsed from the last clock tick.

  • Returns S_OK if successful, or an error value otherwise.
v
Boolean value that has one of the following meanings:
TRUE | The marquee advances the pixel value of scrollAmount per the number of milliseconds (ms) set for scrollDelay. For example, the marquee advances 10 pixels for every 6ms if scrollDelay is 6 and scrollAmount is 10.
FALSE | The marquee computes movement based on 60ms ticks of the clock. This means every scrollDelay value under 60 is essentially ignored, and the marquee advances the amount of scrollAmount each 60ms. For example, if scrollDelay is 6 and scrollAmount is 10, the marquee advances 10 pixels every 60ms.

By default, this property is FALSE.

See also get_trueSpeed


Vspace Property

*
  * Previous Topic: IHTMLMarqueeElement::put_vspace
  * Next Topic: IHTMLMarqueeElement::put_hspace

IHTMLMarqueeElement::get_vspace

HRESULT get_vspace(
    long *p
);

Retrieves the vertical margins for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the vertical margins.

Similar to border, except the margins are not painted with color when the element is a link.

See also put_vspace

Up Top of Page

IHTMLMarqueeElement::put_vspace

HRESULT put_vspace(
    long v
);

Sets the vertical margins for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the margins.

Similar to border, except the margins are not painted with color when the element is a link.

See also get_vspace


Width Property

*
  * Previous Topic: IHTMLMarqueeElement::put_width
  * Next Topic: IHTMLMarqueeElement::put_height

IHTMLMarqueeElement::get_width

HRESULT get_width(
    VARIANT *p
);

Retrieves the calculated width of the element, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the width.

This read-only property is an integer value. Although an HTML author can specify the width as a percentage, this property always specifies the width in pixels.

See also put_width

Up Top of Page

IHTMLMarqueeElement::put_width

HRESULT put_width(
    VARIANT v
);

Sets the calculated width of the element, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the width.

This property is an integer value. Although an HTML author can specify the width as a percentage, this property always specifies the width in pixels.

See also get_width


Charset Property

*
  * Previous Topic: IHTMLMetaElement::put_charset
  * Next Topic: IHTMLMimeTypesCollection

IHTMLMetaElement::get_charset

HRESULT get_charset(
    BSTR *p
);

Retrieves the character set of the document.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the character set.

See also put_charset

Up Top of Page

IHTMLMetaElement::put_charset

HRESULT put_charset(
    BSTR v
);

Sets the character set of the document.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the character set.

See also get_charset


Content Property

*
  * Previous Topic: IHTMLMetaElement::put_content
  * Next Topic: IHTMLMetaElement::put_name

IHTMLMetaElement::get_content

HRESULT get_content(
    BSTR *p
);

Retrieves meta-information to be associated with the given name or HTTP response header.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the meta-information.

See also put_content

Up Top of Page

IHTMLMetaElement::put_content

HRESULT put_content(
    BSTR v
);

Sets meta-information to be associated with the given name or HTTP response header.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the meta-information.

See also get_content


HttpEquiv Property

*
  * Previous Topic: IHTMLMetaElement::put_httpEquiv
  * Next Topic: IHTMLMetaElement::put_content

IHTMLMetaElement::get_httpEquiv

HRESULT get_httpEquiv(
    BSTR *p
);

Binds the content of the element to an HTTP response header.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the HTTP response header.

If omitted, the name property should be used to identify the meta-information. The httpEquiv property is not case sensitive.

See also put_httpEquiv

Up Top of Page

IHTMLMetaElement::put_httpEquiv

HRESULT put_httpEquiv(
    BSTR v
);

Binds the content of the element to an HTTP response header.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the HTTP response header.

If omitted, the name property should be used to identify the meta-information. The httpEquiv property is not case sensitive.

See also get_httpEquiv


IHTMLMetaElement

This interface provides support for client-pull.

This element can be used only within the HEAD tag.

IHTMLMetaElement Methods
put_httpEquiv get_httpEquiv put_content
get_content put_name get_name
put_url get_url put_charset
get_charset


Name Property

*
  * Previous Topic: IHTMLMetaElement::put_name
  * Next Topic: IHTMLMetaElement::put_url

IHTMLMetaElement::get_name

HRESULT get_name(
    BSTR *p
);

Retrieves the name of the control, bookmark, or application.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the name.

The name is used to bind the value of the control when submitting a form. The NAME is not the value that is displayed for the button, reset, and submit objects. Submitting the form submits the internally stored value, not the one displayed.

JScript allows the name to be changed at run time. This does not change the name in the programming model, in the collection of elements, but does change the name used for submitting elements.

See also put_name

Up Top of Page

IHTMLMetaElement::put_name

HRESULT put_name(
    BSTR v
);

Sets the name of the control, bookmark, or application.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the name.

The name is used to bind the value of the control when submitting a form. The NAME is not the value that is displayed for the button, reset, and submit objects. Submitting the form submits the internally stored value, not the one displayed.

JScript allows the name to be changed at run time. This does not change the name in the programming model, in the collection of elements, but does change the name used for submitting elements.

See also get_name


Url Property

*
  * Previous Topic: IHTMLMetaElement::put_url
  * Next Topic: IHTMLMetaElement::put_charset

IHTMLMetaElement::get_url

HRESULT get_url(
    BSTR *p
);

Receives the URL that will be loaded after the specified time has elapsed.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the URL.

See also put_url

Up Top of Page

IHTMLMetaElement::put_url

HRESULT put_url(
    BSTR v
);

Specifies a URL to load after the specified time has elapsed.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the URL.

See also get_url


IHTMLMimeTypesCollection::get_length

HRESULT get_length(
    long *p
);

Retrieves the number of elements in the mime-types collection.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the number of elements.


IHTMLMimeTypesCollection

This interface exists for compatibility with other browsers.

Use IOmNavigator::get_mimeTypes to retrieve an interface pointer for a mime-types collection.

IHTMLMimeTypesCollection::get_length


N Property

*
  * Previous Topic: IHTMLNextIdElement::put_n
  * Next Topic: IHTMLNoShowElement

IHTMLNextIdElement::get_n

HRESULT get_n(
    BSTR *p
);

Retrieves the value of the identifier name.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the identifier name.

See also put_n

Up Top of Page

IHTMLNextIdElement::put_n

HRESULT put_n(
    BSTR v
);

Sets the value of the identifier to the string passed in.

  • Returns S_OK if successful, or an error value otherwise.
v
String value specifying the identifier name.

See also get_n


IHTMLNextIdElement

This interface provides the ability access the methods associated with the NEXTID element.

The NEXTID element is a parameter read by and generated by text editing software to create unique identifiers.

This element can only be used within the HEAD tag.

IHTMLNextIdElement Methods


IHTMLNoShowElement

This interface provides access to the properties and methods for this object and is equivalent to the IHTMLElement interface. For more information and a listing of the available methods, see the reference section for the IHTMLElement interface.


Align Property

*
  * Previous Topic: IHTMLObjectElement::put_align
  * Next Topic: IHTMLObjectElement::put_name

IHTMLObjectElement::get_align

HRESULT get_align(
    BSTR *p
);

Retrieves how the element is aligned with adjacent text.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the alignment. Can be one of these values:
absbottom | Aligns the bottom of the element with the absolute bottom of the surrounding text. The absolute bottom is equal to the baseline of the text minus the height of the largest descender in the text.
absmiddle | Aligns the middle of the element with the middle of the surrounding text. The absolute middle is the midpoint between the absolute bottom and texttop of the surrounding text.
baseline | Aligns the bottom of the element with the baseline of the surrounding text.
bottom | Aligns the bottom of the element with the bottom of the surrounding text. The bottom is equal to the baseline minus the standard height of a descender in the text.
left | Aligns the element to the left of the surrounding text. All preceding and subsequent text flows to the right of the element. This is the default value.
middle | Aligns the middle of the element with the surrounding text.
right | Aligns the element to the right of the surrounding text. All subsequent text flows to the left of the element.
texttop | Aligns the top of the element with the absolute top of the surrounding text. The absolute top is the baseline plus the height of the largest ascender in the text.
top | Aligns the top of the element with the top of the text. The top of the text is the baseline plus the standard height of an ascender in the text.

For the INPUT element, this attribute applies only to the image type. It is undefined for all other types.

See also put_align

Up Top of Page

IHTMLObjectElement::put_align

HRESULT put_align(
    BSTR v
);

Specifies how the element is aligned with adjacent text.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the alignment. Can be one of these values:
absbottom | Aligns the bottom of the element with the absolute bottom of the surrounding text. The absolute bottom is equal to the baseline of the text minus the height of the largest descender in the text.
absmiddle | Aligns the middle of the element with the middle of the surrounding text. The absolute middle is the midpoint between the absolute bottom and texttop of the surrounding text.
baseline | Aligns the bottom of the element with the baseline of the surrounding text.
bottom | Aligns the bottom of the element with the bottom of the surrounding text. The bottom is equal to the baseline minus the standard height of a descender in the text.
left | Aligns the element to the left of the surrounding text. All preceding and subsequent text flows to the right of the element. This is the default value.
middle | Aligns the middle of the element with the surrounding text.
right | Aligns the element to the right of the surrounding text. All subsequent text flows to the left of the element.
texttop | Aligns the top of the element with the absolute top of the surrounding text. The absolute top is the baseline plus the height of the largest ascender in the text.
top | Aligns the top of the element with the top of the text. The top of the text is the baseline plus the standard height of an ascender in the text.

For the INPUT element, this attribute applies only to the image type. It is undefined for all other types.

See also get_align


AltHtml Property

*
  * Previous Topic: IHTMLObjectElement::put_altHtml
  * Next Topic: IHTMLObjectElement::put_vspace

IHTMLObjectElement::get_altHtml

HRESULT get_altHtml(
    BSTR *p
);

Returns the string of alternative text that would be displayed for the object if the object is unable to be instantiated, or the browser does not support objects.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the alternative text.

See also put_altHtml

Up Top of Page

IHTMLObjectElement::put_altHtml

HRESULT put_altHtml(
    BSTR v
);

Sets the string of alternative text that could be displayed instead of the object.

  • Returns S_OK if successful, or an error value otherwise.
v
String value specifying the alternate text.

See also get_altHtml


Code Property

*
  * Previous Topic: IHTMLObjectElement::put_code
  * Next Topic: IHTMLObjectElement::get_BaseHref

IHTMLObjectElement::get_code

HRESULT get_code(
    BSTR *p
);

Retrieves a URL referencing where to find the implementation of the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the URL.

See also put_code

Up Top of Page

IHTMLObjectElement::put_code

HRESULT put_code(
    BSTR v
);

Sets a URL referencing where to find the implementation of the object.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the URL.

See also get_code


CodeBase Property

*
  * Previous Topic: IHTMLObjectElement::put_codeBase
  * Next Topic: IHTMLObjectElement::put_codeType

IHTMLObjectElement::get_codeBase

HRESULT get_codeBase(
    BSTR *p
);

Retrieves a URL referencing where to find the implementation of the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives a string specifying the URL for the object implementation.

See also put_codeBase

Up Top of Page

IHTMLObjectElement::put_codeBase

HRESULT put_codeBase(
    BSTR v
);

Sets a URL referencing where to find the implementation of the object.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the URL for the object implementation.

See also get_codeBase


CodeType Property

*
  * Previous Topic: IHTMLObjectElement::put_codeType
  * Next Topic: IHTMLObjectElement::put_code

IHTMLObjectElement::get_codeType

HRESULT get_codeType(
    BSTR *p
);

Retrieves the Internet media type for the code associated with the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the Internet media type.

See also put_codeType

Up Top of Page

IHTMLObjectElement::put_codeType

HRESULT put_codeType(
    BSTR v
);

Sets the Internet media type for the code associated with the object.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the Internet media type.

See also get_codeType


IHTMLObjectElement::get_BaseHref

HRESULT get_BaseHref(
    BSTR *p
);

Returns a string of the BASE href where the object tag can be found. This is often the base href of the document that the object is in, or the value set by a BASE tag.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the base href.

The BASE tag is used to ensure that your document's relative links are associated with the proper document path.

<BASE HREF="http://www.sample.com/hello.htm">


IHTMLObjectElement::get_classid

HRESULT get_classid(
    BSTR *p
);

Specifies the class identifier for the OBJECT.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the class identifier.

The format is: classid="clsid:controlspecificclsid "


IHTMLObjectElement::get_data

HRESULT get_data(
    BSTR *p
);

Retrieves a URL referencing the object's data.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the URL.


IHTMLObjectElement::get_form

HRESULT get_form(
    IHTMLFormElement **p
);

Retrieves a reference to the form the element is embedded on.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives an interface pointer to the form element. This parameter receives NULL if the element is not on a form.

See also IHTMLFormElement


IHTMLObjectElement::get_object

HRESULT get_object(
    IDispatch **p
);

References the contained OBJECT. For instance, if the control's object model uses a conflicting name space, preceding the control's property with object resolves the conflict

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the interface pointer for the element.


IHTMLObjectElement::get_readyState

HRESULT get_readyState(
    long *p
);

Retrieves the current state of an object being downloaded.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the state. Can be one of these values:
complete | The object is completely loaded.
interactive | The object can be interacted with even though it is not fully loaded.
loading | The object is currently being loaded.
unitialized | The object is not created. Usually when the object is being downloaded.

Each object can independently determine which of the states it exposes.


IHTMLObjectElement::get_recordset

HRESULT get_recordset(
    IDispatch **p
);

Retrieves the recordset if the object is a data provider.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives an interface pointer to the recordset.


Height Property

*
  * Previous Topic: IHTMLObjectElement::put_height
  * Next Topic: IHTMLObjectElement::get_readyState

IHTMLObjectElement::get_height

HRESULT get_height(
     VARIANT *p
);

Retrieves the calculated height of the element, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the height.

If the value of the corresponding HTML attribute was set using a percentage, this property specifies the height in pixels represented by that percentage.

See also put_height

Up Top of Page

IHTMLObjectElement::put_height

HRESULT put_height(
    VARIANT v
);

Sets the calculated height of the element, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the height.

If the value of the corresponding HTML attribute was set using a percentage, this property specifies the height in pixels represented by that percentage.

See also get_height


Hspace Property

*
  * Previous Topic: IHTMLObjectElement::put_hspace
  * Next Topic: IHTMLOListElement

IHTMLObjectElement::get_hspace

HRESULT get_hspace(
    long *p
);

Returns the amount of horizontal space defined in pixels for the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the horizontal space.

See also put_hspace

Up Top of Page

IHTMLObjectElement::put_hspace

HRESULT put_hspace(
    long v
);

Sets the amount of horizontal space defined in pixels for the object

  • Returns S_OK if successful, or an error value otherwise.
v
String value specifying the amount of horizontal space.

See also get_hspace


Name Property

*
  * Previous Topic: IHTMLObjectElement::put_name
  * Next Topic: IHTMLObjectElement::put_codeBase

IHTMLObjectElement::get_name

HRESULT get_name(
    BSTR *p
);

Retrieves the name of the control, bookmark, or application.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the name.

The name is used to bind the value of the control when submitting a form. The NAME is not the value that is displayed for the button, reset, and submit objects. Submitting the form submits the internally stored value, not the one displayed.

JScript allows the name to be changed at run time. This does not change the name in the programming model, in the collection of elements, but does change the name used for submitting elements.

See also put_name

Up Top of Page

IHTMLObjectElement::put_name

HRESULT put_name(
    BSTR v
);

Sets the name of the control, bookmark, or application.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the name.

The name is used to bind the value of the control when submitting a form. The NAME is not the value that is displayed for the button, reset, and submit objects. Submitting the form submits the internally stored value, not the one displayed.

JScript allows the name to be changed at run time. This does not change the name in the programming model, in the collection of elements, but does change the name used for submitting elements.

See also get_name


IHTMLObjectElement

This interface inserts an object onto the HTML page.

This element is a block element.

IHTMLObjectElement Methods
get_object get_classid get_data
get_recordset put_align get_align
put_name get_name put_codeBase
get_codeBase get_codeType put_code
get_code get_BaseHref put_type
get_type get_form put_width
get_width put_height get_height
get_readyState put_onreadystatechange get_onreadystatechange
put_onerror get_onerror put_altHtml
get_altHtml put_vspace get_vspace
put_hspace put_hspace get_hspace

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


Onerror Property

*
  * Previous Topic: IHTMLObjectElement::put_onerror
  * Next Topic: IHTMLObjectElement::put_altHtml

IHTMLObjectElement::get_onerror

HRESULT get_onerror(
    VARIANT *p
);

Retrieves the inline script associated with the onerror event on the OBJECT element. This error event occurs when the loading of the object causes an error.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that contains the script.

For more information on inline script, see Attaching an Event Handler in the Understanding the Event Model documentation.

See also put_onerror

Up Top of Page

IHTMLObjectElement::put_onerror

HRESULT put_onerror(
    VARIANT v
);

Sets the inline script associated with the onerror event on the OBJECT element. This error event occurs when the loading of the object causes an error.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to be set.

For more information on inline script, see Attaching an Event Handler in the Understanding the Event Model documentation.

See also get_onerror


Onreadystatechange Property

*
  * Previous Topic: IHTMLObjectElement::put_onreadystatechange
  * Next Topic: IHTMLObjectElement::put_onerror

IHTMLObjectElement::get_onreadystatechange

HRESULT get_onreadystatechange(
    VARIANT *p
);

Retrieves the inline script associated with the onreadystatechange event on the OBJECT element. This event is fired whenever the readyState for the object has changed.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that contains the script.

For more information on inline script, see Attaching an Event Handler in the Understanding the Event Model documentation.

See also put_onreadystatechange

Up Top of Page

IHTMLObjectElement::put_onreadystatechange

HRESULT put_onreadystatechange(
    VARIANT v
);

Sets the inline script associated with the onreadystatechange event on the OBJECT element. This event is fired whenever the readyState for the object has changed.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to be set.

For more information on inline script, see Attaching an Event Handler in the Understanding the Event Model documentation.

See also get_onreadystatechange


Type Property

*
  * Previous Topic: IHTMLObjectElement::put_type
  * Next Topic: IHTMLObjectElement::get_form

IHTMLObjectElement::get_type

HRESULT get_type(
    BSTR *p
);

Retrieves the MIME type of the object. This is used to retrieve a classid for the object when no CLASSID= attribute is given.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the MIME type.

See also put_type

Up Top of Page

IHTMLObjectElement::put_type

HRESULT put_type(
    BSTR v
);

Specifies the MIME type of the object. This is used to retrieve a classid for the object when no CLASSID= attribute is given.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the MIME type.

See also get_type


Vspace Property

*
  * Previous Topic: IHTMLObjectElement::put_vspace
  * Next Topic: IHTMLObjectElement::put_hspace

IHTMLObjectElement::get_vspace

HRESULT get_vspace(
    long *p
);

Returns the amount of vertical space defined in pixels for the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the vertical space.

See also put_vspace

Up Top of Page

IHTMLObjectElement::put_vspace

HRESULT put_vspace(
    long v
);

Sets the amount of vertical space defined in pixels for the object

  • Returns S_OK if successful, or an error value otherwise.
v
String value specifying the amount of vertical space.

See also get_vspace


Width Property

*
  * Previous Topic: IHTMLObjectElement::put_width
  * Next Topic: IHTMLObjectElement::put_height

IHTMLObjectElement::get_width

HRESULT get_width(
    VARIANT *p
);

Retrieves the calculated width of the element, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the width.

This property is an integer value. Although an HTML author can specify the width as a percentage, this property always specifies the width in pixels.

See also put_width

Up Top of Page

IHTMLObjectElement::put_width

HRESULT put_width(
    VARIANT v
);

Sets the calculated width of the element, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the width.

This property is an integer value. Although an HTML author can specify the width as a percentage, this property always specifies the width in pixels.

See also get_width


Compact Property

*
  * Previous Topic: IHTMLOListElement::put_compact
  * Next Topic: IHTMLOListElement::put_start

IHTMLOListElement::get_compact

HRESULT get_compact(
    VARIANT_BOOL *p
);

Determines if the list should be compacted to remove extra space between list elements.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a Boolean value specifying whether to compact the list of elements. If set to TRUE, the list is compacted; if set to FALSE, it' not.

The default value for this property is FALSE.

See also put_compact

Up Top of Page

IHTMLOListElement::put_compact

HRESULT put_compact(
    VARIANT_BOOL v
);

Specifies that the list should be compacted to remove extra space between list elements.

  • Returns S_OK if successful, or an error value otherwise.
v
Boolean value specifying whether to compact the list of elements. If set to TRUE, the list is compacted; if set to FALSE, it's not.

The default value for this property is FALSE.

See also get_compact


IHTMLOListElement IHTMLOListElement *
  * Previous Topic: IHTMLObjectElement::get_hspace
  * Next Topic: IHTMLOListElement::put_compact

IHTMLOListElement

The interface draws lines of text as an ordered list.

This element is a block element.

IHTMLOListElement Methods


Start Property

*
  * Previous Topic: IHTMLOListElement::put_start
  * Next Topic: IHTMLOListElement::put_type

IHTMLOListElement::get_start

HRESULT get_start(
    long *p
);

Retrieves the starting number for a list.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of long integer value specifying the starting point of the list.

See also put_start

Up Top of Page

IHTMLOListElement::put_start

HRESULT put_start(
    long v
);

Sets the starting number for a list.

  • Returns S_OK if successful, or an error value otherwise.
v
Long integer value specifying the starting point of the list.

See also get_start


Type Property

*
  * Previous Topic: IHTMLOListElement::put_type
  * Next Topic: IHTMLOpsProfile

IHTMLOListElement::get_type

HRESULT get_type(
    BSTR *p
);

Retrieves the current style of the list.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives one of these style values:
1 | Use numbers. This is the default value.
a | Use small letters.
A | Use large letters.
i | Use small roman numerals.
I | Use large roman numerals.

See also put_type

Up Top of Page

IHTMLOListElement::put_type

HRESULT put_type(
     BSTR v
);

Changes the style of the list.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the style. Can be one of these values:
1 | Use numbers. This is the default value.
a | Use small letters.
A | Use large letters.
i | Use small roman numerals.
I | Use large roman numerals.

See also get_type


IHTMLOpsProfile::addReadRequest

HRESULT addReadRequest(
    BSTR name,
    VARIANT reserved,
    VARIANT_BOOL *success
);

Adds a name entry to the read request queue.

  • Returns S_OK if successful, or an error value otherwise.
name
String value containing the name to add the request queue.
reserved
Reserved; do not use.
success
Address of a variable that receives TRUE if the request was successfully added to the queue, or FALSE otherwise. This could mean that either the attribute name was not recognized or the attribute is already present in the request queue.

See also doReadRequest


IHTMLOpsProfile::clearRequest

HRESULT clearRequest(void);

Clears the user profile information request. All current user profile request information is removed from the request queue.

  • Returns S_OK if successful, or an error value otherwise.


IHTMLOpsProfile::doReadRequest

HRESULT doReadRequest(
    VARIANT usage,
    VARIANT fname,
    VARIANT domain,
    VARIANT path,
    VARIANT expire,
    VARIANT reserved
);

Performs the compound request accumulated in the read request queue.

  • Returns S_OK if successful, or an error value otherwise.
usage
Type of access requested. This usage code should be one of the 13 codes defined by the Internet Privacy Working Group (IPWG), as described in the following table.
Usage code | Meaning
0 | Used for system administration.
1 | Used for research and/or product development.
2 | Used for completion and support of current transaction.
3 | Used to customize the content and design of a site.
4 | Used to improve the content of a site including advertisements.
5 | Used for notifying visitors about updates to the site.
6 | Used for contacting visitors for marketing of services or products.
7 | Used for linking other collected information.
8 | Used by a site for other purposes.
9 | Disclosed to others for customization or improvement of the content and design of the site.
10 | Disclosed to others, who may contact you, for marketing of services and/or products.
11 | Disclosed to others, who may contact you, for marketing of services and/or products, but you will have the opportunity to ask a site not to do this.
12 | Disclosed to others for any other purpose.
fname
Optional. "Friendly name" of the party requesting access to private information. For security reasons, it is not enough for the user agent to display this friendly name to the end user. In addition to this friendly name, it is essential to display the URL that originates the script requesting profile access. If this script originates from a secure connection (for example, SSL), the SSL certificate can also be used to reliably identify the party requesting access.
domain
Optional. Which pages the user's choice will apply to in the future, besides the current one; the specification follows the cookie standard (RFC-2109 http://www.cis.ohio-state.edu/htbin/rfc/rfc2109.html).
path
Optional. Which pages the user's choice will apply to in the future, besides the current one; the specification follows the cookie standard (RFC-2109 http://www.cis.ohio-state.edu/htbin/rfc/rfc2109.html).
expire
Reserved; do not use.
reserved
Reserved; do not use.

See also addReadRequest


IHTMLOpsProfile::getAttribute

HRESULT getAttribute(
    BSTR name,
    BSTR *value
);

Returns the value of the named attribute for the user profile. If read access for this attribute is not already available, this method simply returns the NULL string.

  • Returns S_OK if successful, or an error value otherwise.
name
String value specifying the name for the user profile.
value
Address of a string variable that receives the value.


IHTMLOpsProfile

This interface provides methods that requests read access to a user's profile information, and to perform read actions on the userProfile element.

IHTMLOpsProfile Methods


Checked Property

*
  * Previous Topic: IHTMLOptionButtonElement::put_checked
  * Next Topic: IHTMLOptionButtonElement::put_defaultChecked

IHTMLOptionButtonElement::get_checked

HRESULT get_checked(
    VARIANT_BOOL *p
);

Retrieves whether the given check box or radio button is selected.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives TRUE if the button is selected, or FALSE otherwise. The default value for this property is FALSE.

Check boxes that are not selected do not return their values when the form is submitted.

See also put_checked

Up Top of Page

IHTMLOptionButtonElement::put_checked

HRESULT put_checked(
    VARIANT_BOOL v
);

Sets whether the given check box or radio button is selected.

  • Returns S_OK if successful, or an error value otherwise.
v
Select flag. Set this parameter to TRUE to select the button, or FALSE otherwise.

Check boxes that are not selected do not return their values when the form is submitted.

See also get_checked


DefaultChecked Property

*
  * Previous Topic: IHTMLOptionButtonElement::put_defaultChecked
  * Next Topic: IHTMLOptionButtonElement::put_onchange

IHTMLOptionButtonElement::get_defaultChecked

HRESULT get_defaultChecked(
    VARIANT_BOOL *p
);

Determines whether the check box or radio button is selected by default.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives TRUE if the button is selected by default, or FALSE otherwise.

This value can be changed programmatically but has no effect on the appearance nor on how forms are submitted.

The default value for this property is TRUE.

See also put_defaultChecked

Up Top of Page

IHTMLOptionButtonElement::put_defaultChecked

HRESULT put_defaultChecked(
    VARIANT_BOOL v
);

Determines whether the check box or radio button is selected by default.

  • Returns S_OK if successful, or an error value otherwise.
v
Selection flag. Set this value to TRUE to select the button, or FALSE otherwise.

This value can be changed programmatically but has no effect on the appearance nor on how forms are submitted.

See also get_defaultChecked


Disabled Property

*
  * Previous Topic: IHTMLOptionButtonElement::put_disabled
  * Next Topic: IHTMLOptionButtonElement::put_status

IHTMLOptionButtonElement::get_disabled

HRESULT get_disabled(
    VARIANT_BOOL *p
);

Determines whether the control is enabled or disabled.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives TRUE if the control is disabled, or FALSE otherwise.

The default value for this property is FALSE.

See also put_disabled

Up Top of Page

IHTMLOptionButtonElement::put_disabled

HRESULT put_disabled(
    VARIANT_BOOL v
);

Enables or disables the control. A disabled control appears dimmed and does not respond to user input.

  • Returns S_OK if successful, or an error value otherwise.
v
Boolean value specifying whether to disable the control. If TRUE, the control is disabled; otherwise, it is enabled.

The default value for this property is FALSE.

See also get_disabled


IHTMLOptionButtonElement::get_form

HRESULT get_form(
    IHTMLFormElement **p
);

Retrieves a reference to the form the element is embedded on.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives an interface pointer to the form element. This parameter receives NULL if the element is not on a form.

See also IHTMLFormElement


IHTMLOptionButtonElement::get_type

HRESULT get_type(
    BSTR *p
);

Retrieves the type of intrinsic control represented by the given element object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the type. The possible values depend on the element as listed in the following table.

Element | Possible value | Description
INPUT | checkbox | Used for simple Boolean attributes or for attributes that can take multiple values at the same time. It is represented by a number of check box fields, each of which has the same name. Each selected check box generates a separate name/value pair in the submitted data, even if this results in duplicate names. The default value for check boxes is on.
file | A file upload element.
hidden | No field is presented to the user, but the content of the field is sent with the submitted form. This value can be used to transmit state information about client/server interaction.
image | An image field that you can click, causing the form to be immediately submitted. The coordinates of the selected point are measured in pixel units from the upper-left corner of the image, and are returned (along with the other contents of the form) in two name/value pairs. The x-coordinate is submitted under the name of the field with .x appended, and the y-coordinate is submitted under the name of the field with .y appended. Any value property is ignored. The image itself is specified by the SRC attribute, exactly as for the Image element.
password | Same as the TEXT attribute, except that text is not displayed as the user enters it.
radio | Used for attributes that accept a single value from a set of alternatives. Each radio-button field in the group should be given the same name. Only the selected radio button in the group generates a name/value pair in the submitted data. Radio buttons require an explicit value property.
reset | reset is a button that when clicked resets the form's fields to their specified initial values. The label to be displayed on the button can be specified just as for the submit button.
submit | submit is a button that when clicked submits the form. You can use the value attribute to provide a non-editable label to be displayed on the button. The default label is application-specific. If a submit button is clicked to submit the form, and that button has a name attribute specified, that button contributes a name/value pair to the submitted data. Otherwise, a submit button makes no contribution to the submitted data.
text | Used for a single-line text-entry field. Use in conjunction with the size and maxLength properties.
SELECT | select-multiple | Specifies a multiple-select list box.
select-one | Specifies a single-select list box.
TEXTAREA | textarea | Used for multiple-line text-entry fields. Use in conjunction with the size and maxLength properties.


Indeterminate Property

*
  * Previous Topic: IHTMLOptionButtonElement::put_indeterminate
  * Next Topic: IHTMLOptionButtonElement::get_form

IHTMLOptionButtonElement::get_indeterminate

HRESULT get_indeterminate(
    VARIANT_BOOL *p
);

Retrieves whether the check box is in the indeterminate state. An indeterminate check box has a dimmed background to represent an indeterminate state.

When indeterminate is set, the check box appears checked, but dimmed. The value of indeterminate is independent of the values for the checked and status properties.

  • Returns S_OK if successful, or an error value otherwise.
v
Address of a value that receives TRUE if the check box is indeterminate, or FALSE otherwise.

This does not change whether the check box is marked as checked, and is different than disabling the control. A check box in the indeterminate state can still receive the focus. When the user clicks an indeterminate button, the indeterminate state is turned off and the check box is appropriately checked or unchecked.

The default value for this property is FALSE.

See also put_indeterminate

Up Top of Page

IHTMLOptionButtonElement::put_indeterminate

HRESULT put_indeterminate(
    VARIANT_BOOL v
);

Changes the user interface of a check box to have a dimmed background to represent an indeterminate state.

When indeterminate is set, the check box appears checked, but dimmed. The value of indeterminate is independent of the values for the checked and status properties.

  • Returns S_OK if successful, or an error value otherwise.
v
Indeterminate flag. If TRUE, the check box is indeterminate.

This does not change whether the check box is marked as checked, and is different than disabling the control. A check box in the indeterminate state can still receive the focus. When the user clicks an indeterminate button, the indeterminate state is turned off and the check box is appropriately checked or unchecked.

The default value for this property is FALSE.

See also get_indeterminate


Name Property

*
  * Previous Topic: IHTMLOptionButtonElement::put_name
  * Next Topic: IHTMLOptionButtonElement::put_checked

IHTMLOptionButtonElement::get_name

HRESULT get_name(
    BSTR *p
);

Retrieves the name of the control, bookmark, or application.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the name.

The name is used to bind the value of the control when submitting a form. The NAME is not the value that is displayed for the button, reset, and submit objects. Submitting the form submits the internally stored value, not the one displayed.

JScript allows the name to be changed at run time. This does not change the name in the programming model, in the collection of elements, but does change the name used for submitting elements.

See also put_name

Up Top of Page

IHTMLOptionButtonElement::put_name

HRESULT put_name(
    BSTR v
);

Sets the name of the control, bookmark, or application.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the name.

The name is used to bind the value of the control when submitting a form. The NAME is not the value that is displayed for the button, reset, and submit objects. Submitting the form submits the internally stored value, not the one displayed.

JScript allows the name to be changed at run time. This does not change the name in the programming model, in the collection of elements, but does change the name used for submitting elements.

See also get_name


Onchange Property

*
  * Previous Topic: IHTMLOptionButtonElement::put_onchange
  * Next Topic: IHTMLOptionButtonElement::put_disabled

IHTMLOptionButtonElement::get_onchange

HRESULT get_onchange(
    VARIANT *p
);

Retrieves the inline script associated with the onchange event on the OptionButtonElement. This event occurs when the contents of the object have changed.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that contains the script.

For more information on inline script, see Attaching an Event Handler in the Understanding the Event Model documentation.

See also put_onchange

Up Top of Page

IHTMLOptionButtonElement::put_onchange

HRESULT put_onchange(
    VARIANT v
);

Sets the inline script associated with the onchange event on the OptionButtonElement. This event occurs when the contents of the object have changed.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to be set.

For more information on inline script, see Attaching an Event Handler in the Understanding the Event Model documentation.

See also get_onchange


IHTMLOptionButtonElement

This interface specifies a form input control.

IHTMLOptionButtonElement Methods
put_value get_value get_type
put_name get_name put_checked
get_checked put_defaultChecked get_defaultChecked
put_onchange get_onchange put_disabled
get_disabled put_status get_status
put_indeterminate get_indeterminate get_form

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


Status Property

*
  * Previous Topic: IHTMLOptionButtonElement::put_status
  * Next Topic: IHTMLOptionButtonElement::put_indeterminate

IHTMLOptionButtonElement::get_status

HRESULT get_status(
    VARIANT_BOOL *p
);

Retrieves the value of a check box or radio button. This property is equivalent to the value property for check boxes and radio buttons.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a value that receives the status. It can be either TRUE or FALSE.

See also put_status

Up Top of Page

IHTMLOptionButtonElement::put_status

HRESULT put_status(
    VARIANT_BOOL v
);

Sets the value of a check box or radio button. This property is equivalent to the value property for check boxes and radio buttons.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the status. It can be either TRUE or FALSE.

See also get_status


Value Property

*
  * Previous Topic: IHTMLOptionButtonElement::put_value
  * Next Topic: IHTMLOptionButtonElement::get_type

IHTMLOptionButtonElement::get_value

HRESULT get_value(
    BSTR *p
);

Retrieves the default or "selected" value of the given control.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value. This read-write property can be any valid string. The purpose of the string depends on the type of control, as described in the following table.
Control type | Description
checkbox | The "selected" value. The control submits this value only if the user has selected the control. Otherwise, the control submits no value.
file | The value, a file name, typed by the user into the control. Unlike other controls, this value is read-only.
hidden | The control submits this value when the form is submitted.
OPTION | The "selected" value. The containing list box control submits this value only if the user has selected the option.
password | The default value. The control displays this value when it is first created and when the user clicks the reset button.
radio | The "selected" value. The control submits this value only if the user has selected the control. Otherwise, the control submits no value.
reset | The button label. If not set, the label defaults to "Reset".
submit | The button label. If not set, the label defaults to "Submit".
text | The default value. The control displays this value when it is first created and when the user clicks the reset button.

See also put_value

Up Top of Page

IHTMLOptionButtonElement::put_value

HRESULT put_value(
    BSTR v
);

Sets the default or "selected" value of the given control.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the value. The purpose of the string depends on the type of control, as described in the following table.
Control Type | Description
checkbox | The "selected" value. The control submits this value only if the user has selected the control. Otherwise, the control submits no value.
file | The value, a file name, typed by the user into the control. Unlike other controls, this value is read-only.
hidden | The control submits this value when the form is submitted.
OPTION | The "selected" value. The containing list box control submits this value only if the user has selected the option.
password | The default value. The control displays this value when it is first created and when the user clicks the reset button.
radio | The "selected" value. The control submits this value only if the user has selected the control. Otherwise, the control submits no value.
reset | The button label. If not set, the label defaults to "Reset".
submit | The button label. If not set, the label defaults to "Submit".
text | The default value. The control displays this value when it is first created and when the user clicks the reset button.

See also get_value


DefaultSelected Property

*
  * Previous Topic: IHTMLOptionElement::put_defaultSelected
  * Next Topic: IHTMLOptionElement::put_index

IHTMLOptionElement::get_defaultSelected

HRESULT get_defaultSelected(
    VARIANT_BOOL *p
);

Determines whether the option is selected by default.

  • Returns S_OK if successful, or an error value otherwise.
v
Address of a variable that receives TRUE if the option is selected by default, or FALSE if not.

This value can be changed programmatically but has no effect on the appearance nor on how forms are submitted.

The default value for this property is TRUE.

See also put_defaultSelected

Up Top of Page

IHTMLOptionElement::put_defaultSelected

HRESULT put_defaultSelected(
    VARIANT_BOOL v
);

Specifies whether the option is selected by default.

  • Returns S_OK if successful, or an error value otherwise.
v
Selection flag. TRUE selects the option; FALSE deselects it.

This value can be changed programmatically but has no effect on the appearance nor on how forms are submitted.

The default value for this property is TRUE.

See also get_defaultSelected


IHTMLOptionElement::get_form

HRESULT get_form(
    IHTMLFormElement **p
);

Retrieves a reference to the form the element is embedded on.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives an interface pointer to the form element. This parameter receives NULL if the element is not on a form.

See also IHTMLFormElement


Index Property

*
  * Previous Topic: IHTMLOptionElement::put_index
  * Next Topic: IHTMLOptionElement::put_text

IHTMLOptionElement::get_index

HRESULT get_index(
    LONG *p
);

Retrieves the ordinal position of the option in the list box.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the ordinal position.

You can assign a value to this property without generating a syntax error, but the value is not stored.

See also put_index

Up Top of Page

IHTMLOptionElement::put_index

HRESULT put_index(
    LONG v
);

Sets the ordinal position of the option in the list box.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the ordinal position.

You can assign a value to this property without generating a syntax error, but the value is not stored.

See also get_index


IHTMLOptionElement

This interface denotes one choice in a SELECT block.

This element is a block element.

IHTMLOptionElement Methods
put_selected get_selected put_value
get_value put_defaultSelected get_defaultSelected
put_index get_index put_text
get_text get_form

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


Selected Property

*
  * Previous Topic: IHTMLOptionElement::put_selected
  * Next Topic: IHTMLOptionElement::put_value

IHTMLOptionElement::get_selected

HRESULT get_selected(
    VARIANT_BOOL *p
);

Indicates whether this item is the default.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives TRUE if the item is the default, or FALSE if not.

This attribute is used to determine whether a value is submitted with the form. If the value of the control matches the default value, the control's value is not submitted. The value is only submitted when the control's value does not match the default value. Therefore, changing this value changes the rule for whether the value is submitted with the form.

The first item is selected by default.

See also put_selected

Up Top of Page

IHTMLOptionElement::put_selected

HRESULT put_selected(
    VARIANT_BOOL v
);

Indicates whether this item is the default.

  • Returns S_OK if successful, or an error value otherwise.
v
Selected flag. Setting this parameter to TRUE selects the item; setting it to FALSE deselects it.

This attribute is used to determine whether a value is submitted with the form. If the value of the control matches the default value, the control's value is not submitted. The value is only submitted when the control's value does not match the default value. Therefore, changing this value changes the rule for whether the value is submitted with the form.

The first item is selected by default.

See also get_selected


Text Property

*
  * Previous Topic: IHTMLOptionElement::put_text
  * Next Topic: IHTMLOptionElement::get_form

IHTMLOptionElement::get_text

HRESULT get_text(
    BSTR *p
);

Retrieves the text string specified by the OPTION tag.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the string.

Assigning a value to the text property changes the text property internally but does not cause the listed value to change. Submitting the form submits the internally stored value, not the one displayed.

See also put_text

Up Top of Page

IHTMLOptionElement::put_text

HRESULT put_text(
    BSTR v
);

Sets the text string specified by the OPTION tag.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the text.

Assigning a value to the text property changes the text property internally but does not cause the listed value to change. Submitting the form submits the internally stored value, not the one displayed.

See also get_text


Value Property

*
  * Previous Topic: IHTMLOptionElement::put_value
  * Next Topic: IHTMLOptionElement::put_defaultSelected

IHTMLOptionElement::get_value

HRESULT get_value(
    BSTR *p
);

Retrieves the value of the given control. The value is submitted to the server as a name/value pair.

  • Returns S_OK if successful, or an error value otherwise.
v
Address of a variable that receives the value. It can be any valid string. The purpose of the string depends on the type of control, as described in the following table.
Control type | Description
checkbox | The "selected" value. The control submits this value only if the user has selected the control. Otherwise, the control submits no value.
file | The value, a file name, typed by the user into the control. Unlike other controls, this value is read-only.
hidden | The control submits this value when the form is submitted.
OPTION | The "selected" value. The containing list box control submits this value only if the user has selected the option.
password | The default value. The control displays this value when it is first created and when the user clicks the reset button.
radio | The "selected" value. The control submits this value only if the user has selected the control. Otherwise, the control submits no value.
reset | The button label. If not set, the label defaults to "Reset".
submit | The button label. If not set, the label defaults to "Submit".
text | The default value. The control displays this value when it is first created and when the user clicks the reset button.

See also put_value

Up Top of Page

IHTMLOptionElement::put_value

HRESULT put_value(
    BSTR v
);

Specifies the value of the given control. The value is submitted to the server as a name/value pair.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the value. It can be any valid string. The purpose of the string depends on the type of control, as described in the following table.
Control type | Description
checkbox | The "selected" value. The control submits this value only if the user has selected the control. Otherwise, the control submits no value.
file | The value, a file name, typed by the user into the control. Unlike other controls, this value is read-only.
hidden | The control submits this value when the form is submitted.
OPTION | The "selected" value. The containing list box control submits this value only if the user has selected the option.
password | The default value. The control displays this value when it is first created and when the user clicks the reset button.
radio | The "selected" value. The control submits this value only if the user has selected the control. Otherwise, the control submits no value.
reset | The button label. If not set, the label defaults to "Reset".
submit | The button label. If not set, the label defaults to "Submit".
text | The default value. The control displays this value when it is first created and when the user clicks the reset button.

See also get_value


IHTMLOptionElementFactory::create

HRESULT create(
    VARIANT text,
    VARIANT value,
    VARIANT defaultselected,
    VARIANT selected,
    IHTMLOptionElement **__MIDL_0017
);

Creates a new instance of the OPTION element. You can add the element to a SELECT block by using the IHTMLSelectElement::add method.

  • Returns S_OK if successful, or an error value otherwise.
text
Value or string specifying the text of the element.
value
String specifying the value of the element.
defaultselected
Value indicating whether this option is selected by default. If TRUE, this option is selected by default; otherwise, it isn't.
selected
Value indicating whether this is the default option in the SELECT block. If TRUE, this option is the default; otherwise, it isn't.
__MIDL_0017
Address of a variable that receives an interface pointer for the new OPTION element.

See also IHTMLOptionElement, IHTMLSelectElement::add


IHTMLOptionElementFactory

This interface creates new instances of the OPTION element.

Use IHTMLWindow2::get_Option to retrieve a pointer to this interface.

IHTMLOptionElementFactory::create


IHTMLOptionsHolder::choosecolordlg

HRESULT choosecolordlg(
    VARIANT initColor,
    long *rgbColor
);

Opens the system color picker dialog box.

  • Returns S_OK if successful, or an error value otherwise.
initColor
VARIANT containing the name of the color in the color picker. For a complete list of colors, see Color Table.
rgbColor
Long integer specifying the value of the color in the color picker. For a complete list of colors, see Color Table.


ErrorCharacter Property

*
  * Previous Topic: IHTMLOptionsHolder::put_errorCharacter
  * Next Topic: IHTMLOptionsHolder::put_errorCode

IHTMLOptionsHolder::get_errorCharacter

HRESULT get_errorCharacter(
    long *p
);

Retrieves the count of the character on the line where an error occurred.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the error code.

See also put_errorCharacter

Up Top of Page

IHTMLOptionsHolder::put_errorCharacter

HRESULT put_errorCharacter(
    long v
);

Sets the count of the character on the line where an error occurred.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the error code.

See also get_errorCharacter


ErrorCode Property

*
  * Previous Topic: IHTMLOptionsHolder::put_errorCode
  * Next Topic: IHTMLOptionsHolder::put_errorMessage

IHTMLOptionsHolder::get_errorCode

HRESULT get_errorCode(
    long *p
);

Retrieves the current error code for the error being reported.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the error code.

See also put_errorCode

Up Top of Page

IHTMLOptionsHolder::put_errorCode

HRESULT put_errorCode(
    long v
);

Sets the error code for the error being reported.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the error code.

See also get_errorCode


ErrorDebug Property

*
  * Previous Topic: IHTMLOptionsHolder::put_errorDebug
  * Next Topic: IHTMLOptionsHolder::put_productVersion

IHTMLOptionsHolder::get_errorDebug

HRESULT get_errorDebug(
    VARIANT_BOOL *p
);

Retrieves the Boolean value indicating whether to debug this error.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives TRUE to debug this error, or FALSE to not.

See also put_errorDebug

Up Top of Page

IHTMLOptionsHolder::put_errorDebug

HRESULT put_errorDebug(
    VARIANT_BOOL v
);

Set the Boolean value indicating whether to debug this error or not.

  • Returns S_OK if successful, or an error value otherwise.
v
Boolean value specifying whether to debug this error. If set to TRUE, the error is debugged; if FALSE, it is not.

See also get_errorDebug


ErrorLine Property

*
  * Previous Topic: IHTMLOptionsHolder::put_errorLine
  * Next Topic: IHTMLOptionsHolder::put_errorCharacter

IHTMLOptionsHolder::get_errorLine

HRESULT get_errorLine(
    long *p
);

Retrieves the inline script associated with the onerror event on the IHTMLOptionsHolder element. This value indicates the line number that an error occurred at and is generally used to report script errors.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that contains the script.

For more information on inline script, see Attaching an Event Handler in the Understanding the Event Model documentation.

See also put_errorLine

Up Top of Page

IHTMLOptionsHolder::put_errorLine

HRESULT put_errorLine(
    long v
);

Sets the inline script associated with the onerror event on the IHTMLOptionsHolder element. This value indicates the line number that an error occurred at and is generally used to report script errors.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to be set.

For more information on inline script, see Attaching an Event Handler in the Understanding the Event Model documentation.

See also get_errorLine


ErrorMessage Property

*
  * Previous Topic: IHTMLOptionsHolder::put_errorMessage
  * Next Topic: IHTMLOptionsHolder::put_errorDebug

IHTMLOptionsHolder::get_errorMessage

HRESULT get_errorMessage(
    BSTR *p
);

Retrieves the string text of the error message to be displayed.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the error text.

See also put_errorMessage

Up Top of Page

IHTMLOptionsHolder::put_errorMessage

HRESULT put_errorMessage(
    BSTR v
);

Sets the string text for the error message to be displayed.

  • Returns S_OK if successful, or an error value otherwise.
v
String variable specifying the error text.

See also get_errorMessage


ExecArg Property

*
  * Previous Topic: IHTMLOptionsHolder::put_execArg
  * Next Topic: IHTMLOptionsHolder::put_errorLine

IHTMLOptionsHolder::get_execArg

HRESULT get_execArg(
    VARIANT *p
);

Retrieves the variant argument of any additional parameters that were passed in.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that contains the arguments.

See also put_execArg

Up Top of Page

IHTMLOptionsHolder::put_execArg

HRESULT put_execArg(
    VARIANT v
);

Sets the variant argument; this allows additional user-data parameters to be passed in.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to be set.

See also get_execArg


FindText Property

*
  * Previous Topic: IHTMLOptionsHolder::put_findText
  * Next Topic: IHTMLOptionsHolder::sizes

IHTMLOptionsHolder::get_findText

HRESULT get_findText(
    BSTR *p
);

Retrieves the text used in a find operation.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that contains the text used for the search operation.

See also put_findText

Up Top of Page

IHTMLOptionsHolder::put_findText

HRESULT put_findText(
    BSTR v
);

Sets the text with which to seed a find operation.

  • Returns S_OK if successful, or an error value otherwise.
v
String value specifying the text used for the search operation.

See also get_findText


IHTMLOptionsHolder::get_document

HRESULT get_document(
    IHTMLDocument2 **p
);

Returns a pointer to the document that the dialog is parented by.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives an interface pointer to the IHTMLDocument2 object.


IHTMLOptionsHolder::get_fonts

HRESULT get_fonts(
    IHTMLFontNamesCollection **p
);

Returns a IHTMLFontNamesCollection pointer for a collection of all the system-supported fonts.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives an interface pointer to the IHTMLFontNamesCollection object.


IHTMLOptionsHolder::get_unsecuredWindowOfDocument

HRESULT get_unsecuredWindowOfDocument(
    IHTMLWindow2 **p
);

Retrieves the IHTMLWindow2 interface pointer to the parent document's window. This in not wrapped by a security proxy, thus is not considered secure.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the interface pointer for the IHTMLWindow2 interface.


IHTMLOptionsHolder::openfiledlg

HRESULT openfiledlg(
    VARIANT initFile,
    VARIANT initDir,
    VARIANT filter,
    VARIANT title,
    BSTR *pathName
);

Opens the system open file dialog window.

  • Returns S_OK if successful, or an error value otherwise.
initFile
VARIANT structure containing the initial file name to open.
initDir
VARIANT structure containing the initial directory to open.
filter
VARIANT structure containing the filters to use in opening the file.
title
VARIANT structure containing the initial title for the file dialog window.
pathName
String variable specifying the path for the file to be opened.

See also savefiledlg


IHTMLOptionsHolder

This interface provides the access methods to pass and control the contents and characteristics of a dialog window.

This object is a container for various options that can to be passed as arguments into a dialog windows presented from the browser.

IHTMLOptionsHolder Methods
get_document get_fonts put_execArg
get_execArg put_errorLine get_errorLine
put_errorCharacter get_errorCharacter put_errorCode
get_errorCode put_errorMessage get_errorMessage
put_errorDebug get_errorDebug put_productVersion
get_productVersion get_unsecuredWindowOfDocument put_findText
get_findText sizes openfiledlg
savefiledlg choosecolordlg showSecurityInfo

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


ProductVersion Property

*
  * Previous Topic: IHTMLOptionsHolder::put_productVersion
  * Next Topic: IHTMLOptionsHolder::get_unsecuredWindowOfDocument

IHTMLOptionsHolder::get_productVersion

HRESULT get_productVersion(
    BSTR *p
);

Retrieves the string indicating the product version information.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the product version information.

See also put_productVersion

Up Top of Page

IHTMLOptionsHolder::put_productVersion

HRESULT put_productVersion(
    BSTR v
);

Sets the string indicating the product version information.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the product version information.

See also get_productVersion


IHTMLOptionsHolder::savefiledlg

HRESULT savefiledlg(
    VARIANT initFile,
    VARIANT initDir,
    VARIANT filter,
    VARIANT title,
    BSTR *pathName
);

Opens the system save file dialog.

  • Returns S_OK if successful, or an error value otherwise.
initFile
VARIANT structure containing the file name to save the file.
initDir
VARIANT structure containing the directory to save the file.
filter
VARIANT structure containing the filters to use in saving the file.
title
VARIANT structure containing the initial title for the file dialog window.
pathName
String variable specifying the path for the file to be saved.


IHTMLOptionsHolder::showSecurityInfo

HRESULT showSecurityInfo(
    void
);

Opens the Internet security information dialog box for the zone based on the document's URL.

  • Returns S_OK if successful, or an error value otherwise.


IHTMLOptionsHolder::sizes

HRESULT sizes(
    BSTR fontName,
    IHTMLFontSizesCollection **pSizesCollection
);

Receives the IHTMLFontSizesCollection pointer to a collection of the sizes available for the font that is passed in as a parameter.

  • Returns S_OK if successful, or an error value otherwise.
fontName
String value specifying the name of the font from which to obtain the font size information.
pSizesCollection
Address of a variable that receives the interface pointer for the IHTMLFontSizesCollection element.


Align Property

*
  * Previous Topic: IHTMLParaElement::put_align
  * Next Topic: IHTMLPhraseElement

IHTMLParaElement::get_align

HRESULT get_align(
    BSTR *p
);

Displays the element left flush, right flush, or centered relative to the display or table.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives one of these values:
center | Align to the center.
left | Align to the left edge.
right | Align to the right edge.

See also put_align

Up Top of Page

IHTMLParaElement::put_align

HRESULT put_align(
    BSTR v
);

Displays the element left flush, right flush, or centered relative to the display or table.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the alignment. Can be one of these values:
center | Align to the center.
left | Align to the left edge.
right | Align to the right edge.

See also get_align


IHTMLParaElement IHTMLParaElement *
  * Previous Topic: IHTMLOptionsHolder::showSecurityInfo
  * Next Topic: IHTMLParaElement::put_align

IHTMLParaElement

This interface denotes a paragraph.

This element is a block element.

IHTMLParaElement Methods


IHTMLPhraseElement

This interface provides access to the properties and methods for this object and is equivalent to the IHTMLElement interface. For more information and a listing of the available methods, see the reference section for the IHTMLElement interface.


IHTMLPluginsCollection::get_length

HRESULT get_length(
    long *p
);

Retrieves the number of elements in the collection.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the number of elements.


IHTMLPluginsCollection

This interface provides access to a zero-based collection of all the EMBED elements in an HTML document. The elements are in the same order as they appear in the document. Use the IOmNavigator::get_plugins property to retrieve an interface pointer of this type.

The collection is indexed first by name, then by ID. If duplicate names are found, a collection of those named items is returned. The resulting collection can be referenced only by ordinal position.

IHTMLPluginsCollection Methods


IHTMLPluginsCollection::refresh

HRESULT refresh(
    VARIANT_BOOL reload
);

Refreshes the content of the collection.

  • Returns S_OK if successful, or an error value otherwise.
reload
Boolean value specifying whether to reload the document.


Background Property

*
  * Previous Topic: IHTMLRuleStyle::put_background
  * Next Topic: IHTMLRuleStyle::put_backgroundColor

IHTMLRuleStyle::get_background

HRESULT get_background(
    BSTR *p
);

Retrieves the value of the CSS background attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute. See background for details. This parameter receives NULL if the attribute is not set.

See also put_background

Up Top of Page

IHTMLRuleStyle::put_background

HRESULT put_background(
    BSTR v
);

Sets the value of the CSS background attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the value of the attribute, or NULL to remove it. See background for details.

See also get_background


BackgroundAttachment Property

*
  * Previous Topic: IHTMLRuleStyle::put_backgroundAttachment
  * Next Topic: IHTMLRuleStyle::put_backgroundPosition

IHTMLRuleStyle::get_backgroundAttachment

HRESULT get_backgroundAttachment(
    BSTR *p
);

Retrieves the value of the CSS background-attachment attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute, which can be one of these strings:
fixed | Background image remains fixed.
scroll | Background image scrolls with text.
See background-attachment for details.

See also put_backgroundAttachment

Up Top of Page

IHTMLRuleStyle::put_backgroundAttachment

HRESULT put_backgroundAttachment(
    BSTR v
);

Sets the value of the CSS background-attachment attribute for the element. If the element has a background image, this attribute determines if the image is fixed with regard to the text of the element, or if it scrolls with the text.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the value of the attribute, or NULL to remove it. Can be one of these strings:
fixed | Background image remains fixed.
scroll | Background image scrolls with text.
See background-attachment for details.

See also get_backgroundAttachment


BackgroundColor Property

*
  * Previous Topic: IHTMLRuleStyle::put_backgroundColor
  * Next Topic: IHTMLRuleStyle::put_backgroundImage

IHTMLRuleStyle::get_backgroundColor

HRESULT get_backgroundColor(
    VARIANT *p
);

Retrieves the value of the CSS background-color attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute. See background-color for details. This parameter receives NULL if the attribute is not set.

See also put_backgroundColor

Up Top of Page

IHTMLRuleStyle::put_backgroundColor

HRESULT put_backgroundColor(
    VARIANT v
);

Sets the CSS background-color attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the background color, or NULL to remove the attribute. The color can be one of the color names or values given in the Color Table reference documentation.

See also get_backgroundColor


BackgroundImage Property

*
  * Previous Topic: IHTMLRuleStyle::put_backgroundImage
  * Next Topic: IHTMLRuleStyle::put_backgroundRepeat

IHTMLRuleStyle::get_backgroundImage

HRESULT get_backgroundImage(
    BSTR *p
);

Retrieves the value of the CSS background-image attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute. See background-image for details. This parameter receives NULL if the attribute is not set.

See also put_backgroundImage

Up Top of Page

IHTMLRuleStyle::put_backgroundImage

HRESULT put_backgroundImage(
    BSTR v
);

Sets a CSS background-image attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the URL of the background image, or NULL to remove the attribute. See background-image for details.

See also get_backgroundImage


BackgroundPosition Property

*
  * Previous Topic: IHTMLRuleStyle::put_backgroundPosition
  * Next Topic: IHTMLRuleStyle::put_backgroundPositionX

IHTMLRuleStyle::get_backgroundPosition

HRESULT get_backgroundPosition(
    BSTR *p
);

Retrieves the value of the CSS background-position attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute. See background-position for details. This parameter receives NULL if the attribute is not set.

See also put_backgroundPosition

Up Top of Page

IHTMLRuleStyle::put_backgroundPosition

HRESULT put_backgroundPosition(
    BSTR v
);

Sets the value of the CSS background-position attribute for the element. The attribute determines the initial position of the background image, if any.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the initial background position, or NULL to remove the attribute. See background-position for details.

See also get_backgroundPosition


BackgroundPositionX Property

*
  * Previous Topic: IHTMLRuleStyle::put_backgroundPositionX
  * Next Topic: IHTMLRuleStyle::put_backgroundPositionY

IHTMLRuleStyle::get_backgroundPositionX

HRESULT get_backgroundPositionX(
    VARIANT *p
);

Retrieves the x-coordinate of the CSS background-position attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the x-coordinate. See background-image for details. This parameter receives NULL if the parameter is not set.

See also put_backgroundPositionX

Up Top of Page

IHTMLRuleStyle::put_backgroundPositionX

HRESULT put_backgroundPositionX(
    VARIANT v
);

Sets the x-coordinate of the CSS background-position attribute for the element. The attribute determines the initial horizontal position of the background image, if any.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the x-coordinate, or NULL to remove the attribute. See background-position for details.

See also get_backgroundPositionX


BackgroundPositionY Property

*
  * Previous Topic: IHTMLRuleStyle::put_backgroundPositionY
  * Next Topic: IHTMLRuleStyle::put_wordSpacing

IHTMLRuleStyle::get_backgroundPositionY

HRESULT get_backgroundPositionY(
    VARIANT *p
);

Retrieves the y-coordinate of the CSS background-position attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the y-coordinate. See background-position for details. This parameter receives NULL if the attribute is not set.

See also put_backgroundPositionY

Up Top of Page

IHTMLRuleStyle::put_backgroundPositionY

HRESULT put_backgroundPositionY(
    VARIANT v
);

Sets the y-coordinate of the CSS background-position attribute for the element. The attribute determines the initial vertical position of the background image, if any.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the y-coordinate, or NULL to remove the attribute. See background-position for details.

See also get_backgroundPositionY


BackgroundRepeat Property

*
  * Previous Topic: IHTMLRuleStyle::put_backgroundRepeat
  * Next Topic: IHTMLRuleStyle::put_backgroundAttachment

IHTMLRuleStyle::get_backgroundRepeat

HRESULT get_backgroundRepeat(
    BSTR *p
);

Retrieves the value of the CSS background-repeat attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute, which can be one of these strings:
norepeat | Do not repeat.
repeaty | Repeat vertically.
repeat | Repeat both horizontally and vertically.
repeatx | Repeat horizontally.
See background-image for details. This parameter receives NULL if the attribute is not set.

See also put_backgroundRepeat

Up Top of Page

IHTMLRuleStyle::put_backgroundRepeat

HRESULT put_backgroundRepeat(
    BSTR v
);

Sets the value of the CSS background-repeat attribute for the element. The attribute determines whether and how the background image, if any, is repeated.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying whether and how the image is repeated, or NULL to remove the attribute. Can be one of these strings:
norepeat | Do not repeat.
repeaty | Repeat vertically.
repeat | Repeat both horizontally and vertically.
repeatx | Repeat horizontally.
See background-repeat for details.

See also get_backgroundRepeat


Border Property

*
  * Previous Topic: IHTMLRuleStyle::put_border
  * Next Topic: IHTMLRuleStyle::put_borderTop

IHTMLRuleStyle::get_border

HRESULT get_border(
    BSTR *p
);

Retrieves the value of the CSS border attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives values that describe the border. See border for details. This parameter receives NULL if the attribute is not set.

See also put_border

Up Top of Page

IHTMLRuleStyle::put_border

HRESULT put_border(
    BSTR v
);

Sets the value of the CSS border attribute for the element. The attribute describes the color, style, and width of the border to display around the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying values that describe the border. See border for details. Set this parameter to NULL to remove the attribute.

See also get_border


BorderBottom Property

*
  * Previous Topic: IHTMLRuleStyle::put_borderBottom
  * Next Topic: IHTMLRuleStyle::put_borderLeft

IHTMLRuleStyle::get_borderBottom

HRESULT get_borderBottom(
    BSTR *p
);

Retrieves the value of the CSS border-bottom attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives values that describe the bottom border. See border-bottom for details. This parameter receives NULL if the attribute is not set.

See also put_borderBottom

Up Top of Page

IHTMLRuleStyle::put_borderBottom

HRESULT put_borderBottom(
    BSTR v
);

Sets the value of the CSS border-bottom attribute for the element. The attribute determines the width, style, and color of the bottom border.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the border width, style, and color. See border-bottom for details. Set this parameter to NULL to remove the attribute.

See also get_borderBottom


BorderBottomColor Property

*
  * Previous Topic: IHTMLRuleStyle::put_borderBottomColor
  * Next Topic: IHTMLRuleStyle::put_borderLeftColor

IHTMLRuleStyle::get_borderBottomColor

HRESULT get_borderBottomColor(
    VARIANT *p
);

Retrieves the value of the CSS border-bottom-color attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the color value. See border-bottom-color for details. This parameter receives NULL if the attribute is not set.

See also put_borderBottomColor

Up Top of Page

IHTMLRuleStyle::put_borderBottomColor

HRESULT put_borderBottomColor(
    VARIANT v
);

Sets the value of the CSS border-bottom-color attribute for the element. The attribute determines the color of the element's bottom border.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the border color, which can be one of the color names or values given in the Color Table reference documentation. Set this parameter to NULL to remove the attribute. See border-bottom-color for details.

See also get_borderBottomColor


BorderBottomStyle Property

*
  * Previous Topic: IHTMLRuleStyle::put_borderBottomStyle
  * Next Topic: IHTMLRuleStyle::put_borderLeftStyle

IHTMLRuleStyle::get_borderBottomStyle

HRESULT get_borderBottomStyle(
    BSTR *p
);

Retrieves the value of the CSS border-bottom-style attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the border style. See border-bottom-style for details. This parameter receives NULL if the attribute is not set.

See also put_borderBottomStyle

Up Top of Page

IHTMLRuleStyle::put_borderBottomStyle

HRESULT put_borderBottomStyle(
    BSTR v
);

Sets the value of the CSS border-bottom-style attribute for the element. The attribute determines the style of the bottom border.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the border style. Set this parameter to NULL to remove the attribute. See border-bottom-style for details.

See also get_borderBottomStyle


BorderBottomWidth Property

*
  * Previous Topic: IHTMLRuleStyle::put_borderBottomWidth
  * Next Topic: IHTMLRuleStyle::put_borderLeftWidth

IHTMLRuleStyle::get_borderBottomWidth

HRESULT get_borderBottomWidth(
    VARIANT *p
);

Retrieves the value of the CSS border-bottom-width attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the border width. See border-bottom-width for details. This parameter receives NULL if the attribute is not set.

See also put_borderBottomWidth

Up Top of Page

IHTMLRuleStyle::put_borderBottomWidth

HRESULT put_borderBottomWidth(
    VARIANT v
);

Sets the value of the CSS border-bottom-width attribute for the element. The attribute determines the width of the bottom border.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the border width. Set this parameter to NULL to remove the attribute. See border-bottom-width for details.

See also get_borderBottomWidth


BorderColor Property

*
  * Previous Topic: IHTMLRuleStyle::put_borderColor
  * Next Topic: IHTMLRuleStyle::put_borderTopColor

IHTMLRuleStyle::get_borderColor

HRESULT get_borderColor(
    BSTR *p
);

Retrieves the value of the CSS border-color attribute of the element. The border color must be used with the border property, except for frames. The color can be one of the color names or values given in the Color Table reference documentation.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the border color values. See border-color for details. This parameter receives NULL if the attribute is not set.

See also put_borderColor

Up Top of Page

IHTMLRuleStyle::put_borderColor

HRESULT put_borderColor(
    BSTR v
);

Sets the value of the CSS border-color attribute for the element. The attribute determines the color of the element's four borders.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the border color, which can be one of the color names or values given in the Color Table reference documentation. Set this parameter to NULL to remove the attribute. See border-left for details.

See also get_borderColor


BorderLeft Property

*
  * Previous Topic: IHTMLRuleStyle::put_borderLeft
  * Next Topic: IHTMLRuleStyle::put_borderColor

IHTMLRuleStyle::get_borderLeft

HRESULT get_borderLeft(
    BSTR *p
);

Retrieves the value of the CSS border-left attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives values that describe the left border. See border-left for details. This parameter receives NULL if the attribute is not set.

See also put_borderLeft

Up Top of Page

IHTMLRuleStyle::put_borderLeft

HRESULT put_borderLeft(
    BSTR v
);

Sets the value of the CSS border-left attribute for the element. The attribute determines the width, style, and color of the left border.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the border width, style, and color. See border-left for details. Set this parameter to NULL to remove the attribute.

See also get_borderLeft


BorderLeftColor Property

*
  * Previous Topic: IHTMLRuleStyle::put_borderLeftColor
  * Next Topic: IHTMLRuleStyle::put_borderWidth

IHTMLRuleStyle::get_borderLeftColor

HRESULT get_borderLeftColor(
    VARIANT *p
);

Retrieves the value of the CSS border-left-color attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the color value. See border-left-color for details. This parameter receives NULL if the attribute is not set.

See also put_borderLeftColor

Up Top of Page

IHTMLRuleStyle::put_borderLeftColor

HRESULT put_borderLeftColor(
    VARIANT v
);

Sets the value of the CSS border-left-color attribute for the element. The attribute determines the color of the element's left border.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the border color, which can be one of the color names or values given in the Color Table reference documentation. Set this parameter to NULL to remove the attribute. See border-left-color for details.

See also get_borderLeftColor


BorderLeftStyle Property

*
  * Previous Topic: IHTMLRuleStyle::put_borderLeftStyle
  * Next Topic: IHTMLRuleStyle::put_width

IHTMLRuleStyle::get_borderLeftStyle

HRESULT get_borderLeftStyle(
    BSTR *p
);

Retrieves the value of the CSS border-left-style attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the border style. See border-left-style for details. This parameter receives NULL if the attribute is not set.

See also put_borderLeftStyle

Up Top of Page

IHTMLRuleStyle::put_borderLeftStyle

HRESULT put_borderLeftStyle(
    BSTR v
);

Sets the value of the CSS border-left-style attribute for the element. The attribute determines the style of the left border.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the border style. Set this parameter to NULL to remove the attribute. See border-left-style for details.

See also get_borderLeftStyle


BorderLeftWidth Property

*
  * Previous Topic: IHTMLRuleStyle::put_borderLeftWidth
  * Next Topic: IHTMLRuleStyle::put_borderStyle

IHTMLRuleStyle::get_borderLeftWidth

HRESULT get_borderLeftWidth(
    VARIANT *p
);

Retrieves the value of the CSS border-left-width attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the border width. See border-left-width for details. This parameter receives NULL if the attribute is not set.

See also put_borderLeftWidth

Up Top of Page

IHTMLRuleStyle::put_borderLeftWidth

HRESULT put_borderLeftWidth(
    VARIANT v
);

Sets the value of the CSS border-left-width attribute for the element. The attribute determines the width of the left border.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the border width. Set this parameter to NULL to remove the attribute. See border-left-width for details.

See also get_borderLeftWidth


BorderRight Property

*
  * Previous Topic: IHTMLRuleStyle::put_borderRight
  * Next Topic: IHTMLRuleStyle::put_borderBottom

IHTMLRuleStyle::get_borderRight

HRESULT get_borderRight(
    BSTR *p
);

Retrieves the value of the CSS border-right attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives values that describe the right border. See border-right for details. This parameter receives NULL if the attribute is not set.

See also put_borderRight

Up Top of Page

IHTMLRuleStyle::put_borderRight

HRESULT put_borderRight(
    BSTR v
);

Sets the value of the CSS border-right attribute for the element. The attribute determines the width, style, and color of the right border.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the border width, style, and color. See border-right for details. Set this parameter to NULL to remove the attribute.

See also get_borderRight


BorderRightColor Property

*
  * Previous Topic: IHTMLRuleStyle::put_borderRightColor
  * Next Topic: IHTMLRuleStyle::put_borderBottomColor

IHTMLRuleStyle::get_borderRightColor

HRESULT get_borderRightColor(
    VARIANT *p
);

Retrieves the value of the CSS border-right-color attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the color value. See border-right-color for details. This parameter receives NULL if the attribute is not set.

See also put_borderRightColor

Up Top of Page

IHTMLRuleStyle::put_borderRightColor

HRESULT put_borderRightColor(
    VARIANT v
);

Sets the value of the CSS border-right-color attribute for the element. The attribute determines the color of the element's right border.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the border color, which can be one of the color names or values given in the Color Table reference documentation. Set this parameter to NULL to remove the attribute. See border-right-color for details.

See also get_borderRightColor


BorderRightStyle Property

*
  * Previous Topic: IHTMLRuleStyle::put_borderRightStyle
  * Next Topic: IHTMLRuleStyle::put_borderBottomStyle

IHTMLRuleStyle::get_borderRightStyle

HRESULT get_borderRightStyle(
    BSTR *p
);

Retrieves the value of the CSS border-right-style attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the border style. See border-right-style for details. This parameter receives NULL if the attribute is not set.

See also put_borderRightStyle

Up Top of Page

IHTMLRuleStyle::put_borderRightStyle

HRESULT put_borderRightStyle(
    BSTR v
);

Sets the value of the CSS border-right-style attribute for the element. The attribute determines the style of the right border.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the border style. Set this parameter to NULL to remove the attribute. See border-right-style for details.

See also get_borderRightStyle


BorderRightWidth Property

*
  * Previous Topic: IHTMLRuleStyle::put_borderRightWidth
  * Next Topic: IHTMLRuleStyle::put_borderBottomWidth

IHTMLRuleStyle::get_borderRightWidth

HRESULT get_borderRightWidth(
    VARIANT *p
);

Retrieves the value of the CSS border-right-width attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the border width. See border-right-width for details. This parameter receives NULL if the attribute is not set.

See also put_borderRightWidth

Up Top of Page

IHTMLRuleStyle::put_borderRightWidth

HRESULT put_borderRightWidth(
    VARIANT v
);

Sets the value of the CSS border-right-width attribute for the element. The attribute determines the width of the right border.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the border width. Set this parameter to NULL to remove the attribute. See border-right-width for details.

See also get_borderRightWidth


BorderStyle Property

*
  * Previous Topic: IHTMLRuleStyle::put_borderStyle
  * Next Topic: IHTMLRuleStyle::put_borderTopStyle

IHTMLRuleStyle::get_borderStyle

HRESULT get_borderStyle(
    BSTR *p
);

Retrieves the value of the CSS border-style attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the border styles. See border-style for details. This parameter receives NULL if the attribute is not set.

See also put_borderStyle

Up Top of Page

IHTMLRuleStyle::put_borderStyle

HRESULT put_borderStyle(
    BSTR v
);

Sets the value of the CSS border-style attribute for the element. The attribute determines the style of the left, right, top, and bottom borders.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the border styles. Set this parameter to NULL to remove the attribute. See border-width for details.

See also get_borderStyle


BorderTop Property

*
  * Previous Topic: IHTMLRuleStyle::put_borderTop
  * Next Topic: IHTMLRuleStyle::put_borderRight

IHTMLRuleStyle::get_borderTop

HRESULT get_borderTop(
    BSTR *p
);

Retrieves the value of the CSS border-top attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives values that describe the top border. See border-top for details. This parameter receives NULL if the attribute is not set.

See also put_borderTop

Up Top of Page

IHTMLRuleStyle::put_borderTop

HRESULT put_borderTop(
    BSTR v
);

Sets the value of the CSS border-top attribute for the element. The attribute determines the width, style, and color of the top border.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the border width, style, and color. See border-top for details. Set this parameter to NULL to remove the attribute.

See also get_borderTop


BorderTopColor Property

*
  * Previous Topic: IHTMLRuleStyle::put_borderTopColor
  * Next Topic: IHTMLRuleStyle::put_borderRightColor

IHTMLRuleStyle::get_borderTopColor

HRESULT get_borderTopColor(
    VARIANT *p
);

Retrieves the value of the CSS border-top-color attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the color value. See border-top-color for details. This parameter receives NULL if the attribute is not set.

See also put_borderTopColor

Up Top of Page

IHTMLRuleStyle::put_borderTopColor

HRESULT put_borderTopColor(
    VARIANT v
);

Sets the value of the CSS border-top-color attribute for the element. The attribute determines the color of the element's top border.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the border color, which can be one of the color names or values given in the Color Table reference documentation. Set this parameter to NULL to remove the attribute. See border-top-color for details.

See also get_borderTopColor


BorderTopStyle Property

*
  * Previous Topic: IHTMLRuleStyle::put_borderTopStyle
  * Next Topic: IHTMLRuleStyle::put_borderRightStyle

IHTMLRuleStyle::get_borderTopStyle

HRESULT get_borderTopStyle(
    BSTR *p
);

Retrieves the value of the CSS border-top-style attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the border style. See border-top-style for details. This parameter receives NULL if the attribute is not set.

See also put_borderTopStyle

Up Top of Page

IHTMLRuleStyle::put_borderTopStyle

HRESULT put_borderTopStyle(
    BSTR v
);

Sets the value of the CSS border-top-style attribute for the element. The attribute determines the style of the top border.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the border style. Set this parameter to NULL to remove the attribute. See border-top-style for details.

See also get_borderTopStyle


BorderTopWidth Property

*
  * Previous Topic: IHTMLRuleStyle::put_borderTopWidth
  * Next Topic: IHTMLRuleStyle::put_borderRightWidth

IHTMLRuleStyle::get_borderTopWidth

HRESULT get_borderTopWidth(
    VARIANT *p
);

Retrieves the value of the CSS border-top-width attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the border width. See border-top-width for details. This parameter receives NULL if the attribute is not set.

See also put_borderTopWidth

Up Top of Page

IHTMLRuleStyle::put_borderTopWidth

HRESULT put_borderTopWidth(
    VARIANT v
);

Sets the value of the CSS border-top-width attribute for the element. The attribute determines the width of the top border.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the border width. Set this parameter to NULL to remove the attribute. See border-top-width for details.

See also get_borderTopWidth


BorderWidth Property

*
  * Previous Topic: IHTMLRuleStyle::put_borderWidth
  * Next Topic: IHTMLRuleStyle::put_borderTopWidth

IHTMLRuleStyle::get_borderWidth

HRESULT get_borderWidth(
    BSTR *p
);

Retrieves the value of the CSS border-width attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the border widths. See border-width for details. This parameter receives NULL if the attribute is not set.

See also put_borderWidth

Up Top of Page

IHTMLRuleStyle::put_borderWidth

HRESULT put_borderWidth(
    BSTR v
);

Sets the value of the CSS border-width attribute for the element. The attribute determines the width of the left, right, top, and bottom borders.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the border widths. Set this parameter to NULL to remove the attribute. See border-width for details.

See also get_borderWidth


Clear Property

*
  * Previous Topic: IHTMLRuleStyle::put_clear
  * Next Topic: IHTMLRuleStyle::put_display

IHTMLRuleStyle::get_clear

HRESULT get_clear(
    BSTR *p
);

Retrieves the value of the CSS clear attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute, which can be one of these strings:
left
right
both
See clear for details. This parameter receives NULL if the attribute is not set.

See also put_clear

Up Top of Page

IHTMLRuleStyle::put_clear

HRESULT put_clear(
    BSTR v
);

Sets the value of the CSS clear attribute for the element. The attribute determines whether the element allows floating elements (typically images) on its left and right sides. More specifically, the attribute specifies the sides where floating elements are not allowed.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the sides where floating elements may not appear. Can be one of these strings:
left
right
both
Set this parameter to NULL to remove the attribute. See clear for details.

See also get_clear


Clip Property

*
  * Previous Topic: IHTMLRuleStyle::put_clip
  * Next Topic: IHTMLRuleStyle::put_filter

IHTMLRuleStyle::get_clip

HRESULT get_clip(
    BSTR *p
);

Retrieves the value of the CSS clip attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the coordinates of the clipping area. This variable receives NULL if the attribute is not set. See clip for details.

See also put_clip

Up Top of Page

IHTMLRuleStyle::put_clip

HRESULT put_clip(
    BSTR v
);

Sets the value of the CSS clip attribute for the element. The attribute determines which part of the element is visible. Any part of the element that is outside the clipping area is transparent.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the coordinates of the clipping area. Each coordinate can be a length value or "auto". Set this parameter to NULL to remove the attribute. See clip for details.

See also get_clip


Color Property

*
  * Previous Topic: IHTMLRuleStyle::put_color
  * Next Topic: IHTMLRuleStyle::put_background

IHTMLRuleStyle::get_color

HRESULT get_color(
    VARIANT *p
);

Retrieves the value of the CSS color attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute. See color for details. This parameter receives NULL if the attribute is not set.

See also put_color

Up Top of Page

IHTMLRuleStyle::put_color

HRESULT put_color(
    VARIANT v
);

Sets the CSS color attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the color, or NULL to remove the attribute. The color can be one of the color names or values given in the Color Table reference documentation. See color for details.

See also get_color


CssText Property

*
  * Previous Topic: IHTMLRuleStyle::put_cssText
  * Next Topic: IHTMLRuleStyle::put_cursor

IHTMLRuleStyle::get_cssText

HRESULT get_cssText(
    BSTR *p
);

Retrieves the persisted representation of the style rule.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the style rule.

See also put_cssText

Up Top of Page

IHTMLRuleStyle::put_cssText

HRESULT put_cssText(
    BSTR v
);

Sets the persisted representation of the style rule.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the style rule.

See also get_cssText


Cursor Property

*
  * Previous Topic: IHTMLRuleStyle::put_cursor
  * Next Topic: IHTMLRuleStyle::put_clip

IHTMLRuleStyle::get_cursor

HRESULT get_cursor(
    BSTR *p
);

Retrieves the value of the CSS cursor attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute. See cursor for details. This variable receives NULL if the attribute is not set.

See also put_cursor

Up Top of Page

IHTMLRuleStyle::put_cursor

HRESULT put_cursor(
    BSTR v
);

Sets the value of the CSS cursor attribute for the element. The attribute determines the type of cursor to display when the mouse is over the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the cursor type. Can be one of these values:
auto | Browser determines the cursor to display based on the current context.
crosshair | A simple crosshair.
default | The platform-dependent default cursor (typically an arrow).
hand | A hand.
move | A four-directional arrow typically used to indicate an object to be moved.
*-resize | An arrow cursor typically used to indicate the edge of an object to be moved during a resize operation.
text | Typically an I-bar used to indicate editable text.
wait | Typically a watch or hourglass used to indicate that the program is busy and the user should wait.

See also get_cursor


Display Property

*
  * Previous Topic: IHTMLRuleStyle::put_display
  * Next Topic: IHTMLRuleStyle::put_visibility

IHTMLRuleStyle::get_display

HRESULT get_display(
    BSTR *p
);

Retrieves the value of the display attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute. The variable receives "none" if the element is not being rendered, or NULL if it is. See display for details.

See also put_display

Up Top of Page

IHTMLRuleStyle::put_display

HRESULT put_display(
    BSTR v
);

Sets the value of the CSS display attribute for the element. The attribute determines whether the element is rendered.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying whether to render the element. If this parameter is "none", the element is not rendered; if NULL, it is rendered. See display for details.

Although you can apply the display attribute to parts of a table (such as a TR or TD element), changing the property has no effect on those parts. However, you can dynamically control the rendering of the entire table by applying the attribute to the TABLE element.

See also get_display


Filter Property

*
  * Previous Topic: IHTMLRuleStyle::put_filter
  * Next Topic: IHTMLRuleStyle::setAttribute

IHTMLRuleStyle::get_filter

HRESULT get_filter(
    BSTR *p
);

Retrieves a filter or collection of filters for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the filter.

See also put_filter

Up Top of Page

IHTMLRuleStyle::put_filter

HRESULT put_filter(
    BSTR v
);

Sets a filter or collection of filters for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the filter.

See also get_filter


Font Property

*
  * Previous Topic: IHTMLRuleStyle::put_font
  * Next Topic: IHTMLRuleStyle::put_color

IHTMLRuleStyle::get_font

HRESULT get_font(
    BSTR *p
);

Retrieves the values of the CSS font-style, font-variant, font-weight, font-size, line-height, and font-family attributes for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the values of the font-related CSS attributes. See font for details. This parameter receives NULL if no font-related CSS attributes are set for the element.

See also put_font

Up Top of Page

IHTMLRuleStyle::put_font

HRESULT put_font(
    BSTR v
);

Sets the value of the CSS font-style, font-variant, font-weight, font-size, line-height, and font-family attributes for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying values for one or more font attributes. This parameter has the following format:
[<font-style> || <font-variant> || <font-weight>] <font-size> /
[<line-height>] <font-family>
See font for details.

See also get_font


FontFamily Property

*
  * Previous Topic: IHTMLRuleStyle::put_fontFamily
  * Next Topic: IHTMLRuleStyle::put_fontStyle

IHTMLRuleStyle::get_fontFamily

HRESULT get_fontFamily(
    BSTR *p
);

Retrieves the value of the CSS font-family attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute. See font-family for details. This parameter receives NULL if the attribute is not set.

See also put_fontFamily

Up Top of Page

IHTMLRuleStyle::put_fontFamily

HRESULT put_fontFamily(
    BSTR v
);

Sets the value of the CSS font-family attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the font family, or NULL to remove the attribute. See font-family for details.

See also get_fontFamily


FontSize Property

*
  * Previous Topic: IHTMLRuleStyle::put_fontSize
  * Next Topic: IHTMLRuleStyle::put_font

IHTMLRuleStyle::get_fontSize

HRESULT get_fontSize(
    VARIANT *p
);

Retrieves the value of the CSS font-size attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute. See font-size for details. This parameter receives NULL if the attribute is not set.

See also put_fontSize

Up Top of Page

IHTMLRuleStyle::put_fontSize

HRESULT put_fontSize(
    VARIANT v
);

Sets the value of the CSS font-size attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the font size, or NULL to remove the attribute. See font-size for details.

See also get_fontSize


FontStyle Property

*
  * Previous Topic: IHTMLRuleStyle::put_fontStyle
  * Next Topic: IHTMLRuleStyle::put_fontVariant

IHTMLRuleStyle::get_fontStyle

HRESULT get_fontStyle(
    BSTR *p
);

Retrieves the value of the CSS font-style attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute, which can be one of these strings:
normal
italic
oblique
See font-style for details. This parameter receives NULL if the attribute is not set.

See also put_fontStyle

Up Top of Page

IHTMLRuleStyle::put_fontStyle

HRESULT put_fontStyle(
    BSTR v
);

Sets the value of the CSS font-style attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the font style, or NULL to remove the attribute. The font style can be one of these strings:
normal
italic
oblique
See font-style for details.

See also get_fontStyle


FontVariant Property

*
  * Previous Topic: IHTMLRuleStyle::put_fontVariant
  * Next Topic: IHTMLRuleStyle::put_fontWeight

IHTMLRuleStyle::get_fontVariant

HRESULT get_fontVariant(
    BSTR *p
);

Retrieves the value of the CSS font-variant attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute, which can be one of these strings:
normal
small-caps
See font-variant for details. This parameter receives NULL if the attribute is not set.

See also put_fontVariant

Up Top of Page

IHTMLRuleStyle::put_fontVariant

HRESULT put_fontVariant(
    BSTR v
);

Sets the value of the CSS font-variant attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the font variation, or NULL to remove the attribute. The font variation can be one of these strings:
normal
small-caps
See font-variant for details.

See also get_fontVariant


FontWeight Property

*
  * Previous Topic: IHTMLRuleStyle::put_fontWeight
  * Next Topic: IHTMLRuleStyle::put_fontSize

IHTMLRuleStyle::get_fontWeight

HRESULT get_fontWeight(
    BSTR *p
);

Retrieves the value of the CSS font-weight attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute, which can be one of these strings:
normal
bold
bolder
lighter
100
200
300
400
500
600
700
800
900
See font-weight for details. This parameter receives NULL if the attribute is not set.

See also put_fontWeight

Up Top of Page

IHTMLRuleStyle::put_fontWeight

HRESULT put_fontWeight(
    BSTR v
);

Sets the value of the CSS font-weight attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the font weight, or NULL to remove the attribute. The font weight can be one of these strings:
normal
bold
bolder
lighter
100
200
300
400
500
600
700
800
900
See font-weight for details.

See also get_fontWeight


IHTMLRuleStyle::get_position

HRESULT get_position(
    BSTR *p
);

Retrieves the value of the CSS position attribute for the element. The attribute specifies whether the element can be positioned and, if so, the position of the element relative to its parent object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute, which can be one of these strings:
absolute | The element is placed relative to the document.
relative | The element is placed relative to its parent object.
static | The element cannot be positioned.
This variable receives NULL if the attribute is not set. See position for details.

The position attribute is not inherited.


IHTMLRuleStyle::getAttribute

HRESULT getAttribute(
    BSTR strAttributeName,
    LONG lFlags,
    VARIANT *AttributeValue
);

Retrieves the value of the given attribute.

  • Returns S_OK if successful, or an error value otherwise.
strAttributeName
String specifying the name of the attribute to retrieve.
lFlags
Long integer that receives the flags.
AttributeValue
Address of a variable that receives a string, number, or Boolean value as defined by the attribute. If the attribute is not present, this method returns NULL.

If two or more attributes have the same name (differing only in uppercase and lowercase letters) and lFlags is FALSE, this method retrieves values only for the last attribute (the last to be created with this name). All other attributes of the same name are ignored.

See also setAttribute


Height Property

*
  * Previous Topic: IHTMLRuleStyle::put_height
  * Next Topic: IHTMLRuleStyle::put_styleFloat

IHTMLRuleStyle::get_height

HRESULT get_height(
    VARIANT *p
);

Retrieves the value of the CSS height attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the height. See height for details. This parameter receives NULL if the attribute is not set.

See also put_height

Up Top of Page

IHTMLRuleStyle::put_height

HRESULT put_height(
    VARIANT v
);

Sets the value of the CSS height attribute for the element. The attribute determines the element's height.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the height, which consists of a floating-point number and a units designator. See height for details. Set this parameter to NULL to remove the attribute.

See also get_height


Left Property

*
  * Previous Topic: IHTMLRuleStyle::put_left
  * Next Topic: IHTMLRuleStyle::get_position

IHTMLRuleStyle::get_left

HRESULT get_left(
    VARIANT *p
);

Retrieves the value of the CSS left attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute. The value is a string consisting of a floating-point number and a units designator. The variable receives NULL if the attribute is not set. See left for details.

See also put_left

Up Top of Page

IHTMLRuleStyle::put_left

HRESULT put_left(
    VARIANT v
);

Sets the value of the CSS left attribute for the element. The attribute determines the left position of the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value consisting of a floating-point number and a units designator. Set this parameter to NULL to remove the attribute. See left for details.

See also get_left


LetterSpacing Property

*
  * Previous Topic: IHTMLRuleStyle::put_letterSpacing
  * Next Topic: IHTMLRuleStyle::put_textDecoration

IHTMLRuleStyle::get_letterSpacing

HRESULT get_letterSpacing(
    VARIANT *p
);

Retrieves the value of the CSS letter-spacing for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute, or NULL if the attribute is not set. See letter-spacing for details.

See also put_letterSpacing

Up Top of Page

IHTMLRuleStyle::put_letterSpacing

HRESULT put_letterSpacing(
    VARIANT v
);

Sets the value of the CSS letter-spacing attribute for the element. The attribute determines the amount of space to add to the default space between letters in the element's text.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the amount of space to add. A negative value is valid. Set this parameter to NULL to remove the attribute. See letter-spacing for details.

See also get_letterSpacing


LineHeight Property

*
  * Previous Topic: IHTMLRuleStyle::put_lineHeight
  * Next Topic: IHTMLRuleStyle::put_marginTop

IHTMLRuleStyle::get_lineHeight

HRESULT get_lineHeight(
    VARIANT *p
);

Retrieves the value of the CSS line-height attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute. See line-height for details. This parameter receives NULL if the attribute is not set.

See also put_lineHeight

Up Top of Page

IHTMLRuleStyle::put_lineHeight

HRESULT put_lineHeight(
    VARIANT v
);

Sets the value of the CSS line-height attribute for the element. The attribute determines the distance between the baselines of subsequent lines of text. Use a negative line height to achieve various shadowing effects.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the line height. The height can be positive or negative. Set this parameter to NULL to remove the attribute.

See also get_lineHeight


ListStyle Property

*
  * Previous Topic: IHTMLRuleStyle::put_listStyle
  * Next Topic: IHTMLRuleStyle::put_whiteSpace

IHTMLRuleStyle::get_listStyle

HRESULT get_listStyle(
    BSTR *p
);

Retrieves the value of the CSS list-style attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute. The variable receives NULL if the attribute is not set. See list-style for details.

The list-style attribute is applicable only on elements that have the display attribute set to "list-item".

This function combines the functionality of the get_listStyleType, get_listStyleImage, and get_listStylePosition functions.

See also put_listStyle

Up Top of Page

IHTMLRuleStyle::put_listStyle

HRESULT put_listStyle(
    BSTR v
);

Sets the value of the CSS list-style attribute for the element. The attribute determines how a list-item marker is drawn.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the values of the attribute. Set this parameter to NULL to remove the attribute. See list-style for details.

The list-style attribute is applicable only on elements that have the display attribute set to "list-item". This property can be set on any element and is inherited down the tree. In HTML, this is typically the case for the LI element.

This function combines the functionality of the put_listStyleType, put_listStyleImage, and put_listStylePosition functions.

If no type or position is specified, the default type is "disk" and the default position is "outside".

See also get_listStyle


ListStyleImage Property

*
  * Previous Topic: IHTMLRuleStyle::put_listStyleImage
  * Next Topic: IHTMLRuleStyle::put_listStyle

IHTMLRuleStyle::get_listStyleImage

HRESULT get_listStyleImage(
    BSTR *p
);

Retrieves the value of the CSS list-style-image attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute, which can be either "none" or the URL of an image used as the list-item marker. The variable receives NULL if the attribute is not set. See list-style-image for details.

The list-style-image attribute is applicable only on elements that have the display attribute set to "list-item".

See also put_listStyleImage

Up Top of Page

IHTMLRuleStyle::put_listStyleImage

HRESULT put_listStyleImage(
    BSTR v
);

Sets the value of the CSS list-style-image attribute for the element. The attribute sets the image to use as the list-item marker. When the image is available, it replaces the marker.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the value of the attribute. Can be either "none" or the URL of an image. Set this parameter to NULL to remove the attribute. See list-style-image for details.

The list-style-image attribute is applicable only on elements that have the display attribute set to "list-item".

See also get_listStyleImage


ListStylePosition Property

*
  * Previous Topic: IHTMLRuleStyle::put_listStylePosition
  * Next Topic: IHTMLRuleStyle::put_listStyleImage

IHTMLRuleStyle::get_listStylePosition

HRESULT get_listStylePosition(
    BSTR *p
);

Retrieves the value of the CSS list-style-position attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute, which can be one of these strings:
inside
outside
The variable receives NULL if the attribute is not set. See list-style-position for details.

The list-style-position attribute is applicable only on elements that have the display attribute set to "list-item".

See also put_listStylePosition

Up Top of Page

IHTMLRuleStyle::put_listStylePosition

HRESULT put_listStylePosition(
    BSTR v
);

Sets the value of the CSS list-style-position attribute for the element. The attribute determines how the list-item marker is drawn with regard to the content.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the value of the attribute. Can be one of these strings:
inside
outside
Set this parameter to NULL to remove the attribute. See list-style-position for details.

The list-style-position attribute is applicable only on elements that have the display attribute set to "list-item".

See also get_listStylePosition


ListStyleType Property

*
  * Previous Topic: IHTMLRuleStyle::put_listStyleType
  * Next Topic: IHTMLRuleStyle::put_listStylePosition

IHTMLRuleStyle::get_listStyleType

HRESULT get_listStyleType(
    BSTR *p
);

Retrieves the value of the CSS list-style-type attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute, which can be one of these strings:
disk
circle
square
decimal
lower-roman
upper-roman
lower-alpha
upper-alpha
none
The variable receives NULL if the attribute is not set. See list-style-type for details.

The list-style-type attribute is applicable only on elements that have the display attribute set to "list-item".

See also put_listStyleType

Up Top of Page

IHTMLRuleStyle::put_listStyleType

HRESULT put_listStyleType(
    BSTR v
);

Sets the value of the CSS list-style-type attribute for the element. The attribute determines the appearance of the list-item marker if the list-style-image is set to "none" or if the image pointed to by the URL cannot be displayed.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the value of the attribute. Can be one of these strings:
disk
circle
square
decimal
lower-roman
upper-roman
lower-alpha
upper-alpha
none
Set this parameter to NULL to remove the attribute. See list-style-type for details.

The list-style-type attribute is applicable only on elements that have the display attribute set to "list-item".

See also get_listStyleType


Margin Property

*
  * Previous Topic: IHTMLRuleStyle::put_margin
  * Next Topic: IHTMLRuleStyle::put_paddingTop

IHTMLRuleStyle::get_margin

HRESULT get_margin(
    BSTR *p
);

Retrieves the value of the CSS margin attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the top, right, bottom, and left margins, in that order. See margin for details. Set this parameter to NULL to remove the attribute.

This function combines the functionality of the get_marginTop, get_marginRight, get_marginBottom, and get_marginLeft functions.

See also put_margin

Up Top of Page

IHTMLRuleStyle::put_margin

HRESULT put_margin(
    BSTR v
);

Sets the value of the CSS margin attribute for the element. The attribute sets the top, right, bottom, and left margins for the text of the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String that specifies the top, right, bottom, and left margins, in that order. See margin for details. Set this parameter to NULL to remove the attribute.

This function combines the functionality of the put_marginTop, put_marginRight, put_marginBottom, and put_marginLeft functions.

See also get_margin


MarginBottom Property

*
  * Previous Topic: IHTMLRuleStyle::put_marginBottom
  * Next Topic: IHTMLRuleStyle::put_marginLeft

IHTMLRuleStyle::get_marginBottom

HRESULT get_marginBottom(
    VARIANT *p
);

Retrieves the value of the CSS margin-bottom attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute. See margin-bottom for details. This parameter receives NULL if the attribute is not set.

See also put_marginBottom

Up Top of Page

IHTMLRuleStyle::put_marginBottom

HRESULT put_marginBottom(
    VARIANT v
);

Sets the value of the CSS margin-bottom attribute for the element. The attribute determines the height of the bottom margin for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the height of the bottom margin. The height can be positive or negative. See margin-bottom for details. Set this parameter to NULL to remove the attribute.

See also get_marginBottom


MarginLeft Property

*
  * Previous Topic: IHTMLRuleStyle::put_marginLeft
  * Next Topic: IHTMLRuleStyle::put_margin

IHTMLRuleStyle::get_marginLeft

HRESULT get_marginLeft(
    VARIANT *p
);

Retrieves the value of the CSS margin-left attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute. See margin-left for details. This parameter receives NULL if the attribute is not set.

See also put_marginLeft

Up Top of Page

IHTMLRuleStyle::put_marginLeft

HRESULT put_marginLeft(
    VARIANT v
);

Sets the value of the CSS margin-left attribute for the element. The attribute determines the width of the left margin for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the width of the left margin. The width can be positive or negative. See margin-left for details. Set this parameter to NULL to remove the attribute.

See also get_marginLeft


MarginRight Property

*
  * Previous Topic: IHTMLRuleStyle::put_marginRight
  * Next Topic: IHTMLRuleStyle::put_marginBottom

IHTMLRuleStyle::get_marginRight

HRESULT get_marginRight(
    VARIANT *p
);

Retrieves the value of the CSS margin-right attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute. See margin-right for details. This parameter receives NULL if the attribute is not set.

See also put_marginRight

Up Top of Page

IHTMLRuleStyle::put_marginRight

HRESULT put_marginRight(
    VARIANT v
);

Sets the value of the CSS margin-right attribute for the element. The attribute determines the width of the right margin for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the width of the right margin. The width can be positive or negative. See margin-right for details. Set this parameter to NULL to remove the attribute.

See also get_marginRight


MarginTop Property

*
  * Previous Topic: IHTMLRuleStyle::put_marginTop
  * Next Topic: IHTMLRuleStyle::put_marginRight

IHTMLRuleStyle::get_marginTop

HRESULT get_marginTop(
    VARIANT *p
);

Retrieves the value of the CSS margin-top attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute. See margin-top for details. This parameter receives NULL if the attribute is not set.

See also put_marginTop

Up Top of Page

IHTMLRuleStyle::put_marginTop

HRESULT put_marginTop(
    VARIANT v
);

Sets the value of the CSS margin-top attribute for the element. The attribute determines the height of the top margin for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the top margin. The height can be positive or negative. See margin-top for details. Set this parameter to NULL to remove the attribute.

See also get_marginTop


Overflow Property

*
  * Previous Topic: IHTMLRuleStyle::put_overflow
  * Next Topic: IHTMLRuleStyle::put_pageBreakBefore

IHTMLRuleStyle::get_overflow

HRESULT get_overflow(
    BSTR *p
);

Retrieves the value of the CSS overflow attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute, which can be one of these strings:
none
clip
scroll
The variable receives NULL if the attribute is not set. See overflow for details.

See also put_overflow

Up Top of Page

IHTMLRuleStyle::put_overflow

HRESULT put_overflow(
    BSTR v
);

Sets the value of the CSS overflow attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the value of the attribute. Can be one of these strings:
none
clip
scroll
Set this parameter to NULL to remove the attribute. See overflow for details.

See also get_overflow


Padding Property

*
  * Previous Topic: IHTMLRuleStyle::put_padding
  * Next Topic: IHTMLRuleStyle::put_border

IHTMLRuleStyle::get_padding

HRESULT get_padding(
    BSTR *p
);

Retrieves the value of the CSS padding attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the amount of top, right, bottom, and left padding, in that order. If this parameter specifies only one value, it applies to all sides. If it specifies two or three, the missing values are taken from the opposite side. See padding for details. This parameter receives NULL if the attribute is not set.

This function combines the functionality of the get_paddingTop, get_paddingRight, get_paddingBottom, and get_paddingLeft functions.

See also put_padding

Up Top of Page

IHTMLRuleStyle::put_padding

HRESULT put_padding(
    BSTR v
);

Sets the value of the CSS padding attribute for the element. The attibute determines the amount of space between the border and the element's content.

  • Returns S_OK if successful, or an error value otherwise.
v
String that specifies the amount of top, right, bottom, and left padding, in that order. See padding for details. Set this parameter to NULL to remove the attribute.

This function combines the functionality of the put_paddingTop, put_paddingRight, put_paddingBottom, and put_paddingLeft functions.

See also get_padding


PaddingBottom Property

*
  * Previous Topic: IHTMLRuleStyle::put_paddingBottom
  * Next Topic: IHTMLRuleStyle::put_paddingLeft

IHTMLRuleStyle::get_paddingBottom

HRESULT get_paddingBottom(
    VARIANT *p
);

Retrieves the value of the CSS padding-bottom attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute. See padding-bottom for details. This parameter receives NULL if the attribute is not set.

See also put_paddingBottom

Up Top of Page

IHTMLRuleStyle::put_paddingBottom

HRESULT put_paddingBottom(
    VARIANT v
);

Sets the value of the CSS padding-bottom attribute for the element. The attribute determines the amount of space between the border and the bottom of the element's content.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the amount of bottom padding. See padding-bottom for details. Set this parameter to NULL to remove the attribute.

See also get_paddingBottom


PaddingLeft Property

*
  * Previous Topic: IHTMLRuleStyle::put_paddingLeft
  * Next Topic: IHTMLRuleStyle::put_padding

IHTMLRuleStyle::get_paddingLeft

HRESULT get_paddingLeft(
    VARIANT *p
);

Retrieves the value of the CSS padding-left attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute. See padding-left for details. This parameter receives NULL if the attribute is not set.

See also put_paddingLeft

Up Top of Page

IHTMLRuleStyle::put_paddingLeft

HRESULT put_paddingLeft(
    VARIANT v
);

Sets the value of the CSS padding-left attribute for the element. The attribute determines the amount of space between the border and the left of the element's content.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the amount of left padding. See padding-left for details. Set this parameter to NULL to remove the attribute.

See also get_paddingLeft


PaddingRight Property

*
  * Previous Topic: IHTMLRuleStyle::put_paddingRight
  * Next Topic: IHTMLRuleStyle::put_paddingBottom

IHTMLRuleStyle::get_paddingRight

HRESULT get_paddingRight(
    VARIANT *p
);

Retrieves the value of the CSS padding-right attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute. See padding-right for details. This parameter receives NULL if the attribute is not set.

See also put_paddingRight

Up Top of Page

IHTMLRuleStyle::put_paddingRight

HRESULT put_paddingRight(
    VARIANT v
);

Sets the value of the CSS padding-right attribute for the element. The attribute determines the amount of space between the border and the right of the element's content.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the amount of right padding. See padding-right for details. Set this parameter to NULL to remove the attribute.

See also get_paddingRight


PaddingTop Property

*
  * Previous Topic: IHTMLRuleStyle::put_paddingTop
  * Next Topic: IHTMLRuleStyle::put_paddingRight

IHTMLRuleStyle::get_paddingTop

HRESULT get_paddingTop(
    VARIANT *p
);

Retrieves the value of the CSS padding-top attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute. See padding-top for details. This parameter receives NULL if the attribute is not set.

See also put_paddingTop

Up Top of Page

IHTMLRuleStyle::put_paddingTop

HRESULT put_paddingTop(
    VARIANT v
);

Sets the value of the CSS padding-top attribute for the element. The attribute determines the amount of space between the border and the top of the element's content.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the amount of top padding. See padding-top for details. Set this parameter to NULL to remove the attribute.

See also get_paddingTop


PageBreakAfter Property

*
  * Previous Topic: IHTMLRuleStyle::put_pageBreakAfter
  * Next Topic: IHTMLRuleStyle::put_cssText

IHTMLRuleStyle::get_pageBreakAfter

HRESULT get_pageBreakAfter(
    BSTR *p
);

Retrieves the value of the CSS page-break-after attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute, which can be one of these strings:
auto | Insert a page break after the element only if necessary.
always | Always insert a page break after the element.
left | Insert one or two page breaks after the element until a blank left page is reached.
right | Insert one or two page breaks after the element until a blank right page is reached.
The variable receives NULL if the attribute is not set. See page-break-after for details.

See also put_pageBreakAfter

Up Top of Page

IHTMLRuleStyle::put_pageBreakAfter

HRESULT put_pageBreakAfter(
    BSTR v
);

Sets the value of the CSS page-break-after attribute for the element. The attribute determines whether a page break occurs after the element and on what page the subsequent content should resume.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the value of the attribute. Can be one of these strings:
auto | Insert a page break after the element only if necessary.
always | Always insert a page break after the element.
left | Insert one or two page breaks after the element until a blank left page is reached.
right | Insert one or two page breaks after the element until a blank right page is reached.
See page-break-after for details.

See also get_pageBreakAfter


PageBreakBefore Property

*
  * Previous Topic: IHTMLRuleStyle::put_pageBreakBefore
  * Next Topic: IHTMLRuleStyle::put_pageBreakAfter

IHTMLRuleStyle::get_pageBreakBefore

HRESULT get_pageBreakBefore(
    BSTR *p
);

Retrieves the value of the CSS page-break-before attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute, which can be one of these strings:
auto | Insert a page break before the element only if necessary.
always | Always insert a page break before the element.
left | Insert one or two page breaks before the element until a blank left page is reached.
right | Insert one or two page breaks before the element until a blank right page is reached.
The variable receives NULL if the attribute is not set. See page-break-before for details.

See also put_pageBreakBefore

Up Top of Page

IHTMLRuleStyle::put_pageBreakBefore

HRESULT put_pageBreakBefore(
    BSTR v
);

Sets the value of the CSS page-break-before attribute for the element. The attribute determines whether a page break occurs before the element, and on what page the subsequent content should resume.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the value of the attribute. Can be one of these strings:
auto | Insert a page break before the element only if necessary.
always | Always insert a page break before the element.
left | Insert one or two page breaks before the element until a blank left page is reached.
right | Insert one or two page breaks before the element until a blank right page is reached.
See page-break-before for details.

See also get_pageBreakBefore


IHTMLRuleStyle::removeAttribute

HRESULT removeAttribute(
    BSTR strAttributeName,
    LONG lFlags,
    VARIANT_BOOL *pfSuccess
);

Removes the given attribute from the element.

  • Returns S_OK if successful, or an error value otherwise.
strAttributeName
String specifying the name of the attribute to remove.
lFlags
Long integer that contains the flags.
pfSuccess
Address of a variable that receives TRUE if the function succeeds, or FALSE otherwise.

See also setAttribute, getAttribute


IHTMLRuleStyle

This interface provides access to the methods that are returned when you access style property of a rule. This serves the same purpose as IHTMLStyle but in the context of a particular rule.

IHTMLRuleStyle Methods
put_fontFamily get_fontFamily put_fontStyle
get_fontStyle put_fontVariant get_fontVariant
put_fontWeight get_fontWeight put_fontSize
get_fontSize put_font get_font
put_color get_color put_background
get_background put_backgroundColor get_backgroundColor
put_backgroundImage get_backgroundImage put_backgroundRepeat
get_backgroundRepeat put_backgroundAttachment get_backgroundAttachment
put_backgroundPosition get_backgroundPosition put_backgroundPositionX
get_backgroundPositionX put_backgroundPositionY get_backgroundPositionY
put_wordSpacing get_wordSpacing put_letterSpacing
get_letterSpacing put_textDecoration get_textDecoration
put_textDecorationNone get_textDecorationNone put_textDecorationUnderline
get_textDecorationUnderline put_textDecorationOverline get_textDecorationOverline
put_textDecorationLineThrough get_textDecorationLineThrough put_textDecorationBlink
get_textDecorationBlink put_verticalAlign get_verticalAlign
put_textTransform get_textTransform put_textAlign
get_textAlign put_textIndent get_textIndent
put_lineHeight get_lineHeight put_marginTop
get_marginTop put_marginRight get_marginRight
put_marginBottom get_marginBottom put_marginLeft
get_marginLeft put_margin get_margin
put_paddingTop get_paddingTop put_paddingRight
get_paddingRight put_paddingBottom get_paddingBottom
put_paddingLeft get_paddingLeft put_padding
get_padding put_border get_border
put_borderTop get_borderTop put_borderRight
get_borderRight put_borderBottom get_borderBottom
put_borderLeft get_borderLeft put_borderColor
get_borderColor put_borderTopColor get_borderTopColor
put_borderRightColor get_borderRightColor put_borderBottomColor
get_borderBottomColor put_borderLeftColor get_borderLeftColor
put_borderWidth get_borderWidth put_borderTopWidth
get_borderTopWidth put_borderRightWidth get_borderRightWidth
put_borderBottomWidth get_borderBottomWidth put_borderLeftWidth
get_borderLeftWidth put_borderStyle get_borderStyle
put_borderTopStyle get_borderTopStyle put_borderRightStyle
get_borderRightStyle put_borderBottomStyle get_borderBottomStyle
put_borderLeftStyle get_borderLeftStyle put_width
get_width put_height get_height
put_styleFloat get_styleFloat put_clear
get_clear put_display get_display
put_visibility get_visibility put_listStyleType
get_listStyleType put_listStylePosition get_listStylePosition
put_listStyleImage get_listStyleImage put_listStyle
get_listStyle put_whiteSpace get_whiteSpace
put_top get_top put_left
get_left get_position put_zIndex
get_zIndex put_overflow get_overflow
put_pageBreakBefore get_pageBreakBefore put_pageBreakAfter
get_pageBreakAfter put_cssText get_cssText
put_cursor get_cursor put_clip
get_clip put_filter get_filter
setAttribute getAttribute removeAttribute

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


IHTMLRuleStyle::setAttribute

HRESULT setAttribute(
    BSTR strAttributeName,
    VARIANT AttributeValue,
    LONG lFlags
);

Sets the value of the given attribute. If the attribute is not already present, the method adds the attribute to the element and sets the value.

  • Returns S_OK if successful, or an error value otherwise.
strAttributeName
String specifying the name of the attribute to set.
AttributeValue
String, number, or Boolean value to assign to the attribute.
lFlags
Long integer value that specifies the flags.

See also getAttribute


StyleFloat Property

*
  * Previous Topic: IHTMLRuleStyle::put_styleFloat
  * Next Topic: IHTMLRuleStyle::put_clear

IHTMLRuleStyle::get_styleFloat

HRESULT get_styleFloat(
    BSTR *p
);

Retrieves the value of the CSS float attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute, which can be one of these strings:
left
right
none
See height for details. This parameter receives NULL if the attribute is not set.

See also put_styleFloat

Up Top of Page

IHTMLRuleStyle::put_styleFloat

HRESULT put_styleFloat(
    BSTR v
);

Sets the value of the CSS float attribute for the element. The attribute determines whether the element floats, causing text to flow around it.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the value of the attribute. Can be one of these strings:
left
right
none
Set this parameter to NULL to remove the attribute. See float for details.

See also get_styleFloat


TextAlign Property

*
  * Previous Topic: IHTMLRuleStyle::put_textAlign
  * Next Topic: IHTMLRuleStyle::put_textIndent

IHTMLRuleStyle::get_textAlign

HRESULT get_textAlign(
    BSTR *p
);

Retrieves the value of the CSS text-align attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute, which can be one of these strings:
left
right
center
justify
See text-align for details. This parameter receives NULL if the attribute is not set.

See also put_textAlign

Up Top of Page

IHTMLRuleStyle::put_textAlign

HRESULT put_textAlign(
    BSTR v
);

Sets the value of the CSS text-align attribute for the element. The attribute determines the alignment of the element's text.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the text alignment, or NULL to remove the attribute. Can be one of these strings:
left
right
center
justify
See text-align for details.

See also get_textAlign


TextDecoration Property

*
  * Previous Topic: IHTMLRuleStyle::put_textDecoration
  * Next Topic: IHTMLRuleStyle::put_textDecorationNone

IHTMLRuleStyle::get_textDecoration

HRESULT get_textDecoration(
    BSTR *p
);

Retrieves the value of the CSS text-decoration attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute, or NULL if the attribute is not set. See text-decoration for details.

See also put_textDecoration

Up Top of Page

IHTMLRuleStyle::put_textDecoration

HRESULT put_textDecoration(
    BSTR v
);

Sets the value of the CSS text-decoration attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the text decorations. Can be "none" or one of the following strings:
underline
overline
line-through
Set this parameter to NULL to remove the attribute. See text-decoration for details.

See also get_textDecoration


TextDecorationBlink Property

*
  * Previous Topic: IHTMLRuleStyle::put_textDecorationBlink
  * Next Topic: IHTMLRuleStyle::put_verticalAlign

IHTMLRuleStyle::get_textDecorationBlink

HRESULT get_textDecorationBlink(
    VARIANT_BOOL *p
);

Retrieves whether the element's CSS text-decoration attribute has a value of "blink".

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives TRUE if the attribute has a value of "blink", or FALSE if not. See text-decoration for details.

See also put_textDecorationBlink

Up Top of Page

IHTMLRuleStyle::put_textDecorationBlink

HRESULT put_textDecorationBlink(
    VARIANT_BOOL v
);

Sets the value of the element's CSS text-decoration attribute to "blink", or removes the "blink" value from the attribute.

  • Returns S_OK if successful, or an error value otherwise.
v
Boolean value. TRUE sets the attribute to "blink"; FALSE removes the "blink" value from the attribute. See text-decoration for details.

See also get_textDecorationBlink


TextDecorationLineThrough Property

*
  * Previous Topic: IHTMLRuleStyle::put_textDecorationLineThrough
  * Next Topic: IHTMLRuleStyle::put_textDecorationBlink

IHTMLRuleStyle::get_textDecorationLineThrough

HRESULT get_textDecorationLineThrough(
    VARIANT_BOOL *p
);

Retrieves whether the element's CSS text-decoration attribute has a value of "line-through".

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives TRUE if the attribute has a value of "line-through", or FALSE if not. See text-decoration for details.

See also put_textDecorationLineThrough

Up Top of Page

IHTMLRuleStyle::put_textDecorationLineThrough

HRESULT put_textDecorationLineThrough(
    VARIANT_BOOL v
);

Sets the value of the element's CSS text-decoration attribute to "line-through", or removes the "line-through" value from the attribute.

  • Returns S_OK if successful, or an error value otherwise.
v
Boolean value. TRUE sets the attribute to "line-through"; FALSE removes the "line-through" value from the attribute. See text-decoration for details.

See also get_textDecorationLineThrough


TextDecorationNone Property

*
  * Previous Topic: IHTMLRuleStyle::put_textDecorationNone
  * Next Topic: IHTMLRuleStyle::put_textDecorationUnderline

IHTMLRuleStyle::get_textDecorationNone

HRESULT get_textDecorationNone(
    VARIANT_BOOL *p
);

Retrieves whether the element's CSS text-decoration attribute has a value of "none".

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives TRUE if the attribute has a value of "none", or FALSE if not. See text-decoration for details.

See also put_textDecorationNone

Up Top of Page

IHTMLRuleStyle::put_textDecorationNone

HRESULT put_textDecorationNone(
    VARIANT_BOOL v
);

Sets the value of the element's CSS text-decoration attribute to "none", or removes the "none" value from the attribute.

  • Returns S_OK if successful, or an error value otherwise.
v
Boolean value. TRUE sets the attribute to "none"; FALSE removes the "none" value from the attribute. See text-decoration for details.

See also get_textDecorationNone


TextDecorationOverline Property

*
  * Previous Topic: IHTMLRuleStyle::put_textDecorationOverline
  * Next Topic: IHTMLRuleStyle::put_textDecorationLineThrough

IHTMLRuleStyle::get_textDecorationOverline

HRESULT get_textDecorationOverline(
    VARIANT_BOOL *p
);

Retrieves whether the element's CSS text-decoration attribute has a value of "overline".

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives TRUE if the attribute has a value of "overline", or FALSE if not. See text-decoration for details.

See also put_textDecorationOverline

Up Top of Page

IHTMLRuleStyle::put_textDecorationOverline

HRESULT put_textDecorationOverline(
    VARIANT_BOOL v
);

Sets the value of the element's CSS text-decoration attribute to "overline", or removes the "overline" value from the attribute.

  • Returns S_OK if successful, or an error value otherwise.
v
Boolean value. TRUE sets the attribute to "overline"; FALSE removes the "overline" value from the attribute. See text-decoration for details.

See also get_textDecorationOverline


TextDecorationUnderline Property

*
  * Previous Topic: IHTMLRuleStyle::put_textDecorationUnderline
  * Next Topic: IHTMLRuleStyle::put_textDecorationOverline

IHTMLRuleStyle::get_textDecorationUnderline

HRESULT get_textDecorationUnderline(
    VARIANT_BOOL *p
);

Retrieves whether the element's CSS text-decoration attribute has a value of "underline".

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives TRUE if the attribute has a value of "underline", or FALSE if not. See text-decoration for details.

See also put_textDecorationUnderline

Up Top of Page

IHTMLRuleStyle::put_textDecorationUnderline

HRESULT put_textDecorationUnderline(
    VARIANT_BOOL v
);

Sets the value of the element's CSS text-decoration attribute to "underline", or removes the "underline" value from the attribute.

  • Returns S_OK if successful, or an error value otherwise.
v
Boolean value. TRUE sets the attribute to "underline"; FALSE removes the "underline" value from the attribute. See text-decoration for details.

See also get_textDecorationUnderline


TextIndent Property

*
  * Previous Topic: IHTMLRuleStyle::put_textIndent
  * Next Topic: IHTMLRuleStyle::put_lineHeight

IHTMLRuleStyle::get_textIndent

HRESULT get_textIndent(
    VARIANT *p
);

Retrieves the value of the CSS text-indent attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute. See text-indent for details. This parameter receives NULL if the attribute is not set.

See also put_textIndent

Up Top of Page

IHTMLRuleStyle::put_textIndent

HRESULT put_textIndent(
    VARIANT v
);

Sets the value of the CSS text-indent attribute for the element. The attribute determines the amount of indention before the element's first line of formatted text.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the amount of indention, or NULL to remove the attribute. The amount can be positive or negative. See text-indent for details.

See also get_textIndent


TextTransform Property

*
  * Previous Topic: IHTMLRuleStyle::put_textTransform
  * Next Topic: IHTMLRuleStyle::put_textAlign

IHTMLRuleStyle::get_textTransform

HRESULT get_textTransform(
    BSTR *p
);

Retrieves the value of the CSS text-transform attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute, which can be one of these strings:
capitalize | First letter in the text is capitalized.
lowercase | All letters in the text are converted to lowercase.
uppercase | All letters in the text are converted to uppercase.
See text-transform for details. This parameter receives NULL if the attribute is not set.

See also put_textTransform

Up Top of Page

IHTMLRuleStyle::put_textTransform

HRESULT put_textTransform(
    BSTR v
);

Sets the value of the CSS text-transform attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the text transformation, or NULL to remove the attribute. Can be one of these strings:
capitalize | First letter in the text is capitalized.
lowercase | All letters in the text are converted to lowercase.
uppercase | All letters in the text are converted to uppercase.
See text-transform for details.

See also get_textTransform


Top Property

*
  * Previous Topic: IHTMLRuleStyle::put_top
  * Next Topic: IHTMLRuleStyle::put_left

IHTMLRuleStyle::get_top

HRESULT get_top(
    VARIANT *p
);

Retrieves the value of the CSS top attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute. The value is a string consisting of a floating-point number and a units designator. The variable receives NULL if the attribute is not set. See top for details.

See also put_top

Up Top of Page

IHTMLRuleStyle::put_top

HRESULT put_top(
    VARIANT v
);

Sets the value of the CSS top attribute for the element. The attribute determines the top position of the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value consisting of a floating-point number and a units designator. Set this parameter to NULL to remove the attribute. See top for details.

See also get_top


VerticalAlign Property

*
  * Previous Topic: IHTMLRuleStyle::put_verticalAlign
  * Next Topic: IHTMLRuleStyle::put_textTransform

IHTMLRuleStyle::get_verticalAlign

HRESULT get_verticalAlign(
    VARIANT *p
);

Retrieves the value of the CSS vertical-align attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute, or NULL if the attribute is not set. Can be one of these strings:
baseline
middle
sub
super
text-top
text-bottom
top
bottom
See vertical-align for details.

See also put_verticalAlign

Up Top of Page

IHTMLRuleStyle::put_verticalAlign

HRESULT put_verticalAlign(
    VARIANT v
);

Sets the value of the CSS vertical-align attribute for the element. The attribute determines the vertical positioning of the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the vertical alignment. Can be a percentage (either positive or negative) of the line height of the element, or one of the values below. These values are relative to the parent element;
baseline
middle
sub
super
text-top
text-bottom
These values are relative to the formatted line of which the element is a part:
top
bottom
Set this parameter to NULL to remove the attribute. See vertical-align for details.

See also get_verticalAlign


Visibility Property

*
  * Previous Topic: IHTMLRuleStyle::put_visibility
  * Next Topic: IHTMLRuleStyle::put_listStyleType

IHTMLRuleStyle::get_visibility

HRESULT get_visibility(
    BSTR *p
);

Retrieves the value of the visibility attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute, which can be one of these strings:
visible
hidden
inherit
The variable receives NULL if the attribute is not set. See visibility for details.

See also put_visibility

Up Top of Page

IHTMLRuleStyle::put_visibility

HRESULT put_visibility(
    BSTR v
);

Sets the value of the CSS visibility attribute for the element. The attribute determines whether the content of the element is visible.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying whether the element is visible. Can be one of these strings:
visible
hidden
inherit
Set this parameter to NULL to remove the attribute. See visibility for details.

Space is reserved for the element's content regardless of the value of the visibility attribute.

See also get_visibility


WhiteSpace Property

*
  * Previous Topic: IHTMLRuleStyle::put_whiteSpace
  * Next Topic: IHTMLRuleStyle::put_top

IHTMLRuleStyle::get_whiteSpace

HRESULT get_whiteSpace(
    BSTR *p
);

Retrieves the value of the CSS white-space attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute, which can be one of these strings:
normal | Consecutive white-space characters are replaced with a single space.
nowrap | Linebreak characters are preserved, but consecutive spaces and tab characters are replaced with a single space.
pre | All white-space characters (including line breaks) are preserved.
The variable receives NULL if the attribute is not set.

See also put_whiteSpace

Up Top of Page

IHTMLRuleStyle::put_whiteSpace

HRESULT put_whiteSpace(
    BSTR v
);

Sets the CSS white-space attribute for the element. The attribute determines whether and how white-space characters in the element are displayed.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the value of the attribute. Can be one of these strings:
normal | Consecutive white-space characters are replaced with a single space.
nowrap | Linebreak characters are preserved, but consecutive spaces and tab characters are replaced with a single space.
pre | All white-space characters (including line breaks) are preserved.
Set this parameter to NULL to remove the attribute.

See also get_whiteSpace


Width Property

*
  * Previous Topic: IHTMLRuleStyle::put_width
  * Next Topic: IHTMLRuleStyle::put_height

IHTMLRuleStyle::get_width

HRESULT get_width(
    VARIANT *p
);

Retrieves the value of the CSS width attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the width. See width for details. This parameter receives NULL if the attribute is not set.

See also put_height

Up Top of Page

IHTMLRuleStyle::put_width

HRESULT put_width(
    VARIANT v
);

Sets the value of the CSS width attribute for the element. The attribute determines the element's width.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the width, which consists of a floating-point number and a units designator. See width for details. Set this parameter to NULL to remove the attribute.

See also get_width


WordSpacing Property

*
  * Previous Topic: IHTMLRuleStyle::put_wordSpacing
  * Next Topic: IHTMLRuleStyle::put_letterSpacing

IHTMLRuleStyle::get_wordSpacing

HRESULT get_wordSpacing(
    VARIANT *p
);

Retrieves the value of the CSS word-spacing attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute, or NULL if the attribute is not set.

See also put_wordSpacing

Up Top of Page

IHTMLRuleStyle::put_wordSpacing

HRESULT put_wordSpacing(
    VARIANT v
);

Sets the value of the CSS word-spacing attribute for the element. The attribute determines the amount of space to add to the default space between words in the element's text.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the amount of space to add. A negative value is valid. Set this parameter to NULL to remove the attribute.

See also get_wordSpacing


ZIndex Property

*
  * Previous Topic: IHTMLRuleStyle::put_zIndex
  * Next Topic: IHTMLRuleStyle::put_overflow

IHTMLRuleStyle::get_zIndex

HRESULT get_zIndex(
    VARIANT *p
);

Retrieves the value of the CSS z-index attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the z-index. The variable receives a positive value if the element is positioned above the text, and a negative value if it is below. The variable receives NULL if the attribute is not set. See z-index for details.

See also put_zIndex

Up Top of Page

IHTMLRuleStyle::put_zIndex

HRESULT put_zIndex(
    VARIANT v
);

Sets the value of the CSS z-index attribute for the element. The attribute determines whether the element is positioned above or below the text.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the z-index. A positive value positions the element above the text, and a negative value positions it below. Set this parameter to NULL to remove the attribute. See z-index for details.

See also get_zIndex


BufferDepth Property

*
  * Previous Topic: IHTMLScreen::put_bufferDepth
  * Next Topic: IHTMLScreen::get_width

IHTMLScreen::get_bufferDepth

HRESULT get_bufferDepth(
    long *p
);

Retrieves an offscreen bitmap buffer.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the buffer depth. Can be one of these values:
0 | No explicit buffering. The colorDepth property is set to the screen depth.
-1 | Perform buffering at the screen depth. The colorDepth property is set to the screen depth.
1, 4, 8, 15, 16, 24, or 32 | Perform buffering using the given bits-per-pixel. The colorDepth is also set to this value. The value 15 specifies 16 bits-per-pixel, in which only 15 bits are used in a 5-5-5 layout of RGB values.

Nonsupported values cause bufferDepth to be set to -1. When bufferDepth is -1 and the user changes system settings that affect the screen depth, the buffer depth is automatically updated to the new depth. This is not the case if you set bufferDepth to a specific value.

See also put_bufferDepth

Up Top of Page

IHTMLScreen::put_bufferDepth

HRESULT put_bufferDepth(
    long v
);

Sets an offscreen bitmap buffer.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the buffer depth. Can be one of these values:
0 | No explicit buffering. The colorDepth property is set to the screen depth.
-1 | Perform buffering at the screen depth. The colorDepth property is set to the screen depth.
1, 4, 8, 15, 16, 24, or 32 | Perform buffering using the given bits-per-pixel. The colorDepth is also set to this value. The value 15 specifies 16 bits-per-pixel, in which only 15 bits are used in a 5-5-5 layout of RGB values.

Nonsupported values cause bufferDepth to be set to -1. When bufferDepth is -1 and the user changes system settings that affect the screen depth, the buffer depth is automatically updated to the new depth. This is not the case if you set bufferDepth to a specific value.

See also get_bufferDepth


IHTMLScreen::get_availHeight

HRESULT get_availHeight(
    long *p
);

Retrieves the height of the working area of the system's screen.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the height value.

See also get_availWidth


IHTMLScreen::get_availWidth

HRESULT get_availWidth(
    long *p
);

Retrieves the width of the working area of the system's screen.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the width value.

See also get_availHeight


IHTMLScreen::get_colorDepth

HRESULT get_colorDepth(
    long *p
) ;

Retrieves the bits-per-pixel used for colors on the destination device or buffer. Script programmers use this value when deciding how best to use colors.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the color depth.

The value of this read-only property depends on the bufferDepth property. If bufferDepth is 0 or -1, colorDepth is equal to the bits-per-pixel value for the screen or printer. If bufferDepth is non-zero, colorDepth is equal to bufferDepth.


IHTMLScreen::get_fontSmoothingEnabled

HRESULT get_fontSmoothingEnabled(
    VARIANT_BOOL *p
);

Retrieves a Boolean of the system setting indicating whether font smoothing is enabled.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives TRUE if font smothing is enabled, or FALSE otherwise.


IHTMLScreen::get_height

HRESULT get_height(
    long *p
);

Retrieves the vertical resolution of the screen, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the vertical resolution.

See also get_width


IHTMLScreen::get_width

HRESULT get_width(
    long *p
);

Retrieves the horizontal resolution of the screen, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the horizontal resolution.

See also get_height


IHTMLScreen

This interface supplies information about the client's screen and rendering capabilities.

IHTMLScreen Methods
get_colorDepth put_bufferDepth get_bufferDepth
get_width get_height put_updateInterval
get_updateInterval get_availHeight get_availWidth
get_fontSmoothingEnabled


UpdateInterval Property

*
  * Previous Topic: IHTMLScreen::put_updateInterval
  * Next Topic: IHTMLScreen::get_availHeight

IHTMLScreen::get_updateInterval

HRESULT get_updateInterval(
    long *p
);

Retrieves the update interval for the screen. The interval causes invalidations to the window to be buffered and then drawn in the given millisecond intervals. The purpose is to limit excessive invalidations that reduce the overall painting performance, which can happen if there is an overabundance of flipbook-style animations occurring at once.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the number of milliseconds between updates to the screen. This parameter receives zero (0) if the update interval is disabled.

See also put_updateInterval

Up Top of Page

IHTMLScreen::put_updateInterval

HRESULT put_updateInterval(
    long v
);

Sets the update interval for the screen. The interval causes invalidation's to the window to be buffered and then drawn in the given millisecond intervals. The purpose is to limit excessive invalidation's that reduce the overall painting performance, which can happen if there is an overabundance of flipbook-style animation's occurring at once.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the number of milliseconds between updates to the screen. A value of zero disables the update interval.

Use this property judiciously—a value too small or too large will adversely affect the page rendering response.

See also get_updateInterval


Defer Property

*
  * Previous Topic: IHTMLScriptElement::put_defer
  * Next Topic: IHTMLScriptElement::get_readyState

IHTMLScriptElement::get_defer

HRESULT get_defer(
    VARIANT_BOOL *p
);

Retrieves the Boolean value indicating whether this script's execution is deferred until the document completes loading.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives TRUE if the script execution is deferred, or FALSE if not.

See also put_defer

Up Top of Page

IHTMLScriptElement::put_defer

HRESULT put_defer(
    VARIANT_BOOL v
);

Sets the Boolean value indicating whether this script's execution is deferred until the document completes loading.

  • Returns S_OK if successful, or an error value otherwise.
v
Boolean value specifying whether the script's execution is deferred until after the document has completed loading. If TRUE, the script execution is deferred; otherwise, the script will execute.

See also get_defer


Event Property

*
  * Previous Topic: IHTMLScriptElement::put_event
  * Next Topic: IHTMLScriptElement::put_text

IHTMLScriptElement::get_event

HRESULT get_event(
    BSTR *p
);

Retrieves the event for which the script is being written.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the event.

See also put_event

Up Top of Page

IHTMLScriptElement::put_event

HRESULT put_event(
    BSTR v
);

Sets the event for which the script is being written.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the event.

See also get_event


IHTMLScriptElement::get_readyState

HRESULT get_readyState(
    BSTR *p
);

Retrieves the current state of an object being downloaded.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the state. Can be one of these values:
complete | The object is completely loaded.
interactive | The object can be interacted with even though it is not fully loaded.
loading | The object is currently being loaded.
unitialized | The object is not created. Usually when the object is being downloaded.

Each object can independently determine which of the states it exposes.


HtmlFor Property

*
  * Previous Topic: IHTMLScriptElement::put_htmlFor
  * Next Topic: IHTMLScriptElement::put_event

IHTMLScriptElement::get_htmlFor

HRESULT get_htmlFor(
    BSTR *p
);

Retrieves which element is being bound to the event script. This htmlFor property corresponds to the HTML FOR= attribute.

For more information on inline script, see Attaching an Event Handler in the Event Model documantation.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the element name.

See also put_htmlFor

Up Top of Page

IHTMLScriptElement::put_htmlFor

HRESULT put_htmlFor(
    BSTR v
);

Sets which element is being bound to the event script. This htmlFor property corresponds to the HTML FOR= attribute.

For more information on inline script, see Attaching an Event Handler in the Event Model documantation.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the element name.

See also get_htmlFor


Onerror Property

*
  * Previous Topic: IHTMLScriptElement::put_onerror
  * Next Topic: IHTMLScriptElement::put_type

IHTMLScriptElement::get_onerror

HRESULT get_onerror(
    VARIANT *p
);

Retrieves the inline script associated with the onerror event on the script element.

For more information on inline script, see Attaching an Event Handler in the Event Model documentation.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that contains the onerror script.

See also put_onerror

Up Top of Page

IHTMLScriptElement::put_onerror

HRESULT put_onerror(
    VARIANT v
);

Sets the inline script associated with the onerror event on the script element.

For more information on inline script, see Attaching an Event Handler in the Event Model documentation.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the onerror script to be set.

See also get_onerror


IHTMLScriptElement

This interface specifies a script for the page that will be interpreted by a script engine.

Code within the SCRIPT block that is not contained within a function is executed immediately as the page is loaded. To keep scripts from being displayed on down-level browsers, the SCRIPT block should be nested within a comment block.

This element is a block element.

IHTMLScriptElement Methods
put_src get_src put_htmlFor
get_htmlFor put_event get_event
put_text get_text put_defer
get_defer get_readyState put_onerror
get_onerror put_type get_type

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


Src Property

*
  * Previous Topic: IHTMLScriptElement::put_src
  * Next Topic: IHTMLScriptElement::put_htmlFor

IHTMLScriptElement::get_src

HRESULT get_src(
    BSTR *p
);

Retrieves an external file that contains the source code.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the URL of the external file.

A script can contain an external reference as well as code within the block. The code specified by src --> precedes the code contained within the document.

See also put_src

Up Top of Page

IHTMLScriptElement::put_src

HRESULT put_src(
    BSTR v
);

Specifies an external file that contains the source code.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the URL of the external file.

A script can contain an external reference as well as code within the block. The code specified by src precedes the code contained within the document.

See also get_src


Text Property

*
  * Previous Topic: IHTMLScriptElement::put_text
  * Next Topic: IHTMLScriptElement::put_defer

IHTMLScriptElement::get_text

HRESULT get_text(
    BSTR *p
);

Retrieves the text contained within the SCRIPT element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the text.

See also put_text

Up Top of Page

IHTMLScriptElement::put_text

HRESULT put_text(
    BSTR v
);

Retrieves the text contained within the SCRIPT element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the text.

See also get_text


Type Property

*
  * Previous Topic: IHTMLScriptElement::put_type
  * Next Topic: IHTMLSelectElement

IHTMLScriptElement::get_type

HRESULT get_type(
    BSTR *p
);

Retrieves the string that represents the language that the current script was written in. The default language is JScript.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string that receives the language type. The possible scripting languages include the following:
JScript | Specifies that the script is written in JScript.
Jscript | Specifies the language as JScript.
vbs | Specifies the language as VBScript.
vbscript | Specifies that the script is written in VBScript.

This is an HTML 4.0 attribute and is equivalent to the language property.

See also put_type

Up Top of Page

IHTMLScriptElement::put_type

HRESULT put_type(
    BSTR v
);

Indicates the type script of the scripting language as a string for the IHTMLScriptElement object. The contents of this script is read only, and can be modified only at design time.

  • Returns S_OK if successful, or an error value otherwise.
v
String value specifying the script type.

See also get_type


IHTMLSelectElement::add

HRESULT add(
    IHTMLElement *element,
    VARIANT before
);

Adds an OPTION element to a SELECT block.

  • Returns S_OK if successful, or an error value otherwise.
element
Interface pointer to the OPTION element to add.
before
Zero-based index specifying the position of the OPTION element within the SELECT block.

See also remove


Disabled Property

*
  * Previous Topic: IHTMLSelectElement::put_disabled
  * Next Topic: IHTMLSelectElement::get_form

IHTMLSelectElement::get_disabled

HRESULT get_disabled(
    VARIANT_BOOL *p
);

Determines whether the control is enabled or disabled.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives TRUE if the control is disabled, or FALSE otherwise.

The default value for this property is FALSE.

See also put_disabled

Up Top of Page

IHTMLSelectElement::put_disabled

HRESULT put_disabled(
    VARIANT_BOOL v
);

Enables or disables the control. A disabled control appears dimmed and does not respond to user input.

  • Returns S_OK if successful, or an error value otherwise.
v
Boolean value specifying whether to disable the control. If TRUE, the control is disabled; otherwise, it is enabled.

The default value for this property is FALSE.

See also get_disabled


IHTMLSelectElement::get__newEnum

HRESULT get__newEnum(
    IUnknown **p
);

Retrieves an enumerator interface which can be used to iterate through the options collection of the select element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the enumerator interface pointer.


IHTMLSelectElement::get_form

HRESULT get_form(
    IHTMLFormElement **p
);

Retrieves a reference to the form the element is embedded on.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives an interface pointer to the form element. This parameter receives NULL if the element is not on a form.

See also IHTMLFormElement


IHTMLSelectElement::get_options

HRESULT get_options(
    IDispatch **p
);

Retrieves an interface pointer for a collection of OPTION elements in a SELECT object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the interface pointer.


IHTMLSelectElement::get_type

HRESULT get_type(
    BSTR *p
);

Retrieves the type of intrinsic control represented by the given element object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the type. The possible values depend on the element, as listed in the following table.
Element | Possible value | Description
INPUT | checkbox | Used for simple Boolean attributes or for attributes that can take multiple values at the same time. It is represented by a number of check box fields, each of which has the same name. Each selected check box generates a separate name/value pair in the submitted data, even if this results in duplicate names. The default value for check boxes is on.
file | A file upload element.
hidden | No field is presented to the user, but the content of the field is sent with the submitted form. This value can be used to transmit state information about client/server interaction.
image | An image field that you can click, causing the form to be immediately submitted. The coordinates of the selected point are measured in pixel units from the upper-left corner of the image, and are returned (along with the other contents of the form) in two name/value pairs. The x-coordinate is submitted under the name of the field with .x appended, and the y-coordinate is submitted under the name of the field with .y appended. Any value property is ignored. The image itself is specified by the SRC attribute, exactly as for the Image element.
password | Same as the TEXT attribute, except that text is not displayed as the user enters it.
radio | Used for attributes that accept a single value from a set of alternatives. Each radio-button field in the group should be given the same name. Only the selected radio button in the group generates a name/value pair in the submitted data. Radio buttons require an explicit value property.
reset | reset is a button that when clicked resets the form's fields to their specified initial values. The label to be displayed on the button can be specified just as for the submit button.
submit | submit is a button that when clicked submits the form. You can use the value attribute to provide a non-editable label to be displayed on the button. The default label is application-specific. If a submit button is clicked to submit the FORM, and that button has a name attribute specified, that button contributes a name/value pair to the submitted data. Otherwise, a submit button makes no contribution to the submitted data.
text | Used for a single-line text-entry field. Use in conjunction with the size and maxLength properties.
SELECT | select-multiple | Specifies a multiple-select list box.
select-one | Specifies a single-select list box.
TEXTAREA | textarea | Used for multiple-line text-entry fields. Use in conjunction with the size and maxLength properties.


IHTMLSelectElement::item

HRESULT item(
    VARIANT name,
    VARIANT index,
    IDispatch **pdisp
);

Retrieves an interface pointer for an element in a SELECT block.

  • Returns S_OK if successful, or an error value otherwise.
name
Number or string specifying the element or collection to retrieve. If this parameter is a number, the method returns the element in the collection at the given position, where the first element has value 0, the second has 1, and so on. If this parameter contains a string, the method returns a collection of elements, where the value of the NAME or ID= property for each element is equal to the string.
index
Number specifying the position of an element to retrieve. This parameter is used when name is a string. The method uses the string to construct a collection of all elements that have a NAME or ID= equal to the string, then retrieves from this collection the element at the position specified by index.
pdisp
Address of a variable that receives an interface pointer to the element object.


Length Property

*
  * Previous Topic: IHTMLSelectElement::put_length
  * Next Topic: IHTMLSelectElement::get__newEnum

IHTMLSelectElement::get_length

HRESULT get_length(
    long *p
);

Retrieves the number of elements in the SELECT block.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the number of elements.

See also put_length

Up Top of Page

IHTMLSelectElement::put_length

HRESULT put_length(
    long v
);

Sets the number of elements in the SELECT block.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the number of elements.

See also get_length


Multiple Property

*
  * Previous Topic: IHTMLSelectElement::put_multiple
  * Next Topic: IHTMLSelectElement::put_name

IHTMLSelectElement::get_multiple

HRESULT get_multiple(
    VARIANT_BOOL *p
);

Determines whether multiple items in the list can be selected.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives TRUE if multiple items can be selected, or FALSE if not.

The default value for this property is FALSE.

See also put_multiple

Up Top of Page

IHTMLSelectElement::put_multiple

HRESULT put_multiple(
    VARIANT_BOOL v
);

Specifies whether multiple items in the list can be selected.

  • Returns S_OK if successful, or an error value otherwise.
v
Multiple-items flag. If TRUE, multiple items can be selected; if FALSE, they cannot.

The default value for this property is FALSE.

See also get_multiple


Name Property

*
  * Previous Topic: IHTMLSelectElement::put_name
  * Next Topic: IHTMLSelectElement::get_options

IHTMLSelectElement::get_name

HRESULT get_name(
    BSTR *p
);

Retrieves the name of the control, bookmark, or application.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the name.

The name is used to bind the value of the control when submitting a form. The NAME is not the value that is displayed for the button, reset, and submit objects. Submitting the form submits the internally stored value, not the one displayed.

JScript allows the name to be changed at run time. This does not change the name in the programming model, in the collection of elements, but does change the name used for submitting elements.

See also put_name

Up Top of Page

IHTMLSelectElement::put_name

HRESULT put_name(
    BSTR v
);

Sets the name of the control, bookmark, or application.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the name.

The name is used to bind the value of the control when submitting a form. The NAME is not the value that is displayed for the button, reset, and submit objects. Submitting the form submits the internally stored value, not the one displayed.

JScript allows the name to be changed at run time. This does not change the name in the programming model, in the collection of elements, but does change the name used for submitting elements.

See also get_name


Onchange Property

*
  * Previous Topic: IHTMLSelectElement::put_onchange
  * Next Topic: IHTMLSelectElement::put_selectedIndex

IHTMLSelectElement::get_onchange

HRESULT get_onchange(
    VARIANT *p
);

Retrieves the inline script associated with the onchange event on the SELECT element. This occurs when the contents of the object have changed.

For more information on inline scripts, see Attaching an Event Handler in the Event Model documentation.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that contains the script.

See also put_onchange

Up Top of Page

IHTMLSelectElement::put_onchange

HRESULT put_onchange(
    VARIANT v
);

Sets the inline script associated with the onchange event on the SELECT element. This occurs when the contents of the object have changed.

For more information on inline scripts, see Attaching an Event Handler in the Event Model documentation.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to be set.

See also get_onchange


IHTMLSelectElement::remove

HRESULT remove(
    long index
);

Removes the given element from the SELECT block.

  • Returns S_OK if successful, or an error value otherwise.
index
Zero-based index of the item to remove.

See also add


SelectedIndex Property

*
  * Previous Topic: IHTMLSelectElement::put_selectedIndex
  * Next Topic: IHTMLSelectElement::get_type

IHTMLSelectElement::get_selectedIndex

HRESULT get_selectedIndex(
    long *p
);

Retreives the index of the selected item in the list box or drop-down list associated with the select object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the index of the selected item.

Options in a select object are indexed in the order in which they are defined, starting with an index of 0. You can set the selectedIndex property at any time. The display of the select object updates immediately when you set the selectedIndex property. Both forms of the syntax specify the same value.

In general, the selectedIndex property is more useful for select objects that are created without the multiple attribute. If you evaluate selectedIndex when multiple options are selected, the selectedIndex property specifies the index of the first option only. Setting selectedIndex clears any other options that are selected in the select object.

The selected property of the select object's options array is more useful for select objects that are created with the multiple attribute. With the selected property, you can evaluate every option in the options array to determine multiple selections, and you can select individual options without clearing the selection of other options.

See also put_selectedIndex

Up Top of Page

IHTMLSelectElement::put_selectedIndex

HRESULT put_selectedIndex(
    long v
);

Selects an item in the list box or drop-down list associated with the select object.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the zero-based index of the item to select.

Options in a select object are indexed in the order in which they are defined, starting with an index of 0. You can set the selectedIndex property at any time. The display of the select object updates immediately when you set the selectedIndex property. Both forms of the syntax specify the same value.

In general, the selectedIndex property is more useful for select objects that are created without the multiple attribute. If you evaluate selectedIndex when multiple options are selected, the selectedIndex property specifies the index of the first option only. Setting selectedIndex clears any other options that are selected in the select object.

The selected property of the select object's options array is more useful for select objects that are created with the multiple attribute. With the selected property, you can evaluate every option in the options array to determine multiple selections, and you can select individual options without clearing the selection of other options.

See also get_selectedIndex


IHTMLSelectElement

This interface provides access to the properties and methods of the SELECT element.

IHTMLSelectElement Methods
put_size get_size put_multiple
get_multiple put_name get_name
get_options put_onchange get_onchange
put_selectedIndex get_selectedIndex get_type
put_value get_value put_disabled
get_disabled get_form add
remove put_length get_length
get__newEnum item tags

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


Size Property

*
  * Previous Topic: IHTMLSelectElement::put_size
  * Next Topic: IHTMLSelectElement::put_multiple

IHTMLSelectElement::get_size

HRESULT get_size(
    long *p
);

Retrieves the number of rows in the list box.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the number of rows.

See also put_size

Up Top of Page

IHTMLSelectElement::put_size

HRESULT put_size(
   long v
);

Specifies the number of rows in the list box.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the number of rows.

See also get_size


IHTMLSelectElement::tags

HRESULT tags(
    VARIANT tagName,
    IDispatch **pdisp
);

Retrieves a collection of all elements in the given collection that have the given HTML tag name.

  • Returns S_OK if successful, or an error value otherwise.
tagName
String specifying the tag name.
pdisp
Address of a variable that receives an interface pointer to the collection.

This method returns an empty collection if no elements having the given name are found. Use the length property on the collection to determine the number of elements it contains.


Value Property

*
  * Previous Topic: IHTMLSelectElement::put_value
  * Next Topic: IHTMLSelectElement::put_disabled

IHTMLSelectElement::get_value

HRESULT get_value(
    BSTR *p
);

Retrieves the value of the object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value.

See also put_value

Up Top of Page

IHTMLSelectElement::put_value

HRESULT put_value(
    BSTR v
);

Sets the value of the object.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the value.

See also get_value


IHTMLSelectionObject::clear IHTMLSelectionObject::clear *
  * Previous Topic: IHTMLSelectionObject::empty
  * Next Topic: IHTMLSelectionObject::get_type

IHTMLSelectionObject::clear

HRESULT clear(
    void
);

Clears the contents of the selection.

  • Returns S_OK if successful, or an error value otherwise.


IHTMLSelectionObject::createRange

HRESULT createRange(
    IDispatch **range
);

Creates a text range from the current selection.

  • Returns S_OK if successful, or an error value otherwise.
range
Address of a variable that receives an interface pointer for the range.

See also IHTMLTxtRange


IHTMLSelectionObject::empty

HRESULT empty(void);

Deselects the current selection, sets the selection type to "none", and sets the item property to NULL.

  • Returns S_OK if successful, or an error value otherwise.


IHTMLSelectionObject::get_type

HRESULT get_type(
    BSTR *p
);

Retrieves the type of selection.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the type. Can be one of these values:
None | The selection is an insertion point (no text is selected).
Text | The selection is a text selection.


IHTMLSelectionObject

This interface provides the access methods for the selection object representing the active selection, a highlighted block of text and/or other elements in the document upon which a user or a script can carry out some action. You typically use the selection object as input from the user identifying what portion of the document to act on, or as output to the user showing the results of an action.

Users and scripts both can create selections. Users create selections by dragging the mouse over a portion of the document. Scripts create them by calling the select method on a text range or similar object. You can retrieve the active selection by applying the selection keyword to the document object. To carry out work on a selection, you can create a text range object from the selection by using the createRange method.

A document can have only one selection at a time. The selection has a type that determines whether it is empty or contains a contiguous block of consecutive text and/or elements. Although an empty selection contains nothing, it is useful for marking a position in the document.

IHTMLSelectionObject Methods


IHTMLSpanElement

This interface provides access to the properties and methods for this object and is equivalent to the IHTMLElement interface. For more information and a listing of the available methods, see the reference section for the IHTMLElement interface.


Align Property

*
  * Previous Topic: IHTMLSpanFlow::put_align
  * Next Topic: IHTMLStyle

IHTMLSpanFlow::get_align

HRESULT get_align(
    BSTR *p
);

Retrieves how the element is aligned with adjacent text.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the alignment. Can be one of these values:
absbottom | Aligns the bottom of the element with the absolute bottom of the surrounding text. The absolute bottom is equal to the baseline of the text minus the height of the largest descender in the text.
absmiddle | Aligns the middle of the element with the middle of the surrounding text. The absolute middle is the midpoint between the absolute bottom and texttop of the surrounding text.
baseline | Aligns the bottom of the element with the baseline of the surrounding text.
bottom | Aligns the bottom of the element with the bottom of the surrounding text. The bottom is equal to the baseline minus the standard height of a descender in the text.
left | Aligns the element to the left of the surrounding text. All preceding and subsequent text flows to the right of the element. This is the default value.
middle | Aligns the middle of the element with the surrounding text.
right | Aligns the element to the right of the surrounding text. All subsequent text flows to the left of the element.
texttop | Aligns the top of the element with the absolute top of the surrounding text. The absolute top is the baseline plus the height of the largest ascender in the text.
top | Aligns the top of the element with the top of the text. The top of the text is the baseline plus the standard height of an ascender in the text.

For the INPUT element, this attribute applies only to the image type. It is undefined for all other types.

See also put_align

Up Top of Page

IHTMLSpanFlow::put_align

HRESULT put_align(
    BSTR v
);

Sets how the element is aligned with adjacent text.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the alignment. Can be one of these values:
absbottom | Aligns the bottom of the element with the absolute bottom of the surrounding text. The absolute bottom is equal to the baseline of the text minus the height of the largest descender in the text.
absmiddle | Aligns the middle of the element with the middle of the surrounding text. The absolute middle is the midpoint between the absolute bottom and texttop of the surrounding text.
baseline | Aligns the bottom of the element with the baseline of the surrounding text.
bottom | Aligns the bottom of the element with the bottom of the surrounding text. The bottom is equal to the baseline minus the standard height of a descender in the text.
left | Aligns the element to the left of the surrounding text. All preceding and subsequent text flows to the right of the element. This is the default value.
middle | Aligns the middle of the element with the surrounding text.
right | Aligns the element to the right of the surrounding text. All subsequent text flows to the left of the element.
texttop | Aligns the top of the element with the absolute top of the surrounding text. The absolute top is the baseline plus the height of the largest ascender in the text.
top | Aligns the top of the element with the top of the text. The top of the text is the baseline plus the standard height of an ascender in the text.

For the INPUT element, this attribute applies only to the image type. It is undefined for all other types.

See also get_align


IHTMLSpanFlow

This interface has no structural role or established rendering convention. It allows users to define their own method of rendering using style sheets.

IHTMLSpanFlow Methods


Background Property

*
  * Previous Topic: IHTMLStyle
  * Next Topic: IHTMLStyle::get_backgroundAttachment

IHTMLStyle::get_background

HRESULT get_background(
    BSTR *p
);

Retrieves the value of the CSS background attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute. See background for details. This parameter receives NULL if the attribute is not set.

See also put_background

Up Top of Page

IHTMLStyle::put_background

HRESULT put_background(
    BSTR v
);

Sets the value of the CSS background attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the value of the attribute, or NULL to remove it. See background for details.

See also get_background


BackgroundAttachment Property

*
  * Previous Topic: IHTMLStyle::get_background
  * Next Topic: IHTMLStyle::get_backgroundColor

IHTMLStyle::get_backgroundAttachment

HRESULT get_backgroundAttachment(
    BSTR *p
);

Retrieves the value of the CSS background-attachment attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute, which can be one of these strings:
fixed | Background image remains fixed.
scroll | Background image scrolls with text.
See background-attachment for details.

See also put_backgroundAttachment

Up Top of Page

IHTMLStyle::put_backgroundAttachment

HRESULT put_backgroundAttachment(
    BSTR v
);

Sets the value of the CSS background-attachment attribute for the element. If the element has a background image, this attribute determines if the image is fixed with regard to the text of the element, or if it scrolls with the text.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the value of the attribute, or NULL to remove it. Can be one of these strings:
fixed | Background image remains fixed.
scroll | Background image scrolls with text.
See background-attachment for details.

See also get_backgroundAttachment


BackgroundColor Property

*
  * Previous Topic: IHTMLStyle::get_backgroundAttachment
  * Next Topic: IHTMLStyle::get_backgroundImage

IHTMLStyle::get_backgroundColor

HRESULT get_backgroundColor(
    VARIANT *p
);

Retrieves the value of the CSS background-color attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute. See background-color for details. This parameter receives NULL if the attribute is not set.

See also put_backgroundColor

Up Top of Page

IHTMLStyle::put_backgroundColor

HRESULT put_backgroundColor(
    VARIANT v
);

Sets the CSS background-color attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the background color, or NULL to remove the attribute. The color can be one of the color names or values given in the Color Table reference documentation.

See also get_backgroundColor


BackgroundImage Property

*
  * Previous Topic: IHTMLStyle::get_backgroundColor
  * Next Topic: IHTMLStyle::get_backgroundPosition

IHTMLStyle::get_backgroundImage

HRESULT get_backgroundImage(
    BSTR *p
);

Retrieves the value of the CSS background-image attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute. See background-image for details. This parameter receives NULL if the attribute is not set.

See also put_backgroundImage

Up Top of Page

IHTMLStyle::put_backgroundImage

HRESULT put_backgroundImage(
    BSTR v
);

Sets a CSS background-image attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the URL of the background image, or NULL to remove the attribute. See background-image for details.

See also get_backgroundImage


BackgroundPosition Property

*
  * Previous Topic: IHTMLStyle::get_backgroundImage
  * Next Topic: IHTMLStyle::get_backgroundPositionX

IHTMLStyle::get_backgroundPosition

HRESULT get_backgroundPosition(
    BSTR *p
);

Retrieves the value of the CSS background-position attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute. See background-image for details. This parameter receives NULL if the attribute is not set.

See also put_backgroundPosition

Up Top of Page

IHTMLStyle::put_backgroundPosition

HRESULT put_backgroundPosition(
    BSTR v
);

Sets the value of the CSS background-position attribute for the element. The attribute determines the initial position of the background image, if any.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the initial background position, or NULL to remove the attribute. See background-position for details.

See also get_backgroundPosition


BackgroundPositionX Property

*
  * Previous Topic: IHTMLStyle::get_backgroundPosition
  * Next Topic: IHTMLStyle::get_backgroundPositionY

IHTMLStyle::get_backgroundPositionX

HRESULT get_backgroundPositionX(
    VARIANT *p
);

Retrieves the x-coordinate of the CSS background-position attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the x-coordinate. See background-image for details. This parameter receives NULL if the parameter is not set.

See also put_backgroundPositionX

Up Top of Page

IHTMLStyle::put_backgroundPositionX

HRESULT put_backgroundPositionX(
    VARIANT v
);

Sets the x-coordinate of the CSS background-position attribute for the element. The attribute determines the initial horizontal position of the background image, if any.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the x-coordinate, or NULL to remove the attribute. See background-position for details.

See also get_backgroundPositionX


BackgroundPositionY Property

*
  * Previous Topic: IHTMLStyle::get_backgroundPositionX
  * Next Topic: IHTMLStyle::get_backgroundRepeat

IHTMLStyle::get_backgroundPositionY

HRESULT get_backgroundPositionY(
    VARIANT *p
);

Retrieves the y-coordinate of the CSS background-position attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the y-coordinate. See background-image for details. This parameter receives NULL if the attribute is not set.

See also put_backgroundPositionY

Up Top of Page

IHTMLStyle::put_backgroundPositionY

HRESULT put_backgroundPositionY(
    VARIANT v
);

Sets the y-coordinate of the CSS background-position attribute for the element. The attribute determines the initial vertical position of the background image, if any.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the y-coordinate, or NULL to remove the attribute. See background-position for details.

See also get_backgroundPositionY


BackgroundRepeat Property

*
  * Previous Topic: IHTMLStyle::get_backgroundPositionY
  * Next Topic: IHTMLStyle::get_border

IHTMLStyle::get_backgroundRepeat

HRESULT get_backgroundRepeat(
    BSTR *p
);

Retrieves the value of the CSS background-repeat attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute, which can be one of these strings:
norepeat | Do not repeat.
repeaty | Repeat vertically.
repeat | Repeat both horizontally and vertically.
repeatx | Repeat horizontally.
See background-image for details. This parameter receives NULL if the attribute is not set.

See also put_backgroundRepeat

Up Top of Page

IHTMLStyle::put_backgroundRepeat

HRESULT put_backgroundRepeat(
    BSTR v
);

Sets the value of the CSS background-repeat attribute for the element. The attribute determines whether and how the background image, if any, is repeated.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying whether and how the image is repeated, or NULL to remove the attribute. Can be one of these strings:
norepeat | Do not repeat.
repeaty | Repeat vertically.
repeat | Repeat both horizontally and vertically.
repeatx | Repeat horizontally.
See background-repeat for details.

See also get_backgroundRepeat


Border Property

*
  * Previous Topic: IHTMLStyle::get_backgroundRepeat
  * Next Topic: IHTMLStyle::get_borderBottom

IHTMLStyle::get_border

HRESULT get_border(
    BSTR *p
);

Retrieves the value of the CSS border attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives values that describe the border. See border for details. This parameter receives NULL if the attribute is not set.

See also put_border

Up Top of Page

IHTMLStyle::put_border

HRESULT put_border(
    BSTR v
);

Sets the value of the CSS border attribute for the element. The attribute describes the color, style, and width of the border to display around the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying values that describe the border. See border for details. Set this parameter to NULL to remove the attribute.

See also get_border


BorderBottom Property

*
  * Previous Topic: IHTMLStyle::get_border
  * Next Topic: IHTMLStyle::get_borderBottomColor

IHTMLStyle::get_borderBottom

HRESULT get_borderBottom(
    BSTR *p
);

Retrieves the value of the CSS border-bottom attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives values that describe the bottom border. See border-bottom for details. This parameter receives NULL if the attribute is not set.

See also put_borderBottom

Up Top of Page

IHTMLStyle::put_borderBottom

HRESULT put_borderBottom(
    BSTR v
);

Sets the value of the CSS border-bottom attribute for the element. The attribute determines the width, style, and color of the bottom border.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the border width, style, and color. See border-bottom for details. Set this parameter to NULL to remove the attribute.

See also get_borderBottom


BorderBottomColor Property

*
  * Previous Topic: IHTMLStyle::get_borderBottom
  * Next Topic: IHTMLStyle::get_borderBottomStyle

IHTMLStyle::get_borderBottomColor

HRESULT get_borderBottomColor(
    VARIANT *p
);

Retrieves the value of the CSS border-bottom-color attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the color value. See border-bottom-color for details. This parameter receives NULL if the attribute is not set.

See also put_borderBottomColor

Up Top of Page

IHTMLStyle::put_borderBottomColor

HRESULT put_borderBottomColor(
    VARIANT v
);

Sets the value of the CSS border-bottom-color attribute for the element. The attribute determines the color of the element's bottom border.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the border color, which can be one of the color names or values given in the Color Table reference documentation. See border-bottom-color for details. Set this parameter to NULL to remove the attribute.

See also get_borderBottomColor


BorderBottomStyle Property

*
  * Previous Topic: IHTMLStyle::get_borderBottomColor
  * Next Topic: IHTMLStyle::get_borderBottomWidth

IHTMLStyle::get_borderBottomStyle

HRESULT get_borderBottomStyle(
    BSTR *p
);

Retrieves the value of the CSS border-bottom-style attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the border style. See border-bottom-style for details. This parameter receives NULL if the attribute is not set.

See also put_borderBottomStyle

Up Top of Page

IHTMLStyle::put_borderBottomStyle

HRESULT put_borderBottomStyle(
    BSTR v
);

Sets the value of the CSS border-bottom-style attribute for the element. The attribute determines the style of the bottom border.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the border style. See border-bottom-style for details. Set this parameter to NULL to remove the attribute.

See also get_borderBottomStyle


BorderBottomWidth Property

*
  * Previous Topic: IHTMLStyle::get_borderBottomStyle
  * Next Topic: IHTMLStyle::get_borderColor

IHTMLStyle::get_borderBottomWidth

HRESULT get_borderBottomWidth(
    VARIANT *p
);

Retrieves the value of the CSS border-bottom-width attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the border width. See border-bottom-width for details. This parameter receives NULL if the attribute is not set.

See also put_borderBottomWidth

Up Top of Page

IHTMLStyle::put_borderBottomWidth

HRESULT put_borderBottomWidth(
    VARIANT v
);

Sets the value of the CSS border-bottom-width attribute for the element. The attribute determines the width of the bottom border.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the border width. See border-bottom-width for details. Set this parameter to NULL to remove the attribute.

See also get_borderBottomWidth


BorderColor Property

*
  * Previous Topic: IHTMLStyle::get_borderBottomWidth
  * Next Topic: IHTMLStyle::get_borderLeft

IHTMLStyle::get_borderColor

HRESULT get_borderColor(
    BSTR *p
);

Retrieves the value of the CSS border-color attribute of the element and must be used with the border property, except for frames. The color can be one of the color names or values given in the Color Table reference documentation.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the border color values. See border-color for details. This parameter receives NULL if the attribute is not set.

See also put_borderColor

Up Top of Page

IHTMLStyle::put_borderColor

HRESULT put_borderColor(
    BSTR v
);

Sets the value of the CSS border-color attribute for the element. The attribute determines the color of the element's four borders.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the border color, which can be one of the color names or values given in the Color Table reference documentation. See border-left for details. Set this parameter to NULL to remove the attribute.

See also get_borderColor


BorderLeft Property

*
  * Previous Topic: IHTMLStyle::get_borderColor
  * Next Topic: IHTMLStyle::get_borderLeftColor

IHTMLStyle::get_borderLeft

HRESULT get_borderLeft(
    BSTR *p
);

Retrieves the value of the CSS border-left attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives values that describe the left border. See border-left for details. This parameter receives NULL if the attribute is not set.

See also put_borderLeft

Up Top of Page

IHTMLStyle::put_borderLeft

HRESULT put_borderLeft(
    BSTR v
);

Sets the value of the CSS border-left attribute for the element. The attribute determines the width, style, and color of the left border.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the border width, style, and color. See border-left for details. Set this parameter to NULL to remove the attribute.

See also get_borderLeft


BorderLeftColor Property

*
  * Previous Topic: IHTMLStyle::get_borderLeft
  * Next Topic: IHTMLStyle::get_borderLeftStyle

IHTMLStyle::get_borderLeftColor

HRESULT get_borderLeftColor(
    VARIANT *p
);

Retrieves the value of the CSS border-left-color attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the color value. See border-left-color for details. This parameter receives NULL if the attribute is not set.

See also put_borderLeftColor

Up Top of Page

IHTMLStyle::put_borderLeftColor

HRESULT put_borderLeftColor(
    VARIANT v
);

Sets the value of the CSS border-left-color attribute for the element. The attribute determines the color of the element's left border.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the border color, which can be one of the color names or values given in the Color Table reference documentation. See border-left-color for details. Set this parameter to NULL to remove the attribute.

See also get_borderLeftColor


BorderLeftStyle Property

*
  * Previous Topic: IHTMLStyle::get_borderLeftColor
  * Next Topic: IHTMLStyle::get_borderLeftWidth

IHTMLStyle::get_borderLeftStyle

HRESULT get_borderLeftStyle(
    BSTR *p
);

Retrieves the value of the CSS border-left-style attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the border style. See border-left-style for details. This parameter receives NULL if the attribute is not set.

See also put_borderLeftStyle

Up Top of Page

IHTMLStyle::put_borderLeftStyle

HRESULT put_borderLeftStyle(
    BSTR v
);

Sets the value of the CSS border-left-style attribute for the element. The attribute determines the style of the left border.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the border style. See border-left-style for details. Set this parameter to NULL to remove the attribute.

See also get_borderLeftStyle


BorderLeftWidth Property

*
  * Previous Topic: IHTMLStyle::get_borderLeftStyle
  * Next Topic: IHTMLStyle::get_borderRight

IHTMLStyle::get_borderLeftWidth

HRESULT get_borderLeftWidth(
    VARIANT *p
);

Retrieves the value of the CSS border-left-width attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the border width. See border-left-width for details. This parameter receives NULL if the attribute is not set.

See also put_borderLeftWidth

Up Top of Page

IHTMLStyle::put_borderLeftWidth

HRESULT put_borderLeftWidth(
    VARIANT v
);

Sets the value of the CSS border-left-width attribute for the element. The attribute determines the width of the left border.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the border width. See border-left-width for details. Set this parameter to NULL to remove the attribute.

See also get_borderLeftWidth


BorderRight Property

*
  * Previous Topic: IHTMLStyle::get_borderLeftWidth
  * Next Topic: IHTMLStyle::get_borderRightColor

IHTMLStyle::get_borderRight

HRESULT get_borderRight(
    BSTR *p
);

Retrieves the value of the CSS border-right attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives values that describe the right border. See border-right for details. This parameter receives NULL if the attribute is not set.

See also put_borderRight

Up Top of Page

IHTMLStyle::put_borderRight

HRESULT put_borderRight(
    BSTR v
);

Sets the value of the CSS border-right attribute for the element. The attribute determines the width, style, and color of the right border.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the border width, style, and color. See border-right for details. Set this parameter to NULL to remove the attribute.

See also get_borderRight


BorderRightColor Property

*
  * Previous Topic: IHTMLStyle::get_borderRight
  * Next Topic: IHTMLStyle::get_borderRightStyle

IHTMLStyle::get_borderRightColor

HRESULT get_borderRightColor(
    VARIANT *p
);

Retrieves the value of the CSS border-right-color attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the color value. See border-right-color for details. This parameter receives NULL if the attribute is not set.

See also put_borderRightColor

Up Top of Page

IHTMLStyle::put_borderRightColor

HRESULT put_borderRightColor(
    VARIANT v
);

Sets the value of the CSS border-right-color attribute for the element. The attribute determines the color of the element's right border.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the border color, which can be one of the color names or values given in the Color Table reference documentation. See border-right-color for details. Set this parameter to NULL to remove the attribute.

See also get_borderRightColor


BorderRightStyle Property

*
  * Previous Topic: IHTMLStyle::get_borderRightColor
  * Next Topic: IHTMLStyle::get_borderRightWidth

IHTMLStyle::get_borderRightStyle

HRESULT get_borderRightStyle(
    BSTR *p
);

Retrieves the value of the CSS border-right-style attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the border style. See border-right-style for details. This parameter receives NULL if the attribute is not set.

See also put_borderRightStyle

Up Top of Page

IHTMLStyle::put_borderRightStyle

HRESULT put_borderRightStyle(
    BSTR v
);

Sets the value of the CSS border-right-style attribute for the element. The attribute determines the style of the right border.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the border style. See border-right-style for details. Set this parameter to NULL to remove the attribute.

See also get_borderRightStyle


BorderRightWidth Property

*
  * Previous Topic: IHTMLStyle::get_borderRightStyle
  * Next Topic: IHTMLStyle::get_borderStyle

IHTMLStyle::get_borderRightWidth

HRESULT get_borderRightWidth(
    VARIANT *p
);

Retrieves the value of the CSS border-right-width attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the border width. See border-right-width for details. This parameter receives NULL if the attribute is not set.

See also put_borderRightWidth

Up Top of Page

IHTMLStyle::put_borderRightWidth

HRESULT put_borderRightWidth(
    VARIANT v
);

Sets the value of the CSS border-right-width attribute for the element. The attribute determines the width of the right border.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the border width. See border-right-width for details. Set this parameter to NULL to remove the attribute.

See also get_borderRightWidth


BorderStyle Property

*
  * Previous Topic: IHTMLStyle::get_borderRightWidth
  * Next Topic: IHTMLStyle::get_borderTop

IHTMLStyle::get_borderStyle

HRESULT get_borderStyle(
    BSTR *p
);

Retrieves the value of the CSS border-style attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the border styles. See border-style for details. This parameter receives NULL if the attribute is not set.

See also put_borderStyle

Up Top of Page

IHTMLStyle::put_borderStyle

HRESULT put_borderStyle(
    BSTR v
);

Sets the value of the CSS border-style attribute for the element. The attribute determines the style of the left, right, top, and bottom borders.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the border styles. See border-width for details. Set this parameter to NULL to remove the attribute.

See also get_borderStyle


BorderTop Property

*
  * Previous Topic: IHTMLStyle::get_borderStyle
  * Next Topic: IHTMLStyle::get_borderTopColor

IHTMLStyle::get_borderTop

HRESULT get_borderTop(
    BSTR *p
);

Retrieves the value of the CSS border-top attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives values that describe the top border. See border-top for details. This parameter receives NULL if the attribute is not set.

See also put_borderTop

Up Top of Page

IHTMLStyle::put_borderTop

HRESULT put_borderTop(
    BSTR v
);

Sets the value of the CSS border-top attribute for the element. The attribute determines the width, style, and color of the top border.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the border width, style, and color. See border-top for details. Set this parameter to NULL to remove the attribute.

See also get_borderTop


BorderTopColor Property

*
  * Previous Topic: IHTMLStyle::get_borderTop
  * Next Topic: IHTMLStyle::get_borderTopStyle

IHTMLStyle::get_borderTopColor

HRESULT get_borderTopColor(
    VARIANT *p
);

Retrieves the value of the CSS border-top-color attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the color value. See border-top-color for details. This parameter receives NULL if the attribute is not set.

See also put_borderTopColor

Up Top of Page

IHTMLStyle::put_borderTopColor

HRESULT put_borderTopColor(
    VARIANT v
);

Sets the value of the CSS border-top-color attribute for the element. The attribute determines the color of the element's top border.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the border color, which can be one of the color names or values given in the Color Table reference documentation. See border-top-color for details. Set this parameter to NULL to remove the attribute.

See also get_borderTopColor


BorderTopStyle Property

*
  * Previous Topic: IHTMLStyle::get_borderTopColor
  * Next Topic: IHTMLStyle::get_borderTopWidth

IHTMLStyle::get_borderTopStyle

HRESULT get_borderTopStyle(
    BSTR *p
);

Retrieves the value of the CSS border-top-style attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the border style. See border-top-style for details. This parameter receives NULL if the attribute is not set.

See also put_borderTopStyle

Up Top of Page

IHTMLStyle::put_borderTopStyle

HRESULT put_borderTopStyle(
    BSTR v
);

Sets the value of the CSS border-top-style attribute for the element. The attribute determines the style of the top border.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the border style. See border-top-style for details. Set this parameter to NULL to remove the attribute.

See also get_borderTopStyle


BorderTopWidth Property

*
  * Previous Topic: IHTMLStyle::get_borderTopStyle
  * Next Topic: IHTMLStyle::get_borderWidth

IHTMLStyle::get_borderTopWidth

HRESULT get_borderTopWidth(
    VARIANT *p
);

Retrieves the value of the CSS border-top-width attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the border width. See border-top-width for details. This parameter receives NULL if the attribute is not set.

See also put_borderTopWidth

Up Top of Page

IHTMLStyle::put_borderTopWidth

HRESULT put_borderTopWidth(
    VARIANT v
);

Sets the value of the CSS border-top-width attribute for the element. The attribute determines the width of the top border.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the border width. See border-top-width for details. Set this parameter to NULL to remove the attribute.

See also get_borderTopWidth


BorderWidth Property

*
  * Previous Topic: IHTMLStyle::get_borderTopWidth
  * Next Topic: IHTMLStyle::get_clear

IHTMLStyle::get_borderWidth

HRESULT get_borderWidth(
    BSTR *p
);

Retrieves the value of the CSS border-width attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the border widths. See border-width for details. This parameter receives NULL if the attribute is not set.

See also put_borderWidth

Up Top of Page

IHTMLStyle::put_borderWidth

HRESULT put_borderWidth(
    BSTR v
);

Sets the value of the CSS border-width attribute for the element. The attribute determines the width of the left, right, top, and bottom borders.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the border widths. See border-width for details. Set this parameter to NULL to remove the attribute.

See also get_borderWidth


Clear Property

*
  * Previous Topic: IHTMLStyle::get_borderWidth
  * Next Topic: IHTMLStyle::get_clip

IHTMLStyle::get_clear

HRESULT get_clear(
    BSTR *p
);

Retrieves the value of the CSS clear attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute, which can be one of these strings:
left
right
both
See clear for details. This parameter receives NULL if the attribute is not set.

See also put_clear

Up Top of Page

IHTMLStyle::put_clear

HRESULT put_clear(
    BSTR v
);

Sets the value of the CSS clear attribute for the element. The attribute determines whether the element allows floating elements (typically images) on its left and right sides. More specifically, the attribute specifies the sides where floating elements are not allowed.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the sides where floating elements cannot appear. Can be one of these strings:
left
right
both
See clear for details. Set this parameter to NULL to remove the attribute.

See also get_clear


Clip Property

*
  * Previous Topic: IHTMLStyle::get_clear
  * Next Topic: IHTMLStyle::get_color

IHTMLStyle::get_clip

HRESULT get_clip(
    BSTR *p
);

Retrieves the value of the CSS clip attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the coordinates of the clipping area. This variable receives NULL if the attribute is not set. See clip for details.

See also put_clip

Up Top of Page

IHTMLStyle::put_clip

HRESULT put_clip(
    BSTR v
);

Sets the value of the CSS clip attribute for the element. The attribute determines which part of the element is visible. Any part of the element that is outside the clipping area is transparent.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the coordinates of the clipping area. Each coordinate can be a length value or "auto". See clip for details. Set this parameter to NULL to remove the attribute.

See also get_clip


Color Property

*
  * Previous Topic: IHTMLStyle::get_clip
  * Next Topic: IHTMLStyle::get_cssText

IHTMLStyle::get_color

HRESULT get_color(
    VARIANT *p
);

Retrieves the value of the CSS color attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute. See color for details. This parameter receives NULL if the attribute is not set.

See also put_color

Up Top of Page

IHTMLStyle::put_color

HRESULT put_color(
    VARIANT v
);

Sets the CSS color attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the color, or NULL to remove the attribute. See color for details. The color can be one of the color names or values given in the Color Table reference documentation.

See also get_color


CssText Property

*
  * Previous Topic: IHTMLStyle::get_color
  * Next Topic: IHTMLStyle::get_cursor

IHTMLStyle::get_cssText

HRESULT get_cssText(
    BSTR *p
);

Retrieves the persisted representation of the style rule.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the style rule.

See also put_cssText

Up Top of Page

IHTMLStyle::put_cssText

HRESULT put_cssText(
    BSTR v
);

Sets the persisted representation of the style rule.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the style rule.

See also get_cssText


Cursor Property

*
  * Previous Topic: IHTMLStyle::get_cssText
  * Next Topic: IHTMLStyle::get_display

IHTMLStyle::get_cursor

HRESULT get_cursor(
    BSTR *p
);

Retrieves the value of the CSS cursor attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute. See cursor for details. This variable receives NULL if the attribute is not set.

See also put_cursor

Up Top of Page

IHTMLStyle::put_cursor

HRESULT put_cursor(
    BSTR v
);

Sets the value of the CSS cursor attribute for the element. The attribute determines the type of cursor to display when the mouse is over the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the cursor type. Can be one of these values:
auto | The UA determines the cursor to display based on the current context.
crosshair | A simple crosshair.
default | The platform-dependent default cursor (typically an arrow).
hand | A hand.
move | A four-directional arrow typically used to indicate an object to be moved.
*-resize | An arrow cursor typically used to indicate the edge of an object to be moved during a resize operation.
text | Typically an I-bar used to indicate editable text.
wait | Typically a watch or hourglass used to indicate that the program is busy and the user should wait.

See also get_cursor


Display Property

*
  * Previous Topic: IHTMLStyle::get_cursor
  * Next Topic: IHTMLStyle::get_filter

IHTMLStyle::get_display

HRESULT get_display(
    BSTR *p
);

Retrieves the value of the display attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute. The variable receives "none" if the element is not being rendered, or NULL if it is. See display for details.

See also put_display

Up Top of Page

IHTMLStyle::put_display

HRESULT put_display(
    BSTR v
);

Sets the value of the CSS display attribute for the element. The attribute determines whether the element is rendered.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying whether to render the element. If this parameter is "none", the element is not rendered; if NULL, it is rendered. See display for details.

Although you can apply the display attribute to parts of a table (such as a TR or TD element), changing the property has no effect on those parts. However, you can dynamically control the rendering of the entire table by applying the attribute to the TABLE element.

See also get_display


Filter Property

*
  * Previous Topic: IHTMLStyle::get_display
  * Next Topic: IHTMLStyle::get_font

IHTMLStyle::get_filter

HRESULT get_filter(
    BSTR *p
);

Retrieves a filter or collection of filters for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the filter.

See also put_filter

Up Top of Page

IHTMLStyle::put_filter

HRESULT put_filter(
    BSTR v
);

Sets a filter or collection of filters for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the filter.

See also get_filter


Font Property

*
  * Previous Topic: IHTMLStyle::get_filter
  * Next Topic: IHTMLStyle::get_fontFamily

IHTMLStyle::get_font

HRESULT get_font(
    BSTR *p
);

Retrieves the values of the CSS font-style, font-variant, font-weight, font-size, line-height, and font-family attributes for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the values of the font-related CSS attributes. See font for details. This parameter receives NULL if no font-related CSS attributes are set for the element.

See also put_font

Up Top of Page

IHTMLStyle::put_font

HRESULT put_font(
    BSTR v
);

Sets the value of the CSS font-style, font-variant, font-weight, font-size, line-height, and font-family attributes for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying values for one or more font attributes. This parameter has the following format:
[<font-style> || <font-variant> || <font-weight>] <font-size> /
[<line-height>] <font-family>
See font for details.

See also get_font


FontFamily Property

*
  * Previous Topic: IHTMLStyle::get_font
  * Next Topic: IHTMLStyle::get_fontSize

IHTMLStyle::get_fontFamily

HRESULT get_fontFamily(
    BSTR *p
);

Retrieves the value of the CSS font-family attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute. See font-family for details. This parameter receives NULL if the attribute is not set.

See also put_fontFamily

Up Top of Page

IHTMLStyle::put_fontFamily

HRESULT put_fontFamily(
    BSTR v
);

Sets the value of the CSS font-family attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the font family, or NULL to remove the attribute. See font-family for details.

See also get_fontFamily


FontSize Property

*
  * Previous Topic: IHTMLStyle::get_fontFamily
  * Next Topic: IHTMLStyle::get_fontStyle

IHTMLStyle::get_fontSize

HRESULT get_fontSize(
    VARIANT *p
);

Retrieves the value of the CSS font-size attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute. See font-size for details. This parameter receives NULL if the attribute is not set.

See also put_fontSize

Up Top of Page

IHTMLStyle::put_fontSize

HRESULT put_fontSize(
    VARIANT v
);

Sets the value of the CSS font-size attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the font size, or NULL to remove the attribute. See font-size for details.

See also get_fontSize


FontStyle Property

*
  * Previous Topic: IHTMLStyle::get_fontSize
  * Next Topic: IHTMLStyle::get_fontVariant

IHTMLStyle::get_fontStyle

HRESULT get_fontStyle(
    BSTR *p
);

Retrieves the value of the CSS font-style attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute, which can be one of these strings:
normal
italic
oblique
See font-style for details. This parameter receives NULL if the attribute is not set.

See also put_fontStyle

Up Top of Page

IHTMLStyle::put_fontStyle

HRESULT put_fontStyle(
    BSTR v
);

Sets the value of the CSS font-style attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the font style, or NULL to remove the attribute. The font style can be one of these strings:
normal
italic
oblique
See font-style for details.

See also get_fontStyle


FontVariant Property

*
  * Previous Topic: IHTMLStyle::get_fontStyle
  * Next Topic: IHTMLStyle::get_fontWeight

IHTMLStyle::get_fontVariant

HRESULT get_fontVariant(
    BSTR *p
);

Retrieves the value of the CSS font-variant attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute, which can be one of these strings:
normal
small-caps
See font-variant for details. This parameter receives NULL if the attribute is not set.

The default value for this property is 1.

See also put_fontVariant

Up Top of Page

IHTMLStyle::put_fontVariant

HRESULT put_fontVariant(
    BSTR v
);

Sets the value of the CSS font-variant attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the font variation, or NULL to remove the attribute. The font variation can be one of these strings:
normal
small-caps
See font-variant for details.

The default value for the font-variant attribute is "normal".

See also get_fontVariant


FontWeight Property

*
  * Previous Topic: IHTMLStyle::get_fontVariant
  * Next Topic: IHTMLStyle::get_height

IHTMLStyle::get_fontWeight

HRESULT get_fontWeight(
    BSTR *p
);

Retrieves the value of the CSS font-weight attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute, which can be one of these strings:
normal
bold
bolder
lighter
100
200
300
400
500
600
700
800
900
See font-weight for details. This parameter receives NULL if the attribute is not set.

See also put_fontWeight

Up Top of Page

IHTMLStyle::put_fontWeight

HRESULT put_fontWeight(
    BSTR v
);

Sets the value of the CSS font-weight attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the font weight, or NULL to remove the attribute. The font weight can be one of these strings:
normal
bold
bolder
lighter
100
200
300
400
500
600
700
800
900
See font-weight for details.

See also get_fontWeight


IHTMLStyle::get_position

HRESULT get_position(
    BSTR *p
);

Retrieves the value of the CSS position attribute for the element. The attribute specifies whether the element can be positioned and, if so, the position of the element relative to its parent object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute, which can be one of these strings:
absolute | The element is placed relative to the document.
relative | The element is placed relative to its parent object.
static | The element cannot be positioned.
See position for details. This variable receives NULL if the attribute is not set.

The position attribute is not inherited.


IHTMLStyle::getAttribute

HRESULT getAttribute(
    BSTR strAttributeName,
    LONG fFlags,
    VARIANT *AttributeValue
);

Retrieves the value of the given attribute.

  • Returns S_OK if successful, or an error value otherwise.
strAttributeName
String specifying the name of the attribute to retrieve.
fFlags
Long integer that receives the flags.
AttributeValue
Address of a variable that receives a string, number, or Boolean value as defined by the attribute. If the attribute is not present, this method returns NULL.

If two or more attributes have the same name (differing only in uppercase and lowercase letters) and fFlags is FALSE, this method retrieves values only for the last attribute (the last to be created with this name). All other attributes of the same name are ignored.

See also setAttribute


Height Property

*
  * Previous Topic: IHTMLStyle::get_fontWeight
  * Next Topic: IHTMLStyle::get_left

IHTMLStyle::get_height

HRESULT get_height(
    VARIANT *p
);

Retrieves the value of the CSS height attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the height. See height for details. This parameter receives NULL if the attribute is not set.

See also put_height

Up Top of Page

IHTMLStyle::put_height

HRESULT put_height(
    VARIANT v
);

Sets the value of the CSS height attribute for the element. The attribute determines the element's height.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the height, which consists of a floating-point number and a units designator. See height for details. Set this parameter to NULL to remove the attribute.

See also get_height


Left Property

*
  * Previous Topic: IHTMLStyle::get_height
  * Next Topic: IHTMLStyle::get_letterSpacing

IHTMLStyle::get_left

HRESULT get_left(
    VARIANT *p
);

Retrieves the value of the CSS left attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute. The value is a string consisting of a floating-point number and a units designator. The variable receives NULL if the attribute is not set. See left for details.

See also put_left

Up Top of Page

IHTMLStyle::put_left

HRESULT put_left(
    VARIANT v
);

Sets the value of the CSS left attribute for the element. The attribute determines the left position of the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value consisting of a floating-point number and a units designator. See left for details. Set this parameter to NULL to remove the attribute.

See also get_left


LetterSpacing Property

*
  * Previous Topic: IHTMLStyle::get_left
  * Next Topic: IHTMLStyle::get_lineHeight

IHTMLStyle::get_letterSpacing

HRESULT get_letterSpacing(
    VARIANT *p
);

Retrieves the value of the CSS letter-spacing for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute, or NULL if the attribute is not set. See letter-spacing for details.

See also put_letterSpacing

Up Top of Page

IHTMLStyle::put_letterSpacing

HRESULT put_letterSpacing(
    VARIANT v
);

Sets the value of the CSS letter-spacing attribute for the element. The attribute determines the amount of space to add to the default space between letters in the element's text.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the amount of space to add. A negative value is valid. See letter-spacing for details. Set this parameter to NULL to remove the attribute.

See also get_letterSpacing


LineHeight Property

*
  * Previous Topic: IHTMLStyle::get_letterSpacing
  * Next Topic: IHTMLStyle::get_listStyle

IHTMLStyle::get_lineHeight

HRESULT get_lineHeight(
    VARIANT *p
);

Retrieves the value of the CSS line-height attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute. See line-height for details. The variable receives NULL if the attribute is not set.

See also put_lineHeight

Up Top of Page

IHTMLStyle::put_lineHeight

HRESULT put_lineHeight(
    VARIANT v
);

Sets the value of the CSS line-height attribute for the element. The attribute determines the distance between the baselines of subsequent lines of text. Use a negative line height to achieve various shadowing effects.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the line height. The height can be positive or negative. Set this parameter to NULL to remove the attribute.

See also get_lineHeight


ListStyle Property

*
  * Previous Topic: IHTMLStyle::get_lineHeight
  * Next Topic: IHTMLStyle::get_listStyleImage

IHTMLStyle::get_listStyle

HRESULT get_listStyle(
    BSTR *p
);

Retrieves the value of the CSS list-style attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute. See list-style for details. The variable receives NULL if the attribute is not set.

The list-style attribute is applicable only on elements that have the display attribute set to "list-item".

This function combines the functionality of the get_listStyleType, get_listStyleImage, and get_listStylePosition functions.

See also put_listStyle

Up Top of Page

IHTMLStyle::put_listStyle

HRESULT put_listStyle(
    BSTR v
);

Sets the value of the CSS list-style attribute for the element. The attribute determines how a list-item marker is drawn.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the values of the attribute. See list-style for details. Set this parameter to NULL to remove the attribute.

The list-style attribute is applicable only on elements that have the display attribute set to "list-item". This property can be set on any element and is inherited down the tree. In HTML, this is typically the case for the LI element.

This function combines the functionality of the put_listStyleType, put_listStyleImage, and put_listStylePosition functions.

If no type or position is specified, the default type is "disk" and the default position is "outside".

See also get_listStyle


ListStyleImage Property

*
  * Previous Topic: IHTMLStyle::get_listStyle
  * Next Topic: IHTMLStyle::get_listStylePosition

IHTMLStyle::get_listStyleImage

HRESULT get_listStyleImage(
    BSTR *p
);

Retrieves the value of the CSS list-style-image attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute, which can be either "none" or the URL of the image used as the list-item marker. See list-style-image for details. The variable receives NULL if the attribute is not set.

The list-style-image attribute is applicable only on elements that have the display attribute set to "list-item".

See also put_listStyleImage

Up Top of Page

IHTMLStyle::put_listStyleImage

HRESULT put_listStyleImage(
    BSTR v
);

Sets the value of the CSS list-style-image attribute for the element. The attribute sets the image to use as the list-item marker. When the image is available, it replaces the marker.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the value of the attribute. Can be either "none" or the URL of an image. See list-style-image for details. Set this parameter to NULL to remove the attribute.

The list-style-image attribute is applicable only on elements that have the display attribute set to "list-item".

See also get_listStyleImage


ListStylePosition Property

*
  * Previous Topic: IHTMLStyle::get_listStyleImage
  * Next Topic: IHTMLStyle::get_listStyleType

IHTMLStyle::get_listStylePosition

HRESULT get_listStylePosition(
    BSTR *p
);

Retrieves the value of the CSS list-style-position attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute, which can be one of these strings:
inside
outside
See list-style-position for details. The variable receives NULL if the attribute is not set.

The list-style-position attribute is applicable only on elements that have the display attribute set to "list-item".

See also put_listStylePosition

Up Top of Page

IHTMLStyle::put_listStylePosition

HRESULT put_listStylePosition(
    BSTR v
);

Sets the value of the CSS list-style-position attribute for the element. The attribute determines how the list-item marker is drawn with regard to the content.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the value of the attribute. Can be one of these strings:
inside
outside
See list-style-position for details. Set this parameter to NULL to remove the attribute.

The list-style-position attribute is applicable only on elements that have the display attribute set to "list-item".

See also get_listStylePosition


ListStyleType Property

*
  * Previous Topic: IHTMLStyle::get_listStylePosition
  * Next Topic: IHTMLStyle::get_margin

IHTMLStyle::get_listStyleType

HRESULT get_listStyleType(
    BSTR *p
);

Retrieves the value of the CSS list-style-type attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute, which can be one of these strings:
disk
circle
square
decimal
lower-roman
upper-roman
lower-alpha
upper-alpha
none
See list-style-type for details. The variable receives NULL if the attribute is not set.

The list-style-type attribute is applicable only on elements that have the display attribute set to "list-item".

See also put_listStyleType

Up Top of Page

IHTMLStyle::put_listStyleType

HRESULT put_listStyleType(
    BSTR v
);

Sets the value of the CSS list-style-type attribute for the element. The attribute determines the appearance of the list-item marker if the list-style-image is set to "none" or if the image pointed to by the URL cannot be displayed.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the value of the attribute. Can be one of these strings:
disk
circle
square
decimal
lower-roman
upper-roman
lower-alpha
upper-alpha
none
See list-style-type for details. Set this parameter to NULL to remove the attribute.

The list-style-type attribute is applicable only on elements that have the display attribute set to "list-item".

See also get_listStyleType


Margin Property

*
  * Previous Topic: IHTMLStyle::get_listStyleType
  * Next Topic: IHTMLStyle::get_marginBottom

IHTMLStyle::get_margin

HRESULT get_margin(
    BSTR *p
);

Retrieves the value of the CSS margin attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the top, right, bottom, and left margins, in that order. See margin for details. Set this parameter to NULL to remove the attribute.

This function combines the functionality of the get_marginTop, get_marginRight, get_marginBottom, and get_marginLeft functions.

See also put_margin

Up Top of Page

IHTMLStyle::put_margin

HRESULT put_margin(
    BSTR v
);

Sets the value of the CSS margin attribute for the element. The attribute sets the top, right, bottom, and left margins for the text of the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String that specifies the top, right, bottom, and left margins, in that order. See margin for details. Set this parameter to NULL to remove the attribute.

This function combines the functionality of the put_marginTop, put_marginRight, put_marginBottom, and put_marginLeft functions.

See also get_margin


MarginBottom Property

*
  * Previous Topic: IHTMLStyle::get_margin
  * Next Topic: IHTMLStyle::get_marginLeft

IHTMLStyle::get_marginBottom

HRESULT get_marginBottom(
    VARIANT *p
);

Retrieves the value of the CSS margin-bottom attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute. See margin-bottom for details. This parameter receives NULL if the attribute is not set.

See also put_marginBottom

Up Top of Page

IHTMLStyle::put_marginBottom

HRESULT put_marginBottom(
    VARIANT v
);

Sets the value of the CSS margin-bottom attribute for the element. The attribute determines the height of the bottom margin for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the height of the bottom margin. The height can be positive or negative. See margin-bottom for details. Set this parameter to NULL to remove the attribute.

See also get_marginBottom


MarginLeft Property

*
  * Previous Topic: IHTMLStyle::get_marginBottom
  * Next Topic: IHTMLStyle::get_marginRight

IHTMLStyle::get_marginLeft

HRESULT get_marginLeft(
    VARIANT *p
);

Retrieves the value of the CSS margin-left attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute. See margin-left for details. This parameter receives NULL if the attribute is not set.

See also put_marginLeft

Up Top of Page

IHTMLStyle::put_marginLeft

HRESULT put_marginLeft(
    VARIANT v
);

Sets the value of the CSS margin-left attribute for the element. The attribute determines the width of the left margin for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the width of the left margin. The width can be positive or negative. See margin-left for details. Set this parameter to NULL to remove the attribute.

See also get_marginLeft


MarginRight Property

*
  * Previous Topic: IHTMLStyle::get_marginLeft
  * Next Topic: IHTMLStyle::get_marginTop

IHTMLStyle::get_marginRight

HRESULT get_marginRight(
    VARIANT *p
);

Retrieves the value of the CSS margin-right attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute. See margin-right for details. This parameter receives NULL if the attribute is not set.

See also put_marginRight

Up Top of Page

IHTMLStyle::put_marginRight

HRESULT put_marginRight(
    VARIANT v
);

Sets the value of the CSS margin-right attribute for the element. The attribute determines the width of the right margin for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the width of the right margin. The width can be positive or negative. See margin-right for details. Set this parameter to NULL to remove the attribute.

See also get_marginRight


MarginTop Property

*
  * Previous Topic: IHTMLStyle::get_marginRight
  * Next Topic: IHTMLStyle::get_overflow

IHTMLStyle::get_marginTop

HRESULT get_marginTop(
    VARIANT *p
);

Retrieves the value of the CSS margin-top attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute. See margin-top for details. This parameter receives NULL if the attribute is not set.

See also put_marginTop

Up Top of Page

IHTMLStyle::put_marginTop

HRESULT put_marginTop(
    VARIANT v
);

Sets the value of the CSS margin-top attribute for the element. The attribute determines the height of the top margin for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the top margin. The height can be positive or negative. See margin-top for details. Set this parameter to NULL to remove the attribute.

See also get_marginTop


Overflow Property

*
  * Previous Topic: IHTMLStyle::get_marginTop
  * Next Topic: IHTMLStyle::get_padding

IHTMLStyle::get_overflow

HRESULT get_overflow(
    BSTR *p
);

Retrieves the value of the CSS overflow attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute, which can be one of these strings:
none
clip
scroll
See overflow for details. The variable receives NULL if the attribute is not set.

See also put_overflow

Up Top of Page

IHTMLStyle::put_overflow

HRESULT put_overflow(
    BSTR v
);

Sets the value of the CSS overflow attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the value of the attribute. Can be one of these strings:
none
clip
scroll
See overflow for details. Set this parameter to NULL to remove the attribute.

See also get_overflow


Padding Property

*
  * Previous Topic: IHTMLStyle::get_overflow
  * Next Topic: IHTMLStyle::get_paddingBottom

IHTMLStyle::get_padding

HRESULT get_padding(
    BSTR *p
);

Retrieves the value of the CSS padding attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the amount of top, right, bottom, and left padding, in that order. If this parameter specifies only one value, it applies to all sides. If it specifies two or three, the missing values are taken from the opposite side. See padding for details. This parameter receives NULL if the attribute is not set.

This function combines the functionality of the get_paddingTop, get_paddingRight, get_paddingBottom, and get_paddingLeft functions.

See also put_padding

Up Top of Page

IHTMLStyle::put_padding

HRESULT put_padding(
    BSTR v
);

Sets the value of the CSS padding attribute for the element. The attibute determines the amount of space between the border and the element's content.

  • Returns S_OK if successful, or an error value otherwise.
v
String that specifies the amount of top, right, bottom, and left padding, in that order. See padding for details. Set this parameter to NULL to remove the attribute.

This function combines the functionality of the put_paddingTop, put_paddingRight, put_paddingBottom, and put_paddingLeft functions.

See also get_padding


PaddingBottom Property

*
  * Previous Topic: IHTMLStyle::get_padding
  * Next Topic: IHTMLStyle::get_paddingLeft

IHTMLStyle::get_paddingBottom

HRESULT get_paddingBottom(
    VARIANT *p
);

Retrieves the value of the CSS padding-bottom attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute. See padding-bottom for details. This parameter receives NULL if the attribute is not set.

See also put_paddingBottom

Up Top of Page

IHTMLStyle::put_paddingBottom

HRESULT put_paddingBottom(
    VARIANT v
);

Sets the value of the CSS padding-bottom attribute for the element. The attribute determines the amount of space between the border and the bottom of the element's content.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the amount of bottom padding. See padding-bottom for details. Set this parameter to NULL to remove the attribute.

See also get_paddingBottom


PaddingLeft Property

*
  * Previous Topic: IHTMLStyle::get_paddingBottom
  * Next Topic: IHTMLStyle::get_paddingRight

IHTMLStyle::get_paddingLeft

HRESULT get_paddingLeft(
    VARIANT *p
);

Retrieves the value of the CSS padding-left attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute. See padding-left for details. This parameter receives NULL if the attribute is not set.

See also put_paddingLeft

Up Top of Page

IHTMLStyle::put_paddingLeft

HRESULT put_paddingLeft(
    VARIANT v
);

Sets the value of the CSS padding-left attribute for the element. The attribute determines the amount of space between the border and the left of the element's content.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the amount of left padding. See padding-left for details. Set this parameter to NULL to remove the attribute.

See also get_paddingLeft


PaddingRight Property

*
  * Previous Topic: IHTMLStyle::get_paddingLeft
  * Next Topic: IHTMLStyle::get_paddingTop

IHTMLStyle::get_paddingRight

HRESULT get_paddingRight(
    VARIANT *p
);

Retrieves the value of the CSS padding-right attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute. See padding-right for details. This parameter receives NULL if the attribute is not set.

See also put_paddingRight

Up Top of Page

IHTMLStyle::put_paddingRight

HRESULT put_paddingRight(
    VARIANT v
);

Sets the value of the CSS padding-right attribute for the element. The attribute determines the amount of space between the border and the right of the element's content.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the amount of right padding. See padding-right for details. Set this parameter to NULL to remove the attribute.

See also get_paddingRight


PaddingTop Property

*
  * Previous Topic: IHTMLStyle::get_paddingRight
  * Next Topic: IHTMLStyle::get_pageBreakAfter

IHTMLStyle::get_paddingTop

HRESULT get_paddingTop(
    VARIANT *p
);

Retrieves the value of the CSS padding-top attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute. See padding-top for details. This parameter receives NULL if the attribute is not set.

See also put_paddingTop

Up Top of Page

IHTMLStyle::put_paddingTop

HRESULT put_paddingTop(
    VARIANT v
);

Sets the value of the CSS padding-top attribute for the element. The attribute determines the amount of space between the border and the top of the element's content.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the amount of top padding. See padding-top for details. Set this parameter to NULL to remove the attribute.

See also get_paddingTop


PageBreakAfter Property

*
  * Previous Topic: IHTMLStyle::get_paddingTop
  * Next Topic: IHTMLStyle::get_pageBreakBefore

IHTMLStyle::get_pageBreakAfter

HRESULT get_pageBreakAfter(
    BSTR *p
);

Retrieves the value of the CSS page-break-after attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute, which can be one of these strings:
auto | Insert a page break after the element only if necessary.
always | Always insert a page break after the element.
left | Insert one or two page breaks after the element until a blank left page is reached.
right | Insert one or two page breaks after the element until a blank right page is reached.
See page-break-after for details. The variable receives NULL if the attribute is not set.

See also put_pageBreakAfter

Up Top of Page

IHTMLStyle::put_pageBreakAfter

HRESULT put_pageBreakAfter(
    BSTR v
);

Sets the value of the CSS page-break-after attribute for the element. The attribute determines whether a page break occurs after the element and on what page the subsequent content should resume.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the value of the attribute. Can be one of these strings:
auto | Insert a page break after the element only if necessary.
always | Always insert a page break after the element.
left | Insert one or two page breaks after the element until a blank left page is reached.
right | Insert one or two page breaks after the element until a blank right page is reached.
See page-break-after for details.

See also get_pageBreakAfter


PageBreakBefore Property

*
  * Previous Topic: IHTMLStyle::get_pageBreakAfter
  * Next Topic: IHTMLStyle::get_pixelHeight

IHTMLStyle::get_pageBreakBefore

HRESULT get_pageBreakBefore(
    BSTR *p
);

Retrieves the value of the CSS page-break-before attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute, which can be one of these strings:
auto | Insert a page break before the element only if necessary.
always | Always insert a page break before the element.
left | Insert one or two page breaks before the element until a blank left page is reached.
right | Insert one or two page breaks before the element until a blank right page is reached.
See page-break-before for details. The variable receives NULL if the attribute is not set.

See also put_pageBreakBefore

Up Top of Page

IHTMLStyle::put_pageBreakBefore

HRESULT put_pageBreakBefore(
    BSTR v
);

Sets the value of the CSS page-break-before attribute for the element. The attribute determines whether a page break occurs before the element, and on what page the subsequent content should resume.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the value of the attribute. Can be one of these strings:
auto | Insert a page break before the element only if necessary.
always | Always insert a page break before the element.
left | Insert one or two page breaks before the element until a blank left page is reached.
right | Insert one or two page breaks before the element until a blank right page is reached.
See page-break-before for details.

See also get_pageBreakBefore


PixelHeight Property

*
  * Previous Topic: IHTMLStyle::get_pageBreakBefore
  * Next Topic: IHTMLStyle::get_pixelLeft

IHTMLStyle::get_pixelHeight

HRESULT get_pixelHeight(
    long *p
);

Retrieves the height of the element, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the height.

Unlike the height attribute, this attribute's value is an integer, not a string, and is always interpreted in pixels.

See also put_pixelHeight

Up Top of Page

IHTMLStyle::put_pixelHeight

HRESULT put_pixelHeight(
    long v
);

Sets the height of the element, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
v
Long integer value specifying the height. Setting this property changes the height without changing the units designator.

Unlike the height attribute, this attribute's value is an integer, not a string, and is always interpreted in pixels.

See also get_pixelHeight


PixelLeft Property

*
  * Previous Topic: IHTMLStyle::get_pixelHeight
  * Next Topic: IHTMLStyle::get_pixelTop

IHTMLStyle::get_pixelLeft

HRESULT get_pixelLeft(
    long *p
);

Retrieves the left position of the element, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the left position.

Unlike the left attribute, this attribute's value is an integer, not a string, and is always interpreted in pixels.

See also put_pixelLeft

Up Top of Page

IHTMLStyle::put_pixelLeft

HRESULT put_pixelLeft(
    long v
);

Sets the left position of the element, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
v
Long integer value specifying the left position. Setting this property changes the value of the left position without changing the units designator.

Unlike the left attribute, this attribute's value is an integer, not a string, and is always interpreted in pixels.

See also get_pixelLeft


PixelTop Property

*
  * Previous Topic: IHTMLStyle::get_pixelLeft
  * Next Topic: IHTMLStyle::get_pixelWidth

IHTMLStyle::get_pixelTop

HRESULT get_pixelTop(
   long *p
);

Retrieves the top position of the element, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the top position.

Unlike the top attribute, this attribute's value is an integer, not a string, and is always interpreted in pixels.

See also put_pixelTop

Up Top of Page

IHTMLStyle::put_pixelTop

HRESULT put_pixelTop(
    long v
);

Sets the top position of the element, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
v
Long integer value specifying the top position. Setting this property changes the value of the top position without changing the units designator.

Unlike the top attribute, this attribute's value is an integer, not a string, and is always interpreted in pixels.

See also get_pixelTop


PixelWidth Property

*
  * Previous Topic: IHTMLStyle::get_pixelTop
  * Next Topic: IHTMLStyle::get_posHeight

IHTMLStyle::get_pixelWidth

HRESULT get_pixelWidth(
    long *p
);

Retrieves the width of the element, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the width.

Unlike the width attribute, this attribute's value is an integer, not a string, and is always interpreted in pixels.

See also put_pixelWidth

Up Top of Page

IHTMLStyle::put_pixelWidth

HRESULT put_pixelWidth(
    long v
);

Sets the width of the element, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
v
Long integer value specifying the width. Setting this property changes the width without changing the units designator.

Unlike the width attribute, this attribute's value is an integer, not a string, and is always interpreted in pixels.

See also get_pixelWidth


PosHeight Property

*
  * Previous Topic: IHTMLStyle::get_pixelWidth
  * Next Topic: IHTMLStyle::get_position

IHTMLStyle::get_posHeight

HRESULT get_posHeight(
    float *p
);

Retrieves the height of the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the height position.

Unlike the height property, this property's value is a floating-point number, not a string.

See also put_posHeight

Up Top of Page

IHTMLStyle::put_posHeight

HRESULT put_posHeight(
    float v
);

Sets the height of the element.

  • Returns S_OK if successful, or an error value otherwise.
v
Floating-point value specifying the height of the element.

Setting this property changes the value of the height but leaves the units designator for the property unchanged.

Unlike the height property, this property's value is a floating-point number, not a string.

See also get_posHeight


PosLeft Property

*
  * Previous Topic: IHTMLStyle::get_position
  * Next Topic: IHTMLStyle::get_posTop

IHTMLStyle::get_posLeft

HRESULT get_posLeft(
    float *p
) ;

Retrieves the left position of the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the left position.

Unlike the left property, this property's value is a floating-point number, not a string.

See also put_posLeft

Up Top of Page

IHTMLStyle::put_posLeft

HRESULT put_posLeft(
    float v
);

Sets the left position of the element.

  • Returns S_OK if successful, or an error value otherwise.
v
Floating-point value specifying the left position.

Setting this property changes the value of the left position but leaves the units designator for the property unchanged.

Unlike the left property, this property's value is a floating-point number, not a string.

See also get_posLeft


PosTop Property

*
  * Previous Topic: IHTMLStyle::get_posLeft
  * Next Topic: IHTMLStyle::get_posWidth

IHTMLStyle::get_posTop

HRESULT get_posTop(
    float *p
);

Retrieves the top position of the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the top position.

Unlike the top property, this property's value is a floating-point number, not a string.

See also put_posTop

Up Top of Page

IHTMLStyle::put_posTop

HRESULT put_posTop(
    float v
);

Sets the top position of the element.

  • Returns S_OK if successful, or an error value otherwise.
v
Floating-point value specifying the top position.

Setting this property changes the value of the top position but leaves the units designator for the property unchanged.

Unlike the top property, this property's value is a floating-point number, not a string.

See also get_posTop


PosWidth Property

*
  * Previous Topic: IHTMLStyle::get_posTop
  * Next Topic: IHTMLStyle::get_styleFloat

IHTMLStyle::get_posWidth

HRESULT get_posWidth(
    float *p
);

Retrieves the width position of the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the width position.

Unlike the width property, this property's value is a floating-point number, not a string.

See also put_posWidth

Up Top of Page

IHTMLStyle::put_posWidth

HRESULT put_posWidth(
    float v
);

Sets the width of the element.

  • Returns S_OK if successful, or an error value otherwise.
v
Floating-point value specifying the width of the element.

Setting this property changes the value of the width but leaves the units designator for the property unchanged.

Unlike the width property, this property's value is a floating-point number, not a string.

See also get_posWidth


IHTMLStyle::removeAttribute

HRESULT removeAttribute(
    BSTR strAttributeName,
    VARIANT_BOOL fCaseSensitive,
    VARIANT_BOOL *pfSuccess
);

Removes the given attribute from the element.

  • Returns S_OK if successful, or an error value otherwise.
strAttributeName
String specifying the name of the attribute to remove.
fCaseSensitive
Boolean value specifying whether to use a case-sensitive search to locate the attribute. If TRUE, the uppercase and lowercase letters in strAttributeName must match exactly those in the attribute name.
pfSuccess
Address of a variable that receives TRUE if the function succeeds, or FALSE otherwise.

If two or more attributes have the same name (differing only in uppercase and lowercase letters) and fCaseSensitive is false, this method removes only the last attribute (the last to be created with this name). All other attributes of the same name are ignored.

See also getAttribute, setAttribute


IHTMLStyle::setAttribute

HRESULT setAttribute(
    BSTR strAttributeName,
    VARIANT AttributeValue,
    VARIANT_BOOL fCaseSensitive
);

Sets the value of the given attribute. If the attribute is not already present, the method adds the attribute to the element and sets the value.

  • Returns S_OK if successful, or an error value otherwise.
strAttributeName
String specifying the name of the attribute to set.
AttributeValue
String, number, or Boolean value to assign to the attribute.
fCaseSensitive
Boolean value specifying whether to use a case-sensitive search to locate the attribute. If TRUE, the uppercase and lowercase letters in strAttributeName must match exactly those in the attribute name.

Be careful when spelling attribute names. If fCaseSensitive is TRUE and strAttributeName does not have the same uppercase and lowercase letters as the attribute, this method creates a new attribute.

If two or more attributes have the same name (differing only in uppercase and lowercase letters) and fCaseSensitive is FALSE, this method assigns values only to the first attribute (the first to be created with this name). All other attributes of the same name are ignored.

See also getAttribute


IHTMLStyle

This interface provides access to the methods that are returned when you access the style object. A style object represents the current settings of all possible inline styles for a given element. Inline styles are CSS style assignments that an author applies directly to individual HTML elements using the STYLE attribute. You use the style object to examine these assignments and either make new assignments or change existing ones.

You retrieve the style object by using the IHTMLElement::get_style function. You retrieve the current setting for an inline style by calling member functions of the style object.

The style object does not give access to the style assignments in style sheets. To obtain information about styles in style sheets, you must use the IHTMLStyleSheetsCollection interface to gain access to the individual style sheets defined in the document.

IHTMLStyle Methods
put_fontFamily get_fontFamily put_fontStyle
get_fontStyle put_fontVariant get_fontVariant
put_fontWeight get_fontWeight put_fontSize
get_fontSize put_font get_font
put_color get_color put_background
get_background put_backgroundColor get_backgroundColor
put_backgroundImage get_backgroundImage put_backgroundRepeat
get_backgroundRepeat put_backgroundAttachment get_backgroundAttachment
put_backgroundPosition get_backgroundPosition put_backgroundPositionX
get_backgroundPositionX put_backgroundPositionY get_backgroundPositionY
put_wordSpacing get_wordSpacing put_letterSpacing
get_letterSpacing put_textDecoration get_textDecoration
put_textDecorationNone get_textDecorationNone put_textDecorationUnderline
get_textDecorationUnderline put_textDecorationOverline get_textDecorationOverline
put_textDecorationLineThrough get_textDecorationLineThrough put_textDecorationBlink
get_textDecorationBlink put_verticalAlign get_verticalAlign
put_textTransform get_textTransform put_textAlign
get_textAlign put_textIndent get_textIndent
put_lineHeight get_lineHeight put_marginTop
get_marginTop put_marginRight get_marginRight
put_marginBottom get_marginBottom put_marginLeft
get_marginLeft put_margin get_margin
put_paddingTop get_paddingTop put_paddingRight
get_paddingRight put_paddingBottom get_paddingBottom
put_paddingLeft get_paddingLeft put_padding
get_padding put_border get_border
put_borderTop get_borderTop put_borderRight
get_borderRight put_borderBottom get_borderBottom
put_borderLeft get_borderLeft put_borderColor
get_borderColor put_borderTopColor get_borderTopColor
put_borderRightColor get_borderRightColor put_borderBottomColor
get_borderBottomColor put_borderLeftColor get_borderLeftColor
put_borderWidth get_borderWidth put_borderTopWidth
get_borderTopWidth put_borderRightWidth get_borderRightWidth
put_borderBottomWidth get_borderBottomWidth put_borderLeftWidth
get_borderLeftWidth put_borderStyle get_borderStyle
put_borderTopStyle get_borderTopStyle put_borderRightStyle
get_borderRightStyle put_borderBottomStyle get_borderBottomStyle
put_borderLeftStyle get_borderLeftStyle put_width
get_width put_height get_height
put_styleFloat get_styleFloat put_clear
get_clear put_display get_display
put_visibility get_visibility put_listStyleType
get_listStyleType put_listStylePosition get_listStylePosition
put_listStyleImage get_listStyleImage put_listStyle
get_listStyle put_whiteSpace get_whiteSpace
put_top get_top put_left
get_left get_position put_zIndex
get_zIndex put_overflow get_overflow
put_pageBreakBefore get_pageBreakBefore put_pageBreakAfter
get_pageBreakAfter put_cssText get_cssText
put_pixelTop get_pixelTop put_pixelLeft
get_pixelLeft put_pixelWidth get_pixelWidth
put_pixelHeight get_pixelHeight put_posTop
get_posTop put_posLeft get_posLeft
put_posWidth get_posWidth put_posHeight
get_posHeight put_cursor get_cursor
put_clip get_clip put_filter
get_filter setAttribute getAttribute
removeAttribute toString

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


StyleFloat Property

*
  * Previous Topic: IHTMLStyle::get_posWidth
  * Next Topic: IHTMLStyle::get_textAlign

IHTMLStyle::get_styleFloat

HRESULT get_styleFloat(
    BSTR *p
);

Retrieves the value of the CSS float attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute, which can be one of these strings:
left
right
none
See height for details. This parameter receives NULL if the attribute is not set.

See also put_styleFloat

Up Top of Page

IHTMLStyle::put_styleFloat

HRESULT put_styleFloat(
    BSTR v
);

Sets the value of the CSS float attribute for the element. The attribute determines whether the element floats, causing text to flow around it.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the value of the attribute. Can be one of these strings:
left
right
none
See float for details. Set this parameter to NULL to remove the attribute.

See also get_styleFloat


TextAlign Property

*
  * Previous Topic: IHTMLStyle::get_styleFloat
  * Next Topic: IHTMLStyle::get_textDecoration

IHTMLStyle::get_textAlign

HRESULT get_textAlign(
    BSTR *p
);

Retrieves the value of the CSS text-align attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute, which can be one of these strings:
left
right
center
justify
See text-align for details. This parameter receives NULL if the attribute is not set.

See also put_textAlign

Up Top of Page

IHTMLStyle::put_textAlign

HRESULT put_textAlign(
    BSTR v
);

Sets the value of the CSS text-align attribute for the element. The attribute determines the alignment of the element's text.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the text alignment, or NULL to remove the attribute. Can be one of these strings:
left
right
center
justify
See text-align for details.

See also get_textAlign


TextDecoration Property

*
  * Previous Topic: IHTMLStyle::get_textAlign
  * Next Topic: IHTMLStyle::get_textDecorationBlink

IHTMLStyle::get_textDecoration

HRESULT get_textDecoration(
    BSTR *p
);

Retrieves the value of the CSS text-decoration attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute, or NULL if the attribute is not set. See text-decoration for details.

See also put_textDecoration

Up Top of Page

IHTMLStyle::put_textDecoration

HRESULT put_textDecoration(
    BSTR v
);

Sets the value of the CSS text-decoration attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the text decorations. Can be "none" or one of the following strings:
underline
overline
line-through
See text-decoration for details. Set this parameter to NULL to remove the attribute.

See also get_textDecoration


TextDecorationBlink Property

*
  * Previous Topic: IHTMLStyle::get_textDecoration
  * Next Topic: IHTMLStyle::get_textDecorationLineThrough

IHTMLStyle::get_textDecorationBlink

HRESULT get_textDecorationBlink(
    VARIANT_BOOL *p
);

Retrieves whether the element's CSS text-decoration attribute has a value of "blink".

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives TRUE if the attribute has a value of "blink", or FALSE if not. See text-decoration for details.

See also put_textDecorationBlink

Up Top of Page

IHTMLStyle::put_textDecorationBlink

HRESULT put_textDecorationBlink(
    VARIANT_BOOL v
);

Sets the value of the element's CSS text-decoration attribute to "blink", or removes the "blink" value from the attribute.

  • Returns S_OK if successful, or an error value otherwise.
v
Boolean value. TRUE sets the attribute to "blink"; FALSE removes the "blink" value from the attribute. See text-decoration for details.

See also get_textDecorationBlink


TextDecorationLineThrough Property

*
  * Previous Topic: IHTMLStyle::get_textDecorationBlink
  * Next Topic: IHTMLStyle::get_textDecorationNone

IHTMLStyle::get_textDecorationLineThrough

HRESULT get_textDecorationLineThrough(
    VARIANT_BOOL *p
);

Retrieves whether the element's CSS text-decoration attribute has a value of "line-through".

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives TRUE if the attribute has a value of "line-through", or FALSE if not. See text-decoration for details.

See also put_textDecorationLineThrough

Up Top of Page

IHTMLStyle::put_textDecorationLineThrough

HRESULT put_textDecorationLineThrough(
    VARIANT_BOOL v
);

Sets the value of the element's CSS text-decoration attribute to "line-through", or removes the "line-through" value from the attribute.

  • Returns S_OK if successful, or an error value otherwise.
v
Boolean value. TRUE sets the attribute to "line-through"; FALSE removes the "line-through" value from the attribute. See text-decoration for details.

See also get_textDecorationLineThrough


TextDecorationNone Property

*
  * Previous Topic: IHTMLStyle::get_textDecorationLineThrough
  * Next Topic: IHTMLStyle::get_textDecorationOverline

IHTMLStyle::get_textDecorationNone

HRESULT get_textDecorationNone(
    VARIANT_BOOL *p
);

Retrieves whether the element's CSS text-decoration attribute has a value of "none".

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives TRUE if the attribute has a value of "none", or FALSE if not. See text-decoration for details.

See also put_textDecorationNone

Up Top of Page

IHTMLStyle::put_textDecorationNone

HRESULT put_textDecorationNone(
    VARIANT_BOOL v
);

Sets the value of the element's CSS text-decoration attribute to "none", or removes the "none" value from the attribute.

  • Returns S_OK if successful, or an error value otherwise.
v
Boolean value. TRUE sets the attribute to "none"; FALSE removes the "none" value from the attribute. See text-decoration for details.

See also get_textDecorationNone


TextDecorationOverline Property

*
  * Previous Topic: IHTMLStyle::get_textDecorationNone
  * Next Topic: IHTMLStyle::get_textDecorationUnderline

IHTMLStyle::get_textDecorationOverline

HRESULT get_textDecorationOverline(
    VARIANT_BOOL *p
);

Retrieves whether the element's CSS text-decoration attribute has a value of "overline".

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives TRUE if the attribute has a value of "overline", or FALSE if not. See text-decoration for details.

See also put_textDecorationOverline

Up Top of Page

IHTMLStyle::put_textDecorationOverline

HRESULT put_textDecorationOverline(
    VARIANT_BOOL v
);

Sets the value of the element's CSS text-decoration attribute to "overline", or removes the "overline" value from the attribute.

  • Returns S_OK if successful, or an error value otherwise.
v
Boolean value. TRUE sets the attribute to "overline"; FALSE removes the "overline" value from the attribute. See text-decoration for details.

See also get_textDecorationOverline


TextDecorationUnderline Property

*
  * Previous Topic: IHTMLStyle::get_textDecorationOverline
  * Next Topic: IHTMLStyle::get_textIndent

IHTMLStyle::get_textDecorationUnderline

HRESULT get_textDecorationUnderline(
    VARIANT_BOOL *p
);

Retrieves whether the element's CSS text-decoration attribute has a value of "underline".

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives TRUE if the attribute has a value of "underline", or FALSE if not. See text-decoration for details.

See also put_textDecorationUnderline

Up Top of Page

IHTMLStyle::put_textDecorationUnderline

HRESULT put_textDecorationUnderline(
    VARIANT_BOOL v
);

Sets the value of the element's CSS text-decoration attribute to "underline", or removes the "underline" value from the attribute.

  • Returns S_OK if successful, or an error value otherwise.
v
Boolean value. TRUE sets the attribute to "underline"; FALSE removes the "underline" value from the attribute. See text-decoration for details.

See also get_textDecorationUnderline


TextIndent Property

*
  * Previous Topic: IHTMLStyle::get_textDecorationUnderline
  * Next Topic: IHTMLStyle::get_textTransform

IHTMLStyle::get_textIndent

HRESULT get_textIndent(
    VARIANT *p
);

Retrieves the value of the CSS text-indent attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute. See text-indent for details. This parameter receives NULL if the attribute is not set.

See also put_textIndent

Up Top of Page

IHTMLStyle::put_textIndent

HRESULT put_textIndent(
    VARIANT v
);

Sets the value of the CSS text-indent attribute for the element. The attribute determines the amount of indention before the element's first line of formatted text.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the amount of indention, or NULL to remove the attribute. The amount can be positive or negative. See text-indent for details.

See also get_textIndent


TextTransform Property

*
  * Previous Topic: IHTMLStyle::get_textIndent
  * Next Topic: IHTMLStyle::get_top

IHTMLStyle::get_textTransform

HRESULT get_textTransform(
    BSTR *p
);

Retrieves the value of the CSS text-transform attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute, which can be one of these strings:
capitalize | First letter in the text is capitalized.
lowercase | All letters in the text are converted to lowercase.
uppercase | All letters in the text are converted to uppercase.
See text-transform for details. This parameter receives NULL if the attribute is not set.

See also put_textTransform

Up Top of Page

IHTMLStyle::put_textTransform

HRESULT put_textTransform(
    BSTR v
);

Sets the value of the CSS text-transform attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the text transformation, or NULL to remove the attribute. Can be one of these strings:
capitalize | First letter in the text is capitalized.
lowercase | All letters in the text are converted to lowercase.
uppercase | All letters in the text are converted to uppercase.
See text-transform for details.

See also get_textTransform


Top Property

*
  * Previous Topic: IHTMLStyle::get_textTransform
  * Next Topic: IHTMLStyle::get_verticalAlign

IHTMLStyle::get_top

HRESULT get_top(
    VARIANT *p
);

Retrieves the value of the CSS top attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute. The value is a string consisting of a floating-point number and a units designator. See top for details. The variable receives NULL if the attribute is not set.

See also put_top

Up Top of Page

IHTMLStyle::put_top

HRESULT put_top(
    VARIANT v
);

Sets the value of the CSS top attribute for the element. The attribute determines the top position of the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value consisting of a floating-point number and a units designator. See top for details. Set this parameter to NULL to remove the attribute.

See also get_top


IHTMLStyle::toString

HRESULT toString(
   BSTR *String
);

Retrieves a string representation of the style object.

  • Returns S_OK if successful, or an error value otherwise.
String
Address of a variable that receives the string representation.


VerticalAlign Property

*
  * Previous Topic: IHTMLStyle::get_top
  * Next Topic: IHTMLStyle::get_visibility

IHTMLStyle::get_verticalAlign

HRESULT get_verticalAlign(
    VARIANT *p
);

Retrieves the value of the CSS vertical-align attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute, or NULL if the attribute is not set. Can be one of these strings:
baseline
middle
sub
super
text-top
text-bottom
top
bottom
See vertical-align for details.

See also put_verticalAlign

Up Top of Page

IHTMLStyle::put_verticalAlign

HRESULT put_verticalAlign(
    VARIANT v
);

Sets the value of the CSS vertical-align attribute for the element. The attribute determines the vertical positioning of the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the vertical alignment. Can be a percentage (either positive or negative) of the line height of the element, or one of the values below. These values are relative to the parent element:
baseline
middle
sub
super
text-top
text-bottom
These values are relative to the formatted line of which the element is a part:
top
bottom
See vertical-align for details. Set this parameter to NULL to remove the attribute.

See also get_verticalAlign


Visibility Property

*
  * Previous Topic: IHTMLStyle::get_verticalAlign
  * Next Topic: IHTMLStyle::get_whiteSpace

IHTMLStyle::get_visibility

HRESULT get_visibility(
    BSTR *p
);

Retrieves the value of the visibility attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute, which can be one of these strings:
visible
hidden
inherit
See visibility for details. The variable receives NULL if the attribute is not set.

See also put_visibility

Up Top of Page

IHTMLStyle::put_visibility

HRESULT put_visibility(
    BSTR v
);

Sets the value of the CSS visibility attribute for the element. The attribute determines whether the content of the element is visible.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying whether the element is visible. Can be one of these strings:
visible
hidden
inherit
See visibility for details. Set this parameter to NULL to remove the attribute.

Space is reserved for the element's content regardless of the value of the visibility attribute.

See also get_visibility


WhiteSpace Property

*
  * Previous Topic: IHTMLStyle::get_visibility
  * Next Topic: IHTMLStyle::get_width

IHTMLStyle::get_whiteSpace

HRESULT get_whiteSpace(
    BSTR *p
);

Retrieves the value of the CSS white-space attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute, which can be one of these strings:
normal | Consecutive white-space characters are replaced with a single space.
nowrap | Linebreak characters are preserved, but consecutive spaces and tab characters are replaced with a single space.
pre | All white-space characters (including line breaks) are preserved.
The variable receives NULL if the attribute is not set.

See also put_whiteSpace

Up Top of Page

IHTMLStyle::put_whiteSpace

HRESULT put_whiteSpace(
    BSTR v
);

Sets the CSS white-space attribute for the element. The attribute determines whether and how white-space characters in the element are displayed.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the value of the attribute. Can be one of these strings:
normal | Consecutive white-space characters are replaced with a single space.
nowrap | Linebreak characters are preserved, but consecutive spaces and tab characters are replaced with a single space.
pre | All white-space characters (including line breaks) are preserved.
Set this parameter to NULL to remove the attribute.

See also get_whiteSpace


Width Property

*
  * Previous Topic: IHTMLStyle::get_whiteSpace
  * Next Topic: IHTMLStyle::get_wordSpacing

IHTMLStyle::get_width

HRESULT get_width(
    VARIANT *p
);

Retrieves the value of the CSS width attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the width. See width for details. This parameter receives NULL if the attribute is not set.

See also put_width

Up Top of Page

IHTMLStyle::put_width

HRESULT put_width(
   VARIANT v
);

Sets the value of the CSS width attribute for the element. The attribute determines the element's width.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the width, which consists of a floating-point number and a units designator. See width for details. Set this parameter to NULL to remove the attribute.

See also get_width


WordSpacing Property

*
  * Previous Topic: IHTMLStyle::get_width
  * Next Topic: IHTMLStyle::get_zIndex

IHTMLStyle::get_wordSpacing

HRESULT get_wordSpacing(
    VARIANT *p
);

Retrieves the value of the CSS word-spacing attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the value of the attribute, or NULL if the attribute is not set.

See also put_wordSpacing

Up Top of Page

IHTMLStyle::put_wordSpacing

HRESULT put_wordSpacing(
    VARIANT v
);

Sets the value of the CSS word-spacing attribute for the element. The attribute determines the amount of space to add to the default space between words in the element's text.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the amount of space to add. A negative value is valid. Set this parameter to NULL to remove the attribute.

See also get_wordSpacing


ZIndex Property

*
  * Previous Topic: IHTMLStyle::get_wordSpacing
  * Next Topic: IHTMLStyle::getAttribute

IHTMLStyle::get_zIndex

HRESULT get_zIndex(
    VARIANT *p
);

Retrieves the value of the CSS z-index attribute for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the z-index. The variable receives a positive value if the element is positioned above the text, and a negative value if it is below. See z-index for details. The variable receives NULL if the attribute is not set.

See also put_zIndex

Up Top of Page

IHTMLStyle::put_zIndex

HRESULT put_zIndex(
    VARIANT v
);

Sets the value of the CSS z-index attribute for the element. The attribute determines whether the element is positioned above or below the text.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the z-index. A positive value positions the element above the text, and a negative value positions it below. See z-index for details. Set this parameter to NULL to remove the attribute.

See also get_zIndex


Disabled Property

*
  * Previous Topic: IHTMLStyleElement
  * Next Topic: IHTMLStyleElement::get_media

IHTMLStyleElement::get_disabled

HRESULT get_disabled(
    VARIANT_BOOL *p
);

Retrieves the Boolean value that determines whether this style element is disabled.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives TRUE if the style element is enabled, or FALSE otherwise.

See also put_disabled

Up Top of Page

IHTMLStyleElement::put_disabled

HRESULT put_disabled(
    VARIANT_BOOL v
);

Sets the Boolean value that determines whether this style element is disabled.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the status of the StyleElement. This parameter is TRUE if the style element is disabled, or FALSE otherwise. See STYLE for details.

See also get_disabled


IHTMLStyleElement::get_readyState

HRESULT get_readyState(
    BSTR *p
);

Retrieves the current state of an object being downloaded.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the current state. Can be one of these values:
complete | The object is completely loaded.
interactive | The object can be interacted with even though it is not fully loaded.
loading | The object is currently being loaded.
uninitialized | The object is not created. Usually when the object is being downloaded.

Each object can independently determine which of the states it exposes.


IHTMLStyleElement::get_styleSheet

HRESULT get_styleSheet(
    IHTMLStyleSheet **p
);

Retrieves an interface pointer that provides access to the style sheet object's properties and methods.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the interface pointer.

See also IHTMLStyleSheet


Media Property

*
  * Previous Topic: IHTMLStyleElement::get_disabled
  * Next Topic: IHTMLStyleElement::get_onerror

IHTMLStyleElement::get_media

HRESULT get_media(
    BSTR *p
);

Retrieves the string that indicates which media this style element applies to.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string that receives the media type.

See also put_media

Up Top of Page

IHTMLStyleElement::put_media

HRESULT put_media(
    BSTR v
);

Sets the inline script that indicates which media this style element applies to.

  • Returns S_OK if successful, or an error value otherwise.
v
String value specifying the type of media for this style element.

See also get_media, IHTMLLinkElement


Onerror Property

*
  * Previous Topic: IHTMLStyleElement::get_media
  * Next Topic: IHTMLStyleElement::get_onload

IHTMLStyleElement::get_onerror

HRESULT get_onerror(
    VARIANT *p
);

Retrieves the inline script associated with the onerror event on the style element. This error event occurs when the loading of a document or image causes an error.

For more information on inline script, see Attaching an Event Handler in the Event Model documentation.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that contains the error script. See onerror for more information.

See also put_onerror

Up Top of Page

IHTMLStyleElement::put_onerror

HRESULT put_onerror(
    VARIANT v
);

Sets the inline script associated with the onerror event on the style element. This error event occurs when the loading of a document or image causes an error.

For more information on inline script, see Attaching an Event Handler in the Event Model documentation.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to be set. See onerror for more information.

See also get_onerror


Onload Property

*
  * Previous Topic: IHTMLStyleElement::get_onerror
  * Next Topic: IHTMLStyleElement::get_onreadystatechange

IHTMLStyleElement::get_onload

HRESULT get_onload(
    VARIANT *p
);

Retrieves the script associated with the onload event on the STYLE element. Occurs immediately after the browser loads the given object.

For more information on inline script, see Attaching an Event Handler in the Event Model documentation.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that contains the script.

See also put_onload

Up Top of Page

IHTMLStyleElement::put_onload

HRESULT put_onload(
    VARIANT v
);

Sets the script associated with the onload event on the STYLE element. Occurs immediately after the browser loads the given object.

For more information on inline script, see Attaching an Event Handler in the Event Model documentation.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to be set.

See also get_onload


Onreadystatechange Property

*
  * Previous Topic: IHTMLStyleElement::get_onload
  * Next Topic: IHTMLStyleElement::get_readyState

IHTMLStyleElement::get_onreadystatechange

HRESULT get_onreadystatechange(
    VARIANT *p
);

Retrieves the script associated with the onreadystatechange event on the STYLE element.

For more information on inline script, see Attaching an Event Handler in the Event Model documentation.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that contains the script.

See also put_onreadystatechange

Up Top of Page

IHTMLStyleElement::put_onreadystatechange

HRESULT put_onreadystatechange(
    VARIANT v
);

Sets the script associated with the onreadystatechange event on the STYLE element.

For more information on inline script, see Attaching an Event Handler in the Event Model documentation.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to be set.

See also get_onreadystatechange


IHTMLStyleElement

This interface specifies the style sheet for the page.

This element can be used only within either the HEAD or BODY element.

IHTMLStyleElement Methods
put_type get_type get_readyState
put_onreadystatechange get_onreadystatechange put_onload
get_onload put_onerror get_onerror
get_styleSheet put_disabled get_disabled
put_media get_media

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


Type Property

*
  * Previous Topic: IHTMLStyleElement::get_styleSheet
  * Next Topic: IHTMLStyleElement::put_disabled

IHTMLStyleElement::get_type

HRESULT get_type(
    BSTR *p
);

Retrieves the CSS language in which the style sheet is written.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the CSS language. It can be any string, including an empty string. Valid style sheets are typically set to "text/css".

See also put_type

Up Top of Page

IHTMLStyleElement::put_type

HRESULT put_type(
    BSTR v
);

Sets the CSS language in which the style sheet is written.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the CSS language. It can be any string, including an empty string. Valid style sheets are typically set to "text/css".

See also get_type


IHTMLStyleSheet::addImport

HRESULT addImport(
    BSTR bstrURL,
    long lIndex,
long *plIndex
);

Adds a style sheet to the imports collection for the given style sheet.

  • Returns S_OK if successful, or an error value otherwise.
bstrURL
String specifying the location of the source file for the style sheet.
lIndex
Integer specifying the requested position of the style sheet in the collection. The position is zero-based.
plIndex
Address of a variable that receives an integer index value specifying the position of the imported style sheet in the imports collection.


IHTMLStyleSheet::addRule

HRESULT addRule(
    BSTR bstrSelector,
    BSTR bstrStyle,
    long lIndex,
    long *plNewIndex
);

Creates a new style rule using the given selector and style assignment.

  • Returns S_OK if successful, or an error value otherwise.
bstrSelector
String specifying the selector for the new rule.
bstrStyle
String specifying the style assignments for this style rule.
lIndex
Zero-based position in the style sheet where the style rule is to be placed.
plNewIndex
Address of a variable that receives the new zero-based index of the style rule.


Disabled Property

*
  * Previous Topic: IHTMLStyleSheet::get_cssText
  * Next Topic: IHTMLStyleSheet::get_href

IHTMLStyleSheet::get_disabled

HRESULT get_disabled(
    VARIANT_BOOL *p
);

Determines whether the style sheet is enabled or disabled. "False" for style sheets that do not specify a title and that are not currently selected.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives TRUE if the style sheet is enabled, or FALSE otherwise. This parameter receives FALSE if the style sheet does not specify a title or is not currently selected.

The value of this property can change per media-dependent style sheets. The application of individual style sheets can be turned on and off dynamically. Note that the value of this property is also controlled by whether titled style sheets are applied.

See also put_disabled

Up Top of Page

IHTMLStyleSheet::put_disabled

HRESULT put_disabled(
    VARIANT_BOOL v
);

Enables or disables the style sheet.

  • Returns S_OK if successful, or an error value otherwise.
v
TRUE to enable the style sheet, or FALSE to disable it.

See also get_disabled


IHTMLStyleSheet::get_cssText

HRESULT get_cssText(
    BSTR *p
);

Retrieves a string of the rules set in the style sheet defined in the CSS format as it would look, if the style sheet were saved.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the rules set.


IHTMLStyleSheet::get_id

HRESULT get_id(
    BSTR *p
);

Retrieves the identifier of the style sheet.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the identifier.


IHTMLStyleSheet::get_imports

HRESULT get_imports(
    IHTMLStyleSheetsCollection **p
);

Retrieves a zero-based collection of all the imported style sheets defined for the given styleSheet object. An imported style sheet is one that is brought into the document using the CSS @import attribute.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives a pointer to the collection. See IHTMLStyleSheetsCollection for details.


IHTMLStyleSheet::get_owningElement

HRESULT get_owningElement(
    IHTMLElement **p
);

Retrieves the element that is next in the HTML hierarchy. This usually contains the STYLE or LINK that defined the style sheet.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives an interface pointer to the element.

See also IHTMLElement


IHTMLStyleSheet::get_parentStyleSheet

HRESULT get_parentStyleSheet(
    IHTMLStyleSheet **p
);

Retrieves an interface pointer to the styleSheet object that imported the current style sheet. This property is intended for imported styleSheets.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives an interface pointer to the parent style sheet. This parameter receives NULL if the style sheet is part of a LINK or STYLE element.


IHTMLStyleSheet::get_readOnly

HRESULT get_readOnly(
    VARIANT_BOOL *p
);

Indicates whether the rule object can be edited.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives TRUE if the rule object can be edited, or FALSE if not.


IHTMLStyleSheet::get_rules

HRESULT get_rules(
    IHTMLStyleSheetRulesCollection **p
);

Retrieves an IHTMLStyleSheetRulesCollection pointer to the collection of the rules in this styleSheet. If there are no rules, the length of the collection returned is zero.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives an interface pointer to IHTMLStyleSheetRulesCollection.


IHTMLStyleSheet::get_type

HRESULT get_type(
    BSTR *p
);

Retrieves the CSS language the style sheet is written in.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the type. It can be any string, including an empty string. Currently, style sheets having any type other than "text/css" are not supported.


Href Property

*
  * Previous Topic: IHTMLStyleSheet::get_disabled
  * Next Topic: IHTMLStyleSheet::get_id

IHTMLStyleSheet::get_href

HRESULT get_href(
    BSTR *p
);

Retrieves the URL of a linked style sheet.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string that receives the URL. If the style sheet is a STYLE element, this parameter receives NULL.

See also put_href

Up Top of Page

IHTMLStyleSheet::put_href

HRESULT put_href(
    BSTR v
);

Sets the URL of a linked styleSheet; that is, it is part of a LINK element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the URL.

See also get_href


Media Property

*
  * Previous Topic: IHTMLStyleSheet::get_imports
  * Next Topic: IHTMLStyleSheet::get_owningElement

IHTMLStyleSheet::get_media

HRESULT get_media(
    BSTR *p
);

Receives the string that indicates which media this style applies to.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a sting variable that receives the media type.

See also put_media

Up Top of Page

IHTMLStyleSheet::put_media

HRESULT put_media(
    BSTR v
);

Sets the string that indicates which media this style element applies to. See IHTMLLinkElement::put_media for values.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the media type for the styleSheet element.

See also get_media


IHTMLStyleSheet::removeImport

HRESULT removeImport(
    long lIndex
);

Removes the imported style sheet by ordinal position in the imports collection based on the value of the index passed in.

  • Returns S_OK if successful, or an error value otherwise.
lIndex
Long integer value indicating which imported style sheet to remove.


IHTMLStyleSheet::removeRule

HRESULT removeRule(
    long lIndex
);

Removes the rule by ordinal position based on the value of the index passed in. The rule is deleted from the style sheet, and the document is updated to reflect any changes.

  • Returns S_OK if successful, or an error value otherwise.
lIndex
Long integer value indicating which style rule to remove.


IHTMLStyleSheet

This interface provides access to an object representing a single style sheet in the document.

The styleSheet object represents an instance of the STYLE or LINK tag with a relationship (rel attribute) of the STYLESHEET object.

You use the object to retrieve information about the style sheet, such as the URL of the source file for the style sheet and the element in the document that owns (defines) the style sheet. You also use the object to modify the style sheet.

You retrieve a pointer to the style sheet object by using the IHTMLDocument2::get_styleSheets method. You can retrieve a collection of all styleSheets in the document by using the IHTMLStyleSheet::get_imports method. Each item in the collection is a style sheet. A style sheet object is available for a style sheet only if it is included in a document with a STYLE or LINK element, or with an @import statement in the STYLE element.

IHTMLStyleSheet Methods
put_title get_title get_parentStyleSheet
get_owningElement put_disabled get_disabled
get_readOnly get_imports put_href
get_href get_type get_id
addImport addRule removeImport
removeRule put_media get_media
get_cssText get_rules

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


Title Property

*
  * Previous Topic: IHTMLStyleSheet::get_rules
  * Next Topic: IHTMLStyleSheet::get_type

IHTMLStyleSheet::get_title

HRESULT get_title(
    BSTR *p
);

Retrieves the title of the styleSheet.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the title. This parameter receives FALSE if the style sheet has no title or the title is not currently selected.

The application of individual style sheets can be turned on and off dynamically. Note that the value of this property is also controlled by whether titled style sheets are applied.

See also put_title

Up Top of Page

IHTMLStyleSheet::put_title

HRESULT put_title(
    BSTR v
);

Sets the title of the styleSheet element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the title.

See also get_title


IHTMLStyleSheetRule::get_readOnly

HRESULT get_readOnly(
    VARIANT_BOOL *p
);

Retrieves a Boolean value that indicates whether this rule is readOnly.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives TRUE if the attribute has a value of "readOnly", or FALSE if not. See readOnly for details.


IHTMLStyleSheetRule::get_style

HRESULT get_style(
    IHTMLRuleStyle **p
);

Retrieves an IHTMLRuleStyle pointer to the styleSheet object that contains this rule.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives an IHTMLRuleStyle interface pointer to the styleSheet object.


SelectorText Property

*
  * Previous Topic: IHTMLStyleSheetRule::get_readOnly
  * Next Topic: IHTMLStyleSheetRule::get_style

IHTMLStyleSheetRule::get_selectorText

HRESULT get_selectorText(
    BSTR *p
);

Retrieves the selection string for the style sheet rule.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the selection text.

See also put_selectorText

Up Top of Page

IHTMLStyleSheetRule::put_selectorText

HRESULT put_selectorText(
    BSTR v
);

Currently not implemented.

See also get_selectorText


IHTMLStyleSheetRule

This interface provides access to the methods that are returned when you access styleSheet object.

This object is returned from the rules collection of a styleSheet. It represents a particular rule in a style sheet.

IHTMLStyleSheetRule Methods


IHTMLStyleSheetRulesCollection::get_length

HRESULT get_length(
    long *p
);

Returns the number of elements in a collection. This method provides the same capabilities as the length property.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a value that receives the number of elements in the collection. This is an integer value or a string specifying the index value of the style sheet to retrieve. Integer indexes are zero-based, meaning the first style sheet in the collection has index 0.


IHTMLStyleSheetRulesCollection::item

HRESULT item(
    long index,
    IHTMLStyleSheetRule **ppHTMLStyleSheetRule
);

Retrieves an element or a collection from the given collection. The index parameter determines which action to take.

  • Returns S_OK if successful, or an error value otherwise.
index
Value that contains the number specifying the position of an element to retrieve.
ppHTMLStyleSheetRule
Address of a pointer to the IHTMLStyleSheetRule interface of the styleSheets element.


IHTMLStyleSheetRulesCollection

This interface provides the abilities to obtain the number of styleSheets in the collection, and access a single styleSheet element from the collection.

A collection of the rules in a styleSheet element. This is returned from the style sheets rules property.

IHTMLStyleSheetRulesCollection Methods


IHTMLStyleSheetsCollection::get__newEnum

HRESULT get__newEnum(
    IUnknown **p
);

Retrieves an enumerator interface which can be used to iterate through the styleSheets collection of the STYLE element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a pointer to an IUnknown interface.


IHTMLStyleSheetsCollection::get_length

HRESULT get_length(
    long *p
);

Retrieves the number of elements in a collection.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a long integer variable that receives the length.

This property is read-write on the areas and the options collection for image maps and select boxes, respectively. This allows a developer to shrink the collection.


IHTMLStyleSheetsCollection::item

HRESULT item(
    VARIANT *pvarIndex,
    VARIANT *pvarResult
);

Retrieves an styleSheet element or a collection of styleSheets. The index determines which action to take.

  • Returns S_OK if successful, or an error value otherwise.
pvarIndex
Address of a VARIANT structure specifying the element or collection to retrieve. If this parameter is a number, the method returns the element in the collection at the given position, where the first element has value 0, the second has 1, and so on. If this parameter is a string, the method returns a collection of elements, where the value of the name or id property for each element is equal to the string.
pvarResult
Address of a VARIANT structure that receives an element object or a collection of element objects if successful, or NULL otherwise.


IHTMLStyleSheetsCollection

This interface provides the abilities to obtain the number of styleSheets in the collection, and to iterate through the styleSheets collection of the STYLE element.

A zero-based collection of style sheets is exposed from the document object. Each style sheet object represents an individual style sheet that is defined for the document. This object represents instances of the LINK and STYLE elements with a relationship (rel attribute) of STYLESHEET.

Imported style sheets are contained within a STYLE element and are accessible through the IHTMLStyleSheet::get_imports method.

IHTMLStyleSheetsCollection Methods


Align Property

*
  * Previous Topic: IHTMLTable::deleteTHead
  * Next Topic: IHTMLTable::get_background

IHTMLTable::get_align

HRESULT get_align(
    BSTR *p
);

Retrieves how the table should be aligned.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives one of these values:
center | Aligns to the center.
left | Aligns to the left edge. This is the default value.
right | Aligns to the right edge.

See also put_align

Up Top of Page

IHTMLTable::put_align

HRESULT put_align(
    BSTR v
);

Sets how the table should be aligned.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the alignment. Can be one of these values:
center | Aligns to the center.
left | Aligns to the left edge. This is the default value.
right | Aligns to the right edge.

See also get_align


Background Property

*
  * Previous Topic: IHTMLTable::get_align
  * Next Topic: IHTMLTable::get_bgColor

IHTMLTable::get_background

HRESULT get_background(
    BSTR *p
);

Retrieves the current background picture for the table, if any. The picture is tiled behind the text and graphics in the table.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the URL of the background picture.

See also put_background

Up Top of Page

IHTMLTable::put_background

HRESULT put_background(
    BSTR v
);

Sets a background picture for the table. The picture is tiled behind the text and graphics in the table.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the URL of the background picture.

See also get_background


BgColor Property

*
  * Previous Topic: IHTMLTable::get_background
  * Next Topic: IHTMLTable::get_border

IHTMLTable::get_bgColor

HRESULT get_bgColor(
    VARIANT *p
);

Retrieves the current background color of the table.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the color. The color can be one of the color names or values given in the Color Table reference documentation.

See also put_bgColor

Up Top of Page

IHTMLTable::put_bgColor

HRESULT put_bgColor(
    VARIANT v
);

Sets the background color of the table.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the color. The color can be one of the color names or values given in the Color Table reference documentation.

See also get_bgColor


Border Property

*
  * Previous Topic: IHTMLTable::get_bgColor
  * Next Topic: IHTMLTable::get_borderColor

IHTMLTable::get_border

HRESULT get_border(
    VARIANT *p
);

Retrieves the border color and must be used with the border property, except for frames. The color can be one of the color names or values given in the Color Table reference documentation.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives one of the color names or values given in the Color Table reference documentation.

See also put_border

Up Top of Page

IHTMLTable::put_border

HRESULT put_border(
    VARIANT v
);

Sets the border color and must be used with the border property, except for frames.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains either a string or numeric value specifying the color. The color can be one of the color names or values given in the Color Table reference documentation.

See also get_border


BorderColor Property

*
  * Previous Topic: IHTMLTable::get_border
  * Next Topic: IHTMLTable::get_borderColorDark

IHTMLTable::get_borderColor

HRESULT get_borderColor(
    VARIANT *p
);

Retrieves the border color and must be used with the border property.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the color. The color can be one of the color names or values given in the Color Table reference documentation.

See also put_borderColor

Up Top of Page

IHTMLTable::put_borderColor

HRESULT put_borderColor(
    VARIANT v
);

Sets the border color and must be used with the border property.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the color. The color can be one of the color names or values given in the Color Table reference documentation.

See also get_borderColor


BorderColorDark Property

*
  * Previous Topic: IHTMLTable::get_borderColor
  * Next Topic: IHTMLTable::get_borderColorLight

IHTMLTable::get_borderColorDark

HRESULT get_borderColorDark(
    VARIANT *p
);

Retrieves independent border color control over one of the two colors used to draw a 3-D border, opposite of borderColorLight, and must be used with the border property.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the color. The color can be one of the color names or values given in the Color Table reference documentation.

See also put_borderColorDark

Up Top of Page

IHTMLTable::put_borderColorDark

HRESULT put_borderColorDark(
    VARIANT v
);

Sets independent border color control over one of the two colors used to draw a 3-D border, opposite of borderColorLight, and must be used with the border property.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the color. The color can be one of the color names or values given in the Color Table reference documentation.

See also get_borderColorDark


BorderColorLight Property

*
  * Previous Topic: IHTMLTable::get_borderColorDark
  * Next Topic: IHTMLTable::get_caption

IHTMLTable::get_borderColorLight

HRESULT get_borderColorLight(
    VARIANT *p
);

Retrieves independent border color control over one of the two colors used to draw a 3-D border, opposite of borderColorDark, and must be used with the border property.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the color. The color can be one of the color names or values given in the Color Table reference documentation.

See also put_borderColorLight

Up Top of Page

IHTMLTable::put_borderColorLight

HRESULT put_borderColorLight(
    VARIANT v
);

Sets independent border color control over one of the two colors used to draw a 3-D border, opposite of borderColorDark, and must be used with the border property.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the color. The color can be one of the color names or values given in the Color Table reference documentation.

See also get_borderColorLight


CellPadding Property

*
  * Previous Topic: IHTMLTable::get_caption
  * Next Topic: IHTMLTable::get_cellSpacing

IHTMLTable::get_cellPadding

HRESULT get_cellPadding(
    VARIANT *p
);

Retrieves the amount of space between the border of the cell and the contents of the cell.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the cell padding.

See also put_cellPadding

Up Top of Page

IHTMLTable::put_cellPadding

HRESULT put_cellPadding(
    VARIANT v
);

Sets the amount of space between the border of the cell and the contents of the cell.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains either a string or value specifying the cell padding.

See also get_cellPadding


CellSpacing Property

*
  * Previous Topic: IHTMLTable::get_cellPadding
  * Next Topic: IHTMLTable::get_cols

IHTMLTable::get_cellSpacing

HRESULT get_cellSpacing(
    VARIANT *p
);

Retrieves the amount of space between cells in a table.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the cell spacing.

See also put_cellSpacing

Up Top of Page

IHTMLTable::put_cellSpacing

HRESULT put_cellSpacing(
    VARIANT v
);

Sets the amount of space between cells in a table.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure containing either a string or value specifying the cell spacing.

See also get_cellSpacing


Cols Property

*
  * Previous Topic: IHTMLTable::get_cellSpacing
  * Next Topic: IHTMLTable::get_dataPageSize

IHTMLTable::get_cols

HRESULT get_cols(
    long *p
);

Retrieves the number of columns in the table.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a long integer that receives the number of columns.

See also put_cols

Up Top of Page

IHTMLTable::put_cols

HRESULT put_cols(
    long v
);

Sets the number of columns in the table.

  • Returns S_OK if successful, or an error value otherwise.
v
Long integer value specifying the number of columns.

Providing this number can speed up the processing of the table.

See also get_cols


IHTMLTable::createCaption

HRESULT createCaption(
    IHTMLTableCaption **caption
);

Creates a table caption. If no caption exists, this creates an empty table caption and adds it to the table, and returns a pointer to it. If captions already exist, this method returns a pointer to the first one in the list.

  • Returns S_OK if successful, or an error value otherwise.
caption
Address of a pointer to a variable of IHTMLTableCaption type.

See also deleteCaption


IHTMLTable::createTFoot

HRESULT createTFoot(
    IDispatch **foot
);

Creates a TFoot for the table. If a table foot already exists, this returns a pointer to it. Otherwise, an empty foot is created and added to a table, and a pointer to the empty foot is returned.

  • Returns S_OK if successful, or an error value otherwise.
foot
Address of a pointer to an IDispatch interface.

See also deleteTFoot


IHTMLTable::createTHead

HRESULT createTHead(
    IDispatch **head
);

Creates a THead for the table. When a table head already exists, this will return a pointer to it. If a table head doesn't exist, an empty table head is created and the pointer to that is returned.

  • Returns S_OK if successful, or an error value otherwise.
head
Address of a pointer to an IDispatch interface.

See also deleteTHead


DataPageSize Property

*
  * Previous Topic: IHTMLTable::get_cols
  * Next Topic: IHTMLTable::get_frame

IHTMLTable::get_dataPageSize

HRESULT get_dataPageSize(
    long *p
);

Retrieves the number of records displayed in a databound repeated table.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a long integer that receives the number of records.

Use the nextPage and previousPage methods to display the subsequent and previous number of records in the table.

See also put_dataPageSize

Up Top of Page

IHTMLTable::put_dataPageSize

HRESULT put_dataPageSize(
    long v
);

Sets the number of records displayed in a databound repeated table.

  • Returns S_OK if successful, or an error value otherwise.
v
Long integer value specifying the number of records to display.

Use the nextPage and previousPage methods to display the subsequent and previous number of records in the table.

See also get_dataPageSize


IHTMLTable::deleteCaption

HRESULT deleteCaption(
    void
);

Deletes the caption from a table. If there are multiple captions in the table, this method deletes the first caption and all its contents from the table.

  • Returns S_OK if successful, or an error value otherwise.

See also createCaption


IHTMLTable::deleteRow

HRESULT deleteRow(
    long index
);

Removes the row indicated by the value of the zero-based index parameter from this table section.

  • Returns S_OK if successful, or an error value otherwise.
index
Long integer value specifying the index position in the table.

See also insertRow


IHTMLTable::deleteTFoot

HRESULT deleteTFoot(
    void
);

Deletes a TFoot from the table. If there is a foot, this removes it and all its contents from the table. If multiple TFoots are defined, the next one in source order is promoted as the TFoot of the table.

  • Returns S_OK if successful, or an error value otherwise.

See also createTFoot


IHTMLTable::deleteTHead

HRESULT deleteTHead(
    void
);

Deletes a THead from the table. If there is a head, this method removes it and all its contents from the table. If other THeads had been defined, the next one in source order is now promoted to the THead of the table.

  • Returns S_OK if successful, or an error value otherwise.

See also createTHead


Frame Property

*
  * Previous Topic: IHTMLTable::get_dataPageSize
  * Next Topic: IHTMLTable::get_height

IHTMLTable::get_frame

HRESULT get_frame(
    BSTR *p
);

Retrieves a description of the border frame around the table.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives one of these strings:
above | Displays a border on the top side of the border frame.
below | Displays a border on the bottom side of the table frame.
border | Displays a border on all sides of the table frame.
box | Displays a border on all sides of the table frame.
insides | Displays a border on the top and bottom sides of the table frame.
lhs | Displays a border on the left side of the table frame.
rhs | Displays a border on the right side of the table frame.
void | Removes all outside table borders.
vsides | Displays a border on the left and right sides of the table frame.

The default value for this property is "void".

See also put_frame

Up Top of Page

IHTMLTable::put_frame

HRESULT put_frame(
    BSTR v
);

Sets the appearance of the border frame around the table.

  • Returns S_OK if successful, or an error value otherwise.
v
String value specifying the appearance of the border frame. Can be one of these strings:
above | Displays a border on the top side of the border frame.
below | Displays a border on the bottom side of the table frame.
border | Displays a border on all sides of the table frame.
box | Displays a border on all sides of the table frame.
insides | Displays a border on the top and bottom sides of the table frame.
lhs | Displays a border on the left side of the table frame.
rhs | Displays a border on the right side of the table frame.
void | Removes all outside table borders.
vsides | Displays a border on the left and right sides of the table frame.

The default value for this property is "void".

See also get_frame


IHTMLTable::get_caption

HRESULT get_caption(
    IHTMLTableCaption **p
);

Returns an IHTMLTableCaption pointer to the first caption in the table. If the table does not contain a caption, NULL is returned.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a pointer to the IHTMLTableCaption interface of the element.


IHTMLTable::get_readyState

HRESULT get_readyState(
    BSTR *p
);

Returns the readyState enumeration string for the table's current ready state.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the enumeration.


IHTMLTable::get_rows

HRESULT get_rows(
    IHTMLElementCollection **p
);

Retrieves a collection of all rows in the table. This is a collection of all the TR elements defined in the THEAD, TBODY, and TFOOT elements of the table.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a pointer to the IHTMLElementCollection interface of the table.


IHTMLTable::get_tBodies

HRESULT get_tBodies(
    IHTMLElementCollection **p
);

Returns an IHTMLTableSection pointer to all the table bodies in this table. The length of this collection is the count of bodies returned.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a pointer to the IHTMLElementCollection interface of the table.


IHTMLTable::get_tFoot

HRESULT get_tFoot(
    IHTMLTableSection **p
);

Returns an IHTMLTableSection pointer to the foot section of a table. It returns NULL if there isn't one. If multiple table foots are listed in an HTML document, only the first one is treated as the foot of the table.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a pointer to the IHTMLTableSection interface of the table.

See also get_tHead


IHTMLTable::get_tHead

HRESULT get_tHead(
    IHTMLTableSection **p
);

Returns an IHTMLTableSection pointer to the head section of a table. It returns NULL if there isn't one. If multiple table heads are listed in an HTML document, only the first one is treated as the head of the table.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a pointer to the IHTMLTableSection interface of the table.

See also get_tFoot


Height Property

*
  * Previous Topic: IHTMLTable::get_frame
  * Next Topic: IHTMLTable::get_onreadystatechange

IHTMLTable::get_height

HRESULT get_height(
    VARIANT *p
);

Retrieves the height of the table, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the height.

If the value of the corresponding HTML attribute was set using a percentage, this property specifies the height, in pixels, represented by that percentage.

See also put_height

Up Top of Page

IHTMLTable::put_height

HRESULT put_height(
    VARIANT v
);

Sets the height of the table, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the value specifying the height.

If the value of the corresponding HTML attribute was set using a percentage, this property specifies the height in pixels represented by that percentage.

See also get_height


IHTMLTable::insertRow

HRESULT insertRow(
    long index,
    IDispatch **row
);

Inserts an empty row into the table section. The row is added at the position indicated by the zero-based index provided. For example, passing in 1 adds the row between 0 and 1, thus becoming the row with index 1. Passing in -1 or the size of the collection causes the row to be appended.

  • Returns S_OK if successful, or an error value otherwise.
index
Long integer value that contains the index of the table row position.
row
Address of a pointer to an IDispatch interface.

See also deleteRow


IHTMLTable::nextPage

HRESULT nextPage(
    void
);

Displays the next block of records in a repeated databound table. The number of records is determined by the dataPageSize property on the TABLE element.

  • Returns S_OK if successful, or an error value otherwise.

See also previousPage


Onreadystatechange Property

*
  * Previous Topic: IHTMLTable::get_height
  * Next Topic: IHTMLTable::get_readyState

IHTMLTable::get_onreadystatechange

HRESULT get_onreadystatechange(
    VARIANT *p
);

Retrieves the inline script associated with the onreadystatechange event for the table element. This script is executed when the onreadystatechange event is fired.

For more information on inline script, see Attaching an Event Handler in the Event Model documentation.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that contains the script.

See also put_onreadystatechange

Up Top of Page

IHTMLTable::put_onreadystatechange

HRESULT put_onreadystatechange(
    VARIANT v
);

Sets the inline script associated with the onreadystatechange event for the table element. This script is executed when the onreadystatechange event is fired.

For more information on inline script, see Attaching an Event Handler in the Event Model documentation.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to be set.

See also get_onreadystatechange


IHTMLTable::previousPage

HRESULT previousPage(void);

Displays the previous block of records in a repeated databound table. The number of records is determined by the dataPageSize property on the TABLE element.

  • Returns S_OK if successful, or an error value otherwise.

See also nextPage


IHTMLTable::refresh

HRESULT refresh(
    void
);

Refreshes the content of the table.

  • Returns S_OK if successful, or an error value otherwise.


Rules Property

*
  * Previous Topic: IHTMLTable::get_rows
  * Next Topic: IHTMLTable::get_tBodies

IHTMLTable::get_rules

HRESULT get_rules(
    BSTR *p
);

Retrieves which dividing lines are displayed (inner borders).

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives one of these values:
all | Displays a border on all rows and columns.
cols | Displays borders between all table columns.
groups | Displays horizontal borders between all table groups. Groups are specified by the THEAD, TBODY, TFOOT, and COLGROUP elements.
none | Removes all interior table borders.
rows | Displays horizontal borders between all table rows.

See also put_rules

Up Top of Page

IHTMLTable::put_rules

HRESULT put_rules(
    BSTR v
);

Specifies which dividing lines are displayed (inner borders).

  • Returns S_OK if successful, or an error value otherwise.
v
String value specifying the dividing rules. Can be one of these values:
all | Displays a border on all rows and columns.
cols | Displays borders between all table columns.
groups | Displays horizontal borders between all table groups. Groups are specified by the THEAD, TBODY, TFOOT, and COLGROUP elements.
none | Removes all interior table borders.
rows | Displays horizontal borders between all table rows.

See also get_rules


IHTMLTable

This interface is used to specify that the contained content is organized into a table with rows and columns.

Valid tags within a table include:

  • TR
  • CAPTION
  • THEAD
  • TBODY
  • TFOOT
  • COLGROUP
  • COL

This element is a block element.

IHTMLTable Methods
put_cols get_cols put_border
get_border put_frame get_frame
put_rules get_rules put_cellSpacing
get_cellSpacing put_cellPadding get_cellPadding
put_background get_background put_bgColor
get_bgColor put_borderColor get_borderColor
put_borderColorLight get_borderColorLight put_borderColorDark
get_borderColorDark put_align get_align
refresh get_rows put_width
get_width put_height get_height
put_dataPageSize get_dataPageSize nextPage
previousPage get_tHead get_tFoot
get_tBodies get_caption createTHead
deleteTHead createTFoot deleteTFoot
createCaption deleteCaption insertRow
deleteRow get_readyState put_onreadystatechange
get_onreadystatechange


Width Property

*
  * Previous Topic: IHTMLTable::get_tHead
  * Next Topic: IHTMLTable::insertRow

IHTMLTable::get_width

HRESULT get_width(
    VARIANT *p
);

Retrieves the width of the table, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the width.

This read-only property is an integer value. Although an HTML author can specify the width as a percentage, this property always specifies the width in pixels.

See also put_width

Up Top of Page

IHTMLTable::put_width

HRESULT put_width(
    VARIANT v
);

Sets the width of the table, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the width.

This property is an integer value. Although an HTML author can specify the width as a percentage, this property always specifies the width in pixels.

See also get_width


Align Property

*
  * Previous Topic: IHTMLTableCaption
  * Next Topic: IHTMLTableCaption::get_vAlign

IHTMLTableCaption::get_align

HRESULT get_align(
    BSTR *p
);

Retrieves the alignment of the caption.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives on of these values:
bottom | Aligns bottom center.
center | Centers the caption.
left | Left aligns.
right | Right aligns.
top | Aligns top-center.

See also put_align

Up Top of Page

IHTMLTableCaption::put_align

HRESULT put_align(
    BSTR v
);

Sets the alignment of the caption.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the alignment. Can be one of these values:
bottom | Aligns bottom center.
center | Centers the caption.
left | Left aligns.
right | Right aligns.
top | Aligns top-center.

See also get_align


IHTMLTableCaption

This interface specifies a caption for a table.

This element is a block element.

IHTMLTableCaption Methods


VAlign Property

*
  * Previous Topic: IHTMLTableCaption::get_align
  * Next Topic: IHTMLTableCaption::put_align

IHTMLTableCaption::get_vAlign

HRESULT get_vAlign(
    BSTR *p
);

Retrieves whether the caption appears at the top or bottom.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives one of these strings:
bottom | Places the caption at the bottom of the table.
top | Places the caption at the top of the table. This is the default value for this property.

See also put_vAlign

Up Top of Page

IHTMLTableCaption::put_vAlign

HRESULT put_vAlign(
    BSTR v
);

Sets whether the caption appears at the top or bottom.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the caption placement. Can be one of these strings:
bottom | Places the caption at the bottom of the table.
top | Places the caption at the top of the table. This is the default value for this property.

See also get_vAlign


Align Property

*
  * Previous Topic: IHTMLTableCell
  * Next Topic: IHTMLTableCell::get_background

IHTMLTableCell::get_align

HRESULT get_align(
    BSTR *p
);

Displays the element left flush, right flush, or centered relative to the display or table.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives one of these values:
center | Aligns to the center.
left | Aligns to the left edge.
right | Aligns to the right edge.

See also put_align

Up Top of Page

IHTMLTableCell::put_align

HRESULT put_align(
    BSTR v
);

Displays the element left flush, right flush, or centered relative to the display or table.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the string specifying the alignment. Can be one of these values:
center | Aligns to the center.
left | Aligns to the left edge.
right | Aligns to the right edge.

See also get_align


Background Property

*
  * Previous Topic: IHTMLTableCell::get_align
  * Next Topic: IHTMLTableCell::get_bgColor

IHTMLTableCell::get_background

HRESULT get_background(
    BSTR *p
);

Retrieves a background picture for the cell. The picture is tiled behind the text and graphics in the table cell.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the URL of the background picture.

See also put_background

Up Top of Page

IHTMLTableCell::put_background

HRESULT put_background(
    BSTR v
);

Sets a background picture for the cell. The picture is tiled behind the text and graphics in the table cell.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the string specifying the URL of the background picture.

See also get_background


BgColor Property

*
  * Previous Topic: IHTMLTableCell::get_background
  * Next Topic: IHTMLTableCell::get_borderColor

IHTMLTableCell::get_bgColor

HRESULT get_bgColor(
    VARIANT *p
);

Retrieves the background color behind the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the color. The color can be one of the color names or values given in the Color Table reference documentation.

See also put_bgColor

Up Top of Page

IHTMLTableCell::put_bgColor

HRESULT put_bgColor(
    VARIANT v
);

Sets the background color behind the element.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the string or value specifying the color. The color can be one of the color names or values given in the Color Table reference documentation.

See also get_bgColor


BorderColor Property

*
  * Previous Topic: IHTMLTableCell::get_bgColor
  * Next Topic: IHTMLTableCell::get_borderColorDark

IHTMLTableCell::get_borderColor

HRESULT get_borderColor(
    VARIANT *p
);

Retrieves the border color and must be used with the border property.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the color. The color can be one of the color names or values given in the Color Table reference documentation.

See also put_borderColor

Up Top of Page

IHTMLTableCell::put_borderColor

HRESULT put_borderColor(
    VARIANT v
);

Sets the border color and must be used with the border property.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the string or value specifying the color. The color can be one of the color names or values given in the Color Table reference documentation.

See also get_borderColor


BorderColorDark Property

*
  * Previous Topic: IHTMLTableCell::get_borderColor
  * Next Topic: IHTMLTableCell::get_borderColorLight

IHTMLTableCell::get_borderColorDark

HRESULT get_borderColorDark(
    VARIANT *p
);

Retrieves independent border color control over one of the two colors used to draw a 3-D border, opposite of borderColorLight, and must be used with the border property.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the color. The color can be one of the color names or values given in the Color Table reference documentation.

See also put_borderColorDark

Up Top of Page

IHTMLTableCell::put_borderColorDark

HRESULT put_borderColorDark(
    VARIANT v
);

Sets independent border color control over one of the two colors used to draw a 3-D border, opposite of borderColorLight, and must be used with the border property.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the string or value specifying the color for borderColorDark. The color can be one of the color names or values given in the Color Table reference documentation.

See also get_borderColorDark


BorderColorLight Property

*
  * Previous Topic: IHTMLTableCell::get_borderColorDark
  * Next Topic: IHTMLTableCell::get_cellIndex

IHTMLTableCell::get_borderColorLight

HRESULT get_borderColorLight(
    VARIANT *p
);

Retrieves independent border color control over one of the two colors used to draw a 3-D border, opposite of borderColorDark, and must be used with the border property.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the color. The color can be one of the color names or values given in the Color Table reference documentation.

See also put_borderColorLight

Up Top of Page

IHTMLTableCell::put_borderColorLight

HRESULT put_borderColorLight(
    VARIANT v
);

Sets independent border color control over one of the two colors used to draw a 3-D border, opposite of borderColorDark, and must be used with the border property.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the string or value specifying the color for borderColorLight. The color can be one of the color names or values given in the Color Table reference documentation.

See also get_borderColorLight


ColSpan Property

*
  * Previous Topic: IHTMLTableCell::get_cellIndex
  * Next Topic: IHTMLTableCell::get_height

IHTMLTableCell::get_colSpan

HRESULT get_colSpan(
    long *p
);

Retrieves how many columns in the TABLE this cell spans.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a long integer receiving the number of columns spanned.

See also put_colSpan

Up Top of Page

IHTMLTableCell::put_colSpan

HRESULT put_colSpan(
    long v
);

Sets how many columns in the TABLE this cell should span.

  • Returns S_OK if successful, or an error value otherwise.
v
Long integer value specifying the number of columns to span.

See also get_colSpan


IHTMLTableCell::get_cellIndex

HRESULT get_cellIndex(
    long *p
);

Retrieves the cell index value.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a long integer that receives the cell index value.


Height Property

*
  * Previous Topic: IHTMLTableCell::get_colSpan
  * Next Topic: IHTMLTableCell::get_noWrap

IHTMLTableCell::get_height

HRESULT get_height(
    VARIANT *p
);

Retrieves the calculated height of the element, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the height.

If the value of the corresponding HTML attribute was set using a percentage, this property specifies the height in pixels represented by that percentage.

See also put_height

Up Top of Page

IHTMLTableCell::put_height

HRESULT put_height(
    VARIANT v
);

Sets the calculated height of the element, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the value specifying the height.

If the value of the corresponding HTML attribute was set using a percentage, this property specifies the height in pixels represented by that percentage.

See also get_height


NoWrap Property

*
  * Previous Topic: IHTMLTableCell::get_height
  * Next Topic: IHTMLTableCell::get_rowSpan

IHTMLTableCell::get_noWrap

HRESULT get_noWrap(
    VARIANT_BOOL *p
);

Determines whether automatic word wrapping is enabled or disabled for the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives TRUE if automatic word-wrapping is enabled for the element, or FALSE otherwise. The default value for this property is FALSE.

See also put_noWrap

Up Top of Page

IHTMLTableCell::put_noWrap

HRESULT put_noWrap(
    VARIANT_BOOL v
);

Enables or disables automatic word wrapping for the element.

  • Returns S_OK if successful, or an error value otherwise.
v
Word-wrap flag. If TRUE, the browser performs automatic word wrapping on the element. If FALSE, it doesn't. The default value for this property is FALSE.

See also get_noWrap


RowSpan Property

*
  * Previous Topic: IHTMLTableCell::get_noWrap
  * Next Topic: IHTMLTableCell::get_vAlign

IHTMLTableCell::get_rowSpan

HRESULT get_rowSpan(
    long *p
);

Retrieves how many rows in a TABLE this cell spans.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a long integer receiving the number of rows spanned.

See also put_rowSpan

Up Top of Page

IHTMLTableCell::put_rowSpan

HRESULT put_rowSpan(
    long v
);

Sets how many rows in a TABLE this cell should span.

  • Returns S_OK if successful, or an error value otherwise.
v
Long integer value specifying the number of rows to span.

See also get_rowSpan


IHTMLTableCell

This interface specifies a cell in a table.

This element is a block element.

IHTMLTableCell Methods
put_rowSpan get_rowSpan put_colSpan
get_colSpan put_align get_align
put_vAlign get_vAlign put_bgColor
get_bgColor put_noWrap get_noWrap
put_background get_background put_borderColor
get_borderColor put_borderColorLight get_borderColorLight
put_borderColorDark get_borderColorDark put_width
get_width put_height get_height
get_cellIndex


VAlign Property

*
  * Previous Topic: IHTMLTableCell::get_rowSpan
  * Next Topic: IHTMLTableCell::get_width

IHTMLTableCell::get_vAlign

HRESULT get_vAlign(
    BSTR *p
);

Retrieves how the text and other content of an element is vertically aligned within the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives one of these strings:
baseline | Aligns the baseline of the first line of text with the baselines in adjacent elements.
bottom | Aligns the text at the bottom of the element.
middle | Aligns the text in the middle of the element. This is the default value for this property.
top | Aligns the text at the top of the element.

See also put_vAlign

Up Top of Page

IHTMLTableCell::put_vAlign

HRESULT put_vAlign(
    BSTR v
);

Sets how the text and other content of an element is vertically aligned within the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the vertical alignment. Can be one of these strings:
baseline | Aligns the baseline of the first line of text with the baselines in adjacent elements.
bottom | Aligns the text at the bottom of the element.
middle | Aligns the text in the middle of the element. This is the default value for this property.
top | Aligns the text at the top of the element.

See also get_vAlign


Width Property

*
  * Previous Topic: IHTMLTableCell::get_vAlign
  * Next Topic: IHTMLTableCell::put_align

IHTMLTableCell::get_width

HRESULT get_width(
    VARIANT *p
);

Retrieves the calculated width of the element, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the width.

This property is an integer value. Although an HTML author can specify the width as a percentage, this property always specifies the width in pixels.

See also put_width

Up Top of Page

IHTMLTableCell::put_width

HRESULT put_width(
    VARIANT v
);

Sets the calculated width of the element, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the value specifying the width.

This property is an integer value. Although an HTML author can specify the width as a percentage, this property always specifies the width in pixels.

See also get_width


Align Property

*
  * Previous Topic: IHTMLTableCol
  * Next Topic: IHTMLTableCol::get_vAlign

IHTMLTableCol::get_align

HRESULT get_align(
    BSTR *p
);

Displays the element left flush, right flush, or centered relative to the display or table.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives one of these values:
center | Aligns to the center.
left | Aligns to the left edge.
right | Aligns to the right edge.

See also put_align

Up Top of Page

IHTMLTableCol::put_align

HRESULT put_align(
    BSTR v
);

Displays the element left flush, right flush, or centered relative to the display or table.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the alignment. Can be one of these values:
center | Aligns to the center.
left | Aligns to the left edge.
right | Aligns to the right edge.

See also get_align


Span Property

*
  * Previous Topic: IHTMLTableCol::get_vAlign
  * Next Topic: IHTMLTableCol::get_width

IHTMLTableCol::get_span

HRESULT get_span(
    long *p
);

Retrieves the number of columns in the group.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a long integer that receives the number of columns.

This attribute should be ignored if the COLGROUP element contains one or more COL elements. The purpose of this attribute is to provide a more convenient way of grouping columns without the need to specify COL elements.

See also put_span

Up Top of Page

IHTMLTableCol::put_span

HRESULT put_span(
    long v
);

Sets how many columns are in the group.

  • Returns S_OK if successful, or an error value otherwise.
v
Number of columns in the group.

This attribute should be ignored if the COLGROUP element contains one or more COL elements. The purpose of this attribute is to provide a more convenient way of grouping columns without the need to specify COL elements.

See also get_span


IHTMLTableCol

This interface is used to specify column-based defaults for the table properties.

This element is a block element.

IHTMLTableCol Methods
put_span get_span put_width
get_width put_align get_align
put_vAlign get_vAlign

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


VAlign Property

*
  * Previous Topic: IHTMLTableCol::get_align
  * Next Topic: IHTMLTableCol::get_span

IHTMLTableCol::get_vAlign

HRESULT get_vAlign(
    BSTR *p
);

Retrieves how the text and other content of an element is vertically aligned within the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives one of these strings:
baseline | Aligns the baseline of the first line of text with the baselines in adjacent elements.
bottom | Aligns the text at the bottom of the element.
middle | Aligns the text in the middle of the element. This is the default value for this property.
top | Aligns the text at the top of the element.

See also put_vAlign

Up Top of Page

IHTMLTableCol::put_vAlign

HRESULT put_vAlign(
    BSTR v
);

Sets how the text and other content of an element is vertically aligned within the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the vertical alignment. Can be one of these strings:
baseline | Aligns the baseline of the first line of text with the baselines in adjacent elements.
bottom | Aligns the text at the bottom of the element.
middle | Aligns the text in the middle of the element. This is the default value for this property.
top | Aligns the text at the top of the element.

See also get_vAlign


Width Property

*
  * Previous Topic: IHTMLTableCol::get_span
  * Next Topic: IHTMLTableCol::put_align

IHTMLTableCol::get_width

HRESULT get_width(
    VARIANT *p
);

Retrieves the calculated width of the element, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the width.

This property is an integer value. Although an HTML author can specify the width as a percentage, this property always specifies the width in pixels.

See also put_width

Up Top of Page

IHTMLTableCol::put_width

HRESULT put_width(
    VARIANT v
);

Sets the calculated width of the element, in pixels.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the width.

This property is an integer value. Although an HTML author can specify the width as a percentage, this property always specifies the width in pixels.

See also get_width


Align Property

*
  * Previous Topic: IHTMLTableRow::deleteCell
  * Next Topic: IHTMLTableRow::get_bgColor

IHTMLTableRow::get_align

HRESULT get_align(
    BSTR *p
);

Displays the element left flush, right flush, or centered relative to the display or table.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives one of these values:
center | Aligns to the center.
left | Aligns to the left edge.
right | Aligns to the right edge.

See also put_align

Up Top of Page

IHTMLTableRow::put_align

HRESULT put_align(
    BSTR v
);

Displays the element left flush, right flush, or centered relative to the display or table.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the alignment. Can be one of these values:
center | Aligns to the center.
left | Aligns to the left edge.
right | Aligns to the right edge.

See also get_align


BgColor Property

*
  * Previous Topic: IHTMLTableRow::get_align
  * Next Topic: IHTMLTableRow::get_borderColor

IHTMLTableRow::get_bgColor

HRESULT get_bgColor(
    VARIANT *p
);

Retrieves the background color behind the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the color. The color can be one of the color names or values given in the Color Table reference documentation.

See also put_bgColor

Up Top of Page

IHTMLTableRow::put_bgColor

HRESULT put_bgColor(
    VARIANT v
);

Sets the background color behind the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the color. The color can be one of the color names or values given in the Color Table reference documentation.

See also get_bgColor


BorderColor Property

*
  * Previous Topic: IHTMLTableRow::get_bgColor
  * Next Topic: IHTMLTableRow::get_borderColorDark

IHTMLTableRow::get_borderColor

HRESULT get_borderColor(
    VARIANT *p
);

Retrieves the border color and must be used with the border property.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the color. The color can be one of the color names or values given in the Color Table reference documentation.

See also put_borderColor

Up Top of Page

IHTMLTableRow::put_borderColor

HRESULT put_borderColor(
    VARIANT v
);

Sets the border color and must be used with the border property.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the color. The color can be one of the color names or values given in the Color Table reference documentation.

See also get_borderColor


BorderColorDark Property

*
  * Previous Topic: IHTMLTableRow::get_borderColor
  * Next Topic: IHTMLTableRow::get_borderColorLight

IHTMLTableRow::get_borderColorDark

HRESULT get_borderColorDark(
    VARIANT *p
);

Retrieves independent border color control over one of the two colors used to draw a 3-D border, opposite of borderColorLight, and must be used with the border property.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the color. The color can be one of the color names or values given in the Color Table reference documentation.

See also put_borderColorDark

Up Top of Page

IHTMLTableRow::put_borderColorDark

HRESULT put_borderColorDark(
    VARIANT v
);

Sets independent border color control over one of the two colors used to draw a 3-D border, opposite of borderColorLight, and must be used with the border property.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure containing the string specifying the color value. The color can be one of the color names or values given in the Color Table reference documentation.

See also get_borderColorDark


BorderColorLight Property

*
  * Previous Topic: IHTMLTableRow::get_borderColorDark
  * Next Topic: IHTMLTableRow::get_cells

IHTMLTableRow::get_borderColorLight

HRESULT get_borderColorLight(
    VARIANT *p
);

Retrieves independent border color control over one of the two colors used to draw a 3-D border, opposite of borderColorDark, and must be used with the border property.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the color. The color can be one of the color names or values given in the Color Table reference documentation.

See also put_borderColorLight

Up Top of Page

IHTMLTableRow::put_borderColorLight

HRESULT put_borderColorLight(
    VARIANT v
);

Sets independent border color control over one of the two colors used to draw a 3-D border, opposite of borderColorDark, and must be used with the border property.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure containing the string specifying the color value. The color can be one of the color names or values given in the Color Table reference documentation.

See also get_borderColorLight


IHTMLTableRow::deleteCell

HRESULT deleteCell(
    long index
);

Removes a cell and all its contents from the row.

  • Returns S_OK if successful, or an error value otherwise.
index
Long integer value specifying the row position index to be deleted.

See also insertCell


IHTMLTableRow::get_cells

HRESULT get_cells(
    IHTMLElementCollection **p
);

Retrieves a collection of all cells in the row of a table. This is a collection of TH and TD elements.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives an interface pointer to the collection.


IHTMLTableRow::get_rowIndex

HRESULT get_rowIndex(
   long *p
);

Returns the zero-based position index of this row relative to the table.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a long integer that receives the position index value.


IHTMLTableRow::get_sectionRowIndex

HRESULT get_sectionRowIndex(
    long *p
);

Returns the zero-based index of this row with respect to the section that this is in (that is, the rowIndex of the first row in this section).

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a long integer that receives the section row index value.


IHTMLTableRow::insertCell

HRESULT insertCell(
    long index
);

Inserts an empty cell into this row. The cell is inserted at the zero-based index passed into the table. If -1, or the size of the cells collection for this row is passed in, the cell is appended and a pointer to the cell created is returned.

  • Returns S_OK if successful, or an error value otherwise.
index
Long integer specifying the index value for the table cell.

See also deleteCell


IHTMLTableRow

This interface specifies a row in a table.

Within a row, the following tags are valid:

  • TD
  • TH

This element is a block element.

IHTMLTableRow Methods
put_align get_align put_vAlign
get_vAlign put_bgColor get_bgColor
put_borderColor get_borderColor put_borderColorLight
get_borderColorLight put_borderColorDark get_borderColorDark
get_rowIndex get_sectionRowIndex get_cells
insertCell deleteCell

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


VAlign Property

*
  * Previous Topic: IHTMLTableRow::get_sectionRowIndex
  * Next Topic: IHTMLTableRow::insertCell

IHTMLTableRow::get_vAlign

HRESULT get_vAlign(
    BSTR *p
);

Retrieves how the text and other content of an element is vertically aligned within the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives one of these strings:
baseline | Aligns the baseline of the first line of text with the baselines in adjacent elements.
bottom | Aligns the text at the bottom of the element.
middle | Aligns the text in the middle of the element. This is the default value for this property.
top | Aligns the text at the top of the element.

See also get_vAlign

Up Top of Page

IHTMLTableRow::put_vAlign

HRESULT put_vAlign(
    BSTR v
);

Sets how the text and other content of an element is vertically aligned within the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the vertical alignment. Can be one of these strings:
baseline | Aligns the baseline of the first line of text with the baselines in adjacent elements.
bottom | Aligns the text at the bottom of the element.
middle | Aligns the text in the middle of the element. This is the default value for this property.
top | Aligns the text at the top of the element.

See also get_vAlign


Align Property

*
  * Previous Topic: IHTMLTableSection::get_rows
  * Next Topic: IHTMLTableSection::get_vAlign

IHTMLTableSection::get_align

HRESULT get_align(
   BSTR *p
);

Displays the element left flush, right flush, or centered relative to the display or table.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives one of these values:
center | Aligns to the center.
left | Aligns to the left edge.
right | Aligns to the right edge.

See also put_align

Up Top of Page

IHTMLTableSection::put_align

HRESULT put_align(
    BSTR v
);

Displays the element left flush, right flush, or centered relative to the display or table.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the alignment. Can be one of these values:
center | Aligns to the center.
left | Aligns to the left edge.
right | Aligns to the right edge.

See also get_align


BgColor Property

*
  * Previous Topic: IHTMLTableSection::deleteRow
  * Next Topic: IHTMLTableSection::get_rows

IHTMLTableSection::get_bgColor

HRESULT get_bgColor(
    VARIANT *p
);

Retrieves the background color behind the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that receives the color. The color can be one of the color names or values given in the Color Table reference documentation.

See also put_bgColor

Up Top of Page

IHTMLTableSection::put_bgColor

HRESULT put_bgColor(
    VARIANT v
);

Sets the background color behind the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the color. The color can be one of the color names or values given in the Color Table reference documentation.

See also get_bgColor


IHTMLTableSection::deleteRow

HRESULT deleteRow(
    long index
);

Removes the row indicated by the value of the index parameter from this table section.

  • Returns S_OK if successful, or an error value otherwise.
index
Long integer value that specifies the position of the row.

See also insertRow


IHTMLTableSection::get_rows

HRESULT get_rows(
    IHTMLElementCollection **p
);

Returns a zero-based collection of the rows in this section of the table.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a pointer to the IHTMLElementCollection interface of the table.


IHTMLTableSection::insertRow

HRESULT insertRow(
    long index,
    IDispatch **row
);

Inserts an empty row into this table section. The row is added at the position indicated by the index provided. For example, passing in 1 adds the row between 0 and 1, thus becoming the row with index 1. Passing in -1 or the size of the collection causes the row to be appended.

  • Returns S_OK if successful, or an error value otherwise.
index
Long integer that contains the value specifying the position in the table.
row
Address of a pointer to an IDispatch interface.

See also deleteRow


IHTMLTableSection

This interface is used to designate rows as the body of the table.

This element is exposed for all tables, even if the table did not explicitly define a TBODY element.

This element is a block element.

IHTMLTableSection Methods
put_align get_align put_vAlign
get_vAlign put_bgColor get_bgColor
get_rows insertRow
deleteRow


VAlign Property

*
  * Previous Topic: IHTMLTableSection::get_align
  * Next Topic: IHTMLTableSection::insertRow

IHTMLTableSection::get_vAlign

HRESULT get_vAlign(
    BSTR *p
);

Retrieves how the text and other content of an element is vertically aligned within the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives one of these strings:
baseline | Aligns the baseline of the first line of text with the baselines in adjacent elements.
bottom | Aligns the text at the bottom of the element.
middle | Aligns the text in the middle of the element. This is the default value for this property.
top | Aligns the text at the top of the element.

See also put_vAlign

Up Top of Page

IHTMLTableSection::put_vAlign

HRESULT put_vAlign(
    BSTR v
);

Sets how the text and other content of an element is vertically aligned within the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the vertical alignment. Can be one of these strings:
baseline | Aligns the baseline of the first line of text with the baselines in adjacent elements.
bottom | Aligns the text at the bottom of the element.
middle | Aligns the text in the middle of the element. This is the default value for this property.
top | Aligns the text at the top of the element.

See also get_vAlign


Cols Property

*
  * Previous Topic: IHTMLTextAreaElement::createTextRange
  * Next Topic: IHTMLTextAreaElement::get_defaultValue

IHTMLTextAreaElement::get_cols

HRESULT get_cols(
    long *p
);

Retrieves the width, in columns (characters), of a TEXTAREA control.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the number of columns.

See also put_cols

Up Top of Page

IHTMLTextAreaElement::put_cols

HRESULT put_cols(
    long v
);

Sets the width, in columns (characters), of the TEXTAREA control.

  • Returns S_OK if successful, or an error value otherwise.
v
Long integer that receives the number of columns.

See also get_cols


IHTMLTextAreaElement::createTextRange

HRESULT createTextRange(
    IHTMLTxtRange **range
);

Creates a text range object for the element. You use a text range to examine and modify the text within the element.

  • Returns S_OK if successful, or an error value otherwise.
range
Address of a variable that receives an interface pointer to the text range.

See also IHTMLTxtRange


DefaultValue Property

*
  * Previous Topic: IHTMLTextAreaElement::get_cols
  * Next Topic: IHTMLTextAreaElement::get_disabled

IHTMLTextAreaElement::get_defaultValue

HRESULT get_defaultValue(
    BSTR *p
);

Retrieves the default value of the TEXTAREA element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the default value.

This value can be changed programmatically but has no effect on the appearance nor on how forms are submitted.

See also put_defaultValue

Up Top of Page

IHTMLTextAreaElement::put_defaultValue

HRESULT put_defaultValue(
    BSTR v
);

Sets the default value of the TEXTAREA element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the default value.

This value can be changed programmatically but has no effect on the appearance nor on how forms are submitted.

See also get_defaultValue


Disabled Property

*
  * Previous Topic: IHTMLTextAreaElement::get_defaultValue
  * Next Topic: IHTMLTextAreaElement::get_form

IHTMLTextAreaElement::get_disabled

HRESULT get_disabled(
    VARIANT_BOOL *p
);

Determines whether the control is enabled or disabled.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives TRUE if the control is disabled, or FALSE otherwise.

The default value for this property is FALSE.

See also put_disabled

Up Top of Page

IHTMLTextAreaElement::put_disabled

HRESULT put_disabled(
    VARIANT_BOOL v
);

Enables or disables the control. A disabled control appears dimmed and does not respond to user input.

  • Returns S_OK if successful, or an error value otherwise.
v
Boolean value specifying whether to disable the control. If TRUE, the control is disabled; otherwise, it is enabled.

The default value for this property is FALSE.

See also get_disabled


IHTMLTextAreaElement::get_form

HRESULT get_form(
    IHTMLFormElement **p
);

Retrieves a reference to the form the element is embedded on.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives an interface pointer to the form element. This parameter receives NULL if the element is not on a form.

See also IHTMLFormElement


IHTMLTextAreaElement::get_type

HRESULT get_type(
    BSTR *p
);

Retrieves the type of intrinsic control represented by the given element object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the type. The possible values depend on the element, as listed in the following table.

Element | Possible value | Description
INPUT | checkbox | Used for simple Boolean attributes or for attributes that can take multiple values at the same time. It is represented by a number of check box fields, each of which has the same name. Each selected check box generates a separate name/value pair in the submitted data, even if this results in duplicate names. The default value for check boxes is on.
file | A file upload element.
hidden | No field is presented to the user, but the content of the field is sent with the submitted form. This value can be used to transmit state information about client/server interaction.
image | An image field that you can click, causing the form to be immediately submitted. The coordinates of the selected point are measured in pixel units from the upper-left corner of the image, and are returned (along with the other contents of the form) in two name/value pairs. The x-coordinate is submitted under the name of the field with .x appended, and the y-coordinate is submitted under the name of the field with .y appended. Any value property is ignored. The image itself is specified by the SRC attribute, exactly as for the Image element.
password | Same as the TEXT attribute, except that text is not displayed as the user enters it.
radio | Used for attributes that accept a single value from a set of alternatives. Each radio-button field in the group should be given the same name. Only the selected radio button in the group generates a name/value pair in the submitted data. Radio buttons require an explicit value property.
reset | reset is a button that when clicked resets the form's fields to their specified initial values. The label to be displayed on the button can be specified just as for the submit button.
submit | submit is a button that when clicked submits the form. You can use the value attribute to provide a non-editable label to be displayed on the button. The default label is application-specific. If a submit button is clicked to submit the form, and that button has a name attribute specified, that button contributes a name/value pair to the submitted data. Otherwise, a submit button makes no contribution to the submitted data.
text | Used for a single-line text-entry field. Use in conjunction with the size and maxLength properties.
SELECT | select-multiple | Specifies a multiple-select list box.
select-one | Specifies a single-select list box.
TEXTAREA | textarea | Used for multiple-line text-entry fields. Use in conjunction with the size and maxLength properties.


Name Property

*
  * Previous Topic: IHTMLTextAreaElement::get_form
  * Next Topic: IHTMLTextAreaElement::get_onchange

IHTMLTextAreaElement::get_name

HRESULT get_name(
    BSTR *p
);

Retrieves the name of the TEXTAREA element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the name.

The name is used to bind the value of the control when submitting a form. The name is not the value that is displayed in the entry field of the element. Submitting the form submits the internally stored value, not the one displayed.

JScript allows the name to be changed at run time. This does not change the name in the programming model, in the collection of elements, but does change the name used for submitting elements.

See also put_name

Up Top of Page

IHTMLTextAreaElement::put_name

HRESULT put_name(
    BSTR v
);

Sets the name of the TEXTAREA element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the name.

The name is used to bind the value of the element when submitting a form. The name is not the value that is displayed in the entry field of the element. Submitting the form submits the internally stored value, not the one displayed.

JScript allows the name to be changed at run time. This does not change the name in the programming model, in the collection of elements, but does change the name used for submitting elements.

See also get_name


Onchange Property

*
  * Previous Topic: IHTMLTextAreaElement::get_name
  * Next Topic: IHTMLTextAreaElement::get_onselect

IHTMLTextAreaElement::get_onchange

HRESULT get_onchange(
    VARIANT *p
);

Retrieves the inline script associated with the onchange event for the TEXTAREA element. The onchange event occurs when the contents of the object have changed.

For more information on inline script, see Attaching an Event Handler in the Event Model documentation.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that contains the script.

See also put_onchange

Up Top of Page

IHTMLTextAreaElement::put_onchange

HRESULT put_onchange(
    VARIANT v
);

Sets the inline script associated with the onchange event for the TEXTAREA element. The onchange event occurs when the contents of the object have changed.

For more information on inline script, see Attaching an Event Handler in the Event Model documentation.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to be set.

See also get_onchange


Onselect Property

*
  * Previous Topic: IHTMLTextAreaElement::get_onchange
  * Next Topic: IHTMLTextAreaElement::get_readOnly

IHTMLTextAreaElement::get_onselect

HRESULT get_onselect(
    VARIANT *p
);

Retrieves the inline script associated with the onselect event for the TEXTAREA element. The onselect event fires at the beginning of a user-initiated select. This event can be canceled, and it participates in the bubbling model.

For more information on inline script, see Attaching an Event Handler in the Event Model documentation.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that contains the script.

See also put_onselect

Up Top of Page

IHTMLTextAreaElement::put_onselect

HRESULT put_onselect(
    VARIANT v
);

Sets the inline script associated with the onselect event for the TEXTAREA element. The onselect event fires at the beginning of a user-initiated select. This event can be canceled, and it participates in the bubbling model.

For more information on inline script, see Attaching an Event Handler in the Event Model documentation.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to be set.

See also get_onselect


ReadOnly Property

*
  * Previous Topic: IHTMLTextAreaElement::get_onselect
  * Next Topic: IHTMLTextAreaElement::get_rows

IHTMLTextAreaElement::get_readOnly

HRESULT get_readOnly(
    VARIANT_BOOL *p
);

Determines whether the element's contents are read-only, meaning that the user cannot enter or edit text in the control.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives TRUE if the element is read-only, or FALSE if not.

This is different than disabled. Read-only still allows the element to receive the focus, while disabled does not allow the element to receive the focus.

The default value for this property is FALSE.

See also put_readOnly

Up Top of Page

IHTMLTextAreaElement::put_readOnly

HRESULT put_readOnly(
    VARIANT_BOOL v
);

Specifies whether the element's contents are read-only, meaning that the user cannot enter or edit text in the control.

  • Returns S_OK if successful, or an error value otherwise.
v
Read-only flag. TRUE sets the element to read-only; FALSE does not.

This is different than disabled. Read-only still allows the element to receive the focus, while disabled does not allow the element to receive the focus.

The default value for this property is FALSE.

See also get_readOnly


Rows Property

*
  * Previous Topic: IHTMLTextAreaElement::get_readOnly
  * Next Topic: IHTMLTextAreaElement::get_status

IHTMLTextAreaElement::get_rows

HRESULT get_rows(
    long *p
);

Retrieves the height, in rows, of the TEXTAREA control.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the number of rows.

See also put_rows

Up Top of Page

IHTMLTextAreaElement::put_rows

HRESULT put_rows(
    long v
);

Sets the height, in rows, of the TEXTAREA control.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the number of rows.

See also get_rows


IHTMLTextAreaElement::select

HRESULT select(
    void
);

Highlights the input area of a form element.

  • Returns S_OK if successful, or an error value otherwise.

You can use the select method with the focus method to highlight a field and position the cursor for a user response.


Status Property

*
  * Previous Topic: IHTMLTextAreaElement::get_rows
  * Next Topic: IHTMLTextAreaElement::get_type

IHTMLTextAreaElement::get_status

HRESULT get_status(
    VARIANT *p
);

Retrieves the status of the TEXTAREA element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the status. It can be TRUE, FALSE, or NULL.

See also put_status

Up Top of Page

IHTMLTextAreaElement::put_status

HRESULT put_status(
    VARIANT v
);

Sets the status of the TEXTAREA element.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the status. Can be TRUE, FALSE, or NULL.

See also get_status


IHTMLTextAreaElement

This interface specifies a multiline text input control.

The default font is fixed pitch.

IHTMLTextAreaElement Methods
get_type put_value get_value
put_name get_name put_status
get_status put_disabled get_disabled
get_form put_defaultValue get_defaultValue
select put_onchange get_onchange
put_onselect get_onselect put_readOnly
get_readOnly put_rows get_rows
put_cols get_cols put_wrap
get_wrap createTextRange

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


Value Property

*
  * Previous Topic: IHTMLTextAreaElement::get_type
  * Next Topic: IHTMLTextAreaElement::get_wrap

IHTMLTextAreaElement::get_value

HRESULT get_value(
    BSTR *p
);

Retrieves the current text from the entry field of the TEXTAREA element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the text.

See also put_value

Up Top of Page

IHTMLTextAreaElement::put_value

HRESULT put_value(
    BSTR v
);

Sets the text entry field of the TEXTAREA element, replacing any existing text.

  • Returns S_OK if successful, or an error value otherwise.
v
String to place in the entry field of the element.

See also get_value


Wrap Property

*
  * Previous Topic: IHTMLTextAreaElement::get_value
  * Next Topic: IHTMLTextAreaElement::put_cols

IHTMLTextAreaElement::get_wrap

HRESULT get_wrap(
    BSTR *p
);

Retrieves how word-wrapping is handled in the element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives one of these strings:
off | Word-wrapping is disabled. The lines appear exactly as the user types them. This is the default value for this property.
physical | The text is displayed and submitted word-wrapped.
virtual | The text is displayed word-wrapped but is submitted as typed.

See also put_wrap

Up Top of Page

IHTMLTextAreaElement::put_wrap

HRESULT put_wrap(
    BSTR v
);

Specifies how to handle word-wrapping in the element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying one of these values:
off | Word-wrapping is disabled. The lines appear exactly as the user types them. This is the default value for this property.
physical | The text is displayed and submitted word-wrapped.
virtual | The text is displayed word-wrapped but is submitted as typed.

See also get_wrap


IHTMLTextContainer::createControlRange

HRESULT createControlRange(
    IDispatch **range
);

Creates a selection range object for control-based selection rather than text-based selection. If there are currently controls selected in the text container, the control range is initialized with them; otherwise, it is created empty and controls need to be explicitly added to it. This is opposite of the text range, which defaults to the whole text container if there is no selection. This returns an IHTMLControlRange object.

  • Returns S_OK if successful, or an error value otherwise.
range
Address of a pointer to a variable of IDispatch type.


IHTMLTextContainer::get_scrollHeight

HRESULT get_scrollHeight(
    long *p
);

Retrieves the element's scrolling height, in pixels. This is the distance between the top and bottom edges of the element's visible content. The physical height of the content, including nonvisible content, can be obtained with the IHTMLElement::get_offsetHeight property.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the scroll height.

This property is read-only on HTML documents, and read-write on fixed regions.

See also get_scrollWidth


IHTMLTextContainer::get_scrollWidth

HRESULT get_scrollWidth(
    long *p
);

Retrieves the element's scrolling width, in pixels. This is the distance between the left and right edges of the element's visible content.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the scroll width.

This property is read-only on HTML documents, and read-write on fixed regions.

See also get_scrollHeight


Onscroll Property

*
  * Previous Topic: IHTMLTextContainer::createControlRange
  * Next Topic: IHTMLTextContainer::get_scrollHeight

IHTMLTextContainer::get_onscroll

HRESULT get_onscroll(
    VARIANT *p
);

Occurs when the scroll box is repositioned. The default action of this event is to scroll.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that contains the script.

See also put_onscroll

Up Top of Page

IHTMLTextContainer::put_onscroll

HRESULT put_onscroll(
    VARIANT v
);

Occurs when the scroll box is repositioned. The default action of this event is to scroll.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to be set.

See also get_onscroll


ScrollLeft Property

*
  * Previous Topic: IHTMLTextContainer::get_scrollHeight
  * Next Topic: IHTMLTextContainer::get_scrollTop

IHTMLTextContainer::get_scrollLeft

HRESULT get_scrollLeft(
    long *p
);

Retrieves the distance, in pixels, between the left edge of the element and the leftmost portion of the element that is currently visible in the window. This is equal to the horizontal distance that the content of the element has been scrolled.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the scroll-left distance.

This read-write property is always a nonnegative integer. Although it can be set to any positive or negative value, the property is set to zero if the assigned value is less than zero, and is set to the value of scrollWidth if the assigned value is greater than this. The default value is zero.

This property is always zero for elements that do not support scroll bars. For these elements, setting the property has no effect.

See also put_scrollLeft

Up Top of Page

IHTMLTextContainer::put_scrollLeft

HRESULT put_scrollLeft(
    long v
);

Sets the distance, in pixels, between the left edge of the element and the leftmost portion of the element that is currently visible in the window. This is equal to the horizontal distance that the content of the element has been scrolled.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the scroll-left distance.

This read-write property is always a nonnegative integer. Although it can be set to any positive or negative value, the property is set to zero if the assigned value is less than zero, and is set to the value of scrollWidth if the assigned value is greater than this. The default value is zero.

This property is always zero for elements that do not support scroll bars. For these elements, setting the property has no effect.

See also get_scrollLeft


ScrollTop Property

*
  * Previous Topic: IHTMLTextContainer::get_scrollLeft
  * Next Topic: IHTMLTextContainer::get_scrollWidth

IHTMLTextContainer::get_scrollTop

HRESULT get_scrollTop(
    long *p
);

Retrieves the distance, in pixels, between the top of the element and the topmost portion of the content that is currently visible in the window. This is equal to the vertical distance that the content of the element has been scrolled.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the scroll top distance.

This read-write property is always a nonnegative integer. Although it can be set to any positive or negative value, the property is set to zero if the assigned value is less than zero, and is set to the value of scrollHeight if the assigned value is greater than this. The default value is zero.

This property is always zero for elements that do not have scroll bars. For these elements, setting the property has no effect.

See also put_scrollTop

Up Top of Page

IHTMLTextContainer::put_scrollTop

HRESULT put_scrollTop(
    long v
);

Sets the distance, in pixels, between the top of the element and the topmost portion of the content that is currently visible in the window. This is equal to the vertical distance that the content of the element has been scrolled.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying the scroll top distance.

This read-write property is always a nonnegative integer. Although it can be set to any positive or negative value, the property is set to zero if the assigned value is less than zero, and is set to the value of scrollHeight if the assigned value is greater than this. The default value is zero.

This property is always zero for elements that do not have scroll bars. For these elements, setting the property has no effect.

See also get_scrollTop


IHTMLTextContainer

This interface provides access to properties and methods that are common to the BODY, BUTTON, CAPTION, DIV, MARQUEE, TABLE, and TEXTAREA elements.

IHTMLTextContainer Methods
createControlRange get_scrollHeight get_scrollWidth
put_scrollTop get_scrollTop put_scrollLeft
get_scrollLeft put_onscroll get_onscroll

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


IHTMLTextElement

This interface provides access to the properties and methods for this object and is equivalent to the IHTMLElement interface. See the reference section for the IHTMLElement interface for more information and a listing of the available methods.


Text Property

*
  * Previous Topic: IHTMLTitleElement
  * Next Topic: IHTMLTitleElement::put_text

IHTMLTitleElement::get_text

HRESULT get_text(
    BSTR *p
);

Retrieves the text contained within the TITLE element.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the text.

See also put_text

Up Top of Page

IHTMLTitleElement::put_text

HRESULT put_text(
    BSTR v
);

Retrieves the text contained within the TITLE element.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the text.

See also get_text


IHTMLTitleElement

This interface identifies the contents of the document in a global context.

This element can be only used within the HEAD element.

This element is a block element.

IHTMLTitleElement Methods


IHTMLTxtRange::collapse

HRESULT collapse(
    VARIANT_BOOL Start
);

Creates an empty range either at the beginning or end of the current range.

  • Returns S_OK if successful, or an error value otherwise.
Start
Boolean value specifying where to create the empty range. TRUE creates an empty range at the beginning of the current range; FALSE creates it at the end.

See also expand


IHTMLTxtRange::compareEndPoints

HRESULT compareEndPoints(
    BSTR how,
    IHTMLTxtRange *SourceRange,
    long *ret
);

Compares two end points and returns -1, 0, or 1 for less than, equal, or greater than, respectively.

  • Returns S_OK if successful, or an error value otherwise.
how
String describing the end points to compare. Can be one of these values:
StartToEnd | Compares the start point of the current range to the end point of the given range.
StartToStart | Compares the start point of the current range to the start point of the given range.
EndToStart | Compares the end point of the current range to the start point of the given range.
EndToEnd | Compares the end point of the current range to the end point of the given range.
SourceRange
Interface pointer of the range object against which the current range is to be compared.
ret
Address of a variable that receives the result of the comparison. Can be one of these values:
-1 | The end point of SourceRange is less than that of the current range.
0 | The end point of SourceRange is equal to that of the current range.
1 | The end point of SourceRange is greater than that of the current range.

See also setEndPoint


IHTMLTxtRange::duplicate

HRESULT duplicate(
    IHTMLTxtRange **Duplicate
);

Creates a duplicate of the range.

  • Returns S_OK if successful, or an error value otherwise.
Duplicate
Address of a variable that receives an interface pointer for the duplicate range.

See also IHTMLTxtRange


IHTMLTxtRange::execCommand

HRESULT execCommand(
    BSTR cmdID,
    VARIANT_BOOL showUI,
    VARIANT value,
    VARIANT_BOOL *pfRet
);

Executes the given command over the current selection or text range.

  • Returns S_OK if successful, or an error value otherwise.
cmdID
Identifier of a command. Can be any command identifier given in the list of Command Identifiers.
showUI
Flag specifying whether to display a user interface if the command supports one. If TRUE, the command displays a user interface, if applicable; otherwise, it doesn't.
value
Value to pass to the command. Possible values depend on the value of cmdID.
pfRet
Address of a variable that receives TRUE if the function is successful, or FALSE otherwise.

See also execCommandShowHelp


IHTMLTxtRange::execCommandShowHelp

HRESULT execCommandShowHelp(
    BSTR cmdID,
    VARIANT_BOOL *pfRet
);

Displays help information for the given command identifier.

  • Returns S_OK if successful, or an error value otherwise.
cmdID
Identifier of a command. Can be any command identifier given in the list of Command Identifiers.
pfRet
Address of a variable that receives TRUE if successful, or FALSE otherwise.

See also execCommand


IHTMLTxtRange::expand

HRESULT expand(
    BSTR Unit,
    VARIANT_BOOL *Success
);

Expands the range so that partial units are completed contained.

  • Returns S_OK if successful, or an error value otherwise.
Unit
String specifying the unit by which to expand the range. Can be one of these values:
Character | Expands a character.
Word | Expands a word. A word is a collection of characters terminated by a space or other white space character, such as a tab or return character.
Sentence | Expands a sentence. A sentence is a collection of words terminated by a punctuation character, such as a period.
Textedit | Expands to enclose the entire range.
Success
Address of a variable that receives TRUE if the the range was successfully expanded, or FALSE if not.

See also collapse


IHTMLTxtRange::findText

HRESULT findText(
    BSTR String,
    long count,
    long Flags,
    VARIANT_BOOL *Success
);

Searches for text in the given range. Positions the start and end points of the range to encompass the search string.

  • Returns S_OK if successful, or an error value otherwise.
String
String specifying the text to find.
count
Long integer that receives the count.
Flags
Long integer that receives the search flags.
Success
Address of a variable that receives TRUE if the text is found, or FALSE if not.


IHTMLTxtRange::get_htmlText

HRESULT get_htmlText(
    BSTR *p
);

Retrieves the HTML source as a valid HTML fragment.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the HTML source.

This property corresponds to the fragment portion of the CF_HTML clipboard format. For more information about CF_HTML, see HTML Clipboard Format.

See also put_text


IHTMLTxtRange::getBookmark

HRESULT getBookmark(
    BSTR *Bookmark
);

Retrieves a bookmark (opaque string) that can be used with moveToBookmark to return to the same range.

  • Returns S_OK if successful, or an error value otherwise.
Bookmark
Address of a variable that receives the bookmark if successful, or NULL otherwise.

See also moveToBookmark


IHTMLTxtRange::inRange

HRESULT inRange(
    IHTMLTxtRange *Range,
    VARIANT_BOOL *InRange
);

Determines whether the specified range is within or equal to the current range.

  • Returns S_OK if successful, or an error value otherwise.
Range
Interface pointer of the range to test.
InRange
Address of a variable that receives TRUE if Range is within the current range, or FALSE if not.

See also IHTMLTxtRange


IHTMLTxtRange::isEqual

HRESULT isEqual(
    IHTMLTxtRange *Range,
    VARIANT_BOOL *IsEqual
);

Determines whether the specified range is equal to the current range.

  • Returns S_OK if successful, or an error value otherwise.
Range
Interface pointer of the range to test.
IsEqual
Address of a variable that receives TRUE if Range is equal to the current range, or FALSE if not.

See also inRange


IHTMLTxtRange::move

HRESULT move(
    BSTR Unit,
    long Count,
    long *ActualCount
);

Collapses the given text range and moves the empty range by the given number of units.

  • Returns S_OK if successful, or an error value otherwise.
Unit
String specifying the units to move. Can be one of these values:
Character | Moves one or more characters.
Word | Moves one or more words. A word is a collection of characters terminated by a space or other white space character.
Sentence | Moves one or more sentences. A sentence is a collection of words terminated by a punctuation character, such as a period.
Textedit | Moves to the start or end of the original range.
Count
Integer specifying the number of units to move. This can be positive or negative.
ActualCount
Address of a variable that receives the actual number of units moved.

See also moveStart


IHTMLTxtRange::moveEnd

HRESULT moveEnd(
    BSTR Unit,
    long Count,
    long *ActualCount
);

Changes the scope of the range by moving the end position of the range.

  • Returns S_OK if successful, or an error value otherwise.
Unit
String specifying the units to move. Can be one of these values:
Character | Moves one or more characters.
Word | Moves one or more words. A word is a collection of characters terminated by a space or other white space character.
Sentence | Moves one or more sentences. A sentence is a collection of words terminated by a punctuation character, such as a period.
Textedit | Moves to the start or end of the original range.
Count
Integer specifying the number of units to move. This can be positive or negative.
ActualCount
Address of a variable that receives the actual number of units moved.

See also move, moveStart


IHTMLTxtRange::moveStart

HRESULT moveStart(
    BSTR Unit,
    long Count,
    long *ActualCount
);

Changes the scope of the range by moving the start position of the range.

  • Returns S_OK if successful, or an error value otherwise.
Unit
String specifying the units to move. Can be one of these values:
Character | Moves one or more characters.
Word | Moves one or more words. A word is a collection of characters terminated by a space or other white space character.
Sentence | Moves one or more sentences. A sentence is a collection of words terminated by a punctuation character, such as a period.
Textedit | Moves to the start or end of the original range.
Count
Integer specifying the number of units to move. This can be positive or negative.
ActualCount
Address of a variable that receives the actual number of units moved.

See also move, moveEnd


IHTMLTxtRange::moveToBookmark

HRESULT moveToBookmark(
    BSTR Bookmark,
    VARIANT_BOOL *Success
);

Moves to a bookmark. Bookmarks are opaque strings that are created with the getBookmark method.

  • Returns S_OK if successful, or an error value otherwise.
Bookmark
String specifying the bookmark.
Success
Address of a variable that receives TRUE if successful, or FALSE otherwise.

See also getBookmark


IHTMLTxtRange::moveToElementText

HRESULT moveToElementText(
    IHTMLElement *element
);

Moves the text range so that the start and end positions of the range encompass the text in the given element.

  • Returns S_OK if successful, or an error value otherwise.
element
Interface pointer of an element.

See also IHTMLElement


IHTMLTxtRange::moveToPoint

HRESULT moveToPoint(
    long x,
    long y
);

Moves the start and end positions of the text range to the given point. The coordinates of the point must be in pixels and be relative to the upper-left corner of the window. The resulting text range is empty, but can be expanded and moved using methods such as expand and moveEnd.

  • Returns S_OK if successful, or an error value otherwise.
x
Integer specifying the x-coordinate, in pixels.
y
Integer specifying the y-coordinate, in pixels.


IHTMLTxtRange::parentElement

HRESULT parentElement(
    IHTMLElement **Parent
);

Retrieves the parent element for the given text range. The parent element is the element that completely encloses the text in the range.

  • Returns S_OK if successful, or an error value otherwise.
Parent
Address of a variable that receives an interface pointer for the parent element.

If the text range spans text in more than one element, the method returns the smallest element that encloses all the elements. When you insert text into a range that spans multiple elements, the text is placed within the parent element rather than in any of the contained elements.

See also IHTMLElement


IHTMLTxtRange::pasteHTML

HRESULT pasteHTML(
    BSTR html
);

Pastes HTML text into the given text range. The text completely replaces any previous text and HTML elements in the range.

  • Returns S_OK if successful, or an error value otherwise.
html
String specifying the HTML text to paste.

Although this method never fails, it might alter the HTML text to make it fit the given text range. For example, attempting to paste a table cell into a text range that does not contain a table might cause the method to insert a TABLE element. For predictable results, you should paste only well-formed HTML text that is appropriate for the given text range.

You cannot use this method while the document is loading. Wait for the onload event before attempting to use it.


IHTMLTxtRange::queryCommandEnabled

HRESULT queryCommandEnabled(
    BSTR cmdID,
    VARIANT_BOOL *pfRet
);

Determines whether the given command is currently available.

  • Returns S_OK if successful, or an error value otherwise.
cmdID
Identifier of a command. Can be any command identifier given in the list of Command Identifiers.
pfRet
Address of a variable that receives TRUE if the command is available, or FALSE otherwise.

See also queryCommandSupported


IHTMLTxtRange::queryCommandIndeterm

HRESULT queryCommandIndeterm(
    BSTR cmdID,
    VARIANT_BOOL *pfRet
);

Determines whether the given command is in the indeterminate state.

  • Returns S_OK if successful, or an error value otherwise.
cmdID
Identifier of a command. Can be any command identifier given in the list of Command Identifiers.
pfRet
Address of a variable that receives TRUE if the given command is in the indeterminate state, or FALSE otherwise.


IHTMLTxtRange::queryCommandState

HRESULT queryCommandState(
    BSTR cmdID,
    VARIANT_BOOL *pfRet
);

Retrieves the current status of the given command. The status indicates whether the command has been carried out on the object.

  • Returns S_OK if successful, or an error value otherwise.
cmdID
Identifier of a command. Can be any command identifier given in the list of Command Identifiers.
pfRet
Address of a variable that receives TRUE if the given command has been carried out, FALSE if it has not, or NULL if the function cannot determine the status of the command.


IHTMLTxtRange::queryCommandSupported

HRESULT queryCommandSupported(
    BSTR cmdID,
    VARIANT_BOOL *pfRet
);

Determines whether the given command is supported.

  • Returns S_OK if successful, or an error value otherwise.
cmdID
Identifier of a command. Can be any command identifier given in the list of Command Identifiers.
pfRet
Address of a variable that receives TRUE if the command is supported, or FALSE otherwise.

See also queryCommandEnabled


IHTMLTxtRange::queryCommandText

HRESULT queryCommandText(
    BSTR cmdID,
    BSTR *pcmdText
);

Returns the string associated with a command.

  • Returns S_OK if successful, or an error value otherwise.
cmdID
Identifier of a command. Can be any command identifier given in the list of Command Identifiers.
pcmdText
Address of a string variable that receives the command text.

See also queryCommandValue


IHTMLTxtRange::queryCommandValue

HRESULT queryCommandValue(
    BSTR cmdID,
    VARIANT *pcmdValue
);

Retrieves the current value of the given command.

  • Returns S_OK if successful, or an error value otherwise.
cmdID
Identifier of a command. Can be any command identifier given in the list of Command Identifiers.
pcmdValue
Address of a variable that receives a string representing the command value. If the command is not supported, this variable receives NULL.

See also queryCommandText


IHTMLTxtRange::scrollIntoView

HRESULT scrollIntoView(
    VARIANT_BOOL fStart
);

Scrolls the range into view, aligning it at either the top or bottom of the window.

  • Returns S_OK if successful, or an error value otherwise.
fStart
Boolean value specifying the alignment of the range. TRUE aligns the range at the top of the window; FALSE aligns it at the bottom.

Depending on the size of the given object and the current window, this method might not be able to put the item at the very top or very bottom, but will always position the object as close to the requested position as possible.


IHTMLTxtRange::select

HRESULT select(
    void
);

Makes the active selection equal to the current object.

  • Returns S_OK if successful, or an error value otherwise.


IHTMLTxtRange::setEndPoint

HRESULT setEndPoint(
    BSTR how,
    IHTMLTxtRange *SourceRange
);

Sets the end point of one range based on the end point of another.

  • Returns S_OK if successful, or an error value otherwise.
how
String describing the end points. Can be one of these values:
StartToEnd | Sets the start point of the current range to the end point of the given range.
StartToStart | Sets the start point of the current range to the start point of the given range.
EndToStart | Sets the end point of the current range to the start point of the given range.
EndToEnd | Sets the end point of the current range to the end point of the given range.
SourceRange
Interface pointer of the range object to be used for setting the end point of the current range.

See also compareEndPoints


Text Property

*
  * Previous Topic: IHTMLTxtRange::get_htmlText
  * Next Topic: IHTMLTxtRange::getBookmark

IHTMLTxtRange::get_text

HRESULT get_text(
    BSTR *p
);

Retrieves the text contained within the range.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the text.

The text is formatted within the current context of the document.

Up Top of Page

IHTMLTxtRange::put_text

HRESULT put_text(
    BSTR v
);

Sets the text contained within the range.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the text.

The text is formatted within the current context of the document.

See also get_text


IHTMLTxtRange

This interface provides the ability to access the text range object in an HTML element. You use this interface to retrieve and modify text in an element, to locate specific strings in the text, and to carry out commands that affect the appearance of the text.

You retrieve a text range object by using the createTextRange method of the IHTMLBodyElement, IHTMLInputHiddenElement, IHTMLInputTextElement, IHTMLTextAreaElement, or IHTMLButtonElement interface. You can modify the extent of the text range by moving its start and end positions with methods such as move, moveToElementText, and findText. Within the text range, you can retrieve and modify plain text or HTML text. These forms of text are identical except that HTML text includes HTML tags; plain text does not.

IHTMLTxtRange Methods
get_htmlText put_text get_text
parentElement duplicate inRange
isEqual scrollIntoView collapse
expand move moveStart
moveEnd select pasteHTML
moveToElementText setEndPoint compareEndPoints
findText moveToPoint getBookmark
moveToBookmark queryCommandSupported queryCommandEnabled
queryCommandState queryCommandIndeterm queryCommandText
queryCommandValue execCommand execCommandShowHelp

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


Compact Property

*
  * Previous Topic: IHTMLUListElement
  * Next Topic: IHTMLUListElement::get_type

IHTMLUListElement::get_compact

HRESULT get_compact(
    VARIANT_BOOL *p
);

Determines whether the list is to be compacted to remove extra space between list elements.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives TRUE if the list is being compacted, or FALSE otherwise. The default value for this property is FALSE.

See also put_compact

Up Top of Page

IHTMLUListElement::put_compact

HRESULT put_compact(
    VARIANT_BOOL v
);

Specifies whether to compact the list to remove extra space between list elements.

  • Returns S_OK if successful, or an error value otherwise.
v
Compact flag. Set this parameter to TRUE to compact the list, or FALSE otherwise. The default value for this property is FALSE.

See also get_compact


Type Property

*
  * Previous Topic: IHTMLUListElement::get_compact
  * Next Topic: IHTMLUListElement::put_compact

IHTMLUListElement::get_type

HRESULT get_type(
    BSTR *p
);

Retrieves the current style of the list.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that receives the style. Can be one of these strings:
1 | Use numbers. This is the default value.
a | Use small letters.
A | Use large letters.
i | Use small roman numerals.
I | Use large roman numerals.

See also put_type

Up Top of Page

IHTMLUListElement::put_type

HRESULT put_type(
    BSTR v
);

Changes the style of the list.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the list style. Can be one of these strings:
1 | Use numbers. This is the default value.
a | Use small letters.
A | Use large letters.
i | Use small roman numerals.
I | Use large roman numerals.

See also get_type


IHTMLUListElement IHTMLUListElement *
  * Previous Topic: IHTMLTxtRange::setEndPoint
  * Next Topic: IHTMLUListElement::get_compact

IHTMLUListElement

This interface draws lines of text as a bulleted list.

This element is a block element.

IHTMLUListElement Methods


IHTMLUnknownElement

This interface provides access to the properties, and methods for this object and is equivalent to the IHTMLElement interface. For more information and a listing of the available methods, see the reference section for the IHTMLElement interface.


IHTMLWindow2::alert

HRESULT alert(
    BSTR message
);

Displays an Alert dialog box with a message and an OK button.

  • Returns S_OK if successful, or an error value otherwise.
message
String specifying the message to display in the dialog box.

The title bar of the Alert dialog box cannot be changed.

See also confirm, prompt


IHTMLWindow2::blur

HRESULT blur(
    void
);

Causes the window to lose focus and fires the onblur event.

  • Returns S_OK if successful, or an error value otherwise.

See also focus


IHTMLWindow2::clearInterval

HRESULT clearInterval(
    long timerID
);

Cancels a repeated evaluation of an expression that was set with the setInterval method.

  • Returns S_OK if successful, or an error value otherwise.
timerID
Specifies a time-out identifier returned by a previous call to the setInterval method.

See also setInterval


IHTMLWindow2::clearTimeout

HRESULT clearTimeout(
    long timerID
);

Cancels a time-out that was set with the setTimeout method.

  • Returns S_OK if successful, or an error value otherwise.
timerID
Specifies a time-out identifier returned by a previous call to the setTimeout method.

See also setTimeout


IHTMLWindow2::close

HRESULT close(
    void
);

Closes the current browser window.

  • Returns S_OK if successful, or an error value otherwise.


IHTMLWindow2::confirm

HRESULT confirm(
    BSTR message,
    VARIANT_BOOL *confirmed
);

Displays a Confirm dialog box with the specified message, and OK and Cancel buttons.

  • Returns S_OK if successful, or an error value otherwise.
message
String specifying the message to display in the dialog box.
confirmed
Address of a variable that receives TRUE if the message is confirmed, or FALSE otherwise.

The title bar of the confirm dialog box cannot be changed.

See also alert, prompt


DefaultStatus Property

*
  * Previous Topic: IHTMLWindow2::get_closed
  * Next Topic: IHTMLWindow2::get_document

IHTMLWindow2::get_defaultStatus

HRESULT get_defaultStatus(
    BSTR *p
);

Retrieves the default message displayed in the status bar at the bottom of the window.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the default status message.

Do not confuse the defaultStatus property with the status property retrieved by the get_status method. The status property reflects a priority or transient message in the status bar, such as the message that appears when an onmouseover event occurs over an anchor.

See also put_defaultStatus

Up Top of Page

IHTMLWindow2::put_defaultStatus

HRESULT put_defaultStatus(
    BSTR v
);

Sets the default message displayed in the status bar at the bottom of the window.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the status message.

See also get_defaultStatus


IHTMLWindow2::execScript

HRESULT execScript(
    BSTR code,
    BSTR language,
    VARIANT *pvarRet
);

Executes the specified script.

  • Returns S_OK if successful, or an error value otherwise.
code
String specifying the script code to execute.
language
String specifying the language in which the code is executed. The default is JScript.
pvarRet
Address of a variable that receives the return value from the script code.


IHTMLWindow2::focus

HRESULT focus(
    void
);

Causes the window to receive the input focus and execute the code, if any, associated with the onfocus event.

  • Returns S_OK if successful, or an error value otherwise.

See also blur


IHTMLWindow2::get__newEnum

HRESULT get__newEnum(
    IUnknown **p
);

Returns an OLE enumeration interface. This will enumerate over the frames collection of this window.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a pointer to an IUnknown interface.


IHTMLWindow2::get_clientInformation

HRESULT get_clientInformation(
    IOmNavigator **p
);

Retrieves an interface pointer to a navigator object that represents the browser. The object provides information about the browser.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the interface pointer.

See also IOmNavigator


IHTMLWindow2::get_closed

HRESULT get_closed(
    VARIANT_BOOL *p
);

Retrieves a value indicating whether the window is closed.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives TRUE if the window is closed, or FALSE otherwise.


IHTMLWindow2::get_document

HRESULT get_document(
    IHTMLDocument2 **p
);

Retrieves an interface pointer to the document object for the document that the browser is displaying.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the interface pointer.

See also IHTMLDocument2


IHTMLWindow2::get_event

HRESULT get_event(
    IHTMLEventObj **p
);

Retrieves an interface pointer to the event object that contains information relevant to the most recent event.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the interface pointer.

See also IHTMLEventObj


IHTMLWindow2::get_external

HRESULT get_external(
    IDispatch **p
);

Retrieves external access to an additional object model provided by host applications of the Internet Explorer browser components.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the interface pointer.

In the Internet Explorer stand-alone browser, no external object model is available. In a hosting scenario where it is available, the object model is defined by the application hosting the Internet Explorer components, and the hosting application should be referred to for documentation. For further details on how to implement extensions to the object model, see the Internet Client SDK documentation on "Reusing the WebBrowser and MSHTML".


IHTMLWindow2::get_frames

HRESULT get_frames(
    IHTMLFramesCollection2 **p
);

Retrieves an interface pointer to a zero-based collection of all the FRAME elements in an HTML document, if the document contains the FRAMESET element. If the document contains the BODY element, this is a collection of all IFRAME elements in the document. In either case, the elements are in the same order as they appear in the document.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the interface pointer.

The collection is indexed first by name, then by ID. If duplicate names are found, a collection of those named items is returned. The resulting collection can be only referenced by ordinal position.


IHTMLWindow2::get_history

HRESULT get_history(
    IOmHistory **p
);

Retrieves an interface pointer to a history object that contains information about all the URLs that the client has visited.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the interface pointer.


IHTMLWindow2::get_Image

HRESULT get_Image(
    IHTMLImageElementFactory **p
);

Returns an IHTMLImageElementFactory pointer that is used to create an offscreen image.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives an IHTMLImageElementFactory interface pointer.


IHTMLWindow2::get_location

HRESULT get_location(
    IHTMLLocation **p
);

Retrieves an interface pointer to a location object. The object contains information about the current location (full URL) of the document.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the interface pointer.


IHTMLWindow2::get_navigator

HRESULT get_navigator(
    IOmNavigator **p
);

Retrieves an interface pointer to a navigator object that represents the browser. The object provides information about the browser.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the interface pointer.

See also IOmNavigator


IHTMLWindow2::get_Option

HRESULT get_Option(
    IHTMLOptionElementFactory **p
);

Retrieves an interface pointer to a factory object that you can use to create OPTION elements. You can add the elements to a SELECT block by using the IHTMLSelectElement::add method.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the interface pointer.

See also IHTMLOptionElementFactory, IHTMLSelectElement::add


IHTMLWindow2::get_parent

HRESULT get_parent(
    IHTMLWindow2 **p
);

Retrieves an interface pointer to the parent object in the object hierarchy.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable the receives the interface pointer.

In a FRAMESET and FRAME relationship, this function retrieves an object representing the FRAMESET window. On a document, the parent is the window.


IHTMLWindow2::get_screen

HRESULT get_screen(
    IHTMLScreen **p
);

Retrieves an interface pointer to a screen object that provides information about the client's screen and rendering abilities

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the interface pointer.

See also IHTMLScreen


IHTMLWindow2::get_self

HRESULT get_self(
    IHTMLWindow2 **p
);

Retrieves an interface pointer to the current window.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the interface pointer.

Use the self property to disambiguate a window property from a form of the same name.


IHTMLWindow2::get_top

HRESULT get_top(
    IHTMLWindow2 **p
);

Retrieves an interface pointer to the topmost ancestor window, which is the current window's own parent.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the interface pointer.


IHTMLWindow2::get_window

HRESULT get_window(
    IHTMLWindow2 **p
);

Retrieves an interface pointer to the current window.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the interface pointer.

Use the self property to disambiguate a window property from a form of the same name.


IHTMLWindow2::moveBy IHTMLWindow2::moveBy *
  * Previous Topic: IHTMLWindow2::get_window
  * Next Topic: IHTMLWindow2::moveTo

IHTMLWindow2::moveBy

HRESULT moveBy(
    long x,
    long y
);

Currently not implemented, and has no effect when called.


IHTMLWindow2::moveTo

HRESULT moveTo(
    long x,
    long y
);

Currently not implemented, and has no effect when called.

See also scrollBy


Name Property

*
  * Previous Topic: IHTMLWindow2::get_location
  * Next Topic: IHTMLWindow2::get_navigator

IHTMLWindow2::get_name

HRESULT get_name(
    BSTR *p
);

Retrieves the name of the window.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the name.

The name property on the window comes from the FRAME definition. There is no other way to persist a window name in HTML.

See also put_name

Up Top of Page

IHTMLWindow2::put_name

HRESULT put_name(
    BSTR v
);

Sets the name of the window.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the name.

The name property on the window comes from the FRAME definition. There is no other way to persist a window name in HTML.

See also get_name


IHTMLWindow2::navigate

HRESULT navigate(
    BSTR url
);

Causes the browser to browse to the location specified by the URL.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the URL.

This method performs the same action as the IHTMLLocation::put_href method.


OffscreenBuffering Property

*
  * Previous Topic: IHTMLWindow2::get_navigator
  * Next Topic: IHTMLWindow2::get_onbeforeunload

IHTMLWindow2::get_offscreenBuffering

HRESULT get_offscreenBuffering(
    VARIANT *p
);

Determines whether an offscreen buffer is being used.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives a value indicating if a buffer is being used.

See also put_offscreenBuffering

Up Top of Page

IHTMLWindow2::put_offscreenBuffering

HRESULT put_offscreenBuffering(
    VARIANT v
);

Specifies whether to use an offscreen buffer.

  • Returns S_OK if successful, or an error value otherwise.
v
Value specifying whether to use an offscreen buffer.

See also get_offscreenBuffering


Onbeforeunload Property

*
  * Previous Topic: IHTMLWindow2::get_offscreenBuffering
  * Next Topic: IHTMLWindow2::get_onblur

IHTMLWindow2::get_onbeforeunload

HRESULT get_onbeforeunload(
    VARIANT *p
);

Retrieves the inline script associated with the onbeforeunload event before a window element is unloaded. This event is fired before the onunload event. It provides an opportunity to warn the user if the window is currently in an unsaved state and the information will be lost.

For more information on inline script, see Attaching an Event Handler in the Event Model documentation.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that contains the script.

The handler for this event should return NULL if doing the unload is safe, or a text string to prompt the user to decide to cancel or continue with the unload operation. Only the user's response to the warning can stop the new navigation causing the unload; the event handler itself cannot unilaterally block the operation. If the handler returns a non-NULL string, a modal dialog box appears that displays the explanatory string. The dialog box shows three buttons with the message for user action:

  • Continue—the unload operation proceeds.
  • Cancel—the navigation causing the unload is immediately canceled.
  • Help—(strongly recommended)—displays additional explanatory text, such as "This operation may cause existing content information to be lost. Choose Continue if this is OK, or Cancel to retain the information."

In the case of frames, the full sequence of onbeforeunload events are fired on each frame in the same order, depth-first, that onunload events are about to be fired. A dialog box is presented for each event handler that returns a non-NULL string. The first Cancel response stops the potential navigation, in which case no unload occurs. If there is no Cancel response, the unload proceeds and onunload events fire.

See also put_onbeforeunload

Up Top of Page

IHTMLWindow2::put_onbeforeunload

HRESULT put_onbeforeunload(
    VARIANT v
);

Sets the inline script associated with the onbeforeunload event before a window element is unloaded. This event is fired before the onunload event. It provides an opportunity to warn the user if the window is currently in an unsaved state and the information will be lost.

For more information on inline script, see Attaching an Event Handler in the Event Model documentation.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to be set.

The handler for this event should return NULL if doing the unload is safe, or a text string to prompt the user to decide to cancel or continue with the unload operation. Only the user's response to the warning can stop the new navigation causing the unload; the event handler itself cannot unilaterally block the operation. If the handler returns a non-NULL string, a modal dialog box appears that displays the explanatory string. The dialog box shows three buttons with the message for user action:

  • Continue—the unload operation proceeds.
  • Cancel—the navigation causing the unload is immediately canceled.
  • Help—(strongly recommended)—displays additional explanatory text, such as "This operation may cause existing content information to be lost. Choose Continue if this is OK, or Cancel to retain the information."

In the case of frames, the full sequence of onbeforeunload events is fired on each frame in the same order, depth-first, that onunload events are about to be fired. A dialog box is presented for each event handler that returns a non-NULL string. The first Cancel response stops the potential navigation, in which case no unload occurs. If there is no Cancel response, the unload proceeds and onunload events fire.

See also get_onbeforeunload


Onblur Property

*
  * Previous Topic: IHTMLWindow2::get_onbeforeunload
  * Next Topic: IHTMLWindow2::get_onerror

IHTMLWindow2::get_onblur

HRESULT get_onblur(
    VARIANT *p
);

Retrieves the inline script associated with the onblur event when the window element loses the focus.

For more information on inline script, see Attaching an Event Handler in the Event Model documentation.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a string variable that contains the script.

See also put_onblur

Up Top of Page

IHTMLWindow2::put_onblur

HRESULT put_onblur(
    VARIANT v
);

Sets the inline script associated with the onblur event when the window element loses the focus.

For more information on inline script, see Attaching an Event Handler in the Event Model documentation.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to be set.

See also get_onblur


Onerror Property

*
  * Previous Topic: IHTMLWindow2::get_onblur
  * Next Topic: IHTMLWindow2::get_onfocus

IHTMLWindow2::get_onerror

HRESULT get_onerror(
    VARIANT *p
);

Retrieves the inline script associated with the onerror event on the window element.

For more information on inline scripts, see Attaching an Event Handler in the Event Model documentation.

  • Returns S_OK if successful, or an error value otherwise.
v
Address of a VARIANT structure that contains the onerror script.

See also put_onerror

Up Top of Page

IHTMLWindow2::put_onerror

HRESULT put_onerror(
    VARIANT v
);

Sets the inline script associated with the onerror event on the window element.

For more information on inline scripts, see Attaching an Event Handler in the Event Model documentation.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the onerror script to be set.

See also get_onerror


Onfocus Property

*
  * Previous Topic: IHTMLWindow2::get_onerror
  * Next Topic: IHTMLWindow2::get_onhelp

IHTMLWindow2::get_onfocus

HRESULT get_onfocus(
    VARIANT *p
);

Retrieves the inline script associated with the onfocus event on the window element.

For more information on inline scripts, see Attaching an Event Handler in the Event Model documentation.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that contains the onfocus script.

See also put_onfocus

Up Top of Page

IHTMLWindow2::put_onfocus

HRESULT put_onfocus(
    VARIANT v
);

Sets the inline script associated with the onfocus event on the window element. This script is executed when the window receives focus.

For more information on inline scripts, see Attaching an Event Handler in the Event Model documentation.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the onfocus script to be set.

See also get_onfocus


Onhelp Property

*
  * Previous Topic: IHTMLWindow2::get_onfocus
  * Next Topic: IHTMLWindow2::get_onload

IHTMLWindow2::get_onhelp

HRESULT get_onhelp(
    VARIANT *p
);

Retrieves the inline script associated with the onhelp event on the window element.

For more information on inline scripts, see Attaching an Event Handler in the Event Model documentation.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that contains the onhelp script.

This script is executed when the user presses the F1 key or clicks the Help button in the browser. The default action of this event is to display the help information for the browser.

See also put_onhelp

Up Top of Page

IHTMLWindow2::put_onhelp

HRESULT put_onhelp(
    VARIANT v
);

Sets the inline script associated with the onhelp event on the window element. This script is executed when the user presses the F1 key or clicks the help button in the browser.

For more information on inline scripts, see Attaching an Event Handler in the Event Model documentation.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the onhelp script to be set.

See also get_onhelp


Onload Property

*
  * Previous Topic: IHTMLWindow2::get_onhelp
  * Next Topic: IHTMLWindow2::get_onresize

IHTMLWindow2::get_onload

HRESULT get_onload(
    VARIANT *p
);

Retrieves the inline script that is executed immediately after the browser loads the given object.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that contains the script.

See also put_onload

Up Top of Page

IHTMLWindow2::put_onload

HRESULT put_onload(
    VARIANT v
);

Sets the inline script associated with the onload event on the window element. This script is executed immediately after the browser loads the given object.

For more information on inline scripts, see Attaching an Event Handler in the Event Model documentation.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the onload script to be set.

See also get_onload


Onresize Property

*
  * Previous Topic: IHTMLWindow2::get_onload
  * Next Topic: IHTMLWindow2::get_onscroll

IHTMLWindow2::get_onresize

HRESULT get_onresize(
    VARIANT *p
);

Retrieves the inline script that is executed when the object is resized.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that contains the script.

See also put_onresize

Up Top of Page

IHTMLWindow2::put_onresize

HRESULT put_onresize(
    VARIANT v
);

Specifies code to execute whenever the window is resized.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to be set.

See also get_onresize


Onscroll Property

*
  * Previous Topic: IHTMLWindow2::get_onresize
  * Next Topic: IHTMLWindow2::get_onunload

IHTMLWindow2::get_onscroll

HRESULT get_onscroll(
    VARIANT *p
);

Retrieves the inline script that is executed when the scroll box is repositioned. The default action of this event is to scroll.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that contains the script.

See also put_onscroll

Up Top of Page

IHTMLWindow2::put_onscroll

HRESULT put_onscroll(
    VARIANT v
);

Specifies code to execute when the scroll box is repositioned. The default action of this event is to scroll.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to be set.

See also get_onscroll


Onunload Property

*
  * Previous Topic: IHTMLWindow2::get_onscroll
  * Next Topic: IHTMLWindow2::get_opener

IHTMLWindow2::get_onunload

HRESULT get_onunload(
    VARIANT *p
);

Retrieves the inline script that is executed immediately before the page is unloaded.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a VARIANT structure that contains the script.

See also put_onunload

Up Top of Page

IHTMLWindow2::put_onunload

HRESULT put_onunload(
    VARIANT v
);

Specifies code to execute immediately before the page is unloaded.

  • Returns S_OK if successful, or an error value otherwise.
v
VARIANT structure that contains the script to be set.

See also get_onunload


IHTMLWindow2::open

HRESULT open(
    BSTR url,
    BSTR name,
    BSTR features,
    VARIANT_BOOL replace,
    IHTMLWindow2 **pomWindowResult
);

Opens a new Web browser window.

  • Returns S_OK if successful, or an error value otherwise.
url
String specifying the URL of the document to display in the new window.
name
String specifying the name of the new window.
features
String specifying the ornaments to add to the new window. This parameter is a list of items separated by semicolons. Each item consists of an option and a value, separated by a colon (for example, "fullscreen:yes;toolbar:yes"). The following table lists the supported options.

Attribute | Values | Description
fullscreen | yes/no/1/0 | Browser displays in full-screen (true) or normal window (false) mode.
toolbar | yes/no/1/0 | Browser toolbar (Back and Forward buttons, and so on)
location | yes/no/1/0 | Input field for entering URLs directly into the browser.
directories | yes/no/1/0 | Directory buttons.
status | yes/no/1/0 | Status line at bottom of window.
menubar | yes/no/1/0 | Menu bar.
scrollbars | yes/no/1/0 | Horizontal and vertical scroll bars are enabled.
resizable | yes/no/1/0 | Do resize handles appear at the edge.
width | pixel | Width of window; defaults to pixels.
height | pixel | Height of window; defaults to pixels.
top | pixel | Top position, in pixels, in relation to the desktop.
left | pixel | Left position, in pixels, in relation to the desktop.

replace
Replace history flag. If TRUE, the URL that is loaded into the new page replaces the current entry in the window's browsing history. If FALSE, a new entry is created in the window's browsing history.
pomWindowResult
Address of a variable that receives an interface pointer to the new window object.


Opener Property

*
  * Previous Topic: IHTMLWindow2::get_onunload
  * Next Topic: IHTMLWindow2::get_Option

IHTMLWindow2::get_opener

HRESULT get_opener(
    VARIANT *p
);

Retrieves a reference to the window that created the current window.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the reference to the creating window.

See also put_opener

Up Top of Page

IHTMLWindow2::put_opener

HRESULT put_opener(
    VARIANT v
);

Sets a reference to the window that created the current window.

  • Returns S_OK if successful, or an error value otherwise.
v
String or value specifying the reference to the creating window.

See also get_opener


IHTMLWindow2::prompt

HRESULT prompt(
    BSTR message,
    BSTR defstr,
    VARIANT *textdata
);

Displays a Prompt dialog box with a message, an input field, and OK and Cancel buttons.

  • Returns S_OK if successful, or an error value otherwise.
message
String specifying the message to display in the dialog box.
defstr
String specifying the default value of the input field. If this parameter is NULL, the dialog box displays the value <undefined>.
textdata
Address of a variable that receives the text that the user enters into the input field.

The title bar of the prompt dialog box cannot be changed.

See also alert, confirm


IHTMLWindow2::resizeBy

HRESULT resizeBy(
    long x,
    long y
);

Currently not implemented, and has no effect when called.

See also resizeTo


IHTMLWindow2::resizeTo

HRESULT resizeTo(
    long x,
    long y
);

Currently not implemented, and has no effect when called.

See also resizeBy


IHTMLWindow2::scroll

HRESULT scroll(
    long x,
    long y
);

Scrolls the window to the specified x and y offset relative to the entire document.

  • Returns S_OK if successful, or an error value otherwise.
x
Value specifying the x offset.
y
Value specifying the y offset.


IHTMLWindow2::scrollBy

HRESULT scrollBy(
    long x,
    long y
);

Scrolls the document horizontally by the x value provided, and scrolls the document vertically by the y value provided.

  • Returns S_OK if successful, or an error value otherwise.
x
Long integer that contains the value for the x direction scroll distance.
y
Long integer that contains the value for the y direction scroll distance.

See also scrollTo


IHTMLWindow2::scrollTo

HRESULT scrollTo(
    long x,
    long y
);

Given the area specified as (X,Y) in document coordinates, scrolls the document to that position.

  • Returns S_OK if successful, or an error value otherwise.
x
Long integer that contains the value for the x direction scroll position coordinate.
y
Long integer that contains the value for the y direction scroll position coordinate.


IHTMLWindow2::setInterval

HRESULT setInterval(
    BSTR expression,
    long msec,
    VARIANT *language,
    long *timerID
);

Calls a function repeatedly, or evaluates an expression after a specified number of milliseconds has elapsed.

  • Returns S_OK if successful, or an error value otherwise.
expression
String specifying the code to be executed repeatedly at the specified interval.
msec
Numeric value or numeric string specifying the time-out interval, in milliseconds.
language
String specifying the language that the code is executed in.
timerID
Address of a variable that receives a time-out identifier. This identifier is used only to cancel the evaluation with the clearInterval method.

See also clearInterval


IHTMLWindow2::setTimeout

HRESULT setTimeout(
    BSTR expression,
    long msec,
    VARIANT *language,
    long *timerID
);

Evaluates an expression after a specified number of milliseconds has elapsed.

  • Returns S_OK if successful, or an error value otherwise.
expression
String specifying the code to be executed repeatedly at the specified interval.
msec
Numeric value or numeric string specifying the time-out interval, in milliseconds.
language
String specifying the language that the code is executed in.
timerID
Address of a variable that receives a time-out identifier. This identifier is used only to cancel the evaluation with the clearTimeout method.

See also clearTimeout


IHTMLWindow2::showHelp

HRESULT showHelp(
    BSTR helpURL,
    VARIANT helpArg,
    BSTR features
);

Displays a help file.

  • Returns S_OK if successful, or an error value otherwise.
helpURL
String specifying the URL of the help file.
helpArg
String or value specifying the programmer-defined arguments to pass to the dialog box.
features
Reserved; do not use.


IHTMLWindow2::showModalDialog

HRESULT showModalDialog(
    BSTR dialog,
    VARIANT *varArgIn,
    VARIANT *varOptions,
    VARIANT *varArgOut
);

Displays an HTML dialog box.

  • Returns S_OK if successful, or an error value otherwise.
dialog
String specifying the URL of the dialog box.
varArgIn
Address of a variable that contains programmer-defined arguments to pass into the dialog box.
varOptions
String specifying the attributes of the dialog box. This parameter is a list of items separated by semicolons. Each item consists of an option and a value, separated by a colon (for example, "dialogWidth:200;dialogHeight:100"). The following table lists the supported options.

Attribute | Values | IE3/IE4 | Description
dialogWidth | pixel | IE3/IE4 | Sets the width of the window, in pixels.
dialogHeight | pixel | IE3/IE4 | Sets the height of the window, in pixels.
dialogTop | pixel | IE3/IE4 | Sets the top position of the window, in pixels, relative to the desktop.
dialogLeft | pixel | IE3/IE4 | Sets the left position of the window, in pixels, relative to the desktop.
center | yes/no/1/0 | Not yet implemented in IE4. | Centered relative to the desktop.
font | font-family | Not yet implemented in IE4.
font-size | Not yet implemented in IE4.
font-weight | Not yet implemented in IE4.
font-style | Not yet implemented in IE4. | Describes the font and font attributes. The syntax should look like CSS. For example, font:3;font-size:4. To define multiple font values, use multiple font attributes.
edgeStyle | raised/sunken | Not yet implemented in IE4. | Sets the style of the window border.
borderSize | thick/thin | Not yet implemented in IE4. | Sets the thickness of the window border.
help | yes/no/1/0 | Not yet implemented in IE4. | Determines whether the help icon appears in the title bar
min | yes/no/1/0 | Not yet implemented in IE4. | Determines whether the minimize button appears in the title bar.
max | yes/no/1/0 | Not yet implemented in IE4. | Determines whether the maximize button appears in the title bar.
system menu | yes/no/1/0 | Not yet implemented in IE4. | Determines whether the system menu is available from the border icon.
sync | yes/no/1/0 | Not yet implemented in IE4.

varArgOut
Address of a variable that receives a return value from the dialog box. For more information, see IHTMLDialog::put_returnValue and IHTMLDialog::get_returnValue.


Status Property

*
  * Previous Topic: IHTMLWindow2::get_self
  * Next Topic: IHTMLWindow2::get_top

IHTMLWindow2::get_status

HRESULT get_status(
    BSTR *p
);

Retrieves the message displayed in the status bar at the bottom of the window.

  • Returns S_OK if successful, or an error value otherwise.
p
Address of a variable that receives the status message.

Do not confuse the status property with the defaultStatus property retrieved by the get_defaultStatus method. The status property reflects a priority or transient message in the status bar, such as the message that appears when an onmouseover event occurs over an anchor.

See also put_status

Up Top of Page

IHTMLWindow2::put_status

HRESULT put_status(
    BSTR v
);

Sets the message displayed in the status bar at the bottom of the window.

  • Returns S_OK if successful, or an error value otherwise.
v
String specifying the status message.

See also get_status


IHTMLWindow2::toString

HRESULT toString(
    BSTR *String
);

Retrieves a string representation of the window object.

  • Returns S_OK if successful, or an error value otherwise.
String
Address of a variable that receives the string representation.


IHTMLWindow2

This interface provides access to the window object which represents an open window in the browser. You use the window object to retrieve information about the state of the window and to gain access to the document in the window, to the events that occur in the window, and to features of the browser that affect the window.

Typically, the browser creates one window object when it opens an HTML document. However, if a document defines one or more frames (that is, contains one or more FRAME or IFRAME tags), the browser creates one window object for the original document and one additional window object for each frame. These additional objects are child windows of the original window and can be affected by actions that occur in the original. For example, closing the original window causes all child windows to close. You can also create new windows (and corresponding window objects) by using methods such as open and showModalDialog.

IHTMLWindow2 Methods
get_frames put_defaultStatus get_defaultStatus
put_status get_status setTimeout
clearTimeout alert confirm
prompt get_Image get_location
get_history close put_opener
get_opener get_navigator put_name
get_name get_parent open
get_self get_top get_window
navigate put_onfocus get_onfocus
put_onblur get_onblur put_onload
get_onload put_onbeforeunload get_onbeforeunload
put_onunload get_onunload put_onhelp
get_onhelp put_onerror get_onerror
put_onresize get_onresize put_onscroll
get_onscroll get_document get_event
get__newEnum showModalDialog showHelp
get_screen get_Option focus
get_closed blur scroll
get_clientInformation setInterval clearInterval
put_offscreenBuffering get_offscreenBuffering execScript
toString scrollBy scrollTo
moveTo moveBy resizeTo
resizeBy get_external

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


Internet Component Download

Internet Component Download is a mechanism for downloading and installing code from the Internet.

Microsoft Internet Component Download Overview
Microsoft Internet Component Download Reference


Internet Component Download Using INF

Microsoft Internet Explorer 4.0 introduces the concept of a software package. The packaging mechanism for this software package is a cabinet (CAB) file referenced by the CODEBASE element. A software package typically describes the smallest installable component, an ActiveX™ control, or a Java class library. The software package is addressed by its unique name/identifier and a version number. Legacy CABs that contain an INF file referenced by a CODEBASE attribute in the OBJECT element are automatically treated as a software package, with the unique name or identifier being the same as the GUID in the CLASSID attribute—for example, CLASSID=clsid:{9dba....}.

Software packages are described in the Open Software Description (OSD) vocabulary at http://www.microsoft.com/standards/osd. A software package CAB typically contains an OSD file. For compatibility and ease of use, it is possible to have the OSD reference a Microsoft Internet Explorer 3.0-style code download INF file inside the same CAB.

Packaging Component Code for Automatic Download

Independent software vendors and authors of COM objects for the Internet should package their implementations so they can be downloaded automatically by Web browsers such as Microsoft Internet Explorer. Such objects will be downloaded, for instance, when parsing the OBJECT tag in HTML.

Starting with Internet Explorer 4.0, an Internet Component Download CAB can contain a software package that represents a Java class library to be submitted to the Microsoft Internet Explorer Java Package Manager. Java class libraries are referenced by HTML in the APPLET and OBJECT element with PARAM NAME="useslibrary". When Internet Component Download is handed a CODEBASE that happens to be a CAB file, the following happens:

  • The CAB is inspected to see if it contains an OSD file first. OSD files are basically Extensible Markup Language (XML) files with OSD vocabulary. The OSD specification is located at http://www.microsoft.com/standards/osd/; details on usage of OSD to install Java packages with the Microsoft Java Virtual Machine Package Manager or installing simple ActiveX Controls with OSD syntax can be found in the Extending Internet Component Download Using OSD article.
  • If the CAB contains an OSD, it is processed for native code or Java packages to be installed as part of this software package. An OSD can also point to an INF file in the same CAB file.
  • If the CAB does not contain an OSD file, a search is made for an INF file. If found, it is processed with the Component Download INF grammar detailed in INF setup-script format.

Interpreting the CODEBASE URL

The CODEBASE attribute in an OBJECT element contains a URL pointing to the implementation of a given COM object. This URL is of critical importance for component download, because it must specify all files necessary to implement a particular COM object. HTML authors can author the CODEBASE URL to point to one of two file types in the general case, and a third file type in a special case. Component developers should choose one of the following packaging schemes for their COM objects:

  • A single PE (portable executable, for example, an .ocx, a .dll, or an .exe file): This single executable is downloaded, installed, and registered in one step. This is the simplest way to package a single-file OLE control, but it will not use file compression, and it will not be platform independent except with HTTP.
  • A CAB (cabinet) file: This file contains one or more files, all of which are downloaded together in a compressed cabinet. Exactly one file in the cabinet is an INF file providing further installation information. This INF file can refer to files in the CAB as well as to files at other URLs. This mechanism requires authoring of an INF file and packaging of a CAB file, but in return it provides file compression. It will not be platform independent, however, except with HTTP format negotiation.
  • (Special case) A stand-alone INF file: The stand-alone INF can be used only when browser security is set to low or medium. This will not work in high browser security because a flat INF file cannot be signed, thus making it incompatible with Authenticode™. This file specifies various files that need to be downloaded and set up for the OCX to run. The syntax of the INF file allows URLs pointing to files to download, and platform independence (by enumerating files for various platforms). This mechanism provides platform independence for non-HTTP servers.

Registry settings and self-extracting EXE files

It's best to use self-registering code for Internet Component Download. For OCX, DLL, and EXE files marked as "OleSelfRegister" in the version resource, Internet Component Download will try to run self-registration. For DLLs, this means loading the DLL library and calling the DllRegisterServer entry point, if available. For EXEs, this means running the EXE file with the run-time parameter of "/RegServer". This ensures that COM objects implemented as local servers (for example, Winword.exe) are registered correctly. If an object is not marked as "OleSelfRegister" but registration is necessary, or if it is necessary to override the "OleSelfRegister" flag, one can add the following to an INF file (see the INF setup-script format below):

[foo.ocx]
RegisterServer=no 	; don't register even if marked OleSelfRegister

or

[foo.ocx]
RegisterServer=yes 	; register this even if not marked OleSelfRegister.
                ; This is the typical workaround for getting old
                ; controls to register

Code that is downloaded through Internet Component Download can be a self-extracting EXE because Internet Component Download ignores the "OleSelfRegister" flag if the main URL for code download points directly to an EXE file. In this case it is assumed that this is a self-registering EXE, and this enables self-extracting EXEs to work correctly as long as they ignore the /regsvr command-line parameter. Supporting self-extracting EXEs enables very complex setup mechanisms to be launched automatically through Internet Component Download. For details on how to package your self-extracting EXE as a hook instead of pointing your CODEBASE at it, see the "When and How to Use Hooks" section. However, if a self-extracting EXE is called through this mechanism, any components it installs will not be automatically tracked by Internet Component Download. Such components are permanently installed and are not marked by Internet Component Download for future cleanup.

Including the version number in the CODEBASE URL

In addition to the actual code address, the CODEBASE URL can also include an optional version number by using the following syntax:

"CODEBASE=http://www.foo.com/bar.ocx#Version=a,b,c,d"

The Internet Component Download mechanism downloads and installs the file only if the specified version number is more recent than any existing version of the same file currently installed in the system. If a version number is not specified with a file, it is assumed that any version installed on the system is recent enough.

If the version number specified in the CODEBASE attribute is "-1,-1,-1,-1", Internet Component Download will always try to download the latest version of the desired component. Note that this can be a costly effort involving many network transactions, especially if the Internet search path is searched for the newest version of an object. Note also that because of the Internet search path, it is possible for the Component Download service to try to download code in the absence of a CODEBASE attribute. In fact, if the CODEBASE attribute is the URL fragment "#Version=-1,-1,-1,-1", there is no specific location to download code from, but the Internet search path will still be searched to find the latest version of an object.

Platform independence and HTTP

When code to be downloaded is on an HTTP server, the HTTP Accept header MIME request type can be used to specify which platform the code is to run on, thus allowing platform independence of the CODEBASE URL.

The following MIME types are used to describe PE files (.exe, .dll, .ocx), cabinet files (.cab), and setup scripts (.inf).
File description | MIME type
PE (portable executable) - .exe, .dll, .ocx | application/x-pe-%opersys%-%cpu%
Cabinet files - .cab | application/x-cabinet-%opersys%-%cpu%
Setup scripts - .inf (platform independent) | application/x-setupscript
Macintosh® Binhex files | application/mac-binhex-40

%opersys% and %cpu% specify the operating system and CPU for the platform on which downloaded components will be executed. For example, the MIME type for a Win32® cabinet file running on an Intel® x86-architecture processor would be:

application/x-cabinet-win32-x86

The following are valid values for %opersys% and %cpu%.
Valid values for %opersys% | Meaning
win32 | 32-bit Windows® operating systems (Windows 95 or Windows NT®)
mac | Macintosh® operating system
<other> | will be defined as necessary
Valid values for %cpu% | Meaning
x86 | Intel® x86 family of processors
ppc | Motorola® PowerPC architecture
mips | MIPS® architecture processors
alpha | DEC® Alpha architecture
68k | Motorola® 68k CPU

When the code is on a non-HTTP server (for example, at a local LAN location), an INF file can be used to achieve platform independence by specifying different URLs for files to be downloaded for different platforms.

CAB format

The CAB format used for Internet Component Download is a nonproprietary format based on Lempel-Ziv compression. The Microsoft Internet Client SDK includes a free tool called DIAMOND.EXE that will package cabinet files into this nonproprietary format.

Using the DIAMOND.EXE tool for creating CAB files

The DIAMOND.EXE tool takes a DDF "directive file" specifying which files to combine into a cabinet. The syntax for using this tool from the command line is:

DIAMOND.EXE /f <directive file.ddf>

The following example directive file, Circ3z.dff, would be used for creating a cabinet file containing two files: Circ3.inf and Circ3.ocx. It should be straightforward to add to this list of files.

; DIAMOND directive file for CIRC3.OCX+CIRC3.INF
.OPTION EXPLICIT				; Generate errors on variable typos
.Set CabinetNameTemplate=CIRC3Z.CAB
;** The files specified below are stored, compressed, in cabinet files
.Set Cabinet=on
.Set Compress=on
circ3.INF
circ3.OCX

Note It is possible to use the "code-signing" utilities to sign entire cabinet files using a digital certificate. However, to do this, it is necessary to add the following lines to the DDF file before the list of files for inclusion in the cabinet.

;Reserve space for PKS#7 Code Signature
.Set ReservePerCabinetSize=2048

If a cabinet file is signed, it is assumed that every file inside the cabinet is trusted, including .inf and .ini files. This has two advantages:

  • It is now possible to include powerful INF files inside a trusted cabinet.
  • By signing an entire cabinet, the time for verifying digital certificates can be accelerated due to the cabinet compression.

INF setup-script format

INF syntax understood by Internet Component Download

All URLs in the INF are to be encoded for handling of special characters—for example, 'space' should be encoded as "http://foo/foo%20bar.ocx". Friendly file names are created using the decoded base names of these URLs. URLs, if relative, are based of the context of the main CODEBASE=<url>, unless redirected by the object index, in which case the context is set to that of the redirected URL.

Code downloader-understood main sections

The code downloader looks for and understands the [Add.Code] and [Setup Hooks] sections in the INF file. If both these sections are missing, the INF is assumed to be a standard Win32 INF without code downloader extensions, and a hook is created to have the system process the INF's DefaultInstall section.

The Add.Code section lists all the files to be installed, including optional files.

[Add.Code]
filename1=section-name1
filename2=section-name2

Each file section is identified by the section name in brackets, followed by all the key values, as in an .ini file.

[section-name1]
key1=value1
key2=value2

The following keys are valid in a file section:

File-%opersys%-%cpu%=[url | ignore | thiscab]
%opersys% can be one of [win32 | mac] currently. %cpu% can be one of [x86 | ppc | mips | alpha].

A URL can be specified to indicate the correct file for the target operating system and CPU, or the special value "ignore", which indicates the file is not required for the specified platform. This key is always looked for before the platform-independent description key File= as described below.

File=[url | thiscab]
The value of the file key indicates where the file can be downloaded from. It can be a URL or the special value "thiscab", which indicates that the file is located in the CAB file where the INF file came from. If no value is specified, component download fails if the file is not already installed on the user's computer. If this URL points to a non-HTTP protocol or to an HTTP server that does not support/understand the special Accept Types sent out by the code downloader as discussed in the Platform Independence and HTTP section above, you must use the file-%opersys%-%cpu%= key described in the previous paragraph.
FileVersion=a,b,c,d
The FileVersion key specifies the minimum required version of the file specified by the File key. If no value is specified, any version is acceptable.
Clsid={nnnnnnnn-nnnn-nnnn-nnnn-nnnnnnnnnnnn}
The value of the clsid key is the string representation of the component CLSID, enclosed in braces {}.
DestDir=[10 | 11]
DestDir can be set to 10 to place the file into the \windows directory or to 11 to place the file into the \windows\system directory. If no value is specified, the file is placed in the \cache directory.
RegisterServer=[yes | no]
This is an override to the policy on whether to try to self-register this file. Section "Registry settings and self-extracting .exes" above in this document contain details on the registration policy.
Hook=section-name3
This is the way to specify conditional hooks. If the clsid or file of at least the version specified in this section is not sufficient and no File= or File-%opersys%-%cpu%= values are specified, this key hook is looked for by the component downloader to look for a custom setup hook to install the required file or component. The Hook section looks like the following:
[section-name3]
key1=value1
key2=value2

It is valid for several different file section hooks to point to the same hook section. This is a way to have one hook install one or more components/files. The hook is executed only once if one or more pieces are missing.

with the following valid keys:

File-%opersys%-%cpu%=[url | ignore]
%opersys% can be one of [win32 | mac] currently. %cpu% can be one of [x86 | ppc | mips | alpha].

A URL can be specified to indicate the correct file for the target operating system and CPU, or the special value "ignore", which indicates the file is not required for the specified platform. This is identical to the way you would specify the location of a file name in a section describing the piece in [add.code] except that this has to point to a CAB file and the keyword 'thiscab' is not applicable with this key. This value if absent would cause us to set our context to the CAB that this INF file was located in. This key is always looked for before the platform independent description key File= as described below.

File=[url]
This is a URL to a CAB file that contains one or more files that are needed for the hook. The component download downloads the CAB file and expands it into a unique temporary directory and then executes the hook. This is identical to the way you would specify the location of a file name in a section describing the piece in [add.code], except that this has to point to a CAB file, and the keyword 'thiscab' is not applicable with this key. This value, if absent, would cause us to set our context to the CAB that this INF file was located in.
Run=[cmd-line]
This is the command line to be run in the temporary directory with the extracted files in the CAB file pointed to by the above File= key. The command line can contain some component downloader variables that are expanded before execution. It can also contain translations of Win32 INF syntax based on registry key values on the client. Look for examples and details in the Appendix. If this key is absent, the component downloader looks for InfFile= and InfSection= keys to run a Win32 INF hook.
InfFile=[name of win32 INF file inside the CAB]
This is an optional key that, if absent, sets it to the current INF (the main INF pointed to or found in the CAB pointed to by CODEBASE=). This is a way to use standard Win32 INF syntax for installation of a file or component. Please look for samples and syntax of Win32 INF in the Appendix.
InfSection=[section name in the InfFile mentioned in above key]
This is an optional key that, if absent, sets it to the DefaultInstall section of the INF file specified in the InfFile= key above.

The Setup Hooks section lists all unconditional hooks to be executed before setup of files in the Add.Code section.

[Setup Hooks]
hookname1=section-name4
hookname2=section-name5

Just as within a section describing a file to be installed listed in Add.Code section, you could execute a hook to install/set up that file with the hook= key, you can also list a set unconditional hooks to be always executed before setup of files in Add.Code. This is done by listing all the hooks in order of preferred execution in the Setup Hooks section.

Note When using hooks, it is important to add the following lines to your INF file for compatibility.

[Version]
Signature="$CHICAGO$"
AdvancedINF=2.0

The following is a sample INF file that demonstrates the syntax understood by the Component Download service.

;Sample INF file for CIRC3.OCX
[Add.Code]
circ3.ocx=circ3.ocx
random.dll=random.dll
mfc40.dll=mfc40.dll
foo.ocx=foo.ocx

[circ3.ocx]
; Lines below specify that the specified circ3.ocx (clsid, version) needs to be
; installed on the system. If it doesn't exist already, it can be downloaded from
; the given location (a .CAB).
; Note: if "thiscab" is specified instead of the file location, it is assumed that
; the desired file is present in the same .CAB cabinet that the INF originated from.
; Otherwise, if the location pointed to is a different .CAB, the new cabinet
; is also downloaded and unpacked in order to extract the desired file.
file=http://www.code.com/circ3/circ3.cab
clsid={9DBAFCCF-592F-101B-85CE-00608CEC297B}
; Note that the {}s are required when entering a CLSID in the INF file.
; This is slightly different from the HTML
; syntax for inserting CLSIDs in an <OBJECT> tag.
FileVersion=1,0,0,143

[random.dll]
; Lines below specify that the random.dll needs to be installed in the system.
; If this doesn't exist already, it can be downloaded from the given location.
file=http:// www.code.com/circ3/random.dll
; Note that the FileVersion is optional, and it can also be left empty,
; meaning that any version is ok.
FileVersion=
DestDir=10

; DestDir can be set to 10 or 11 ( LDID_WIN or LDID_SYS by INF convention).
; This places files in \windows or \windows\system, respectively.
; If no dest dir is specified (typical case), code is installed in the occache
; directory.

[mfc40.dll]
; Leaving the file location empty specifies that the installation
; needs mfc40 (version 4,0,0,5), but it should not be downloaded.
; If this file is not already present on the client machine, component download fails.
file=
FileVersion=4,0,0,5

[foo.ocx]
; Leaving the file location empty specifies that the installation
; needs the specified foo.ocx (clsid, version), but it should not be downloaded.
; If this file is not already present on the client machine, component download fails.
file=
clsid={DEADBEEF-592F-101B-85CE-00608CEC297B}
FileVersion=1,0,0,143

Platform independence in .INF files

It is possible to create platform-independent setup scripts that pull files from different locations depending on the desired platform. Internet Component Download INF files use a scheme similar to the one described under "Platform Independence and HTTP" earlier in this section. Specifically, a sample platform-independent INF file would include text such as the following:

[circ3.ocx]
; Lines below specify that the specified circ3.ocx (clsid, version) needs to be
; installed on the system. If it doesn't exist already, can be downloaded from
; the given location (a .CAB).
file-win32-x86=file://products/release/circ3/x86/circ3.cab
file-win32-mips=file://products/release/circ3/mips/circ3.cab
file-mac-ppc=ignore
; The 'ignore' keyword means that this file is not needed for this platform.

clsid={9DBAFCCF-592F-101B-85CE-00608CEC297B}
FileVersion=1,0,0,143

Thus the "file=" syntax used in the INF file is expanded to "file-%opersys%-%cpu =", allowing the INF file to specify multiple locations where various platform-dependent modules can be found and downloaded. See the section above for valid values for %opersys% and %cpu%.

The Internet Component Download Service

The Internet Component Download service is exposed through a single function, CoGetClassObjectFromURL. This system function is called by an application to download, verify, and install code for an OLE component. The function is used in the implementation of Microsoft Internet Explorer.

The CoGetClassObjectFromURL function returns a factory object for a given rclsid. If no CLSID is specified (CLSID_NULL), this function chooses the appropriate CLSID for interpreting the Internet MIME type specified in szContentType. If the desired object is installed on the system, it is instantiated. Otherwise, the necessary code is downloaded and installed from the location specified in szCodeURL or from an object store on the Internet search path (see below).

This "download and install" process involves the following steps:

  1. Download the necessary file(s) (.cab, .inf, or .exe) using URL Moniker(s).
  2. Call WinVerifyTrust to ensure that all downloaded files are safe to install.
  3. Complete self-registration of all COM components.
  4. Add registry entries to keep track of downloaded code (see Appendix on Registry Details).
  5. Call CoGetClassObject for the desired rclsid.

In the common Web-browser scenario, the values for parameters passed to this function are read directly from an HTML OBJECT element. For example, the szCodeURL, dwFileVersionMS, and dwFileVersionLS parameters are specified inside an <OBJECT> tag as "CODEBASE=http://www.foo.com/bar.ocx#Version=a,b,c,d", where szCodeURL is "http://www.foo.com/bar.ocx", dwFileVersionMS is MAKELONG(b, a), and dwFileVersionLS is MAKELONG(d, c).

Because downloading and installation of code occurs asynchronously, CoGetClassObjectFromURL often returns immediately with a return value of E_PENDING. At this point, the IBindStatusCallBack interface is used to communicate the status of the download operation to the client. To participate in this communication, the client must implement IBindStatusCallback and register this interface in the pBindCtx parameter passed into CoGetClassObjectFromURL using RegisterBindStatusCallback. The client can expect to be called with callback notifications for IBindStatusCallback::OnStartBinding (providing an IBinding for controlling the download), IBindStatusCallback::OnProgress (reporting progress), IBindStatusCallback::OnObjectAvailable (which returns the desired object interface pointer), and IBindStatusCallback::OnStopBinding (which returns error codes in case of an error).

Storing/Caching Downloaded Code

Component Download installs most new code in a permanent store in windows\occache. The cache location can be overridden by a registry setting of HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Internet Settings\ActiveXCache. Some components (helper DLLs that need to be on the system PATH but currently are not) will also be installed in \windows and \windows\system. All downloaded code is registered using a new "Module Usage" registry section that keeps track of such code. Downloaded code is not removed automatically, but it is possible in the future to add a user interface to the Control Panel (or elsewhere) allowing a user to clean up this directory.

Internet Search Path

When Internet Component Download is called to download code, it traverses the Internet search path to look for the desired component. This path is a list of object store servers that will be queried every time components are downloaded using CoGetClassObjectFromURL. This way, even if an <OBJECT> tag in an HTML document does not specify a CODEBASE location to download code for an embedded OLE control, the Internet Component Download will still use the Internet search path to find the necessary code.

Internet search path syntax

The search path is specified in a string in the registry, under the key HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Internet Settings\CodeBaseSearchPath. The value for this key is a string in the following format:
CodeBaseSearchPath = <URL1>; <URL2>; ... <URLm>; CODEBASE; <URLm+1>;
    ... <URLn-1>; <URLn>

In this format, each of URL1 through URLn is an absolute URL pointing to HTTP servers acting as "object stores". When processing a call to CoGetClassObjectFromURL, the Internet Component Download service will first try downloading the desired code from the locations URL1 through URLm, then try the location specified in the szCodeURL parameter (corresponding to the CODEBASE attribute in the <OBJECT> tag), and will finally try the locations specified in locations URLm+1 through URLn.

Note that if the CODEBASE keyword is not included in the CodeBaseSearchPath key, calls to CoGetClassObjectFromURL will never check the szCodeURL location for downloading code. By removing the CODEBASE keyword from the CodeBaseSearchPath key, corporate intranet administrators can effectively disable Internet Component Download for corporate users.

Object stores

An object store on the Internet search path is an HTTP server that services requests for downloadable code. During a call to CoGetClassObjectFromURL, Internet Component Download will try to download code from the various object stores on the search path. Specifically, an object store will receive an HTTP POST request with data in the following format:

CLSID={class id}
Version=a,b,c,d
MIMETYPE=mimetype

All the values above are optional, although one of CLSID or MIMETYPE must be present. The object store should parse this information, check an internal database, and either fail the call or redirect the HTTP request to the downloadable code cabinet file (.cab), setup script (.inf), or portable executable (.exe, .dll, .ocx).

The POST parameters should be processed by the object store as follows:

  • If CLSID is provided with no version number, the most recent object matching the CLSID will be returned. If the CLSID is provided with a Version, the object matching the CLSID and with the largest version number greater than or equal to Version will be provided. If no object is available that matches the CLSID with a large enough version number, the 404 error will be returned. MIMETYPE will be ignored when CLSID is provided.
  • If no CLSID is provided but MIMETYPE is provided, the first object found in the database that matches the MIMETYPE will be returned. Version, if provided, is treated exactly as above. If neither CLSID or MIMETYPE is provided, the error return code 400 Bad Request will be returned.

In addition to the POST data described above, queries to object stores will also include HTTP headers for Accept (MIME type) and Accept-Language, thus specifying the desired platforms (see above for Platform Independence and HTTP) and language-localized implementation for a component. Note that these HTTP headers are added to all HTTP requests made by Internet Component Download. This allows object stores to serve different code implementations for differing platforms or even different languages.

Note Internet Component Download uses the first successful response from a server on the Internet search path. Component Download will not continue searching for newer versions of components.

Uses for the Internet search path

The Internet search path can be used in two ways:

  • Object store servers at the beginning of the path will be asked for code before checking the location specified in the szCodeURL parameter for CoGetClassObjectFromURL. Servers at the beginning of the search path will thus be checked before trying the location specified in the CODEBASE attribute of an <OBJECT> tag. This is a useful feature for corporate intranets, because it allows intranet administrators to set up a local object store that is used to serve code for download by employees. In fact, it is possible to disable the CODEBASE attribute for <OBJECT> tags by removing the CODEBASE keyword from the search path.
  • Object store servers at the end of the search path will be asked for code after trying the location specified in the szCodeURL parameter for CoGetClassObjectFromURL, and thus after trying the location specified in the CODEBASE attribute. This allows registration of default object store locations on the World Wide Web, where browsers can find code when no CODEBASE location is explicitly specified.

Registry Details

The Internet Component Download service keeps registry entries for every new downloaded component. These registry entries will be useful for writing a utility for cleaning up the code storage, or for migrating the Component Download service to use a code cache rather than a permanent store.

Why the existing "SharedDLL" mechanism is inadequate

To do correct code caching, the existing shared DLL reference counting scheme will not suffice, because reference counts are easily inflated. Specifically, any application that is reinstalled increases the reference count on a shared DLL even though that DLL already has a reference count belonging to the particular application. This is already broken for current reference counting, but it will especially fail for code download, in which OCXes are used by multiple pages quite regularly and there is no way of knowing which OCXes need reference counts.

New "ModuleUsage" registry mechanism for tracking usage of shared components

To do ref. counting correctly, Component Download maintains a ModuleUsage section in the registry that holds a list of "owners" and "clients" for each shared module. Thus the registry can keep track of who is using a shared module, not just how many clients that module has. The registry entries use the following syntax:

[ModuleUsage]
    [<Fully Qualified Path&File Name>]
        .FileVersion=a,b,c,d
        .Owner = Friendly Name/ID of Owner
        <Client ID > = <info peculiar to this client>
        <Client ID > = <info peculiar to this client>

A ModuleUsage section in a sample registry would look something like the following:

Under My Computer\HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion:

[ModuleUsage]
    [c:/windows/system/mfc40.dll]
        .FileVersion=0,4,0,0
        .Owner ={CLSID of main object rclsid passed to CoGetClassObjectFromURL}
        {CLSID of main object rclsid passed to CoGetClassObjectFromURL}= <any info,
            or default>
        AnotherAppID= <any info, or default>
Key name | Description
<Fully Qualified Path&File Name> | This is the full path of the shared module. This name has to use "/"s instead of "\"s because the "\" is an invalid character in a key name.
.Owner | The application that installs the shared module and creates the original ModuleUsage section will put some identifier in the Owner key section. If the DLL already existed on the system and this Module Usage key did not exist, the .Owner key should be set to "Unknown" and the DLL should not be removed on uninstall. The owner should always also enlist itself as a client.
.File Version | The version number for the shared module. This is unimplemented by Component Download at this time.
<Client ID> | Identifier of a client who is using the shared module. The value corresponding to each client key contains client-specific information. When the client is Internet Component Download, the <Client ID> is {CLSID of main object rclsid passed to CoGetClassObjectFromURL}. For other clients, the client-specific information should be the full path of the client, so that if the client is accidentally deleted it is possible to do garbage collection.

Every client of this module is expected to increment and decrement the existing SharedDLLs section in the registry as well (a client only increments this value once when it adds itself as a client under [ModuleUsage]). This is to allow a migration path for applications currently implementing only a SharedDLLs scheme.

This registry information complements the reference counts in the SharedDLLs section by remembering which clients are actually using a shared module. This counting scheme will work correctly and allow caching of downloaded code. Furthermore, when downloading files, Internet Component Download can use this registry information as an efficient shortcut for verifying whether a file needs to be overwritten because it is an out-of-date version.

Win32 INF Syntax and Variable Substitutions

EXTRACT_DIR
Expands to the directory that the files in the CAB pointed to by the hook section were extracted to. For example, the following line in the Hook section will run the command mysetup.exe in the extracted directory.
run=%EXTRACT_DIR%/mysetup.exe
OBJECT_DIR
Expands to the default destination directory for controls. In Internet Explorer 4.0, this is the Downloaded Program Files folder under the \windows directory. If there is a file name conflict with a previously existing file in this directory, CONFLICT.<n> folders are created under the default destination directory, when n is a monotonically increasing number. OBJECT_DIR reflects the final destination directory including such name conflict resolutions.

Version Number Format and Other Details

Version is a 64-bit number that you could break up as a,b,c,d, with most significant to least significant left to right. Typically the printed version numbers are represented as a.b.d (skipping c = 0), where:

  • a - major version
  • b - minor version
  • c - custom number
  • d - build number

For example, 4.1.6130 is really 4,1,0,6130.

Determining the local version number of a file

If a recent enough version of a file listed in either the CODEBASE attribute in the OBJECT tag or in the FileVersion= key in the section of the INF file is already available on the local computer, no download happens. When deciding if the version of an available local file is good enough, the following algorithm is applied:

  • If the file in question has an associated CLSID (either by the CLASSID attribute in the OBJECT tag for the main object to be instantiated, or specified by the clsid= key in the INF file), the following key is looked for on the client registry:
    HKEY_CLASSES_ROOT:\\CLSID\{... clsid ...}\Installed version\

    The default value of this key if of the format a,b,c,d (as described in the previous section) is assumed to be the available local version of the clsid. This support is for extending version support to non-PE files such as Java class files. To make the version check more robust, the code downloader will also look for an optional named value "path" under the Installed Version key, which if present is validated to be present on the file system on the local computer. This is to ensure that a download takes place when the registry information is intact, but the actual file that implements the classid has been removed from the hard disk.

  • The file version number is retrieved from the version resource and checked for sufficiency. If the file version cannot be retrieved, the version of the file is deemed insufficient and a download is initiated for that file. A trick to always download a non-PE file is to mark its FileVersion=1,0,0,0 or some non-zero version in the INF section.

Order of Processing and Execution of INF

The [Add.Code] section is processed in the order listed, but the files are installed and set up in reverse order. This means that typically you would list the main OCX file first in the INF file, followed by dependent DLLs. The dependent DLLs are guaranteed to be installed and available at registration time of the main OCX.

Unconditional hooks, those hooks in the [Setup Hooks] section in the INF file, are executed in the order listed in that section (Hook1 executed before hook2). Conditional hooks, those hooks in the file sections referenced by file names in the [Add.Code] section, are executed in the order of the [Add.Code] section. Between conditional hooks and file section installation/setup, conditional hooks always get executed before file section installations/setups in the same CAB. Between two file section installations/setups, the order of file installation and setup is the reverse of the listing in the [Add.Code] section. Between two conditional hooks, the order is the same as that listed in the [Add.Code] section. Note this different ordering rule between conditional hooks and file section installation and setup.

When and How to Use Hooks

A hook is a way to override or customize the installation process of one or more pieces required for a component. There are two types of hooks, unconditional and conditional.

Unconditional hooks are hooks that always get executed. These are hooks mentioned in the [Setup Hooks] section of the Internet Component Download INF file. A good example of an unconditional hook is a setup program. The following is an example of a case using a custom setup program to install the component. Its packaging is as follows:

  1. CODEBASE= points to a foo.cab that contains a foosetup.exe, foo.ocx, and foo.inf file. foosetup.exe, when run with the /q parameter, will install foo.ocx silently in the windows\occache directory.
  2. foo.inf has:
    [Setup Hooks]
    hook1=hook1

    [hook1]
    run=%EXTRACT_DIR%\foosetup.exe /q

    [Version]
    ; This section is required for compatibility on both Windows 95 and Windows NT.
    Signature="$CHICAGO$"
    AdvancedInf=2.0

When the Code Downloader pulls down foo.cab, it trust verifies the cabinet and then processes the INF. Seeing that it has no [Add.Code], it processes the [Setup Hooks] section. It extracts all the files in foo.cab in a unique temporary directory and then runs the command line listed in the run= key. All the files left in the temporary directory after the completion of foosetup.exe including foosetup.exe are discarded. See section on "Component Downloader Variables" for details on the use of %EXTRACT_DIR% variable in the run= key.

Conditional hooks are run only when a certain condition evaluates as TRUE. This is typically when the [Add.Code] section points to a certain piece, and that piece is not available on the client's computer. The above example of foo.ocx could be rewritten using conditional hooks as follows:

  1. CODEBASE= points to a foo.cab that contains a foosetup.exe, foo.ocx, and foo.inf file. foosetup.exe, when run with the /q parameter, will install foo.ocx silently in the windows\occache directory.
  2. foo.inf has:
    [Add.Code]
    foo.ocx=foo.ocx

    [foo.ocx]
    Clsid={...}
    hook=hook1

    [hook1]
    run=%EXTRACT_DIR%\foosetup.exe /q

    [Version]
    ; This section is required for compatibility on both Windows 95 and Windows NT.
    Signature="$CHICAGO$"
    AdvancedInf=2.0

    When the Code Downloader sees the above INF, it processes the [Add.Code] section. When processing the foo.ocx section, it sees that the clsid (foo.ocx) is not registered/available on the client computer and so proceeds to execute the hook mentioned in the hook= key when it is hook1. Execution of hook1 is identical to the previous description of the hook as an unconditional hook. When only one component is in question, it doesn't make any difference whether marked conditional or unconditional as the whole code download was triggered because the CLASSID attribute in the OBJECT tag could not be found on the client computer. However, when installing a component that relies on some dependency that is separately installable by itself (such as MFC DLLs), it is good to use conditional hooks to install them.

    When mixing hooks and regular code download setups, read the section on "Order of processing and execution of INF".


Extending Internet Component Download Using OSD

Microsoft® Internet Explorer 3.0 introduced the Internet Component Download (ICD) mechanism. When visiting a Web page, ICD lets your browser pull down and install programs from the Internet automatically. This gave any software author or vendor the ability to package an application and place it on a server for download. But Internet Component Download, as implemented in Internet Explorer 3.0, was limited for the following reasons:

  • No support for Java class libraries
  • No support for stand-alone Java applications
  • INF files are not written according to any standard syntax or grammar
  • Old distribution units are limited in flexibility because they cannot adequately express software dependencies

Open Software Description (OSD) provides the Internet Component Download mechanism with the ability to download Java applications, Java packages, and ActiveX™ Controls. OSD also provides the ability to handle complex file dependencies that might be spread out over multiple distribution units on the Internet, and provides automatic installation of missing components.

For more information on Internet Component Download, see the Microsoft Internet Component Download documentation.

Supporting the Extended Functionality

Each distribution unit requires a single OSD file that contains the installation instructions for the application, just as an INF file does. The advantages of OSD are that it is more expressive than INF and it is being written in a standardized form.

An OSD file is supported in the following cases:

  • Inclusion in cabinet (CAB) files

    Exactly one file in the CAB can be an OSD file. The inclusion of an INF file in CAB is still supported for compatibility. Therefore, a CAB file should contain one OSD file, one INF file, or both an INF file and an OSD file. If both file types are present and your browser (for example, Microsoft Internet Explorer 4.0) knows about OSD files, the CAB is processed according to the following priorities:

    1. The parser looks inside the current CAB for the OSD file. If found, it is processed. It is also legal for the OSD file to reference the INF file. In this case, both files are processed, but notice that the OSD file is really in control here.
    2. If there is no OSD file present, the parser looks for an INF file to process.

    If your browser (for example, Internet Explorer 3.0) does not know about Open Software Description, the INF file is processed first because that is the only option.

  • In the CODEBASE attribute of the OBJECT element

    The CODEBASE attribute can now point to a stand-alone OSD file, which presents the same security/trust issue as having it point to a stand-alone INF file. Both of these are flat text and are not signable with Authenticode™ tools today, so component download will treat them as unsigned. Microsoft Internet Explorer will decline trust in the default browser security modes. One solution is to package the OSD file as the only file in a single CAB file and sign the CAB file.

OSD skeleton

All OSD files use the same basic skeleton. Each OSD file starts out with the Extensible Markup Language (XML) version identification and the documentation type declaration. The documentation type declaration includes the path to the OSD document type declaration (DTD) file, which describes all the elements that are supported by OSD.

The following example shows the XML version identification and documentation type declaration (with the actual location of the OSD DTD file).

<?XML version="1.0"?>
<!DOCTYPE SOFTPKG SYSTEM "http://www.microsoft.com/standards/osd/osd.dtd">

In many instances, the OSD file requires a richer vocabulary to describe the software or its dependencies. For example, describing native code or Java applications requires the elements defined in the Microsoft Internet Component Download DTD file. To include the Internet Component Download DTD file, an XML name space can be created that references that DTD file.

The following example shows how to create the XML name space msicd for the Internet Component Download DTD file.

<?XML::namespace href="http://www.microsoft.com/standards/osd/msicd.dtd" as="msicd"?>

The XML name space allows any of the elements defined in the Microsoft Internet Component Download Reference to be used in the following format:

msicd::<element>

where <element> is an element described in the reference.

The main section of an OSD file begins and ends with the SOFTPKG tag. The three major sections enclosed inside SOFTPKG are used to express installation instructions for Java code, native code (meaning that the files are platform-dependent), and dependency code (one program is used by another). The basic OSD skeleton looks like this:

<?XML version="1.0"?>
<!DOCTYPE SOFTPKG SYSTEM "http://www.microsoft.com/standards/osd/osd.dtd">
<?XML::namespace href="http://www.microsoft.com/standards/osd/msicd.dtd" as="msicd"?>

<SOFTPKG NAME="unique name of distribution" VERSION="4,0,5,0" STYLE="MSICD">
    <MSICD::JAVA> ... </MSICD::JAVA>
    <MSICD::NATIVECODE> ... </MSICD::NATIVECODE>
    <DEPENDENCY> ... </DEPENDENCY>
</SOFTPKG>

Integration with Java

Unlike INF files, OSD files support the inclusion of Java packages and stand-alone Java applications in a distribution unit. Specifically, this is done with the JAVA and PACKAGE tags.

<MSICD::JAVA>
    <PACKAGE NAME="com.ms.package.basic" VERSION="1,1,0,0">
    .
    .
    .
    </PACKAGE>
</MSICD::JAVA>

Relationship between OSD and INF

As mentioned previously, an OSD file is a markup tag file written according to XML syntax and grammar. An INF file is a file containing name-value pairs. Both serve the same purpose of specifying file dependency, program version number, and computer configuration information.

Using OSD to describe distribution units allows a cascading model, where one distribution unit can be dependent on others, which in turn can be dependent on others, and so on. In contrast, INF can express only one level of dependency. Allowing a component to specify dependencies at a high level allows installation details of dependencies to stay within their CABs versus cluttering the main OSD.

Pointing to an INF from the OSD

One can point to an INF in the same CAB as the OSD, for further processing of a subset of setup in the following manner. Setup capability, such as adding/modifying registry entries, advanced setup functionality in custom destination directories, and so on, is not available in the OSD syntax and so would require being pointed to by an accompanying INF file in the CAB.

<MSICD::NATIVECODE>
    <CODE NAME="Adventure Works Goodbye World"
    CLASSID="84D8E454-1000-1000-1000-45EA43332000"
    VERSION="1,0,0,0">
        <IMPLEMENTATION>
            <OS VALUE="win95" / >
            <CODEBASE FILENAME="goodby.inf" />
        </IMPLEMENTATION>
    </CODE>
</MSICD::NATIVECODE>

Sample OSD file sections

Building on the OSD Skeleton and Integration with Java sections, which contained small samples of what an OSD file looks like, this section will show examples of OSD usage.

Introducing the distribution

As previously mentioned, <SOFTPKG> and </SOFTPKG> are the opening and closing tags in the main section of an OSD file. This is analogous to the roles that <HTML> and </HTML> play in an HTML file. After the opening SOFTPKG, the TITLE and ABSTRACT elements are used to give a more verbose description of the distribution.

<?XML version="1.0"?>
<!DOCTYPE SOFTPKG SYSTEM "http://www.microsoft.com/standards/osd/osd.dtd">
<?XML::namespace href="http://www.microsoft.com/standards/osd/msicd.dtd" as="msicd"?>

<SOFTPKG NAME="unique name or GUID" VERSION="1,0,0,0" STYLE="MSICD">
    <TITLE>My Very First Distribution!</TITLE>
    <ABSTRACT>This software distribution will install
        my Hello World program written in C++</ABSTRACT>
    .
    .
    .
</SOFTPKG>

Setting the file location

Use the CODEBASE element to tell the client browser where the files are located. The simplest case is if the files are already in the same CAB as the OSD file. If this is the case, don't use CODEBASE at all. Your browser will automatically look in the current CAB.

If the files are somewhere on the Internet, make CODEBASE point to that URL.

<CODEBASE HREF=<A HREF="http://www.server1.com/install-me.cab">
    http://www.server1.com/install-me.cab</A> / >

Handling different computer setups

Use the IMPLEMENTATION element to indicate what type of hardware your code requires. The following example shows that the program "Adventure Works Hello World" version 1.1 is available for three types of computer setups: a PC running Microsoft Windows® 95, a PC running Microsoft Windows NT®, and a Macintosh® running MacOS.

<MSICD::NATIVECODE>
    <CODE NAME="Adventure Works Hello World"
    CLASSID="84D8E454-0001-0001-0001-45EA43332000"
    VERSION="1,1,0,0" >

        <IMPLEMENTATION>
            <OS VALUE="win95" />
            <CODEBASE HREF="<A HREF="http://www.programs-r-us/hello-
                95.cab">http://www.programs-r-us/hello-95.cab</A>" />
        </IMPLEMENTATION>

        <IMPLEMENTATION>
            <OS VALUE="winnt" />
            <CODEBASE HREF="<A HREF="http://www.programs-r-us/hello-
                95.cab">http://www.programs-r-us/hello-nt.cab</A>" />
        </IMPLEMENTATION>

        <IMPLEMENTATION>
            <OS VALUE="mac" />
            <CODEBASE HREF="<A HREF="http://www.programs-r-us/hello-
                95.cab">http://www.programs-r-us/hello-mac.cab</A>" />
        </IMPLEMENTATION>
    </CODE>
</MSICD::NATIVECODE>

Notice that the CODEBASE in each IMPLEMENTATION grouping actually points to different files on the server.

Setting dependencies

Following the example above, what if Adventure Works comes out with a new program called "Adventure Works Goodbye World." However, Goodbye World is really an extension of Hello World, so you have to have Hello World on your computer before Goodbye World works properly.

The following sample instructs your computer to get Hello World from the location indicated, and then get Goodbye World.

<SOFTPKG NAME="Adventure Works Goodbye World" VERSION="1,0,0,0" STYLE="MSICD">
    <MSICD::NATIVECODE>
        <CODE NAME="Adventure Works Goodbye World"
        CLASSID="84D8E454-1000-1000-1000-45EA43332000"
        VERSION="1,0,0,0">

        <IMPLEMENTATION>
            <OS VALUE="win95" / >
            <CODEBASE HREF="<A HREF="http://www.programs-r-us/hello-
                95.cab">http://www.programs-r-us/goodbye-95.cab</A>" />
        </IMPLEMENTATION>
        </CODE>
    </MSICD::NATIVECODE>

    <DEPENDENCY ACTION="install">
        <SOFTPKG NAME="Adventure Works Hello World" VERSION="1,1,0,0">
            <IMPLEMENTATION>
                <OS VALUE="win95" />
            <CODEBASE HREF="<A HREF="http://www.programs-r-us/hello-
               95.cab">http://www.programs-r-us/hello-95.cab</A>" />
            </IMPLEMENTATION>
        </SOFTPKG>
    </DEPENDENCY>
</SOFTPKG>

Letting OSD worry about all the dependencies means that users don't have to. They only know that they want the Adventure Works Goodbye World application. If there's anything that Goodbye World needs, it will be installed in the fly.

There are two types of dependencies. Notice that the above example has ACTION="install" as an attribute-value of DEPENDENCY. The other type is ACTION="assert".

For example, a user might be running Goodbye World version 1.0 and like it. When version 1.1 comes out, the user decides not to install it and stays with version 1.0. When patches or updates come out specifically for version 1.1 (which the user doesn't have), how does OSD know not to bother the user with these advertisements that don't pertain to him or her? By using ACTION="assert". The following code section shows how OSD can make an advertisement of a version 1.1 patch only to those people running that version.

<SOFTPKG NAME="Vocabulary Patch for Goodbye World version 1.1 only" VERSION="1,0,0,0">

<!-- put the MSICD::NATIVECODE/CODE/IMPLEMENTATION/CODEBASE here for the Vocabulary Patch -->

<DEPENDENCY ACTION="assert">
    <SOFTPKG NAME="Adventure Works Goodbye World" VERSION="1,1,0,0">
        <IMPLEMENTATION>
            <OS VALUE="win95" />
        </IMPLEMENTATION>
    </SOFTPKG>
</DEPENDENCY>
</SOFTPKG>

Therefore, if a computer does not satisfy the prerequisites (having Microsoft Windows 95 and Goodbye World v1.1) indicated in the DEPENDENCY section, it completely ignores this SOFTPKG. Thus the user is not unnecessarily bothered.

More on general OSD structure

The OSD Skeleton section mentions that the OSD file has three main sections: Java, Nativecode, and Dependency. Not all three sections need to appear in an OSD file; only the sections that are used need to be included. For example, if a software author is distributing a stand-alone Java application, the Nativecode and Dependency sections probably won't appear in the OSD.

Notice that the Java, Nativecode, and Dependency items share a similar structure when used in OSD.

<MSICD::JAVA>

<PACKAGE ...>

<IMPLEMENTATION>

<CODEBASE .../>

</IMPLEMENTATION>

</PACKAGE>

</MSICD::JAVA>

<MSICD::NATIVECODE>

<CODE ...>

<IMPLEMENTATION>

<CODEBASE .../>

</IMPLEMENTATION>

</CODE>

</MSICD::NATIVECODE>

<DEPENDENCY>

<SOFTPKG ...>

<IMPLEMENTATION>

<CODEBASE ... />

</IMPLEMENTATION>

</SOFTPKG>

</DEPENDENCY>

Processing order

The DEPENDENCY items to be installed are triggered in the order in which they appear in the OSD file, and they come with no guarantee on the order in which they will actually get installed. The only guarantee is that the dependencies will be installed before the main component in the SOFTPKG tag gets installed. If specific ordering dependencies are necessary, the components should be arranged in a tree fashion as dependency nodes where one can be assured that nodes deepest in the tree will get installed first.

CODE items under NATIVECODE get processed in the order in which they appear in the OSD, but they get installed and registered in the reverse of their order in the OSD. Thus dependent files should be placed below the CODE items that depend on them being available/installed. When the OSD is mixed with an INF (see Internet Component Download INF document for details), the order of processing between CODE items and items in the [Add.Code] section in the INF is as if the CODE items appeared before items in [Add.Code]. Packages under JAVA are installed before CODE items under NATIVECODE.


Microsoft Internet Component Download Overview

Internet Component Download is a system service for downloading and installing code from the Internet, and for certificate checking. This service is used by Microsoft® Internet Exporer to automatically download and install software from code repositories on the Internet. This section explains how code authors should prepare their software for automatic download. It then describes the interface for the component download mechanism, and finally provides some additional implementation details, including a description of the Internet Search Path service, which allows searching for code that can be downloaded.

The following topics are covered in this section:

Microsoft Internet Component Download Using INF
Extending Internet Component Download Using OSD


CLASS

<CLASS
 CLASSID="{id}"
 NAME="classname"
>

Specifies a class within a Java package.

CLASSID="{id}"
Unique identifier for the class file. For Microsoft® Internet Explorer, this value must be in GUID format {hhhhhhhh-hhhh-hhhh-hhhh-hhhhhhhhhhhh}, where "h" is a hexadecimal digit.
NAME="classname"
Required. Name of the class file. The ".class" file extension is required.

Number of allowed occurrences: Any number
Parent elements Child elements
PACKAGE ICON
ISBEAN
TYPELIB

Example

<CLASS NAME="Browserbean" CLASSID="{01234567-89AB-CDEF-0123-456789ABCDEF}">
    <ISBEAN />
    <ICON FILENAME="Browser.ico" />
    <TYPELIB CLASSID="{01234567-89AB-CDEF-0123-456789ABCDEF}" />
</CLASS>

The end tag </CLASS> is required.

Applies To

OSD


CODE

<CODE
 CLASSID="{id}"
 NAME="classname"
 VERSION="a,b,c,d"
>

Describes a specific instance of platform native code.

CLASSID="{id}"
Unique identifier for the component. For Microsoft® Internet Explorer, this value must be in GUID format {hhhhhhhh-hhhh-hhhh-hhhh-hhhhhhhhhhhh}, where "h" is a hexadecimal digit.
NAME="classname"
Required. File name containing the native code. The file name, usually a *.ocx or *.dll file, should be specified without the full path.
VERSION="a,b,c,d"
Major, minor, custom, and build version numbers. The default value is "0,0,0,0".

Number of allowed occurrences: Any number
Parent elements Child elements
NATIVECODE IMPLEMENTATION

Example

<CODE NAME="mycontrol.ocx"
CLASSID="{01234567-89AB-CDEF-0123-456789ABCDEF}"
    VERSION="1,1,1,0">
    .
    .
    .
</CODE>

The end tag </CODE> is required.

Applies To

OSD


ICON

<ICON
 FILENAME="file"
/>

Specifies an icon to be associated with a particular JavaBean.

FILENAME="file"
Name of an icon file to be associated with a particular JavaBean.

Number of allowed occurrences: None or one
Parent elements | Child elements
CLASS | None

Example

<ICON FILENAME="Browser.ico"/>

Applies To

OSD


ISBEAN

<ISBEAN/>

Indicates that a particular class is a JavaBean rather than a regular Java class.

Number of allowed occurrences: None or one
Parent elements | Child elements
CLASS | None

Example

<ISBEAN />

Applies To

OSD


JAVA

<JAVA>

Specifies either a Java PACKAGE or application.

Number of allowed occurrences: Any number
Parent elements Child elements
SOFTPKG PACKAGE

The end tag </JAVA> is required.

Applies To

OSD


NAMESPACE

<NAMESPACE>

Defines a private name space for stand-alone Java applications.

Number of allowed occurrences: None or one
Parent elements | Child elements
JAVA | None

Example

<NAMESPACE>string</NAMESPACE>

The end tag </NAMESPACE> is required.

Applies To

OSD


NATIVECODE

<NATIVECODE>

Specifies one or more platform native code distributions.

Number of allowed occurrences: None or one
Parent elements Child elements
SOFTPKG CODE

The end tag </NATIVECODE> is required.

Applies To

OSD


NEEDSTRUSTEDSOURCE

<NEEDSTRUSTEDSOURCE/ >

Indicates that the immediate caller of classes in this package needs to be fully trusted.

Number of allowed occurrences: None or one
Parent elements | Child elements
PACKAGE | None

Applies To

OSD


PACKAGE

<PACKAGE
 NAME="name"
 VERSION="a,b,c,d"
>

Specifies a Java package or Java application.

NAME="name"
Required. Name of the Java package.
VERSION="a,b,c,d"
Major, minor, custom, and build version numbers.

Number of allowed occurrences: Any number
Parent elements Child elements
JAVA IMPLEMENTATION
CLASS

The end tag </PACKAGE> is required.

Applies To

OSD


Microsoft Internet Component Download Reference

This Internet Component Download reference contains all the elements defined by the Msicd.dtd file. These elements are used to describe distribution units in Open Software Description (OSD) files.

To use these elements in OSD files, an XML (Extensible Markup Language) name space must be created using the following line in the OSD file:

<?XML::namespace href="http://www.microsoft.com/standards/osd/msicd.dtd" as="msicd"?>

To use the tags in the XML name space, prefix the tag with the name space name and two colons. For the JAVA tag, it would be used as follows:

<MSICD::JAVA>

All tags within name-space-defined tags must be defined in the name space and do not need to be prefixed with the name of the name space. Some of the elements defined in the Msicd.dtd file redefine elements that are defined in the Open Software Description Reference, so they can be used within the name space. For more information on OSD, see the Open Software Description (OSD) documentation.

MSICD Elements
CLASS CODE ICON ISBEAN
JAVA NAMESPACE NATIVECODE NEEDSTRUSTEDSOURCE
PACKAGE SYSTEM TYPELIB

MSICD Elements Also Defined in the Osd.dtd File
CODEBASE IMPLEMENTATION LANGUAGE OS
OSVERSION PROCESSOR SOFTPKG

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


SYSTEM

<SYSTEM />

When used as a child element of PACKAGE, indicates that the package contains system classes. System classes are fully trusted and have a single global instance per Java VM. Nonsystem classes have applet-level sandboxed security but may request other permissions if the distribution unit is signed.

When used as a child element of CODE, indicates that all files described by the CODE section should be installed in the designated system directory.

Number of allowed occurrences: None or one
Parent elements | Child elements
CODE | None
PACKAGE

Applies To

OSD


TYPELIB

<TYPELIB
 CLASSID="{id}"
/>

Specifies the type library file (*.tlb) for a particular JavaBean.

CLASSID="{id}"
Required. Unique identifier for the type library file associated with a particular JavaBean. For Microsoft® Internet Explorer, this file must be specified in GUID format {hhhhhhhh-hhhh-hhhh-hhhh-hhhhhhhhhhhh}, where "h" is a hexadecimal digit.

Number of allowed occurrences: None or one
Parent elements | Child elements
CLASS | None

Example

<TYPELIB CLASSID="{01234567-89AB-CDEF-0123-456789ABCDEF}" />

Applies To

OSD


Offline Browsing

Supporting Offline Browsing in Applications and Components

To further provide users with the best browsing experience, Internet Explorer 4.0 introduces offline browsing to the Win32 platform. Offline browsing allows users to view Web pages from the cache, a local repository of files gathered from the Web through normal browsing and the delivery of content subscriptions.

Understanding the Global Offline State

Application Development Considerations for Offline Browsing

Offline Considerations for Component Developers

Considering Backward Compatibility

Conclusion

Understanding the Global Offline State

In conjunction with this feature, users can choose to work offline by selecting the corresponding menu item from the File menu in Internet Explorer 4.0.

Once this item is selected, the system enters a global offline state independent of any current network connection, and content is read exclusively from the cache. If the content is not available locally, Internet Explorer 4.0 prompts the user to go online or to continue working offline.

The following document describes the API elements that enable third-party developers to hook into the offline browsing architecture. It also provides some recommendations to developers to help them provide a seamless experience to users.

Application Development Considerations for Offline Browsing

At the core of Internet Explorer 4.0 is URLMON.DLL and WININET.DLL. These DLLs handle all low-level requests made by the browser for Internet resources. Using the WININET and URLMON APIs, developers targeting Internet, Intranet, and Extranet environments can easily contribute to a positive offline browsing experience.

Determining the Global Offline State

Internet Explorer 4.0 uses URL Monikers which in turn uses the WININET API to perform all network requests including URL navigation and caching. WININET automatically checks the global offline state before making a resource request. If the system is globally offline, WININET attempts to retrieve the resource exclusively from the cache. If the resource is present, the request succeeds. Otherwise, the request fails. If the request fails, Internet Explorer 4.0 checks if the user is in the global offline state. An application can use the WININET InternetQueryOption function to check the global offline state.

   // Returns true if the global state is offline. Otherwise, false.
   BOOL IsGlobalOffline(void)
   {
      DWORD dwState = 0, dwSize = sizeof(DWORD);
      BOOL fRet = FALSE;

      if(InternetQueryOption(NULL,
         INTERNET_OPTION_CONNECTED_STATE, &dwState,
         &dwSize))
      {
         if(dwState & INTERNET_STATE_DISCONNECTED_BY_USER)
            fRet = TRUE;
      }
      return fRet;
   }

If the user explicitly chooses to navigate to unavailable content, Internet Explorer uses the WININET InternetGoOnline function to present the user with a dialog box that allows the user to "Connect" or "Stay Offline." If "Connect" is chosen, the function invokes InternetAutoDial. This function attempts to establish a network connection and, upon success, takes the system out of global offline mode. If InternetGoOnline succeeds, the system is connected and globally online. An application can then make the request for the resource again.

Here's some code that demonstrates the overall logic:

   // Cache the Internet handle if not already available.
   DWORD dwAccessType = INTERNET_OPEN_TYPE_PRECONFIG;
   DWORD dwInetOpenFlags = 0;

   hInternet = InternetOpen(
         "007",
         dwAccessType,
         NULL,
         NULL,
         dwInetOpenFlags);

   hFile = InternetOpenUrl(
         hInternet,
         szURL,
         NULL, 0, 0, 0);

   if (!hFile)
   {
      if (IsGlobalOffline())
      {
         // If globally offline, ask the user for permission to go online.
         if (InternetGoOnline(szURL, g_hwnd, INTERENT_GOONLINE_REFRESH))
         {
            // try again now that we're online
            hFile = InternetOpenUrl(
               hInternet,
               szURL,
               NULL, 0, 0, 0);
            if (!hFile)
            {
               InternetCloseHandle(hInternet);
               return;
            }
      }
   }

If the user chooses to go online and the second request fails, the resource simply may not exist as is the case when a user specifies a bad URL in the address bar or clicks on a stale hyperlink.

Detecting if Content is Locally Available

While it is essential that the user be presented with a dialog box before they are taken out of global offline mode, applications should make every effort to avoid bothering the user unnecessarily. When the user is viewing hyperlinks on a page, Internet Explorer 4.0 provides the user with a visual indicator, a small crossed-out circle attached to the cursor known as the offline hand, to indicate that the content is not available in the cache.

Not in Cache

By recognizing this cursor, the user is given the chance to preempt the "go online" dialog box. The following code can be used to determine if the content at a specified address is available locally.

   BOOL IsAvailableOffline(LPCWSTR wszUrl)
   {
      HRESULT hr;
      DWORD   dwUsesNet, dwCached;
      DWORD   dwSize;

      if (!wszUrl)
        return E_INVALIDARG;

      // First, let URLMON check the protocol scheme.
      hr = CoInternetQueryInfo(wszUrl,
            QUERY_USES_NETWORK,
            0,
            &dwUsesNet,
            sizeof(dwUsesNet),
            &dwSize,
            0);

      if (FAILED(hr) || !dwUsesNet)
         return true;

      // Then let URLMON peek in the cache.
      hr = CoInternetQueryInfo(wszUrl,
            QUERY_IS_CACHED_OR_MAPPED,
            0,
            &dwCached,
            sizeof(dwCached),
            &dwSize,
            0);

      if (FAILED(hr))
        return false;

      return dwCached;
   }

The offline hand is a cursor resource in SHDOCVW.DLL. The following code demonstrates how to load and display the cursor:

   HINSTANCE hInst = LoadLibrary("shdocvw.dll");
   hCursor = (HCURSOR)LoadCursor(hInst,
      MAKEINTRESOURCE(IDC_OFFLINE_HAND));
   if (hCursor)
      SetCursor(hCursor);

Setting the Global Offline Mode

A third-party can use the API elements presented above or implement their own. Given the user's explicit permission, here is how an application or component can change the offline mode of the system:

   void SetGlobalOffline(BOOL fGoOffline)
   {
      INTERNET_CONNECTED_INFO ci;

      memset(&ci, 0, sizeof(ci));
      if(fGoOffline)
      {
         ci.dwConnectedState = INTERNET_STATE_DISCONNECTED_BY_USER;
         ci.dwFlags = ISO_FORCE_DISCONNECTED;
      }
      else
     {
        ci.dwConnectedState = INTERNET_STATE_CONNECTED;
     }

     InternetSetOption(NULL,
         INTERNET_OPTION_CONNECTED_STATE, &ci, sizeof(ci));
   }

Typically, only application developers should attempt to manipulate the global offline state. Just as applications should minimize the interruption of the user's experience, component developers should focus upon seamless integration into their container's UI. The following section discusses how a specialized container, the Active Desktop, enables components to provide consistent behavior with minimal additional implementation requirements.

Offline Considerations for Component Developers

Internet Explorer 4.0 turns the user's desktop into a Web page by introducing the Active Desktop. Users can can add any content viewable in the browser as an item to the Active Desktop using the Web tab of the system's Display property sheet. Programmatically, Active Desktop items can be added using the IActiveDesktop interface. Custom components such as ActiveX controls and Java applets can be integrated into the Active Desktop by embedding them in content inserted into the Active Desktop.

Since the majority of users does not have a persistent connection to a network, components used as Active Desktop items should not make network requests when the user first logs in. A system configured for dialup use that is not in global offline mode will automatically present dialer UI or incur unexpected dial-up charges each time the user logs in. A control that ignores this recommendation will quickly lose popularity with users.

Understanding the Offline Ambient

The discussion regarding the global offline state makes it clear that applications and components that make calls through URLMON and WININET need not add any special flags to their requests to achieve offline behavior. Since the global offline state is an integral part of these low-level components, no attempt will be made to access the net when the system is globally offline. When the system is not globally offline, however, a network-aware component must consider the case where the system is disconnected from the Internet.

To help components that access network resources exhibit desirable behavior when embedded in the Active Desktop, Internet Explorer 4.0 introduces a new ambient property with a dispatch ID of DISPID_AMBIENT_OFFLINEIFNOTCONNECTED. Before attempting any network requests, an ActiveX control should retrieve the value of this ambient. If the ambient property is true, a component should check the connection state of the system using the WININET InternetGetConnectedState function. If the function indicates that the computer is disconnected, the control should add the appropriate offline flag in its requests to URLMON and WININET. This will prevent these APIs from displaying dialer UI. Note that a component is free to check the connected state and act appropriately regardless of the container in which they are embedded.

Detecting the Offline Ambient

A control need only retrieve the property once at initialization time through the IDispatch interface exposed by the container's client site. A control detects additional changes to all ambients via its implementation of IOleControl::OnAmbientPropertyChange. The following code shows how a control built using the Active Template Library (ATL) might implement this:

   #include <idispids.h>

   // Cache the container's OFFLINEIFNOTCONNECTED ambient.
   HRESULT GetAmbientOffline(LPUNKNOWN pUnkContainer,
              BOOL* pfAmbientOffline)
   {
      HRESULT hr;

      if (!pfAmbientOffline || !pUnkContainer)
         return E_INVALIDARG;

      *pfAmbientOffline = false;

      // Obtain container OA interface through its client site.
      CComQIPtr<IDispatch, &IID_IDispatch> spDisp(pUnkContainer);

    DISPPARAMS dispParams = {NULL, NULL, 0, 0};
    VARIANT vResult = {0};
    hr = spDisp->Invoke(
        DISPID_AMBIENT_OFFLINEIFNOTCONNECTED,
        IID_NULL,
        0,
        DISPATCH_PROPERTYGET,
        &dispParams,
        &vResult,
        NULL,
        NULL);

    if (SUCCEEDED(hr))
    {
         // Cache the value in a member variable.
         *pfAmbientOffline =
            (VARIANT_TRUE == V_BOOL(&vResult) ? true : false);

       VariantClear(&vResult);
       }
    return hr;
   }

   // Implementation of IObjectWithSite::SetSite:
   // Mostly delegates to ATL's default implementation
   // but additionally retrieves the ambient.
   STDMETHODIMP CAxOffl::SetSite(LPUNKNOWN pUnkSite)
   {
      HRESULT hr;
      if (SUCCEEDED(hr =
            IObjectWithSiteImpl<CAxOffl>::SetSite(pUnkSite))
        && pUnkSite)
      {
         hr = GetAmbientOffline(&m_AmbientOffline, m_spUnkSite);
      }

      return hr;
   }

   // Listen for notifications regarding changes to this ambient.
   STDMETHODIMP CAxOffl::OnAmbientPropertyChange(DISPID dispid)
   {
      HRESULT hr;

      if (dispid == DISPID_AMBIENT_OFFLINEIFNOTCONNECTED)
      {
       hr = GetOfflineIfNotConnected();
      }
      return S_OK;
   }

An ActiveX control that uses URL Monikers to make network resource requests should add BINDF_OFFLINE to the bind flags it returns via IBindStatusCallback::GetBindInfo as follows:

   void SetBindfFlags(BOOL fAmbientOffline, LPDWORD  grfBINDF)
   {
      if(fAmbientOffline)
      {
         DWORD dwConnectedStateFlags;
         if((!(InternetGetConnectedState(&dwConnectedStateFlags, 0)))
            &&
              (0 == (dwConnectedStateFlags &
                             INTERNET_CONNECTION_MODEM_BUSY)))
         {   // use the cache
            *grfBINDF |= BINDF_OFFLINEOPERATION;
            *grfBINDF &= ~BINDF_GETFROMCACHE_IF_NET_FAIL;
         }
         else // Use the net; cache if net request fails.
         {
            *grfBINDF |= BINDF_GETFROMCACHE_IF_NET_FAIL;
            *grfBINDF &= ~BINDF_OFFLINEOPERATION;
         }
      }
   }

Similarly, an ActiveX control that uses WININET should add INTERNET_FLAG_OFFLINE to the flags it passes to InternetOpen.

   void SetInetOpenFlags(BOOL fAmbientOffline, LPDWORD pdwOpenFlags)
   {
      // A component should first and foremost pay attention to
      // the offline ambient provided by its container.
      if  (fAmbientOffline)
      {
         DWORD dwConnectedStateFlags;
         BOOL fIsConnected =
            InternetGetConnectedState(&dwConnectedStateFlags, 0);

         // If not connected and not because the line is busy.
         if ( (!fIsConnected) && (0 ==
           (dwConnectedStateFlags & INTERNET_CONNECTION_MODEM_BUSY)))
         {
            // use the cache exclusively
            *pdwOpenFlags |= INTERNET_FLAG_OFFLINE;
        *pdwOpenFlags &= ~INTERNET_FLAG_CACHE_IF_NET_FAIL;
         }
         else
         {
            // Do not treat this as an offline operation
            // but use the cache if the net request fails.
        *pdwOpenFlags |= INTERNET_FLAG_CACHE_IF_NET_FAIL;
            *pdwOpenFlags &= ~INTERNET_FLAG_OFFLINE;
         }
      }
   }

While an application developer can use discretion in setting the bind flags by independently displaying a UI if a site is inaccessible, a control should always make an offline request to the URLMON or WININET APIs when it determines the system is disconnected from the network and the OFFLINEIFNOTCONNECTED ambient is set to TRUE. Contrary behavior will result in a repeated, unsolicited online request UI to be presented to the user.

Considering Backward Compatibility

Component authors who wish to maintain compatibility with previous versions of Internet Explorer should use dynamic rather than static linking when calling functions such as InternetGetConnectedState. This call was not available in Internet Explorer 3.0x. The following code demonstrates how to load and call InternetGetConnectedState without statically linking to WININET.LIB.

   typedef  BOOL (WINAPI* PFNINTERNETGETCONNECTEDSTATE)(LPDWORD, DWORD);

   HRESULT DynInternetGetConnectedState(LPDWORD pdwFlags)
   {
      PFNINTERNETGETCONNECTEDSTATE pfnInternetGetConnectedState;
      BOOL fConnected;

      if (!pdwFlags) return E_INVALIDARG;

      HMODULE hModule = LoadLibrary("wininet.dll");
      if (!hModule)
         return E_FAIL;

      pfnInternetGetConnectedState =
         (PFNINTERNETGETCONNECTEDSTATE)GetProcAddress(hModule,
            "InternetGetConnectedState");

      if (!pfnInternetGetConnectedState)
         return E_FAIL;

      fConnected = (*pfnInternetGetConnectedState)(pdwFlags, 0);

      FreeLibrary(hModule);
      return (fConnected ? S_OK : S_FALSE);
   }

If the component implementing this function is hosted in Internet Explorer 3.0x, the call to GetProcAddress will return NULL, and DynInternetGetConnectedState will return E_FAIL. The component can then either make the network request regardless of the connected state or execute its own code to determine the state using sockets.

Conclusion

Internet Explorer 4.0 extends the browsing experience by providing offline services to application and component developers authoring for the Win32 platform. Through the use of this infrastructure, users can look forward to consistent behavior online and offline among all network-savvy applications and components.


Open Software Description (OSD)

The Open Software Description (OSD) is a format based on the Extensible Markup Language (XML). OSD uses unique XML tags to describe software components, including their versions, underlying structure, relationships to other components, and dependencies.

Open Software Description Overview

Open Software Description Reference


How to Automatically Update an ActiveX Control

  1. Create an \osd\GenericSample share off the root directory of your Web server. If you are using the Personal Web Server on your local computer, create a directory (\osd) under the \Webshare\Wwwroot directory and then create a subdirectory (\GenericSample) under the \osd directory.
  2. Copy the contents of the \samples\osd\GenericSample directory of the Internet Client SDK refresh package into the share.
  3. Update the HREF attribute of the CHANNEL element in circ3_orig.cdf, circ3_adv.cdf, and circ3_pc.cdf by replacing <your server> with the name of your actual server.
  4. Copy the updated version of circ3_orig.cdf as circ3.cdf in the same share.
  5. Open Microsoft® Internet Explorer 4.01 or later and browse to circ3.htm (which will install the Circle ActiveX™ Control version 1).
  6. Subscribe to circ3.cdf by clicking the addchannel.gif (1685 bytes) link.
    • If you are subscribing a user to an automatic subscription, it is important to obtain the user's consent first.
    • Click Customize to configure Internet Explorer to either send an e-mail notification upon new software availability, or choose a custom schedule to tell Internet Explorer when to check for new software. You can set schedules in the CDF file with the SCHEDULE tag under CHANNEL.
    • The circ3.cdf file has a tag that specifies it should be displayed in Internet Explorer under the Favorites/Software Updates folder.

Now assume you have a new build, build 2, of Circle ready to roll out. You want to automatically upgrade all build 1 users as soon as they hit any page that uses the Circle control.

Note This can also be used for a new version, but the control used in this example had only two builds of the same version available.

  1. Copy circ3_pc.cdf on top of circ3.cdf. (Alternatively, use circ3_adv.cdf instead of circ3_pc.cdf if you don't want to automatically preload the user's cache with the bits. Preload does not mean autoinstall; Microsoft Internet Explorer just caches the new bits so the user can later install the control faster and even while offline). The new CDF advertises version 2 of the Circle control.

    Note To run this demonstration again, you must copy circ3_orig.cdf back on top of circ3.cdf. You will also have to copy circ3_v1.cab on top of circ3.cab.

  2. Copy circ3_v2.cab on top of circ3.cab. This is exactly the same as the real-life situation where the external world sees only circ3.cab but you have circ3_v1.cab (version 1) and circ3_v2.cab (version 2). When you update to version 2, you don't want version 1 available anymore, so you copy circ3_v2.cab over circ3.cab, the external distribution cabinet file.
  3. On the client computer, first make sure that the zone you are in is set for Custom. Under ActiveX Controls And Plugins/Download Unsigned ActiveX Controls, select Enable. Note that this is needed only for the demonstration file because the CABs are not signed; if they were signed, this would not be needed. Then select Favorites/Update All Subscriptions, or right-click the Circle channel (under Favorites/Software Updates) and select Update Now. Note that if the CDF had set an automatic schedule, this update would have happened automatically like any other subscription in Internet Explorer.
  4. The Circle channel icon will gleam (red gleam on upper-left corner of the icon). If you set up the e-mail notification during subscription, you will receive an e-mail notifying you of the updated software. When the user clicks the Circle channel, Internet Explorer will navigate to the home page of the channel. This page has instructions on how to download/install the new version of Circle (in this case just a link to an HTML page with the OBJECT element for the new version of Circle).
  5. Alternately, if you return to view circ3.htm (or any page that uses the Circle ActiveX Control version 1), the client will be automatically upgraded to version 2 because Internet Explorer knows that version 2 is available. In this simple example, note that the only way to see the version difference between the two Circle controls is to view the properties on the Circle control in the Downloaded Program Files directory.


Automatically Updating ActiveX Controls

Situation: Your company develops CoolControl, an ActiveX™ control, and user Joe has version 1.0 of CoolControl installed on his system. Joe originally downloaded this control when he visited Site Y, where he also subscribed to a software update channel to automatically receive new versions of this control. Now you have developed version 2.0 of CoolControl and you want all users of CoolControl 1.0 to upgrade. The next time Joe visits any site that uses the CoolControl (including Site Y), he will automatically have CoolControl 2.0 installed from the site of your choice (or even precached so he can install the control offline).

How to Automatically Update an ActiveX Control Using a Software Update Channel


Setting Language Dependency Using OSD

  • Deliver localized language versions of applications/controls to the appropriate language systems automatically through code download.
  • Allow users to download and preview English versions of applications/controls, and provide an automatic notification/download of users' language version when it becomes available (replacing their English version should they choose to do so).
  • Make it easy for developers to author and for PMs to manage.
  • Ensure that the mechanism does not break download on Microsoft® Internet Explorer 3.0.

The model is based on a data file (an OSD file) housed in a signed cabinet (CAB) file (for security) that specifies which languages and platforms the application supports and at which location.

This OSD is alone in a main CAB placed in the GUID directory for the control/application on the object store or at some code base URL location. The OSD tells Internet Component Download which languages are available under the DEPENDENCY element by specifying sections for those languages.

If the specific language CAB is empty or not found and English is supported, code download proceeds to download the English version of the control/application. The next time this object is referenced, Internet Component Download checks the LanguageCheckPeriod default value (expressed in days and implemented by the control/application itself in the OSD). Internet Component Download compares the downloaded date plus elapsed days with the current date to decide whether to download the main CAB again to check for language updates. If the language has become available, Internet Component Download shows a certificate to the user and downloads the localized control (not really informing the user what it's up to).

Applications should make sure they place all the language values they intend to support in the DllRegisterServer routine or in an INF file in the main CAB's OSD from the very beginning. This ensures an appropriate placeholder is put in the registry for future upgrading when the language version matching the browser becomes available. Internet Component Download (code download) looks up the language of the browser by checking the version information of Shdocvw32.dll and compares it to the semicolon-delimited IS01739 name language section. If a match is found, CDL downloads the CAB.

If the specific language CAB is empty or not found and English is not supported (only German, for example), the download will proceed by following the same path as an unmet dependency would in Internet Component Download (an empty box is displayed in the HTML).

Notes:

  • Avoiding repeated certificates.

    A variance between languages is allowed in the amount of time until the version becomes available through the LanguageCheckPeriod key with DWORD values.

    [LanguageCheckPeriod]
                EN   	1
                FR 	5
                ES	30
                JA	60
                DE	30
                KO	90
                ZH-CN	120
                ZH-TW	120

    The number inside the language would specify how much time to allow before checking again for that particular language. This is easy to implement, provides flexibility, and minimizes the certificate downloads for the user.

  • Default language.

    The language version is housed in an object referenced by the default IMPLEMENTATION element.

  • Applications/controls must implement the check period values in the OSD file.

    It's up to the application to implement the LanguageCheckPeriod key under its CLSID. This should be done in the DllRegisterServer routine or in an INF placed in the main data CAB. In the absence of this, given a mismatch, Internet Component Download defaults to 30 days.

Wins:

  • No confusing user interface for the user to have to respond to.
  • The appropriate language version of the control/application is delivered automatically, based on the user's browser language.
  • Easy to administer for the PM through a single OSD in a single CAB.
  • Download hits on the server and time on the net for users is minimized, while letting them preview the application/control in English until their language version becomes available.
  • Method falls within the OSD model using XML, which is maintainable over time.
  • Application/control developers do not have to use satellite localization with complicated dependencies. They have separate CABs for each language.

Constructing CABs for Multiple Languages

To support multiple languages, two types of CAB files need to be present:

  • Main data CAB
  • Individual language CABs

Main data CAB

The main data CAB consists of three text files:

  • INF file to allow installation on Internet Explorer 30
  • INF file to set a language check period
  • Main OSD file

The main OSD file contains the different language implementation information, as well as the locations of the individual language CABs.

You will need to edit these files as languages become available by adding IMPLEMENTATION sections.

The following is an example of the main OSD file.

<?XML version="1.0"?>
<!DOCTYPE SOFTPKG SYSTEM "http://www.microsoft.com/standards/osd/osd.dtd">
<?XML::namespace href="http://www.microsoft.com/standards/osd/msicd.dtd" as="msicd"?>

<SOFTPKG NAME="{039397C0-46DF-11D0-99CB-00C04FD64497}" VERSION="4,3,0,2077" >
    <Title>MS Chat</Title>
    <MSICD::NativeCode>
        <Code NAME="MsChatPr.ocx" CLASSID="clsid:039397C0-46DF-11D0-99CB-00C04FD64497"
            VERSION="4,3,0,2077">
    <IMPLEMENTATION>
        <LANGUAGE VALUE="ja" />
        <Processor VALUE="x86" />
        <Codebase HREF="JaChatPr.cab" />
    </IMPLEMENTATION>
    <IMPLEMENTATION>
        <LANGUAGE VALUE="de" />
        <Processor VALUE="x86" />
        <Codebase HREF="DeChatPr.cab" />
    </IMPLEMENTATION>
    <IMPLEMENTATION>
        <Processor VALUE="x86" />
        <Codebase HREF="EnChatPr.cab" />
    </IMPLEMENTATION>
        </Code>
    <Code NAME="RegEntry">
        <IMPLEMENTATION>
           <Codebase FILENAME="langchk.inf" />
        </IMPLEMENTATION>
    </Code>

    </MSICD::NativeCode>
</SOFTPKG>

The following is a sample INF file to set the language check period.

; Copyright (c) 1996 Microsoft Corporation

[Version]
Signature="$Chicago$"
AdvancedINF=2.5

[DefaultInstall]
AddReg=IEIntl.Add.Reg

[DefaultInstall.NT]
AddReg=IEIntl.Add.Reg

[IEIntl.Add.Reg]
HKCR,%MSCHATCHECK%,"DE",3,"5"
HKCR,%MSCHATCHECK%,"JA",3,"5"
HKCR,%MSCHATCHECK%,"FR",3,"15"
HKCR,%MSCHATCHECK%,"KO",3,"15"
HKCR,%MSCHATCHECK%,"TW",3,"15"
HKCR,%MSCHATCHECK%,"",,"Enabled"

[Strings]
MSCHATCHECK = "CLSID\{039397C0-46DF-11D0-99CB-00C04FD64497}\LanguageCheckPeriod"

Individual language CABs

The individual language CABs contain the following files:

  • Specific language version of object
  • Object OSD file

The object OSD file would contain the information on how to install this language version, including any code dependencies and so on.


Open Software Description Overview

Open Software Description (OSD) provides the vocabulary to do software updates through the Internet. Microsoft® Internet Explorer 4.01 provides some enhancements to this support (for more information on these changes, see Changes in Microsoft Internet Explorer 4.01). When new versions of your software become available, OSD provides a mechanism, known as publishing, to notify the user. In addition, OSD provides the functionality to describe in great detail how to install ActiveX™ Controls, and Java packages and class files.

The OSD vocabulary is used in these ways:

Automatically Notifying Users of New Versions
Updating ActiveX Controls Whenever New Versions Are Available
Extending Internet Component Download
Extending the Channel Definition Format (CDF)

Changes in Microsoft Internet Explorer 4.01

The following table briefly summarizes the changes between Microsoft Internet Explorer 4.0 and Microsoft Internet Explorer 4.01.
Feature | 4.0 | 4.01
Advertise new application version | yes | yes
Precache new application version | yes | yes
OSD-aware shortcuts | no | yes
ActiveX control precache | yes | yes
ActiveX channel upgrade | no | yes
OSD-based Java install | yes | yes

Note Internet Explorer 4.0 is able to precache an ActiveX control only if an OBJECT tag uses the same code base as the software update channel.

Automatically Notifying Users of New Versions

OSD can be used to automatically notify the user when a new version is available, if the user is subscribed to the appropriate software distribution channel. This notification occurs when the user launches the application from the shortcut (.lnk). The new version can be precached in the Internet Explorer cache, waiting to be installed offline or online when the user chooses to upgrade.

This feature is available to applications that:

  • Meet Designed for Microsoft Windows Logo Program (version 3) requirements.
  • Include the MajorVersion and MinorVersion registry keys.
  • Can be uninstalled.

For an example of how to use OSD to automatically notify users of new versions, see Publishing Applications to the Internet Using OSD.

Updating ActiveX Controls Whenever New Versions Are Available

If an ActiveX control is available on the user's computer and the user is subscribed to that control's software update channel, OSD allows the system to automatically update the control with a newer version as soon as the user browses to any Web site that uses that control.

For an example of how to use OSD to automatically update an ActiveX control, see Automatically Updating ActiveX Controls Using Software Update Channels

Extending Internet Component Download

In Microsoft Internet Explorer 3.0, the installation and dependency information for software (usually used for ActiveX Controls) was contained in an INF file. For Microsoft Internet Explorer 4.0, using OSD provides three main advantages:

  • Ability to describe Java packages. Internet Explorer 4.0 can distribute and install Java packages and applications using OSD to describe the distribution unit.
  • Handle complex dependencies. INFs are limited in that they can express only one level of dependency. Using OSD, Internet Explorer 4.0 can process software dependencies of any depth or recursion.
  • Filter criteria for a heterogeneous network. In addition to describing software, OSD can describe the operating requirements of the software. These requirements include:
    • Processor type
    • Operating system
    • Language

For more information on adding language dependencies using OSD, see Setting Language Dependency Using OSD. For more information on extending Internet Component Download, see Extending Internet Component Download Using OSD in the Internet Component Download documentation.

Extending the Channel Definition Format (CDF)

CDF provides the vocabulary for describing a channel, or an automatic distribution of Web content. OSD adds the vocabulary necessary for describing software packages. In Microsoft Internet Explorer, recognizing OSD tags in a CDF file allows automatic software updates. An application of this concept is the Microsoft Internet Explorer 4.0 Software Updates channel itself. This channel is a CDF that contains additional OSD tags.


Publishing Applications to the Internet Using OSD

This article describes how to use Microsoft® Internet Explorer 4.01 support for the Channel Definition Format (CDF) and Open Software Description (OSD) to publish applications to the Internet.

This article describes how to:

  • Prepare the application so it can utilize this functionally.
  • Create a software update channel (described by a CDF file), which your users will subscribe to in order to receive updates.
  • Utilize the OSD vocabulary inside the CDF file to describe new versions of your software.

Notes and Requirements

  • This document applies to applications, not ActiveX™ Controls or Java applets. For more information about updating an ActiveX control, see the Automatically Updating ActiveX Controls Using Software Update Channels article. For more information about Java applets, see the Extending Internet Component Download Using OSD article.
  • Users must have the Enable Scheduled Subscription Updates option set, or they must manually update their subscriptions to allow Internet Explorer 4.01 to check for updates. This option is enabled by default.

Preparing the Application

Before creating a software update channel, the application should be prepared to handle two tasks:

  • Modifying the registry during setup to allow Internet Explorer to maintain the users' security settings and update their subscription to your channel.
  • Modifying the shortcut to enable update notifications to be displayed to users when they use that shortcut to access your application. This step is necessary only if you want the software update dialog box to appear when using the shortcut to the application when an update is available.

Modifying the Registry to Maintain the User's Security Settings

Because your users are receiving updates through the Internet, Internet Explorer respects the URL Security Zone setting you are in when making the software update. The behavior is as follows.
Security Zone level for your site | Software update channel behavior
High | No software update functions available
Medium | Requires the AuthorizedCDFPrefix (see below)
Low | All software update functions available

For the medium setting, you must (during your installation routine) set the AuthorizedCDFPrefix key in the registry for your particular AppName (the Microsoft Application Logo 5 name). This authorizes particular URLs to notify the user of updates. The reason for this is security. By entering the URLs that are authorized to update your software, you prevent rogue sites from publishing false updates.

AuthorizedCDFPrefix is a new key you must create under the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\<Your App Name> branch of the registry. Any number of new string values is added to this key, each of which represents a location where Internet Explorer can get software updates. For example, if one of the strings is "http://testserver", any URL beginning with these letters is authorized to publish software updates. If you want to allow any site to publish updates, you can simply use "http:" as the string.

Modifying the shortcut

In either the installation process for the software or the initial launch of the application, the shortcut to the application must be modified so that the system will be able to notify the user of any updates. This also requires Internet Explorer 4.01 to work.

Note Microsoft Installer (MSI) technology, which will be released in the near future, automatically generates modified shortcuts.

To modify the shortcut, you must do one of following:

  • Call the following Windows® function inside your installation code (or on the very first execution of your program) to create the shortcut:
    IShellLink::SetPath(::{9db1186f-40df-11d1-aa8c-00c04fb67863}: AppName :: Path);

    In this function, ::{9db1186f-40df-11d1-aa8c-00c04fb67863}: is a special identifier that should be used as listed; AppName is the name of your application in the registry's uninstall branch under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\<Your App Name>, and Path is the path to the program (the normal target of the shortcut).

  • "Bless" your shortcut after it is created using the Blesslnk tool provided by Microsoft in the \bin directory of the Internet Client SDK 4.01 refresh package. After placing your shortcut on the user's computer, you must run the following command:
    Blesslnk -l AppName FullPath

    where AppName is the name of your application in the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\<Your App Name> branch of the registry, and FullPath is the full directory path to the shortcut.

Creating the Software Update Channel

Creating your own software update channel for Internet Explorer 4.01 is extremely easy. Simply use the following example, replacing the information with your own by following the simple steps below.

<?XML version="1.0"?>

<CHANNEL HREF="http://testserver/logo5/logo5.htm">
    <TITLE>Green (MSAppLogo5) Test Channel</TITLE>
    <LOGO HREF="http://testserver/logo5/green.ico" STYLE="icon"/>
    <USAGE VALUE="SoftwareUpdate"/>
    <SOFTPKG HREF="http://testserver/logo5/logo5.htm"
        NAME="{55272F7E-1B37-11D1-8933-00805F8A4D63}"
        VERSION="1,1,0,1"
        STYLE="MSAppLogo5"
        PRECACHE="yes">
        <TITLE>Green</TITLE>
        <ABSTRACT>Abstract: Green v1.1 application installed via channel</ABSTRACT>
        <IMPLEMENTATION>
            <CODEBASE HREF="http://testserver/logo5/green-x.exe" />
        </IMPLEMENTATION>
    </SOFTPKG>
</CHANNEL>

Make these changes to customize this example for your own software update channel:

  1. Replace CHANNEL HREF to point to a URL that you want users to be sent to when they first subscribe to the channel and when they click the channel in the future.
  2. Change the TITLE to your own. This will show up in the Internet Explorer Favorites/Software Updates folder. This is usually your software's title plus the words "Update Channel".
  3. The LOGO is shown next to the TITLE in the Internet Explorer Software Updates folder. Choose your own custom icon or delete this tag (from <LOGO to />) to use the default satellite dish logo from Internet Explorer.
  4. Replace SOFTPKG HREF to point to a URL that you want users to be sent to when an update is available. Initially (before there's a new version), if you don't know where the new information will be posted, you can point this to the same location as used for the CHANNEL HREF.
  5. Change the NAME to either a GUID (as shown) representing your software or to the application's name in the Uninstall branch of the registry (not the friendly name). If you don't know the name, run Regedit and look at HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall to find the name. It will be listed under the Uninstall branch on the left.
  6. Change the VERSION number to your own. The version "a,b,c,d" is a.b.d.
  7. Change the PRECACHE to "no" if you do not want Internet Explorer to automatically receive the update at the subscription update time (either way, Internet Explorer will not install the update; it will simply make it available offline on the user's computer if you leave PRECACHE on).
  8. Change the TITLE to reflect your software's name. This will be shown in the update dialog box when the user is notified of an update.
  9. Change the ABSTRACT to give the user a description of the software. This will also be shown in the update dialog box.
  10. Change the CODEBASE to point to the URL of your software. This can point to a CAB or an EXE file. This does not point to an HTML page.

When you are done with these easy steps, put the CDF file on your Web server and request your users to subscribe to this channel when they come to your page. Your text can say, "Click here to subscribe to a channel to receive notifications of future updates of this software. You will remain anonymous, and we will not give out your name and address."

Handling Updates

In the future, when the new version is available, you will need to change the CDF file on your Web server. On the next subscription update on your users' computers, they will get the new CDF. Make the following modifications:

  1. Change the VERSION number to a larger number.
  2. Either overwrite the old CAB, EXE, or other file pointed to by the CODEBASE element with the new file, or change the CODEBASE to point to the new file.
  3. Replace the SOFTPKG HREF to point to the URL that you want the user to be sent to in order to read about the features and installation instructions of the new software.

After the next subscription update, the users can be notified of the new software in two ways:

  • If the shortcut to the application was modified, an update box (like the one below) will appear when they execute the shortcut to the application.

    Software Update Dialog Box

    Note that this requires the user to be running Internet Explorer 4.01 with the Windows Desktop Update. In addition, it requires a modification to the shortcut to your program.

  • In Internet Explorer, under Software Updates, there will be a gleam on your channel like the one shown here on the Circle Control channel.

    Sample Software Update Menu

    When the user clicks the gleaming channel, he or she will be taken to the page described by the <SOFTPKG HREF=http://testserver/your_update_page.htm> tag to read about the update. This page is also the page used to set up the program.

You can use this example with your own software update channel to get up and running very quickly.

For additional information about the OSD vocabulary, see the specification at http://www.microsoft.com/standards/osd. For additional information on CDF, see the specification at http://www.microsoft.com/standards/cdf-f.htm.


ABSTRACT

<ABSTRACT>

Specifies a short summary, or headline, describing the software contained in the distribution unit.

Number of allowed occurrences: None or one
Parent elements | Child elements
IMPLEMENTATION | None
SOFTPKG

The end tag </ABSTRACT> is required.

Example
<ABSTRACT>Enter the short summary or headline here.</ABSTRACT>
Applies To

OSD


CODEBASE

<CODEBASE
FILENAME="file"
HREF="url"
SIZE="n"
STYLE="ActiveSetup" | "MSICD"
/>

Specifies the location of the file or distribution unit to be installed.

FILENAME="file"
Name of the codebase. When this attribute is used, the file is expected to exist in the same archive (CAB file) as the OSD file.
HREF="url"
URL of the codebase. When this attribute is used, the file is expected to exist on the network. Note that either fully qualified or relative URLs are allowed.
SIZE="n"
Maximum allowable size for the distribution unit. The number is given in kilobytes (K). If SIZE is exceeded, the distribution unit will not be downloaded. If SIZE is not specified, no kilobyte limit is enforced. This attribute is valid only within CDF files.
STYLE="ActiveSetup" | "MSICD"
Mechanism the computer uses to download and install files from the Internet. This attribute is valid only within CDF files.
"ActiveSetup" | Uses the ActiveX™ "Active Setup" engine.
"MSICD" | Uses the Microsoft® Internet Component Download (MSICD) to download distribution units and look at the Open Software Description (OSD) file for processing instructions. To use Internet Explorer 3.0 processing procedures, the distribution unit can contain a *.inf file.

Number of allowed occurrences: None or one
Parent elements | Child elements
IMPLEMENTATION | None

When contained within a DEPENDENCY block, only the HREF attribute is used. If no CODEBASE is specified, Internet Explorer checks the object store for the distribution unit. When used as a child element of a NATIVECODE or JAVA block and no CODEBASE is specified, Internet Explorer checks the current distribution unit for the files to be installed.

Applies To

CDF, OSD


DEPENDENCY

<DEPENDENCY
 ACTION="Assert" | "Install"
>

Specifies an additional distribution unit that needs to be present for the software distribution (SOFTPKG) to function correctly.

ACTION="Assert" | "Install"
Action to take if the required distribution unit is not present on the user's computer. When set to "Install", the required files should be downloaded and installed so the software distribution can be processed without errors. When set to "Assert", the SOFTPKG is ignored if the distribution unit is not already on the computer. This is the default. This attribute is valid only in the context of an OSD file. For a CDF file, the value "Assert" is automatically assumed.

Number of allowed occurrences: Any number
Parent elements Child elements
SOFTPKG SOFTPKG

The end tag </DEPENDENCY> is required.

Applies To

CDF, OSD


DISKSIZE DISKSIZE *
  * Previous Topic: DEPENDENCY
  * Next Topic: IMPLEMENTATION

DISKSIZE

Not currently implemented.


IMPLEMENTATION

<IMPLEMENTATION>

Specifies the configuration required by the current software distribution. If the configuration parameters are not met, the SOFTPKG element is not processed.

Number of allowed occurrences: Any number
Parent elements Child elements
CODE CODEBASE
PACKAGE LANGUAGE
SOFTPKG OS
PROCESSOR

The end tag </IMPLEMENTATION> is required.

Example

<SOFTPKG
    HREF="http://www.bar.edu/launch-page.htm"
    NAME="The Second Sample"
    AUTOINSTALL="Yes"
    VERSION="2,1,0,0"
    STYLE="MSICD">

    <TITLE>A second sample software distribution</TITLE>
    <ABSTRACT>This software distribution will be auto-installed on your computer by default.
        The user can override the default settings in the subscription wizard. Needs
        "The First Sample" already installed to work.
    </ABSTRACT>
    <LOGO HREF="ielogo.gif" STYLE="image" / >
    <LANGUAGE VALUE = "en;de" / >
    <USAGE VALUE="email"></USAGE>

    <IMPLEMENTATION>
        <OS VALUE="winnt" />
        <CODEBASE VALUE="http://www.bar.edu/bar/bar-nt.cab" / >
    </IMPLEMENTATION>

    <IMPLEMENTATION>
        <OS VALUE="win95" />
        <CODEBASE VALUE="http://www.bar.edu/bar/bar-95.cab" / >
    </IMPLEMENTATION>

    <DEPENDENCY>
        <SOFTPKG NAME="The First Sample" VERSION="2,1,0,0" / >
    </DEPENDENCY>

</SOFTPKG>

Applies To

CDF, OSD


IMPLTYPE IMPLTYPE *
  * Previous Topic: IMPLEMENTATION
  * Next Topic: LANGUAGE

IMPLTYPE

Not currently implemented.


LANGUAGE

<LANGUAGE
VALUE="language"
/>

Specifies a semicolon-delimited list of RFC 1766 language codes used for international distribution.

VALUE="language"
Required. One or more codes that indicate which languages the software's user interface supports. For example, the code "en" indicates English.

Number of allowed occurrences: Any number
Parent elements | Child elements
IMPLEMENTATION | None
DEPENDENCY
SOFTPKG

Example

<LANGUAGE VALUE="en"/>

Applies To

CDF, OSD


LICENSE LICENSE *
  * Previous Topic: LANGUAGE
  * Next Topic: MEMSIZE

LICENSE

Not currently implemented.


MEMSIZE MEMSIZE *
  * Previous Topic: LICENSE
  * Next Topic: OS

MEMSIZE

Not currently implemented.


OS

<OS
 VALUE="Mac" | "Win95" | "Winnt" />

Specifies the operating system the software supports.

VALUE="Mac" | "Win95" | "Winnt"
Required. Supported operating system.
"Mac" | Macintosh® (MacOS)
"Win95" | Microsoft® Windows® 95
"Winnt" | Microsoft® Windows NT®

Number of allowed occurrences: Any number (per parent element)
Parent elements Child elements
IMPLEMENTATION OSVERSION

Example

<OS VALUE="Win95"/>

Applies To

CDF, OSD


OSVERSION

<OSVERSION
 VALUE="a,b,c,d"
/>

Specifies the version of the operating system the software supports. This element assumes that the software can run on all versions of the operating system greater than or equal to the one specified.

VALUE="a,b,c,d"
Required. Major, minor, custom, and build version numbers.

Number of allowed occurrences: Any number (per parent element)
Parent elements | Child elements
OS | None

Applies To

CDF, OSD


PROCESSOR

<PROCESSOR
 VALUE="Alpha" | "MIPS" | "PPC" | "x86" />

Specifies the type of processor the software will run on.

VALUE="Alpha" | "MIPS" | "PPC" | "x86"
Required. Supported processor is Alpha, MIPS, PowerPC, or x86, respectively.

Number of allowed occurrences: Any number (per parent element)
Parent elements | Child elements
IMPLEMENTATION | None

Example

<PROCESSOR VALUE="x86"/>

Applies To

CDF, OSD


Open Software Description Reference

This Open Software Description (OSD) reference contains all the elements that are defined by the Osd.dtd file. These elements can be used in OSD and Channel Definition Format (CDF) files to describe software. There are additional elements described in Microsoft Internet Component Download Reference that can be used to describe software in more detail and enhance information provided by the OSD elements.
ABSTRACT CODEBASE DEPENDENCY
DISKSIZE IMPLEMENTATION IMPLTYPE
LANGUAGE LICENSE MEMSIZE
OS OSVERSION PROCESSOR
SOFTPKG TITLE VM

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


SOFTPKG

<SOFTPKG
AUTOINSTALL="No" | "Yes"
HREF="url"
NAME="string"
PRECACHE="No" | "Yes"
STYLE="ActiveSetup" | "MSICD"
VERSION="a,b,c,d"
>

Defines a software distribution.

AUTOINSTALL="No" | "Yes"
Browser should download the distribution unit and automatically install it when set to "Yes". The default value is "No". This attribute is valid only within CDF files.
HREF="url"
Required. "Launch URL" for this SOFTPKG element. This attribute is valid only within CDF files.
NAME="string"
Required. Name of this distribution.
PRECACHE="No" | "Yes"
Browser should download the distribution unit and leave it in the cache without attempting to autoinstall when set to "Yes". The AUTOINSTALL attribute takes precedence over PRECACHE when they are used together. The default value is "No". This attribute is valid only within CDF files.
STYLE="ActiveSetup" | "MSICD"
Mechanism the computer uses to download and install files from the Internet. This attribute is valid only within CDF files.
"ActiveSetup" | Use the ActiveX™ "Active Setup" engine.
"MSICD" | Use the Microsoft® Internet Component Download (MSICD) to download distribution units and look at the Open Software Description (OSD) file for processing instructions.
VERSION="a,b,c,d"
Major, minor, custom, and build version numbers.

Number of allowed occurrences: Any number (One or none per CDF or OSD file recommended)
Parent elements Child elements
CHANNEL ABSTRACT
IMPLEMENTATION
LANGUAGE
LOGO
TITLE
USAGE

The end tag </SOFTPKG> is required.

Example

<SOFTPKG
    HREF="http://www.foo.edu/launch-page.htm"
    NAME="The First Sample"
    PRECACHE="Yes"
    VERSION="2,1,0,0"
    STYLE="MSICD">
        <TITLE>This is a sample software distribution</TITLE>
        <ABSTRACT>Put a useful description here. The user will benefit from it.</ABSTRACT>
        <LOGO HREF="ielogo.ico" STYLE="icon" / >
        <LANGUAGE VALUE="en;de"/ >
        <USAGE VALUE="email"></USAGE>
        <IMPLEMENTATION>
            <CODEBASE VALUE="http://www.microsoft.com/foo/foo.cab" / >
</IMPLEMENTATION>
</SOFTPKG>

Note For more information about software distribution and the Open Software Description format, see Creating Software Channels for Internet Explorer 4.0.

Applies To

CDF, OSD


TITLE

<TITLE>

Specifies the string that will appear in the title bar.

Number of allowed occurrences: None or one
Parent Elements | Child Elements
IMPLEMENTATION | None
SOFTPKG

The end tag </TITLE> is required.

Example
<TITLE>Title of the package</TITLE>
Applies To

OSD


VM VM *
  * Previous Topic: TITLE
  * Next Topic: Pluggable Protocols

VM

Not currently implemented.


Appendix A: Registering an Application to a URL Protocol

To enable an application to handle a particular URL protocol you must add a new key, with the appropriate keys and values, to the registry in HKEY_CLASSES_ROOT.

The new registry key must match the protocol scheme that is being added. For instance, to add the protocol note:, the key added to HKEY_CLASSES_ROOT should be note. Under this new key, the Default string value should be the name of the new protocol, and the URLProtocol string value should contain either protocol-specific information or an empty string. Also under the new key, a DefaultIcon key and a shell key should be added. The Default string value under the DefaultIcon key must be the file name to use as an icon for this new URL protocol. Under the shell key, a key using a verb (such as open) should be added. A command key and a DDEEXEC key can be added under the key using a verb. The values under the command and DDEEXEC keys are used to call the application.

The following example shows which registry values must be added to register a new application (notepad.exe in this example) to handle a new URL protocol (note:).

[HKEY_CLASSES_ROOT]
    [note]
        (Default) = "URL:Note Protocol"
        URL Protocol = ""
        [DefaultIcon]
            (Default) = "notepad.exe"
        [shell]
            [open]
                [command]
                    (Default) = "c:\windows\notepad.exe %1"

By adding these settings to the registry, attempts to navigate to URLs such as note:c:\myfile.txt would launch Notepad to edit the file c:\myfile.txt. Of course, all the commands supported under Shell\Open are supported, including DDEEXEC (in other words, "command" is not the only key you can put under the verb).


Appendix B: Debugging Tips

Currently, the retail version of Urlmon.dll handles exceptions caused by all pluggable protocols. Developers trying to debug a custom pluggable protocol handler can do one of the following:

  • Trap the exceptions in your custom pluggable protocol handler before they get passed to Urlmon.dll.
  • Use a debugging tool that has the ability to trap the exceptions before they are passed to Urlmon.dll.

Also, some functions and methods return an HRESULT that is undefined, such as IInternetSecurityManager::SetZoneMapping. Many of these HRESULTs are generated by a macro that sets the low word to a valid Win32® error code and the high word to 8007.


Pluggable Protocols Overview

Pluggable protocols provide capability create custom URL protocols. This section covers the pluggable protocol functionality exported by the Urlmon.dll dynamic-link library (DLL).

Introduction

About URLs and Name Spaces

About Pluggable Protocols

Creating an Asynchronous Pluggable Protocol Handler

Appendix A: Registering an Application to a URL Protocol

Appendix B: Debugging Tips

Introduction

If you want to compile programs that use the functionality provided in Urlmon.dll, you must make sure the Urlmon.h header file is in the include directory, and the Urlmon.lib library file is in the library directory, of the C/C++ compiler you use.

This documentation assumes that you have an understanding of Microsoft® Win32® programming. Also, for asynchronous monikers, asynchronous pluggable protocols, and URL monikers you should have an understanding of OLE and COM programming. For the Internet-related interfaces, methods, and functions, an understanding of the format and syntax of URLs is also required. For more information, see RFC 1738, Uniform Resource Locators (URL). You can find this document at http://ds.internic.net/rfc/rfc1738.txt. External Link

About URLs and Name Spaces

A Uniform Resource Locator (URL) follows the syntax described in RFC 1738, which specifies a protocol scheme followed by a scheme-specific portion (<scheme>:<scheme-specific portion>). For example, in the URL http://www.microsoft.com/, "http" is the scheme and "//www.microsoft.com/" is the scheme-specific portion.

The beginning portion of the scheme-specific portion of the URL contains the server name. This portion of the URL is often referred to as the URL name space.

About Pluggable Protocols

Microsoft Internet Explorer uses two mechanisms for registering new URL protocol handlers. The first method is to register a URL protocol and its associated application so that all attempts to navigate to a URL using that protocol launch the application (for example, registering applications to handle mailto: or news: URLs). The second method uses the Asynchronous Pluggable Protocols API, which allows you to define new protocols by mapping the protocol scheme to a class.

For information on how to register an application for a particular URL protocol, see Appendix B: Registering an Application to a URL Protocol.

Asynchronous pluggable protocols offer three ways to map a protocol scheme to a class:

  • Permanently registering an asynchronous pluggable protocol handler in the registry. The handler is used for any URLs with the specified scheme (such as http, ftp, and so on).
  • Permanently or temporarily registering a pluggable name space handler. The handler is used for any URLs with the specified pattern in the scheme-specific portion of the URL for a particular protocol scheme.
  • Permanently or temporarily registering a MIME filter. The handler manipulates the data stream it receives and returns a data stream for any resources of the specified MIME type.

Note All asynchronous pluggable protocols must support the BINDF_NO_UI and BINDF_SILENTOPERATION flags.

Interfaces related to asynchronous pluggable protocols

  • IBindProtocol
  • IInternet
  • IInternetBindInfo
  • IInternetProtocol
  • IInternetProtocolInfo
  • IInternetProtocolRoot
  • IInternetProtocolSink
  • IInternetSession

Functions related to asynchronous pluggable protocols

  • CoInternetGetSession

About Asynchronous Pluggable Protocols

An asynchronous pluggable protocol handler is an apartment-threaded Component Object Model (COM) object that handles any calls made to the protocol scheme that it is registered for. When a client application makes a request, Urlmon looks up the protocol scheme in the registry and creates an instance of the protocol handler registered for that protocol scheme. If the protocol scheme was successfully mapped to the class identifier (CLSID) of a protocol handler, CoCreateInstance is called with that class asking for an IClassFactory interface. An instance of the protocol handler is obtained with IClassFactory::CreateInstance.

To register a custom URL protocol, add a key for the protocol scheme of the custom URL protocol to the registry under HKEY_CLASSES_ROOT\PROTOCOLS\Handler\protocol_scheme. Under that key, the string value, CLSID, must be set to the CLSID of the protocol handler.

To register the custom protocol scheme example, you would have to add a key named example to the registry under HKEY_CLASSES_ROOT\PROTOCOLS\Handler. Under the new key, HKEY_CLASSES_ROOT\PROTOCOLS\Handler\example, the string value, CLSID, must be assigned the CLSID of the protocol handler. Any URLs with the protocol scheme example: would be handled by the protocol handler associated with the CLSID value.

The protocol handler cannot use any Windows® messaging to switch back to the thread it was instantiated on, since the protocol handler must work on non-GUI threads.

Note All asynchronous pluggable protocols must support the BINDF_NO_UI and BINDF_SILENTOPERATION flags.

About Pluggable Name Space Handlers

A pluggable name space handler is an asynchronous pluggable protocol handler that you can set up to handle various protocol schemes and patterns. If a pluggable name space handler understands a particular URL, the handler will start successfully. Otherwise, the pluggable name space handler indicates that the default protocol handler for that protocol scheme should be used. A pluggable name space handler can be installed permanently or temporarily and can include specific patterns to indicate when it should be used.

Multiple pluggable name space handlers can be registered either temporarily or permanently. Temporarily registered pluggable name space handlers are called first and in the reverse order in which they were registered. This means the temporary pluggable name space handler that was registered last will be called first. Permanent name space handlers are not called in a specific order, so there is no way to ensure which handler will be called first.

Note All asynchronous pluggable name space handlers must support the BINDF_NO_UI and BINDF_SILENTOPERATION flags.

Permanent pluggable name space handlers

To set up a permanent pluggable name space handler, you must register it in the registry with the key HKEY_CLASSES_ROOT\PROTOCOLS\Name-Space Handler\protocol_scheme\handler_name. Under this key, you must set the values for a CLSID and any pattern string that you include. If no pattern strings are set, the handler is called for all requests for the specified protocol scheme.

If there are multiple permanent pluggable name space handlers registered, the order in which they are called is random, so handlers should specify only name spaces that they have control over to avoid handling name spaces specified by another handler.

In the following example, the pluggable name space handler Ohserv-Handler is to be called for all HTTP requests with the URL http://ohserv/.

HKEY_CLASSES_ROOT\PROTOCOLS\Name-Space Handler\http\Ohserv-Handler
    CLSID = {..}
    Pattern1 = "ohserv"

Pattern1 is a pattern string that is used to determine if this handler should be used on a particular URL. If a handler has multiple pattern strings (Pattern1, Pattern2, Pattern3, and so on), the browser checks the pattern strings listed to see if any of them match the URL the browser is trying to access. If there is a match, the handler is used; if there isn't, the handler is not used.

Note Valid pattern strings cannot have a leading wildcard character, such as *.com, and should handle only a specific group of known name spaces (for example, URLs for your company's Web sites). Pattern strings that could include numerous Web sites might conflict with other name space handlers that are provided for that specific site.

Temporary pluggable name space handlers

You can register and unregister a temporary pluggable name space handler by using the IInternetSession interface.

About Pluggable MIME Filters

A pluggable MIME filter is an asynchronous pluggable protocol that receives data through a stream, does some operation on the data, and returns a data stream. The output data might be in a different format from the original stream.

Multiple pluggable MIME filters can be registered either temporarily or permanently. Temporarily registered pluggable MIME filters are called first and in the reverse order in which they were registered. That means the pluggable MIME filters registered last will be called first.

For information on how Internet Explorer 4.0 determines MIME types, see Appendix A: MIME Type Detection in Internet Explorer 4.0.

Note All asynchronous pluggable MIME filters must support the BINDF_NO_UI and BINDF_SILENTOPERATION flags.

Permanent pluggable MIME filters

You must register a permanent pluggable MIME filter in the registry with the key HKEY_CLASSES_ROOT\PROTOCOLS\Filter\\<mime_filter> and with a value for a MIME filter. This value must be a CLSID.

Temporary pluggable MIME filters

You can register and unregister a temporary pluggable MIME filter by using the IInternetSession interface.

Creating an Asynchronous Pluggable Protocol Handler

Use the following steps to create an asynchronous pluggable protocol handler:

  1. Implement the IInternetProtocol interface.
  2. Implement the IInternetProtocolRoot interface.
  3. Implement the IClassFactory interface.
  4. Optional. Implement IInternetProtocolInfo. Support for the HTTP protocol is provided by the transaction handler.
  5. If IInternetProtocolInfo is implemented, provide support for PARSE_SECURITY_URL and PARSE_SECURITY_DOMAIN, so the URL security zone manager can handle the security properly.
  6. Write the code for your protocol handler.
  7. Provide support for BINDF_NO_UI and BINDF_SILENTOPERATION.
  8. Add a subkey for your protocol handler in the registry under HKEY_CLASSES_ROOT\PROTOCOLS\Handler.
  9. Create a string value, CLSID, under the subkey and set the string to the CLSID of your protocol handler.

After the protocol handler is created and added to the registry, it can be used by any application using the functionality provided by Urlmon.dll. The following list contains the general order of the calls made between Urlmon.dll and your protocol handler when a URL with the protocol scheme you registered your handler for is called:

  1. Urlmon.dll calls IUnknown::QueryInterface on your protocol handler for the IInternetProtocolInfo interface.

    Calling the asynchronous pluggable protocol

  2. If IInternetProtocolInfo is implemented, Urlmon.dll calls your pluggable protocol handler's IInternetProtocolInfo::ParseUrl interface.

    Calling the asynchronous pluggable protocol

    If the protocol handler is being called for an update of a subscription by Microsoft Internet Explorer 4.0, the pluggable protocol handler's IInternetProtocolInfo::QueryInfo method will also be called with the QUERYOPTION value set to QUERY_USES_CACHE. Only pluggable protocol handlers that use the Internet cache and return TRUE for the QUERY_USES_CACHE flag will be supported by the Internet Explorer subscription mechanism.

  3. Urlmon.dll calls IUnknown::QueryInterface on your pluggable protocol handler for its IInternetProtocol interface.

    Calling the asynchronous pluggable protocol

  4. Urlmon.dll calls your pluggable protocol handler's IInternetProtocolRoot::Start method with the URL and passes the address of the Urlmon.dll's IInternetProtocolSink and IInternetBindInfo interfaces.

    Calling the asynchronous pluggable protocol

  5. Your pluggable protocol handler should access the requested data. First it will request the data from the Internet.

    Requesting the data from the Internet

  6. After your pluggable protocol handler begins downloading data, your pluggable protocol handler should call the Urlmon.dll's IInternetProtocolSink::ReportData method.

    Notifying the transaction handler that data is available

  7. Urlmon.dll calls your protocol handler's IInternetProtocol::Read method.

    Reading the data

  8. Your pluggable protocol handler might call Urlmon.dll's IInternetProtocolSink::ReportProgress method. The pluggable protocol handler must report the MIME type, using the BINDSTATUS_MIMETYPEAVAILABLE status code, to allow a pluggable MIME filter to be called (if there is a MIME filter registered for the MIME type reported).

  9. Steps 6 through 8 are repeated until your protocol handler is finished downloading the requested data.
  10. Your pluggable protocol handler must call the Urlmon.dll's IInternetProtocolSink::ReportResult method.

  11. Urlmon.dll calls your pluggable protocol handler's IInternetProtocol::LockRequest method.

  12. Urlmon.dll calls your pluggable protocol handler's IInternetProtocolRoot::Terminate method.

    Terminating the pluggable protocol

  13. Urlmon.dll calls your pluggable protocol handler's IInternetProtocol::Read method until all the data is retrieved.

    Reading the remaining data

  14. Urlmon.dll calls your pluggable protocol handler's IInternetProtocol::UnlockRequest method.

    Unlocking the request

Note Your pluggable protocol handler's IInternetProtocol::Read method might continue to get called even after your IInternetProtocol::Read method has indicated that all the data has been read. All asynchronous pluggable protocol handlers must be prepared for this possibility.

Creating a Pluggable MIME Filter

A pluggable MIME filter is essentially an asynchronous pluggable protocol handler that implements an IInternetProtocolSink interface. Urlmon.dll will use the MIME filter's implementation of IInternetProtocolSink to notify the pluggable MIME filter that it has data ready to be filtered.

Also, filters that handle multiple MIME types must register a separate CLSID for each MIME type they handle:

  1. The transaction handler calls the pluggable MIME filter's IInternetProtocolRoot::Start method.

    Reading the data

  2. The transaction handler calls the pluggable MIME filter's IInternetProtocolSink::ReportProgress and IInternetProtocolSink::ReportData methods.

    Reading the data

  3. The pluggable MIME filter calls the transaction handler's IInternetProtocol::Read method.

    Reading the data

  4. The pluggable MIME filter calls the transaction handler's IInternetProtocolSink::ReportData method.

    Reading the data

  5. The transaction handler calls the pluggable MIME filter's IInternetProtocol::Read method.

    Reading the data

More details will be provided in future versions of this documentation.


Pluggable Protocols

Pluggable protocols provide capability create custom URL protocols. This section covers the pluggable protocol functionality exported by the Urlmon.dll dynamic-link library (DLL).

Pluggable Protocols Overview

Pluggable Protocols Reference


Pluggable Protocols Reference

This reference covers the APIs that are exported from the Urlmon.dll dynamic-link library. These APIs allow a developer to:

  • Create monikers that can instantiate a named object and return a pointer to one of the object's interfaces asynchronously.
  • Create an asynchronous moniker whose data is referenced by a URL (Uniform Resource Locator).
  • Implement customized URL protocols, name space handlers, and MIME filters.
  • Use functions that combine the functionality of asynchronous monikers and URL monikers.
  • Manage URL security zones.

The reference contains the interfaces, methods, functions, structures, enumerated types, security zone flags, and error codes used by these APIs.

Interfaces

Methods

Functions

Structures

Enumerated Types


Enumerated Types

This section contains the enumerated types that are exposed by Urlmon.dll.
OIBDG_FLAGS
PARSEACTION
PI_FLAGS

OIBDG_FLAGS

Obsolete. Do not use.

PARSEACTION

typedef enum _tagPARSEACTION {
    PARSE_CANONICALIZE = 1,
    PARSE_FRIENDLY,
    PARSE_SECURITY_URL,
    PARSE_ROOTDOCUMENT,
    PARSE_DOCUMENT,
    PARSE_ANCHOR,
    PARSE_ENCODE,
    PARSE_DECODE,
    PARSE_PATH_FROM_URL,
    PARSE_URL_FROM_PATH,
    PARSE_MIME,
    PARSE_SERVER,
    PARSE_SCHEMA,
    PARSE_SITE,
    PARSE_DOMAIN,
    PARSE_LOCATION,
    PARSE_SECURITY_DOMAIN
} PARSEACTION;

An enumerated type that contains the different options for URL parsing operations.

PARSE_CANONICALIZE
Canonicalize the URL.
PARSE_FRIENDLY
Retrieve the user-friendly name for the URL.
PARSE_SECURITY_URL
Retrieve the URL that should be used by the security manager to make security decisions. The returned URL should either return just the name space of the protocol or map the protocol to a known protocol (such as HTTP).
PARSE_ROOTDOCUMENT
Return the URL of the root document for this site.
PARSE_DOCUMENT
Remove the anchor part of the URL.
PARSE_ANCHOR
Remove everything from the URL before the anchor(#).
PARSE_ENCODE
Encode the URL.
PARSE_DECODE
Decode the URL.
PARSE_PATH_FROM_URL
Get the path from the URL, if available.
PARSE_URL_FROM_PATH
Create a URL from the given path.
PARSE_MIME
Return the MIME type of this URL.
PARSE_SERVER
Return the server name.
PARSE_SCHEMA
Retrieve the schema for this URL.
PARSE_SITE
Retrieve the site associated with this URL.
PARSE_DOMAIN
Retrieve the domain associated with this URL.
PARSE_LOCATION
Retrieve the location associated with this URL.
PARSE_SECURITY_DOMAIN
Retrieve the security form of the URL. The returned URL should return a base URL that contains no username, password, directory path, resource, or any other extra information.


PI_FLAGS

typedef enum _tagPI_FLAGS{
    PI_PARSE_URL = 0x00000001,
    PI_FILTER_MODE = 0x00000002,
    PI_FORCE_ASYNC = 0x00000004,
    PI_USE_WORKERTHREAD = 0x00000008,
    PI_MIMEVERIFICATION = 0x00000010,
    PI_CLSIDLOOKUP = 0x00000020,
    PI_DATAPROGRESS = 0x00000040,
    PI_SYNCHRONOUS = 0x00000080,
    PI_APARTMENTTHREADED = 0x00000100,
    PI_CLASSINSTALL = 0x00000200,
    PD_FORCE_SWITCH = 0x00010000
} PI_FLAGS;

This enumerated type contains the flags that control the asynchronous pluggable protocol handler.

PI_PARSE_URL
Asynchronous pluggable protocol should parse the URL and return S_OK if the URL is syntactically correct; otherwise S_FALSE.
PI_FILTER_MODE
Asynchronous pluggable protocol handler that it is running in filter mode and data will come in through the IInternetProtocolSink interface it exposes. The QueryInterface method will be called on the protocol handler for its IInternetProtocolSink interface.
PI_FORCE_ASYNC
Asynchronous pluggable protocol handler should do as little work as possible on the apartment (or user interface) thread and continue on a worker thread as soon as possible.
PI_USE_WORKERTHREAD
Asynchronous pluggable protocol handler should use worker threads and not use the apartment thread.
PI_MIMEVERIFICATION
Asynchronous pluggable protocol handler should verify and report the MIME type.
PI_CLSIDLOOKUP
Asynchronous pluggable protocol handler should find the CLSID associated with the MIME type.
PI_DATAPROGRESS
Asynchronous pluggable protocol handler should report its progress.
PI_SYNCHRONOUS
Asynchronous pluggable protocol handler should work synchronously.
PI_APARTMENTTHREADED
Asynchronous pluggable protocol handler should use the apartment (or user interface) thread only.
PI_CLASSINSTALL
PD_FORCE_SWITCH


CoInternetGetProtocolFlags

STDAPI CoInternetGetProtocolFlags(
    LPCWSTR pwzUrl,
    DWORD *pdwFlags,
    DWORD dwReserved
);

Retrieves the protocol flags for a specified URL.

pwzUrl
String value containing the URL.
pdwFlags
Address of a double-word value that contains the protocol flags.
dwReserved
Reserved. Must be set to zero.


CoInternetGetSession

STDAPI CoInternetGetSession(
    DWORD dwSessionMode,
    IInternetSession **ppIInternetSession,
    DWORD dwReserved
);

Creates a session that allows temporary asynchronous pluggable protocols to be implemented and returns the IInternetSession interface of the session.

  • Returns one of the following values:
    S_OK | Successful.
    E_OUTOFMEMORY | Not enough memory to create a session.
    E_INVALIDARG | One of the arguments is invalid.
dwSessionMode
Reserved. Must be set to zero.
ppIInternetSession
Address of the pointer to the IInternetSession interface.
dwReserved
Reserved. Must be set to zero.


CoInternetParseUrl

STDAPI CoInternetParseUrl(
    LPCWSTR pwzUrl,
    PARSEACTION ParseAction,
    DWORD dwFlags,
    LPWSTR pszResult,
    DWORD cchResult,
    DWORD *pcchResult,
    DWORD dwReserved
);

Parses URLs. (This is a helper API.)

  • Returns one of the following values:
    S_OK | Success.
    S_FALSE | The buffer was too small to contain the resulting URL.
    INET_E_DEFAULT_ACTION
pwzUrl
String value containing the URL to parse.
ParseAction
PARSEACTION value that determines the information to be parsed from the URL.
dwFlags
Double-word value that controls the parsing operation.
pwzResult
String value that contains the information parsed from the URL.
cchResult
Double-word value that contains the size of the buffer.
pcchResult
Address of a double-word value that contains the size of the information stored in the buffer.
dwReserved
Reserved. Must be set to zero.


Functions

This section describes the functions included in monikers, URLs, security zones, and pluggable protocols.
CoInternetGetProtocolFlags
CoInternetGetSession
CoInternetParseUrl


Interfaces

This section contains the interfaces exposed by monikers, URLs, security zones, and pluggable protocols.
IDataFilter
IEncodingFilterFactory
IInternet
IInternetBindInfo
IInternetProtocol
IInternetProtocolInfo
IInternetProtocolRoot
IInternetProtocolSink
IInternetSession


Methods

This section contains the methods exposed by monikers, URLs, security zones, and pluggable protocols.
IInternetBindInfo::GetBindInfo
IInternetBindInfo::GetBindString
IInternetProtocol::LockRequest
IInternetProtocol::Read
IInternetProtocol::Seek
IInternetProtocol::UnlockRequest
IInternetProtocolInfo::CombineUrl
IInternetProtocolInfo::CompareUrl
IInternetProtocolInfo::ParseUrl
IInternetProtocolInfo::QueryInfo
IInternetProtocolRoot::Abort
IInternetProtocolRoot::Continue
IInternetProtocolRoot::Resume
IInternetProtocolRoot::Start
IInternetProtocolRoot::Suspend
IInternetProtocolRoot::Terminate
IInternetProtocolSink::ReportData
IInternetProtocolSink::ReportProgress
IInternetProtocolSink::ReportResult
IInternetProtocolSink::Switch
IInternetSession::CreateBinding
IInternetSession::GetCache
IInternetSession::GetSessionOption
IInternetSession::RegisterMimeFilter
IInternetSession::RegisterNameSpace
IInternetSession::SetCache
IInternetSession::SetSessionOption
IInternetSession::UnregisterMimeFilter
IInternetSession::UnregisterNameSpace


IDataFilter IDataFilter *
  * Previous Topic: Interfaces
  * Next Topic: IEncodingFilterFactory

IDataFilter

No currently implemented.


IEncodingFilterFactory IEncodingFilterFactory *
  * Previous Topic: IDataFilter
  * Next Topic: IInternet

IEncodingFilterFactory

Not currently implemented.


IInternet

IInternet provides an implementation of the IUnknown interface, which allows client programs to determine if asynchronous pluggable protocols are supported. No additional methods are supported by this interface.


IInternetBindInfo

This interface is implemented by the system and provides data that the protocol might need to bind successfully.
IInternetBindInfo methods | Description
GetBindInfo | Gets the BINDINFO structure associated with the binding operation.
GetBindString | Gets the strings needed by the protocol for its operation.


IInternetProtocol

IInternetProtocol is the main interface that is exposed by an asynchronous pluggable protocol. This interface and IInternetProtocolSink communicate with each other very closely during download operations.
IInternetProtocol methods | Description
LockRequest | Locks the request so that IInternetProtocolRoot::Terminate can be called and the remaining data can be read.
Read | Reads data retrieved by the pluggable protocol handler.
Seek | Moves the current seek offset.
UnlockRequest | Frees any resources associated with a lock. Called only if IInternetProtocol::LockRequest was called.


IInternetProtocol::LockRequest

HRESULT LockRequest(
    [in] DWORD dwOptions
);

Locks the requested resource so that IInternetProtocolRoot::Terminate can be called and the remaining data can be read.

  • Returns S_OK if successful. If the requested resource cannot be locked, the method returns INET_E_CANNOT_LOCK_REQUEST.
dwOptions

For asynchronous pluggable protocols that do not need to lock a request, the method should just return S_OK.


IInternetProtocol::Read

HRESULT Read(
    [out] LPVOID pv,
    [in] ULONG cb,
    [out] ULONG *pcbRead
);

Reads data retrieved by the pluggable protocol handler.

  • Returns one of the following values:
    INET_E_DATA_NOT_AVAILABLE | There is no more data available from the server, but more data was expected.
    INET_E_DOWNLOAD_FAILURE | The read failed.
    E_PENDING | The read operation is pending.
    S_OK | The read was successful, but there is still additional data available.
    S_FALSE | All of the data has been completely downloaded.
pv
Address of the buffer where the information will be stored.
cb
ULONG value that indicates the size of the buffer.
pcbRead
Address of a ULONG value that indicates the amount of data stored in the buffer.

Developers who are implementing an asynchronous pluggable protocol must be prepared to have their implementation of IInternetProtocol::Read continue to be called a few extra times after it has returned S_FALSE.


IInternetProtocol::Seek

HRESULT Seek(
    [in] LARGE_INTEGER dlibMove,
    [in] DWORD dwOrigin,
    [out] ULARGE_INTEGER *plibNewPosition
);

Moves the current seek offset.

  • Returns S_OK if successful, or E_FAIL if the protocol does not support seekable data retrieval.
dlibMove
Large integer value that indicates how far to move the offset.
dwOrigin
DWORD value that indicates where the move should begin.
plibNewPosition
Address of an unsigned long integer value that indicates the new offset.


IInternetProtocol::UnlockRequest

HRESULT UnlockRequest();

Frees any resources associated with a lock.

This method is called only if IInternetProtocol::LockRequest was called.


IInternetProtocolInfo::CombineUrl

HRESULT CombineUrl(
    [in] LPCWSTR pwzBaseUrl,
    [in] LPCWSTR pwzRelativeUrl,
    [in] DWORD dwCombineFlags,
    [out] LPWSTR pwzResult,
    [in] DWORD cchResult,
    [out] DWORD *pcchResult,
    [in] DWORD dwReserved
);

Combines a base and relative URL into a full URL.

  • Returns one of the following values:
    S_OK | Success.
    S_FALSE | The buffer was too small to contain the resulting URL.
    INET_E_DEFAULT_ACTION
pwzBaseUrl
String value containing the base URL.
pwzRelativeUrl
String value containing the relative URL.
dwCombineFlags
Double-word value that controls the combining process. Can be one of the following values:
ICU_BROWSER_MODE
ICU_ENCODE_SPACES_ONLY
ICU_DECODE
ICU_NO_ENCODE
ICU_NO_META
pwzResult
String variable where the full URL will be stored.
cchResult
Double-word value that contains the size of the buffer.
pcchResult
Address of a double-word value to store the size of the information stored in the buffer.
dwReserved
Reserved. Must be set to zero.

For more information on the dwCombineFlags values, see the InternetCombineUrl function in the Win32 Internet Functions Reference.


IInternetProtocolInfo::CompareUrl

HRESULT CompareUrl(
    [in] LPCWSTR pwzUrl1,
    [in] LPCWSTR pwzUrl2,
    [in] DWORD dwCompareFlags
);

Compares two URLs and determines if they are equal.

  • Returns S_OK if equal, or S_FALSE otherwise.
pwzUrl1
String value that contains the first URL.
pwzUrl2
String value that contains the second URL.
dwCompareFlags
Double-word value that controls the comparison. Set to TRUE to ignore slashes, FALSE otherwise.


IInternetProtocolInfo

This interface provides information about the URL being handled by the protocol handler.
IInternetProtocolInfo methods | Description
CombineUrl | Combines a base and relative URL into a full URL.
CompareUrl | Compares two URLs.
ParseUrl | Parses a URL.
QueryInfo | Retrieves information associated with a URL.


IInternetProtocolInfo::ParseUrl

HRESULT ParseUrl(
    [in] LPCWSTR pwzUrl,
    [in] PARSEACTION ParseAction,
    [in] DWORD dwParseFlags,
    [out] LPWSTR pwzResult,
    [in] DWORD cchResult,
    [out] DWORD *pcchResult,
    [in] DWORD dwReserved
);

Parses a URL.

  • Returns one of the following values:
    S_OK | Success.
    S_FALSE | The buffer was too small to contain the resulting URL.
    INET_E_DEFAULT_ACTION
pwzUrl
String value containing the URL to parse.
ParseAction
PARSEACTION value that determines the information to be parsed from the URL.
dwParseFlags
Reserved. Must be set to zero.
pwzResult
String value that contains the information parsed from the URL.
cchResult
Double-word value that contains the size of the buffer.
pcchResult
Address of a double-word value that contains the size of the information stored in the buffer.
dwReserved
Reserved. Must be set to zero.


IInternetProtocolInfo::QueryInfo

HRESULT QueryInfo(
    [in] LPCWSTR pwzUrl,
    [in] QUERYOPTION QueryOption,
    [in] DWORD dwQueryFlags,
    [in, out] LPVOID pBuffer,
    [in] DWORD cbBuffer,
    [in, out] DWORD *pcbBuf,
    [in] DWORD dwReserved
);

Retrieves information related to the specified URL.

  • Returns one of the following values:
    S_OK | The information requested was retrieved successfully.
    S_FALSE | The buffer was too small to store the information.
    INET_E_QUERYOPTION_UNKNOWN | The option requested is unknown.
pwzUrl
String value containing the URL.
QueryOption
QUERYOPTION value that indicates what option to query.
dwQueryFlags
Reserved. Must be set to zero.
pBuffer
Address of the buffer where the information will be stored.
cbBuffer
Double-word value containing the size of the buffer.
pcbBuf
Address of a double-word variable where the size of the requested information will be stored.
dwReserved
Reserved. Must be set to zero.


IInternetProtocolRoot::Abort

HRESULT Abort(
    [in] HRESULT hrReason,
    [in] DWORD dwOptions
);

Aborts an operation that is in progress.

  • Returns one of the following values:
    S_OK | Success.
    E_PENDING | The operation started and will complete asynchronously.
    INET_E_xxx | Internet-specific errors.
hrReason
HRESULT value that contains the reason for the abort.
dwOptions
DWORD value that determines if the abort happens synchronously or asynchronously. The default is asynchronously.


IInternetProtocolRoot::Continue

HRESULT Continue(
    [in] PROTOCOLDATA *pPROTOCOLDATA
);

Allows the pluggable protocol handler to continue processing data on the apartment thread. This method is called in response to a call to IInternetProtocolSink::Switch.

  • Returns one of the following values:
    S_OK | Success.
    E_PENDING | The next state will complete asynchronously.
    INET_E_xxx | Internet-specific errors.
pPROTOCOLDATA
Holder for the PROTOCOLDATA structure data passed to IInternetProtocolSink::Switch.


IInternetProtocolRoot

This interface is used to control the operation of an asynchronous pluggable protocol handler.
IInternetProtocolRoot methods | Description
Abort | Aborts an operation in progress.
Continue | Allows the pluggable protocol handler to continue processing data on the apartment (or user interface) thread. This method is called in response to a call to IInternetProtocolSink::Switch.
Resume | Not currently implemented.
Start | Starts the class associated with the asynchronous pluggable protocol.
Suspend | Not currently implemented.
Terminate | Releases the resources used by the pluggable protocol handler.


IInternetProtocolRoot::Resume IInternetProtocolRoot::Resume *
  * Previous Topic: IInternetProtocolRoot::Continue
  * Next Topic: IInternetProtocolRoot::Start

IInternetProtocolRoot::Resume

Not currently implemented.


IInternetProtocolRoot::Start

HRESULT Start(
    [in] LPCWSTR szUrl,
    [in] IInternetProtocolSink *pOIProtSink,
    [in] IInternetBindInfo *pOIBindInfo,
    [in] DWORD grfPI,
    [in] DWORD dwReserved
);

Starts the operation.

  • Returns one of the following values:
    S_OK | Success.
    E_PENDING | The operation started and will complete asynchronously.
    INET_E_USE_DEFAULT_PROTOCOLHANDLER | The handler cannot handle this URL, so the default handler should be used.
    INET_E_xxx | Internet-specific errors.
szUrl
String value containing the URL. For a pluggable MIME filter, this parameter contains the MIME type.
pOIProtSink
Address of the protocol sink provided by the client.
pOIBindInfo
Address of the IInternetBindInfo interface from which the protocol gets download-specific information.
grfPI
DWORD value containing the flags that determine if the method only parses or if it parses and downloads the URL. Can be one of the PI_FLAGS values.
dwReserved
For pluggable MIME filters, contains the address of a PROTOCOLFILTERDATA structure. Otherwise, it is reserved and must be set to zero.

INET_E_USE_DEFAULT_PROTOCOLHANDLER can be returned only by a pluggable name-space handler or MIME filter. Only a single permanently registered asynchronous pluggable protocol handler can be assigned to a particular scheme (such as FTP), so there are no other handlers to default to.


IInternetProtocolRoot::Suspend IInternetProtocolRoot::Suspend *
  * Previous Topic: IInternetProtocolRoot::Start
  * Next Topic: IInternetProtocolRoot::Terminate

IInternetProtocolRoot::Suspend

Not currently implemented.


IInternetProtocolRoot::Terminate

HRESULT Terminate(
    [in] DWORD dwOptions
);

Releases the resources used by the pluggable protocol handler.

dwOptions
Reserved. Must be set to zero.

Notes to implementers

Urlmon.dll will not call this method until your asynchronous pluggable protocol handler calls Urlmon.dll's IInternetProtocolSink::ReportResult method. When your IInternetProtocolRoot::Terminate method is called, your asynchronous pluggable protocol handler should free all resources it has allocated.

Notes to callers

This method should be called after receiving a call to your IInternetProtocolSink::ReportResult method and after the protocol handler's IInternetProtocol::LockRequest method has been called.


IInternetProtocolSink

This interface receives the reports and binding data from the asynchronous pluggable protocol. It is a free-threaded interface and can be called from any thread.
IInternetProtocolSink methods | Description
ReportData | Reports the amount of data that is available on the thread.
ReportProgress | Reports progress made in a state operation.
ReportResult | Reports the result of an operation on the thread.
Switch | Passes data from an asynchronous pluggable protocol's worker thread intended for the same asynchronous pluggable protocol's apartment thread. IInternetProtocolSink should pass this data, without modification, back to the asynchronous pluggable protocol by calling its IInternetProtocolRoot::Continue method.

This interface is implemented by client applications interacting directly with an asynchronous pluggable protocol and pluggable MIME filters.


IInternetProtocolSink::ReportData

HRESULT ReportData(
    [in] DWORD grfBSCF,
    [in] ULONG ulProgress,
    [in] ULONG ulProgressMax
);

Reports the amount of data that is available on the thread.

  • Returns S_OK if successful, or E_FAIL if called after an IInternetProtocolRoot::Abort call.
grfBSCF
DWORD value that evaluates to a BSCF value that indicates the type of data available. BSCF_LASTDATANOTIFICATION indicates that all available data has been reported.
ulProgress
Unsigned long integer value that indicates the progress made so far.
ulProgressMax
Unsigned long integer value that indicates the total amount of work to be done.


IInternetProtocolSink::ReportProgress

HRESULT ReportProgress(
    [in] ULONG ulStatusCode,
    [in] LPCWSTR szStatusText
);

Reports progress made during a state operation.

  • Returns S_OK if successful, or E_FAIL if called after an Abort operation.
ulStatusCode
BINDSTATUS value that indicates the status of the state operation.
szStatusText
String value that describes the status of the state operation.

Asynchronous pluggable protocol handlers should not generate the BINDSTATUS_BEGINDOWNLOADDATA, BINDSTATUS_ENDDOWNLOADDATA, and BINDSTATUS_DOWNLOADINGDATA reports, since they are generated internally when the data arrives.


IInternetProtocolSink::ReportResult

HRESULT ReportResult(
    [in] HRESULT hrResult,
    [in] DWORD dwError,
    [in] LPCWSTR szResult
);

Reports the result of the operation when called on any thread.

  • Returns S_OK if successful, or E_FAIL if called in the wrong sequence.
hrResult
HRESULT value that indicates the result returned by the operation.
dwError
Unsigned long integer value that is a protocol-specific code.
szResult
Protocol-specific result string that should be NULL if the operation succeeded.

Notes to implementers

After your IInternetProtocolSink::ReportResult method is called, your application should call the protocol handler's IInternetProtocol::LockRequest method to lock the resource you are reading from the protocol handler. Then your application should call the protocol handler's IInternetProtocolRoot::Terminate method.

Notes to callers

The call to IInternetProtocolSink::ReportResult is the last call that your pluggable protocol handler must make to the client application's IInternetProtocolSink interface.


IInternetProtocolSink::Switch

HRESULT Switch(
    [in] PROTOCOLDATA *pPROTOCOLDATA
);

Passes data from an asynchronous pluggable protocol's worker thread intended for the same asynchronous pluggable protocol's apartment thread. The IInternetProtocolSink interface should pass this data, without modification, back to the asynchronous pluggable protocol by calling its IInternetProtocolRoot::Continue method.

  • Returns S_OK if successful, or E_FAIL if called when an asynchronous operation is pending.
pPROTOCOLDATA
Address of a PROTOCOLDATA structure containing the data to be passed back to the apartment thread.

Asynchronous pluggable protocol handlers may operate asynchronously in a separate worker thread. This method allows the protocol handler to pass data back to the apartment (or user interface) thread it was created on.


IInternetSession::CreateBinding

HRESULT CreateBinding(
    [in] LPBC pBC,
    [in] LPCWSTR szUrl,
    [in] IUnknown *pUnkOuter,
    [out, unique] IUnknown **ppUnk,
    [out, unique] IInternetProtocol **ppOInetProt,
    [in] DWORD dwOption
);

Not currently implemented.


IInternetSession::GetCache

HRESULT GetCache(
    [out, unique] IInternetCache **ppOInetCache,
    [in] DWORD dwOption
);

Not currently implemented. Must return E_NOTIMPL.


IInternetSession::GetSessionOption

HRESULT GetSessionOption(
    [in] DWORD dwOption,
    [in, out] LPVOID pBuffer,
    [in, out] DWORD *pdwBufferLength,
    [in] DWORD dwReserved
);

Not currently implemented. Must return E_NOTIMPL..


IInternetSession

This interface is implemented by the client application to create temporary pluggable protocol handlers.
IInternetSession methods | Description
CreateBinding | Not currently implemented.
GetCache | Not currently implemented.
GetSessionOption | Not currently implemented.
RegisterMimeFilter | Temporarily registers a MIME filter.
RegisterNameSpace | Temporarily registers a name space handler.
SetCache | Not currently implemented.
SetSessionOption | Not currently implemented.
UnregisterMimeFilter | Unregisters a pluggable MIME filter.
UnregisterNameSpace | Unregisters a temporary pluggable name space handler.


IInternetSession::RegisterMimeFilter

HRESULT RegisterMimeFilter(
    [in] IClassFactory *pCF,
    [in] REFCLSID rclsid,
    [in] LPCWSTR pwzType
);

Temporarily registers a pluggable MIME filter.

  • Returns one of the following values:
    S_OK | Success.
    E_FAIL | The operation failed.
    E_NOINTERFACE | The class factory could not be obtained.
pCF
Address of an IClassFactory interface where an IInternetProtocol object can be created.
rclsid
Reference to the pluggable MIME handler.
pwzType
String value that contains the MIME to register.

An application can register a pluggable MIME handler for a particular period when it wants to handle requests for some MIMEs by calling IInternetSession::RegisterMimeFilter. This method can be called multiple times using the same interface to register the different MIME types it wants to handle.


IInternetSession::RegisterNameSpace

HRESULT RegisterNameSpace(
    [in] IClassFactory *pCF,
    [in] REFCLSID rclsid,
    [in] LPCWSTR pwzProtocol,
    [in] ULONG cPatterns,
    [in] const LPCWSTR *ppwzPatterns,
    [in] DWORD dwReserved
);

Temporarily registers a pluggable name space handler.

  • Returns one of the following values:
    S_OK | Success.
    E_FAIL | The operation failed.
    E_NOINTERFACE | The class factory could not be obtained.
pCF
Address of an IClassFactory interface where an IInternetProtocol object can be created.
rclsid
Reference to the pluggable name space handler.
pwzProtocol
String value that contains the protocol to be handled.
cPatterns
Unsigned long integer that indicates the number of elements in the ppwzPatterns parameter.
ppwzPatterns
Array of strings containing the patterns the handler will be used for.
dwReserved
Reserved. Must be set to zero.

An application can register a pluggable name space handler for a particular period when it wants to handle requests for some protocols by calling IInternetSession::RegisterNameSpace. If ppwzPatterns and cPatterns are NULL, the registered pluggable name space handler will be called for all protocol requests. This method can be called multiple times using the same interface to register the different name spaces it wants to handle.


IInternetSession::SetCache IInternetSession::SetCache *
  * Previous Topic: IInternetSession::RegisterNameSpace
  * Next Topic: IInternetSession::SetSessionOption

IInternetSession::SetCache

HRESULT SetCache(
    [in] IInternetCache *pOInetCache,
    [in] DWORD dwOption
);

Not currently implemented. Must return E_NOTIMPL.


IInternetSession::SetSessionOption

HRESULT SetSessionOption(
    [in] DWORD dwOption,
    [in] LPVOID pBuffer,
    [in] DWORD dwBufferLength,
    [in] DWORD dwReserved
);

Not currently implemented. Must return E_NOTIMPL.

Sets the options for an Internet session.


IInternetSession::UnregisterMimeFilter

HRESULT UnregisterMimeFilter(
    [in] IClassFactory *pCF,
    [in] LPCWSTR pwzType
);

Unregisters a temporary pluggable MIME filter.

  • Returns S_OK if successful (pluggable name space handler was removed), or E_FAIL if the pluggable name space handler was not registered.
pCF
Address of the IClassFactory interface that created the filter.
pwzType
String value that indicates the MIME that the filter was handling.


IInternetSession::UnregisterNameSpace

HRESULT UnregisterNameSpace(
    [in] IClassFactory *pCF,
    [in] LPCWSTR pszProtocol
);

Unregisters a temporary pluggable name space handler.

  • Returns S_OK if successful, or E_FAIL if the pluggable name space handler was not registered.
pCF
Address of the IClassFactory interface that created the handler.
pszProtocol
String value that contains the protocol that was handled.


PROTOCOLDATA

typedef struct _tagPROTOCOLDATA{
    DWORD grfFlags;
    DWORD dwState;
    LPVOID pData;
    ULONG cbData;
}  PROTOCOLDATA;

Contains state information about the protocol that is transparent to the transaction handler.

grfFlags
Double-word value that contains the flags.
dwState
Double-word value that contains the state of the protocol handler.
pData
Address of the data buffer.
cbData
Double-word value containing the size of the data buffer.


PROTOCOLFILTERDATA

typedef struct _tagPROTOCOLFILTERDATA {
    DWORD cbSize;
    IInternetProtocolSink *pProtocolSink;
    IInternetProtocol *pProtocol;
    IUnknown *pUnk;
    DWORD dwFilterFlags;
} PROTOCOLFILTERDATA;

Contains the IInternetProtocolSink and IInternetProtocol interfaces of the application calling a pluggable MIME filter.

cbSize
Unsigned long integer value containing the size of the structure.
pProtocolSink
Address of the application's implementation of IInternetProtocolSink.
pProtocol
Address of the application's implementation of IInternetProtocol.
pUnk
Address of the IUnknown interface.
dwFilterFlags
Reserved. Must be set to zero.


Structures

This section contains the structures that are exposed by Urlmon.dll.
PROTOCOLDATA
PROTOCOLFILTERDATA


Predefined Protocols

Microsoft® Internet Explorer 4.0 implements various protocols that can be used to identify certain information. This document describes the protocols that Internet Explorer 4.0 implements or supports.

res:

The res: protocol specifies a resource that will be obtained from a module. This protocol takes the following format:

"res://resource file[/resource type]/resource id"

The following list describes each element:
resource file | Required. Specifies the path and file name of the module that contains the resource.
resource type | Optional. Specifies the string or numerical resource type. This can be either a custom resource type or one of the RT_ pre-defined resource types described in FindResource and defined in WINUSER.H. If a numerical resource type is being specified, the actual number of the identifier, not the identifier itself, must follow a '#' character. See the example below for more information. If this parameter is not specified, the default resource type is RT_HTML.
resource id | Required. Specifies the string or numerical identifier of the resource. If a numerical identifier is being specified, the actual number of the identifier, not the identifier itself, must follow a '#' character. See the example below for more information.

The following example shows the correct and incorrect way to format the numerical identifier for the resource type:

//winuser.h defines RT_BITMAP
#include <winuser.h>

//this is correct
"res://mydll.dll/#2/MYBITMAP"

//this is not correct
"res://mydll.dll/RT_BITMAP/MYBITMAP"

The following example shows the correct and incorrect way to format the numerical identifier for the resource identifier:

#define MYBITMAP 234

//this is correct
"res://mydll.dll/#2/#234"

//this is not correct
"res://mydll.dll/#2/MYBITMAP"


Internet Ratings

The Platform for Internet Content Selection (PICS) is a W3C group chartered to define a standard for the creation of rating systems and rating information. PICS is the open W3C standard for solving the problems with minors accessing adult content on the Internet; Microsoft views PICS as the best direction for solving these problems. This document describes how to support ratings on the Microsoft® Internet Explorer platform. It is intended for HTML authors who wish to support PICS ratings on their site, and also for programmers who are developing Web authoring or viewing tools and applications.

The PICS Standard

Internet Ratings API

Internet Ratings API Reference

The PICS Standard

This section describes how the PICS system works, shows an example of rating information within an HTML page, and briefly describes the PICS specification.

How the PICS system works

The PICS system has two types of components: rating systems and rating labels. A rating system defines the criteria for how content is rated. PICS has created a meta-language for defining the different categories and the different values for rating content. For example, the Motion Picture Association of America (MPAA) rating system has one category with five values: G, PG, PG-13, R, and NC-17. Using the PICS specification, rating systems with multiple categories can be defined.

The rating label is the actual rating information. The label can appear on a Web page as part of the HTML content, on a third-party Web site, or anywhere else that a particular client application "knows" to look for them. Each item of content that is rated would have its own label. PICS has defined the syntax for these rating labels, as well as extensions to many Internet protocols to support labels.

The PICS system works by matching labels to their associated systems. The client software, either part of the Web browser or a separate application, allows parents to decide what levels of content they want to allow their children to see for each rating system. Then, as the child uses the PICS-aware Web browser or application, the Web browser finds the rating labels for the content and checks against the values the parent has set by calling a function in the Internet Ratings API. If the content is rated higher than the child is allowed, the content is not displayed.

Example of HTML tagged ratings

Ratings are specified by using an additional tag within the HTML header (<HEAD> rating information </HEAD>). The rating is in English text, as defined by the PICS specification. More details are provided in the full PICS documentation found on the PICS Web site: http://www.w3.org/PICS/ External Link.

The following example shows the general format of rating information within an HTML page.

<HTML>
<HEAD>
<META http-equiv="PICS-Label" content='(PICS-1.0 "http://www.rsac.org"
labels on "1996.11.05T08:15-0500"
until "1996.12.31T23:59-0000"
for "http://www.rsac.org/index.html"
by "RSAC "
rating (language 2 nudity 0 violence 1))'>
</HEAD>

The core of the rating label is the rating string, which provides a list of category/value pairs. For each category, the name and the associated value are listed.

What PICS has defined

PICS has defined two specifications—one for creating rating systems and one for creating rating labels. A rating system defines the criteria for how content is rated. Based on the PICS specification for rating systems, any group or individual could define a system for rating content. Using the PICS specification, you could take the MPAA rating system and define it as a PICS-compliant rating system.

The PICS specification is quite extensive, and it allows for a system to contain multiple categories. The MPAA system has only one category with five values: G, PG, PG-13, R, and NC-17. It has been criticized for being too simplistic and not offering granularity on multiple dimensions. PICS solves this problem by allowing the creator of the rating system to have great flexibility in how the system is defined.

PICS has not defined an actual rating system or an actual scheme for rating Internet content. PICS is a framework and a language that allows any group or organization to rate content on their own criteria. PICS has not created a replacement for the movie rating system, nor does it intend to.

For more information about rating systems, see the PICS specification on their Web site: http://www.w3.org External Link.

Amendments to the PICS specification

The PICS specification makes no provisions for storing information on rating systems locally. On the Microsoft Windows® platform, the text description for PICS rating systems is contained in a text file with an .rat extension. This file would contain all the category and value information that PICS has defined as necessary. Microsoft may define fields for information about a given rating system, including its PICS rating server URL if it has one.

What Internet content providers should know about PICS

Internet Content Providers (ICPs) need to be aware that they must take the initiative in getting their content rated by a PICS-compliant rating system. For a rating system to be useful, the browser application must deny access to sites that are unrated. ICPs should contact the PICS committee for a listing of rating groups that are based on PICS.

Microsoft is committed to supporting the PICS standard and providing API and reference information for other products that want to support PICS. In addition, Microsoft is assisting several third-party groups to create PICS-based rating systems. In particular, the Recreation Software Advisory Council (RSAC) has created a rating system called RSACi. Their Web site, http://www.rsac.org External Link, provides a simple online mechanism for getting content rated through their system.

What developers of Web authoring tools should know about PICS

Developers of Web authoring tools need to be PICS-aware so that their tools support the ability to easily enter META tags into Web pages. Web authoring tools can help promote the PICS technology by providing templates or wizards for adding PICS ratings to documents.

Of significant importance is the ability to maintain ratings for groups or "virtual trees" of pages. Some PICS-compliant rating systems might offer ratings for groups of content. This will allow larger sites to section adult content from general audience content. Web authoring and management tools need to provide the ability to propagate rating information across user-defined groups of pages.

Microsoft intends to provide support for the easy addition of PICS-compliant rating information into appropriate Internet content tools.

Internet Ratings API

The Microsoft Internet Ratings API provides Win32®-based applications with easy access to PICS-based Internet ratings support and related services. These functions provide any application with access to a PICS rating parsing engine, as well as a mechanism for comparing ratings against the user information settings in Internet Explorer 4.0. This API will be available as part of Internet Explorer 4.0.

The functions in the Internet Ratings API set facilitate access to the ratings support in the following ways:

  • Provide a common interface for parsing and obtaining PICS-compliant rating information. A browser or other application can support ratings with the addition of only a few function calls. By providing task-oriented functions, applications need only make a few function calls to support ratings.
  • Eliminate the need for individual applications to define their own control systems. With this API, applications need only find the rating information for a given piece of content. Additional APIs for retrieving some types of Internet ratings are provided.

Overview of Internet ratings functions

The PICS specification allows for rating information to appear in HTML tags, in HTTP headers, and on a third-party URL. For performance reasons, each individual browser is responsible for obtaining HTML- and HTTP-based rating information (for details on obtaining these mechanisms, consult the PICS specification).

The following table summarizes the PICS-support API functions. This table lists all the functions for finding, pairing, and comparing rating information.
Function | Description
RatingAccessDeniedDialog,RatingAccessDeniedDialog2 | Displays a system dialog box informing the user that access has been denied.
RatingCheckUserAccess | Takes in a PICS rating, parses it, and compares it against what a specified user can see.
RatingEnable | Enables and disables ratings.
RatingEnabledQuery | Specifies whether ratings are on or off.
RatingFreeDetails | Frees a pointer to denial information.
RatingObtainCancel | Cancels a call to RatingObtainQuery.
RatingObtainQuery | Obtains ratings from certain locations and compares them.
RatingSetupUI | Displays a modal dialog box that allows a supervising parent to set levels of restrictions.

Using the Internet ratings functions

A browser or other application would typically use the rating functions in the following fashion:

  1. The browser starts, and the user connects to the Internet.
  2. The user enters a URL.
  3. The browser calls the RatingEnabledQuery function. If the function returns S_FALSE, the browser allows access to the content.
  4. The browser calls the RatingObtainQuery function and passes the URL. The function checks the local list, and then the third-party list or any third-party add-on is activated. If the function finds a rating for the URL, it calls RatingCheckUserAccess with the rating. If RatingObtainQuery does not return an error immediately, eventually the browser's callback function will be called.
  5. Meanwhile, the browser searches for a rating label within the content being downloaded from the site. If it finds an HTML/HTTP rating, it calls the RatingCheckUserAccess function.
  6. If no rating label is found within the document, the browser calls RatingCheckUserAccess with a NULL rating label, to determine whether the user can access unrated content.
  7. When both RatingCheckUserAccess and RatingObtainQuery have been called, the browser has received at least one explicit access-allowed or access-denied report. If RatingObtainQuery explicitly allowed or denied access, that result should override any rating found in the document and the user's ability to see unrated content.
  8. If access is denied, the browser calls the RatingAccessDeniedDialog function. Depending on the supervisor's response to the dialog box, this function can indicate that access should be allowed after all.
  9. If access is allowed, the browser displays the content.

Finding HTML/HTTP rating labels

The PICS specification defines the Backus-Naur Form (BNF) syntax for rating information, or rating nuggets. PICS specifies that rating nuggets can appear as part of HTML documents, within the header tags. The PICS specification also allows for rating information to appear as part of the HTTP headers.

For performance and logistic reasons, it is the responsibility of the browser to obtain HTML- and HTTP-level ratings. Details on how to find HTML-based ratings are part of the PICS specification. Details on HTTP ratings and the associated HTTP header are specified by PICS.

The PICS committee might eventually provide reference code for applications that want to find HTML/HTTP-based ratings.


Internet Ratings API Reference

This section contains detailed reference information about the functions in the Microsoft Internet Ratings API.

  • RatingAccessDeniedDialog
  • RatingAccessDeniedDialog2
  • RatingCheckUserAccess
  • RatingEnable
  • RatingEnabledQuery
  • RatingFreeDetails
  • RatingObtainCancel
  • RatingObtainQuery
  • RatingSetupUI


RatingAccessDeniedDialog

HRESULT RatingAccessDeniedDialog(
    HWND hwndParent,
    LPCTSTR pszUsername,
    LPCTSTR pszContentDescription,
    LPVOID pRatingDetails
);

Displays a modal dialog box telling the user that access to the requested content is denied. The supervisor can set an option that adds controls to the dialog box; these controls would allow a supervisor to enter a user name and password to override the rating and allow access.

  • Returns one of the following values:
    S_OK | The supervisor entered the password. Access should be allowed.
    S_FALSE | The user is still denied access to the content.
    Error values | An error occurred.
hwndParent
Handle to the parent window for the modal dialog box.
pszUsername
Address of a string that contains the name of the user who was denied access. If this parameter is NULL, the user name is extracted from the structure specified by pRatingDetails, or the current user name is used.
pszContentDescription
Address of a string that describes the content to which access was denied.
pRatingDetails
Opaque pointer returned by the RatingCheckUserAccess function. This parameter can provide the dialog box with additional information about why access was denied, such as whether the site is considered rated, which ratings exceeded limits, and where the rating was obtained.

See also RatingCheckUserAccess


RatingAccessDeniedDialog2

HRESULT RatingAccessDeniedDialog2(
     HWND hwndParent,
     LPCSTR pszUsername,
     LPVOID pRatingDetails);

This function is identical in functionality to RatingAccessDeniedDialog except that if a ratings dialog box is already being displayed modal to the specified parent window, the details from the second call are inserted into the existing dialog box.

  • Returns one of the following values:
    S_OK | The supervisor entered the password. Access should be allowed.
    S_FALSE | The user is still denied access to the content.
    Error values | An error occurred.
hwndParent
Handle to the parent window for the modal dialog box.
pszUsername
Address of a string that contains the name of the user who was denied access. If this parameter is NULL, the user name is extracted from the structure specified by pRatingDetails, or the current user name is used.
pRatingDetails
Opaque pointer returned by the RatingCheckUserAccess function. This parameter can provide the dialog box with additional information about why access was denied, such as whether the site is considered rated, which ratings exceeded limits, and where the rating was obtained.

See also RatingCheckUserAccess


RatingCheckUserAccess

HRESULT RatingCheckUserAccess(
    LPCTSTR pszUsername,
    LPCTSTR pszURL,
    LPCTSTR pszRatingInfo,
    LPBYTE pData,
    DWORD cbData,
    LPVOID *ppRatingDetails
);

Determines whether the user is allowed to view the given content based on the associated rating label. An application calls this function when it finds a rating label.

  • Returns one of the following values:
    S_OK | Access is allowed.
    S_FALSE | Access is denied.
    Error values | Content should be considered unrated.
pszUsername
Address of a string that contains the name of the user whose access to the content should be validated. A NULL value indicates the currently logged on user. For Internet Explorer version 3.0, NULL is the only valid value for this parameter.
pszURL
Address of the URL to which the rating label is to apply. The function uses this parameter to validate the corresponding field in the rating label, to verify that the rating label actually belongs to the URL for which the label was obtained. This parameter can be NULL if a URL is not applicable.
pszRatingInfo
Address of the PICS label to parse and verify (for example, the text between the "content" single quotation marks in the example in Example of HTML Tagged Ratings). This parameter can be NULL if the application cannot find a rating in the content itself; in this case, the function returns a value that indicates whether the user is allowed to see unrated content.
pData and cbData
Address of the content being rated and the length, in bytes, of the content data stream. These parameters may be necessary if the rating itself contains a hash of the data for security reasons. If pData is NULL, the cbData parameter is ignored, and the hash cannot be validated.
ppRatingDetails
Address of a variable that contains a pointer to an opaque data structure that describes in more detail why access to the content is denied. This parameter has meaning only to the RatingAccessDeniedDialog function. This parameter can be NULL, in which case the dialog box created by RatingAccessDeniedDialog cannot report detailed information to the user. If this parameter is not NULL, the application must call the RatingFreeDetails function to free the data, no matter what value the RatingCheckUserAccess function returns or what value is stored in ppRatingDetails.

This function allows ratings of any content type, including CD-ROMs, news groups, Web sites, and so on, provided the client application can find the rating information. The RatingObtainQuery function makes an internal call to the RatingCheckUserAccess function before calling the application's callback function.

See also RatingAccessDeniedDialog, RatingFreeDetails, RatingObtainQuery


RatingEnable

HRESULT RatingEnable(
     HWND hwndParent,
     LPCSTR pszUsername,
     BOOL fEnable);

Enables or disables ratings.

  • Returns one of the following values:
    S_OK | If fEnable was TRUE, ratings have been enabled. Otherwise, ratings were disabled.
    S_FALSE | Ratings were not successfully enabled or disabled.
    E_ACCESSDENIED | Ratings were enabled, and the user specified a bad password.
    HRESULT_FROM_WIN32(ERROR_BAD_USERNAME) | The specified username was invalid.
hwndParent
Handle of a parent window used for any dialog boxes that might be presented.
pszUsername
Address of a string that contains the name of the user requesting that ratings should be enabled or disabled.
fEnable
Boolean value indicating whether ratings should be enabled or disabled. TRUE indicates that ratings should be enabled. FALSE indicates the contrary.


RatingEnabledQuery

HRESULT RatingEnabledQuery(void)

Reports whether ratings should be enforced or not. If the supervisor has not configured any restrictions or has temporarily disabled them, the application may allow access to all content and need not call any other rating functions.

  • Returns one of the following values:
    S_OK | Ratings are enabled and should be enforced.
    S_FALSE | Ratings are disabled and should be ignored.


RatingFreeDetails

HRESULT RatingFreeDetails(
    LPVOID pRatingDetails
);

Frees the detail information returned by the RatingCheckUserAccess function.

pRatingDetails
Opaque pointer returned by RatingCheckUserAccess.

See also RatingCheckUserAccess


RatingObtainCancel

HRESULT RatingObtainCancel(
    HANDLE hRatingObtainQuery
);

Allows a browser to cancel its request to obtain the rating for a URL.

hRatingObtainQuery
Handle obtained by a previous call to the RatingObtainQuery function.

See also RatingObtainQuery


RatingObtainQuery

HRESULT RatingObtainQuery(
    LPCTSTR pszTargetUrl,
    DWORD dwUserData,
    void (*fCallback)(
        DWORD dwUserData,
        HRESULT hres,
        LPCTSTR pszRating,
        LPVOID lpvRatingDetails
    ),
    HANDLE *phRatingObtainQuery
);

Encapsulates the process of checking ratings that appear on a local list, third-party PICS server, or future third-party add-on rating services.

pszTargetUrl
URL whose ratings are to be queried.
dwUserData
Data to be passed to the callback function specified by fCallback.
fCallback
Application-defined function that is called upon completion. This function is called in the context of a different thread than the one that called RatingObtainQuery.

The callback function has the following parameters:
dwUserData | Data supplied in the initial call to RatingObtainQuery.
hres Result of the query. Can be one of the following values:
S_OK | Rating found and access allowed.
S_FALSE | Rating found and access denied.
Any error values | Rating or service unavailable; look for ratings from other sources if possible.
pszRating | Rating information for the document if it is available. (Note that the application can choose to ignore this parameter because RatingCheckUserAccess has already been called to generate the hres parameter).
lpvRatingDetails | Token that can be used in the RatingAccessDeniedDialog dialog box. This must be freed with a call to RatingFreeDetails.

phRatingObtainQuery
Address of a handle that can be used to cancel this operation. This parameter can be NULL if the handle is not needed.

A browser obtains the URL from the user and calls this function. Asynchronously, this function searches for a rating for the specified document. When the search ends, the function calls the application's callback function, on a different thread than the one that called RatingObtainQuery. While waiting for the callback to be called, browsers may choose to download the content but prevent the user from accessing it until the query is resolved.

If RatingObtainQuery returns an error, the application should assume the site is unrated by local and third-party ratings, and look for the HTML/HTTP-level ratings itself.


RatingSetupUI

HRESULT RatingSetupUI(
    HWND hwndParent,
    LPCSTR pszUsername
);

Displays a modal dialog box that allows a supervising parent to set levels of restrictions. The RatingCheckUserAccess function uses these settings to compare against rating labels.

hwndParent
Handle to the parent window for the modal dialog box.
pszUsername
Address of a string that contains the name of the user whose settings should be configured. If this parameter is NULL, settings for all users are set. This parameter must be NULL in Internet Explorer version 3.0.

This function ensures that the current user is a supervisor before allowing access to the configuration user interface.


Microsoft Script Debugger for Internet Explorer

Microsoft Script Debugger for Internet Explorer is a debugging environment that extends Microsoft Internet Explorer and Microsoft Internet Information Server (IIS) by allowing Web developers to browse, edit, and debug .htm and .asp pages that contain Visual Basic Scripting Edition (VBScript) or JScript (Microsoft's implementation of JavaScript). The Microsoft Script Debugger gives developers a seamless way to combine HTML and script development. Developers can also use the debugger to test programs written in Sun Microsystems Java and run using the Microsoft Java Virtual Machine (VM), and to debug scripts for any scripting language engine that supports ActiveX debugging interfaces.

The Script Debugger provides the same functionality as traditional debuggers, including the ability to:

  • Set and clear breakpoints.
  • Step through and over procedures.
  • Display and change the values of variables and properties.
  • Evaluate expressions.
  • View the call stack, and navigate to any currently-loaded procedure.

The Script Debugger also includes the ability for developers to open and edit HTML pages. The Script Debugger supports script colorization for maximum readability.

The Script Debugger and accompanying documentation is available for download at http://www.microsoft.com/scripting/.


Internet Shortcuts API Reference

This topic explains the Internet Shortcuts API for managing "shortcuts" to URL locations.

IUniformResourceLocator Interface

Internet Shortcut Global Functions

Internet Shortcut Enumerated Types

Internet Shortcut Structures


Internet Shortcut Enumerated Types

This section contains information on the following Internet Shortcut enumerated types:

  • IURL_SETURL_FLAGS
  • IURL_SETURL_INVOKECOMMAND_FLAGS
  • MIMEASSOCIATIONDIALOG_IN_FLAGS
  • TRANSLATEURL_IN_FLAGS
  • URLASSOCIATIONDIALOG_IN_FLAGS


Internet Shortcut Global Functions

This section contains information about the following Internet Shortcut global functions:

  • InetIsOffline
  • MIMEAssociationDialog
  • TranslateURL
  • URLAssociationDialog


InetIsOffline

BOOL InetIsOffline (
    DWORD dwFlags
);

Determines whether the system is connected to the Internet.

  • Returns TRUE if the local system in not currently connected to the Internet. Returns FALSE if the local system is connected to the Internet or if no attempt has yet been made to connect to the Internet.
dwFlags
Input flags for the function. This must be set to zero.


IUniformResourceLocator Interface

This section provides information about the following IUniformResourceLocator interface methods:

  • IUniformResourceLocator::GetURL
  • IUniformResourceLocator::InvokeCommand
  • IUniformResourceLocator::SetURL


IUniformResourceLocator::GetURL

HRESULT GetURL(
    LPSTR *ppszURL
);

Retrieves an object's uniform resource locator (URL).

  • Returns S_OK if the object's URL was retrieved successfully. If the object does not have a URL associated with it, the function returns S_FALSE and sets ppszURL to NULL. Otherwise, the return value is an error code that can be one of the following:
    E_OUTOFMEMORY | There is not enough memory to complete the operation.
    IS_E_EXEC_FAILED | The URL's protocol handler failed to run.
    URL_E_INVALID_SYNTAX | The URL's syntax is invalid.
    URL_E_UNREGISTERED_PROTOCOL | The URL's protocol does not have a registered protocol handler.
ppszURL
Address of an LPSTR that will be filled in with a pointer to the object's URL. Because this method allocates memory for the string, you must instantiate an IMalloc interface and free the memory using IMalloc::Free when it is no longer needed. The following code fragment provides an example of how this can be done.
//  START CODE FRAGMENT
{
    // In this example, pURL is a global IUniformResourceLocator pointer.
    LPSTR lpTemp;

    hres = pURL->GetURL(&lpTemp);
    if (SUCCEEDED(hres)){
        IMalloc* pMalloc;
        hres = SHGetMalloc(&pMalloc);
        if (SUCCEEDED(hres)){
            pMalloc->Free(lpTemp);
            pMalloc->Release();
        }
    }
}
//  END CODE FRAGMENT


IUniformResourceLocator::InvokeCommand

HRESULT InvokeCommand(
    PURLINVOKECOMMANDINFO pURLCommandInfo;
);

Runs a command on an object's URL.

  • Returns S_OK if the object's URL was opened successfully. If the object does not have a URL associated with it, the function returns S_FALSE. Otherwise, the return value is an error code that can be one of the following:
    E_OUTOFMEMORY | There is not enough memory to complete the operation.
    IS_E_EXEC_FAILED | The URL's protocol handler failed to run.
    URL_E_INVALID_SYNTAX | The URL's syntax is invalid.
    URL_E_UNREGISTERED_PROTOCOL | The URL's protocol does not have a registered protocol handler.
pURLCommandInfo
Address of a URLINVOKECOMMANDINFO structure that contains command information for the function.


IUniformResourceLocator::SetURL

HRESULT SetURL(
    LPCSTR pcszURL,
    DWORD dwInFlags
);

Sets an object's URL.

  • Returns S_OK if the object's URL was set successfully. Otherwise, the return value is an error code that can be one of the following:
    E_OUTOFMEMORY | There is not enough memory to complete the operation.
    IS_E_EXEC_FAILED | The URL's protocol handler failed to run.
    URL_E_INVALID_SYNTAX | The URL's syntax is invalid.
    URL_E_UNREGISTERED_PROTOCOL | The URL's protocol does not have a registered protocol handler.
pcszURL
Address of a zero-terminated string that contains the URL to set. The protocol scheme may be included as part of the URL.
dwInFlags
Flag value that specifies the behavior for setting the protocol scheme. This field can contain one of the following values:
IURL_SETURL_FL_GUESS_PROTOCOL | If the protocol scheme is not specified in pcszURL, the system automatically chooses a scheme and adds it to the URL.
IURL_SETURL_FL_USE_DEFAULT_PROTOCOL | If the protocol scheme is not specified in pcszURL, the system adds the default protocol scheme to the URL.


IURL_SETURL_FLAGS

typedef enum iurl_seturl_flags{
    IURL_SETURL_FL_GUESS_PROTOCOL         = 0x0001,
    IURL_SETURL_FL_USE_DEFAULT_PROTOCOL   = 0x0002
}  IURL_SETURL_FLAGS;

The following enumerated values are used with the IUniformResourceLocator::SetURL method. They are passed in as the dwInFlags parameter.

IURL_SETURL_FL_GUESS_PROTOCOL
If the protocol scheme is not specified in the pcszURL parameter to IUniformResourceLocator::SetURL, the system automatically chooses a scheme and adds it to the URL.
IURL_SETURL_FL_USE_DEFAULT_PROTOCOL
If the protocol scheme is not specified in the pcszURL parameter to IUniformResourceLocator::SetURL, the system adds the default protocol to the URL.


IURL_SETURL_INVOKECOMMAND_FLAGS

typedef enum iurl_invokecommand_flags{
    IURL_INVOKECOMMAND_FL_ALLOW_UI           = 0x0001,
    IURL_INVOKECOMMAND_FL_USE_DEFAULT_VERB   = 0x0002,
}  IURL_INVOKECOMMAND_FLAGS;

The following enumerated values are used in the dwFlags member of the URLINVOKECOMMANDINFO structure.

IURL_INVOKECOMMAND_FL_ALLOW_UI
If this bit is set, interaction with the user is allowed and the hwndParent member of the URLINVOKECOMMANDINFO structure is valid. If this bit is clear, interaction with the user is not allowed and the hwndParent member is ignored.
IURL_INVOKECOMMAND_FL_USE_DEFAULT_VERB
If this bit is set, the default verb for the Internet Shortcut's protocol is to be used and the pcszVerb member of the URLINVOKECOMMANDINFO structure is ignored. If this bit is clear, the verb is specified by pcszVerb.


MIMEAssociationDialog

HRESULT WINAPI MIMEAssociationDialog (
    HWND    hwndParent,
    DWORD   dwInFlags,
    LPCSTR  pcszFile,
    LPCSTR  pcszMIMEContentType,
    LPSTR   pszAppBuf,
    UINT    ucAppBufLen
);

Runs the unregistered MIME content type dialog box.

  • Returns S_OK if the content type was successfully associated with the extension. In this case, the extension is associated as the default for the content type, and pszAppBuf points to the string that contains the path of the specified application. The function returns S_FALSE if nothing was registered. Otherwise, the return value will be one of the following:
    E_ABORT | The user canceled the operation.
    E_FLAGS | The flag combination passed in dwInFlags is invalid.
    E_OUTOFMEMORY | There was insufficient memory available to complete the operation.
    E_POINTER | One of the input pointers is invalid.
hwndParent
Handle to the parent window of any posted child windows.
dwInFlags
Bit flag value that specifies if an association is to be registered. The bit flag is the value MIMEASSOCDLG_FL_REGISTER_ASSOC (0x0001). If this bit is set, the selected application is registered as the handler for the given MIME type. If this bit is clear, no association is registered.

An application is registered only if this flag is set and the user indicates that a persistent association is to be made.

Registration is impossible if the string at pcszFile does not contain an extension.

pcszFile
Address of a null-terminated string that contains the name of the target file. This file must conform to the content type described by the pcszMIMEContentType parameter.
pcszMIMEContentType
Address of a null-terminated string that contains the unregistered content type.
pszAppBuf
Address of a buffer that receives the path of the application specified by the user.
ucAppBufLen
Size of pszAppBuf, in characters.

Note This function does not validate the syntax of the input content type string at pcszMIMEContentType. A successful return value does not indicate that the specified MIME content type is valid.


MIMEASSOCIATIONDIALOG_IN_FLAGS

typedef enum mimeassociationdialog_in_flags{
    MIMEASSOCDLG_FL_REGISTER_ASSOC     = 0x0001
} MIMEASSOCIATIONDIALOG_IN_FLAGS;

The following enumerated value is used with the MIMEAssociationDialog function to determine how it executes.

MIMEASSOCDLG_FL_REGISTER_ASSOC
If this bit is set, the selected application is registered as the handler for the given MIME type. If this bit is clear, no association is registered.

An application is registered only if this flag is set and the user indicates that a persistent association is to be made.


Internet Shortcut Structures Internet Shortcut Structures *
  * Previous Topic: URLASSOCIATIONDIALOG_IN_FLAGS
  * Next Topic: URLINVOKECOMMANDINFO

Internet Shortcut Structures

This section provides information about the following Internet Shortcut structure:

  • URLINVOKECOMMANDINFO


TranslateURL

HRESULT WINAPI TranslateURL(
    LPCSTR pcszURL,
    DWORD dwInFlags,
    LPSTR *ppszTranslatedURL
);

Applies common translations to a given URL string, creating a new URL string.

  • Returns S_OK upon success, or S_FALSE if the URL did not require translation. If an error occurs, the function returns one of the following values:
    E_FLAGS | The flag combination passed in dwInFlags is invalid.
    E_OUTOFMEMORY | There was insufficient memory to complete the operation.
    E_POINTER | One of the input pointers is invalid.
pcszURL
Address of the URL string to be translated.
dwInFlags
Bit flags that specify how the URL string is to be translated. This value can be a combination of the following:
TRANSLATEURL_FL_GUESS_PROTOCOL | If the protocol scheme is not specified in the pcszURL parameter to TranslateURL, the system automatically chooses a scheme and adds it to the URL.
TRANSLATEURL_FL_USE_DEFAULT_PROTOCOL | If the protocol scheme is not specified in the pcszURL parameter to TranslateURL, the system adds the default protocol to the URL.
ppszTranslatedURL
Pointer variable that receives the pointer to the newly created, translated URL string, if any. The *ppszTranslatedURL parameter is valid only if the function returns S_OK.

This function does not validate the input URL string. A successful return value does not indicate that the URL strings are valid URLs.


TRANSLATEURL_IN_FLAGS

typedef enum translateurl_in_flags {
    TRANSLATEURL_FL_GUESS_PROTOCOL         = 0x0001,
    TRANSLATEURL_FL_USE_DEFAULT_PROTOCOL   = 0x0002,
} TRANSLATEURL_IN_FLAGS;

The following enumerated values are used with the TranslateURL function to determine how it will execute.

TRANSLATEURL_FL_GUESS_PROTOCOL
If the protocol scheme is not specified in the pcszURL parameter to TranslateURL, the system automatically chooses a scheme and adds it to the URL.
TRANSLATEURL_FL_USE_DEFAULT_PROTOCOL
If the protocol scheme is not specified in the pcszURL parameter to TranslateURL, the system adds the default protocol to the URL.


URLAssociationDialog

HRESULT WINAPI URLAssociationDialog(
    HWND hwndParent,
    DWORD dwInFlags,
    LPCSTR pcszFile,
    LPCSTR pcszURL,
    LPSTR pszAppBuf,
    UINT ucAppBufLen
);

Invokes the unregistered URL protocol dialog box. This dialog box allows the user to select an application to associate with a previously unknown protocol.

  • Returns S_OK if the application is registered with the URL protocol, or S_FALSE if nothing is registered. For example, the function returns S_FALSE when the user elects to perform a one-time execution via the selected application.
hwndParent
Handle to the parent window.
dwInFlags
Bit flags that specify the behavior of the function. This value can be a combination of the following:
URLASSOCDLG_FL_USE_DEFAULT_NAME | Use the default file name (that is, "Internet Shortcut").
URLASSOCDLG_FL_REGISTER_ASSOC | Register the selected application as the handler for the protocol specified in pcszURL. The application is registered only if this flag is set and the user indicates that a persistent association is desired.
pcszFile
Address of a constant zero-terminated string that contains the file name to associate with the URL's protocol.
pcszURL
Address of a constant zero-terminated string that contains the URL with an unknown protocol.
pszAppBuf
Address of a buffer that receives the path of the application specified by the user.
ucAppBufLen
The size of pszAppBuf, in characters.


URLASSOCIATIONDIALOG_IN_FLAGS

typedef enum urlassociationdialog_in_flags {
    URLASSOCDLG_FL_USE_DEFAULT_NAME  = 0x0001,
    URLASSOCDLG_FL_REGISTER_ASSOC    = 0x0002
} URLASSOCIATIONDIALOG_IN_FLAGS;

The following enumerated values are used with the URLAssociationDialog function to determine how it executes.

URLASSOCDLG_FL_USE_DEFAULT_NAME
Use the default file name (that is, "Internet Shortcut").
URLASSOCDLG_FL_REGISTER_ASSOC
Register the selected application as the handler for the protocol specified in the pcszURL parameter of URLAssociationDialog. The application is registered only if this flag is set and the user indicates that a persistent association is desired.


URLINVOKECOMMANDINFO

typedef struct  {
    DWORD    dwcbSize;
    DWORD    dwFlags;
    HWND     hwndParent;
    LPCSTR  pcszVerb;
} URLINVOKECOMMANDINFO, *PURLINVOKECOMMANDINFO;

Contains information for use with the IUniformResourceLocator::InvokeCommand method.

dwcbSize
Size of this structure, in bytes.
dwFlags
Flag value that specifies how the IUniformResourceLocator::InvokeCommand method will execute. This value can be a combination of the following:
IURL_INVOKECOMMAND_FL_ALLOW_UI
Interaction with the user is allowed and the hwndParent member of this structure is valid. If this is not set, interaction with the user is not allowed and the hwndParent member is ignored.
IURL_INVOKECOMMAND_FL_USE_DEFAULT_VERB
Default verb for the Internet Shortcut's protocol is to be used and the pcszVerb member is ignored. If this bit is not set, the verb is specified by pcszVerb.
hwndParent
Handle to the parent window. If dwFlags is set to IURL_INVOKECOMMAND_FL_USE_DEFAULT_VERB, this member is ignored.
pcszVerb
Address of a zero-terminated string that contains the verb to be invoked by IUniformResourceLocator::InvokeCommand. If dwFlags is set to IURL_INVOKECOMMAND_FL_USE_DEFAULT_VERB, this member is ignored.


About the Task Scheduler

The Task Scheduler allows you to perform automated tasks on a chosen computer. The Task Scheduler monitors whatever criteria you choose and executes the task when the criteria for executing the task have been met. For example, you can have the computer run ScanDisk at 7:00 P.M. every Sunday.

What Is a Task?

What Is a Trigger?

What Is an Idle Trigger?

What Is a Scheduled Work Item?

What Is a Task?

A task is any object that the Task Scheduler can execute. These include any of the following (as supported by the operating system on which the task will execute): Win32® application, Win16 application, OS/2 application, MS-DOS® application, batch file (*.bat), command file (*.cmd), or any properly registered file type. A task has one or more triggers that determine when the task should be executed.

You use the ITask interface to control and modify tasks.

What Is a Trigger?

A trigger is a set of criteria that, when met, will activate and cause a task to be executed. There are two types of triggers: time-based and event-based.

Time-based triggers activate at a specified point in time. Not only can you set the time that they become active, but you can also have them activate once, daily, weekly, monthly, on a specified day of the month (the third day of the month), or on a specified day of the week of a month (the second Tuesday of the month).

Event-based triggers activate in response to certain system events. There are event-based triggers that become active when the system starts up, when a user logs on to the local computer, or when the system becomes idle. The last of these are known as idle triggers.

You use the ITaskTrigger interface to control and modify triggers.

What Is an Idle Trigger?

When no keyboard or mouse input occurs, the computer is considered to be in an idle state. An idle trigger is an event-based trigger that becomes active a specified amount of time after the computer becomes idle. When you set the idle-related flags for a task, you create an idle trigger. You use the IScheduledWorkItem::SetIdleWait method to set the amount of time that the system is idle before the task is executed. You can use the IScheduledWorkItem::GetIdleWait method to retrieve this same value. There are three idle-related flags that can be set on a given task: TASK_FLAG_START_ONLY_IF_IDLE, TASK_FLAG_KILL_ON_IDLE_END, and TASK_FLAG_RESTART_ON_IDLE_RESUME (see ITask::SetTaskFlags).

Note The Task Scheduler service that monitors triggers on Microsoft® Windows NT® does not monitor idle conditions and does not activate any idle triggers. This does not, however, affect the task itself. The TASK_EVENT_TRIGGER_ON_IDLE trigger type and the task idle time can be set and retrieved on Windows NT. The information associated with these triggers and flags is persistent. The only difference is that, on Windows NT, the idle trigger is never activated.

What Is a Scheduled Work Item?

A scheduled work item is an item that the Task Scheduler service runs at a time specified by the item's trigger(s). Currently the only type of scheduled work item is a task.

The IScheduledWorkItem interface contains methods that are supported by all types of scheduled work items. Tasks are manipulated using the ITask interface, which derives from IScheduledWorkItem.


Task Scheduler Reference

This reference describes the programming elements that are used and/or implemented by the Task Scheduler.

Interfaces

Structures

Unions

Enumerated Types


Task Scheduler API

This section describes the Task Scheduler. It contains examples as well as references for the OLE interfaces necessary to work with the Task Scheduler.

About the Task Scheduler

Programming the Task Scheduler

Task Scheduler Reference


Programming the Task Scheduler

The collection of interfaces and methods available to the developer from the Task Scheduler represents the programmatic techniques necessary to implement the functionality of task management.

Manipulating Scheduled Work Items

Starting the Task Scheduler Service

Task Names

Task Triggers

The Starting Point: ITaskScheduler

The Target Computer

Manipulating Scheduled Work Items

The IScheduledWorkItem interface allows you to modify an existing work item's behaviors. When you have the interface pointer to IScheduledWorkItem, you have the ability to run, terminate, or modify the characteristics for a given task. The behavior and properties of each scheduled task are accessible through the IScheduledWorkItem interface.

Starting the Task Scheduler Service

The Task Scheduler service is not started by default; the developer is responsible for determining the current running state of the Task Scheduler. The following code is an example of how to start the Task Scheduler service.

//+--------------------------------------------------------------------------
//
//  Function:   StartScheduler
//
//  Synopsis:   Start the task scheduler service if it isn't already running.
//
//  Returns:    ERROR_SUCCESS or a Win32 error code.
//
//  Notes:      This function works for either Win9x or Windows NT.
//              If the service is running but paused, does nothing.
//
//---------------------------------------------------------------------------

#define SCHED_CLASS             TEXT("SAGEWINDOWCLASS")
#define SCHED_TITLE             TEXT("SYSTEM AGENT COM WINDOW")
#define SCHED_SERVICE_APP_NAME  TEXT("mstask.exe")
#define SCHED_SERVICE_NAME      TEXT("Schedule")

DWORD
StartScheduler()
{

    OSVERSIONINFO osver;

    osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);

    // Determine what version of OS we are running on.
    GetVersionEx(&osver);

    if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
    {
        // Start the Win95 version of TaskScheduler.

        HWND hwnd = FindWindow(SCHED_CLASS, SCHED_TITLE);

        if (hwnd != NULL)
        {
            // It is already running.
            return ERROR_SUCCESS;
        }

        //
        //  Execute the task scheduler process.
        //
        STARTUPINFO         sui;
        PROCESS_INFORMATION pi;

        ZeroMemory(&sui, sizeof(sui));
        sui.cb = sizeof (STARTUPINFO);

        TCHAR szApp[MAX_PATH];
        LPTSTR pszPath;

        DWORD dwRet = SearchPath(NULL,
                                 SCHED_SERVICE_APP_NAME,
                                 NULL,
                                 MAX_PATH,
                                 szApp,
                                 &pszPath);

        if (dwRet == 0)
        {
            return GetLastError();
        }

        BOOL fRet = CreateProcess(szApp,
                                  NULL,
                                  NULL,
                                  NULL,
                                  FALSE,
                                  CREATE_NEW_CONSOLE | CREATE_NEW_PROCESS_GROUP,
                                  NULL,
                                  NULL,
                                  &sui,
                                  &pi);

        if (fRet == 0)
        {
            return GetLastError();
        }

        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);

        return ERROR_SUCCESS;
    }
    else
    {

        // If not Win95 then start the NT version as a TaskScheduler service.

        SC_HANDLE   hSC = NULL;
        SC_HANDLE   hSchSvc = NULL;

        hSC = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);

        if (hSC == NULL)
        {
            return GetLastError();
        }

        hSchSvc = OpenService(hSC,
                              SCHED_SERVICE_NAME,
                              SERVICE_START | SERVICE_QUERY_STATUS);

        CloseServiceHandle(hSC);

        if (hSchSvc == NULL)
        {
            return GetLastError();
        }

        SERVICE_STATUS SvcStatus;

        if (QueryServiceStatus(hSchSvc, &SvcStatus) == FALSE)
        {
            CloseServiceHandle(hSchSvc);
            return GetLastError();
        }

        if (SvcStatus.dwCurrentState == SERVICE_RUNNING)
        {
            // The service is already running.
            CloseServiceHandle(hSchSvc);
            return ERROR_SUCCESS;
        }

        if (StartService(hSchSvc, 0, NULL) == FALSE)
        {
            CloseServiceHandle(hSchSvc);
            return GetLastError();
        }

        CloseServiceHandle(hSchSvc);

        return ERROR_SUCCESS;
    }
}

Task Names

A task name is the name of the file that stores the task information. These files all have the .job extension and reside in the Tasks folder. You can retrieve the location of the Tasks folder from the registry by getting the data for the following value:

HKEY_LOCAL_MACHINE
    SOFTWARE
        Microsoft
            SchedulingAgent
                TasksFolder

The task names are always given in wide characters, so you need to convert the string to ANSI characters if your application is not built for Unicode. The ConvertString function handles this for you.

BOOL ConvertString(LPTSTR pszOut, LPWSTR pwszIn, DWORD dwSize)
{
#ifdef UNICODE
    if(lstrcpyn(pszOut, pwszIn, dwSize))
        {
        return TRUE;
        }
#else
    if(WideCharToMultiByte( CP_ACP,
            0,
            pwszIn,
            -1,
            pszOut,
            dwSize,
            NULL,
            NULL))
        {
        return TRUE;
        }
#endif   // UNICODE

return FALSE;
}

All the Task Scheduler methods that take a task name examine the name and add the .job extension if it is not already present.

Creating Tasks

Listing the current tasks is all well and good, but how do you create your own task? There are two ways to do this. The first is to use ITaskScheduler::NewWorkItem. This method will instantiate an ITask interface and assign it the name you provide. The second is to call ITaskScheduler::AddWorkItem. When you take this route, it is your responsibility to instantiate the ITask interface and then add the task with the name you supply.

The name you supply for the task must be unique within the Tasks folder. If a task with that name already exists, ITaskScheduler::NewWorkItem and ITaskScheduler::AddWorkItem return ERROR_FILE_EXISTS. If you get this return value, you should specify a different name and attempt to add the task again.

Deleting Tasks

You use the ITaskScheduler::Delete method to delete a task. You simply supply the name of the task and, if the task is present, it will be deleted.

Editing a Task

When you are viewing the Tasks folder in Windows® Explorer, you can edit the task by double-clicking it. When you do this, the scheduling agent actually calls the tasks object's IScheduledWorkItem::EditWorkItem method. Fortunately, this method has been exposed, so you can do the same thing programmatically without having to implement all the user interface code and resources. The only thing you have to provide is a parent window handle.

For more information on editing tasks, see Task Property Sheet.

Enumerating Tasks

To enumerate tasks, call ITaskScheduler::Enum. This gives you an IEnumWorkItems interface pointer that you can use to retrieve the names of the tasks. When you have the name of a task, you can call ITaskScheduler::Activate to get the ITask interface for the task. When you have the ITask interface pointer, you can get or set any of the task information that you want. The following example enumerates all the tasks and adds them to a list view control to display them. For additional information on list views, see List View Controls.

Note Before the list view is destroyed, the release method for ITask is called for each item in the list view. The caller of ITaskScheduler::Activate is responsible for releasing the returned pointer.

BOOL LoadTaskList(HWND hwndListView)
{
HRESULT          hr;
IEnumWorkItems  *pEnum;

hr = g_pSchedulingAgent->Enum(&pEnum);
if(SUCCEEDED(hr))
    {
    LPWSTR   *ppNames;
    DWORD    dwFetched;

    while(SUCCEEDED(pEnum->Next(5, &ppNames, &dwFetched)) && dwFetched)
        {
        DWORD i;
        TCHAR szString[MAX_PATH];

        for(i = 0; i < dwFetched; i++)
            {
            if(ConvertString(szString, *(ppNames + i), sizeof(szString)))
                {
                LV_ITEM  lvItem;
                ITask *pTask;

                ZeroMemory(&lvItem, sizeof(lvItem));
                lvItem.mask = LVIF_TEXT | LVIF_IMAGE | LVIF_PARAM;
                lvItem.pszText = szString;
                lvItem.iImage = I_IMAGECALLBACK;
                lvItem.iItem = ListView_GetItemCount(hwndListView);

                // Get the ITask for this task.
                hr = g_pSchedulingAgent->Activate(  *(ppNames + i),
                        IID_ITask,
                        (LPUNKNOWN*)&pTask);
                if(SUCCEEDED(hr))
                    {
                lvItem.lParam = (LPARAM)pTask;

                // Add the item to the list.
                ListView_InsertItem(hwndListView, &lvItem);
                }
            }

            // Free the string.
            CoTaskMemFree(*(ppNames + i));
            }

        // Free the array.
        CoTaskMemFree(ppNames);
        }

    pEnum->Release();
    return TRUE;
    }

return FALSE;
}

Executing and Terminating a Task

If you want to programmatically cause a task to run, you simply call the task object's IScheduledWorkItem::Run method. This method attempts to execute the task and returns as soon as the task has started. The Task Scheduler service must be running for this method to succeed.

If it becomes necessary for you to terminate a running task, you can use IScheduledWorkItem::Terminate. This method attempts to terminate the task and returns a success/failure code, informing your application if it was successful or not. IScheduledWorkItem::Terminate attempts to gracefully shut down the application by sending it a WM_CLOSE message. It then waits approximately three minutes for the process to terminate. If the process has not terminated within that three minutes, IScheduledWorkItem::Terminate uses TerminateProcess to terminate the task. As you can see, there is potential here for data loss if the application must be terminated the hard way. Therefore, you should avoid terminating tasks if at all possible.

Manipulating Tasks: ITask

ITask is the interface you use to control a task object. You can set and retrieve all of the task's information, execute and terminate the task, add and delete triggers, and even allow the user to modify the task with a standard user interface.

ITask implements all the methods necessary to set and retrieve all of the task's information. For a complete list of the methods for affecting the task, see the ITask references. The method names are rather self-explanatory.

Task Property Sheet

The IProvideTaskPage::GetPage method provides the ability to retrieve the property sheet page associated with a task object. The information for the task object's general page, schedule, and settings is available from the GetPage method.

VOID EditTaskSettings(ITask *pTask)
{
    IProvideTaskPage   *ptp;
    PROPSHEETHEADER     psh;
    HPROPSHEETPAGE      hpage;

    // Display the "Settings" property page.
    pTask->QueryInterface(IID_IProvideTaskPage, (VOID**)(IProvideTaskPage**)&ptp);

    // The settings will be saved to the task object on release.
    ptp->GetPage(TASKPAGE_SETTINGS, TRUE, &hpage);

    // Display the page in its own property sheet.
    psh.dwSize=sizeof(PROPSHEETHEADER);
    psh.dwFlags=PSH_DEFAULT;
    psh.hwndParent=NULL;
    psh.hInstance=NULL;
    psh.pszCaption=TEXT("Just the settings page on the task object");
    psh.phpage=&hpage;
    psh.nPages=1;

    PropertySheet(&psh);
}

Task Triggers

Applications can use the methods available from the task scheduler interfaces to access, set, or modify the trigger for a task. Triggers specify task start times, repetition criteria, and other parameters.

Creating and Deleting Triggers

When you use IScheduledWorkItem::CreateTrigger, you are creating a brand new ITaskTrigger object. IScheduledWorkItem::CreateTrigger gives you both the new trigger's numeric index and the ITaskTrigger interface pointer. You can then use this interface to modify the trigger parameters. By the same token, IScheduledWorkItem::DeleteTrigger deletes the trigger that has the numeric index specified.

Manipulating Triggers: ITaskTrigger

The ITaskTrigger interface allows you to modify an existing trigger's parameters, but how do you get the ITaskTrigger interface for a trigger object? There are two ways to do this:

  • Create a new trigger using IScheduledWorkItem::CreateTrigger.
  • Use IScheduledWorkItem::GetTrigger. This method takes the desired trigger's numerical index.

When you have the interface, you can use ITaskTrigger::SetTrigger to set the trigger information and ITaskTrigger::GetTrigger to get the trigger object's information. ITaskTrigger::GetTriggerString gives you a formatted string describing the trigger. You can use this string to display information about the trigger.

The Starting Point: ITaskScheduler

The ITaskScheduler interface is the starting point for programming the Task Scheduler. ITaskScheduler allows you to enumerate, add, modify, and delete tasks, and administer tasks on another computer. All you have to do to obtain the ITaskScheduler interface is to call CoCreateInstance with the scheduling agent class identifier and interface identifier. The following example shows how this is done.

#include <mstask.h>

ITaskScheduler  *g_pSchedulingAgent;

BOOL Initialize(void)
{
HRESULT  hr;

CoInitialize(NULL);

hr = CoCreateInstance( CLSID_CSchedulingAgent,
            NULL,
            CLSCTX_INPROC_SERVER,
            IID_ITaskScheduler,
            (LPVOID*)&g_pSchedulingAgent);

return SUCCEEDED(hr);
}

When you no longer need the ITaskScheduler interface, simply call its Release method. All of the methods contained within the IUnknown interface are inherited in ITaskScheduler; these include QueryInterface, AddRef, and Release. Don't forget that you need to call CoInitialize or OleInitialize before calling CoCreateInstance. Also, be sure to call CoUninitialize or OleUninitialize when you are done using OLE.

The Target Computer

In Task Scheduler terms, the target computer is the computer to which any instance of the ITaskScheduler interface is associated. All of the tasks that each instance of the ITaskScheduler interface controls are stored on the target computer and will run on the target computer. When you create a new instance of ITaskScheduler, the local computer is the target computer by default.

You can use ITaskScheduler to administer tasks on a remote computer. There are constraints for remote task administration:

  • You can view tasks on a remote computer running Windows NT® only if you are an administrator on that remote computer.
  • You can edit tasks on a remote Windows® 95 computer only if that remote computer has remote registry software installed and shares the x$ share, where x is the hard drive on which the Tasks folder resides.
  • A computer running Windows 95 must have the remote registry service installed before it can set the target computer to a remote computer, or be specified as a remote target computer.

    For more information on installing the remote registry service, see article Q141460 in the Microsoft Knowledge Base.

You use ITaskScheduler::SetTargetComputer to change the target computer and ITaskScheduler::GetTargetComputer to get the name of the target computer. Computer names are always in Universal Naming Convention (UNC) format.


Enumerated Types Enumerated Types *
  * Previous Topic: TRIGGER_TYPE_UNION
  * Next Topic: TASK_TRIGGER_TYPE

Enumerated Types

This section describes the Task Scheduler enumerated types.


TASK_TRIGGER_TYPE

typedef enum _TASK_TRIGGER_TYPE {
    TASK_TIME_TRIGGER_ONCE            = 0,
    TASK_TIME_TRIGGER_DAILY           = 1,
    TASK_TIME_TRIGGER_WEEKLY          = 2,
    TASK_TIME_TRIGGER_MONTHLYDATE     = 3,
    TASK_TIME_TRIGGER_MONTHLYDOW      = 4,
    TASK_EVENT_TRIGGER_ON_IDLE        = 5,
    TASK_EVENT_TRIGGER_AT_SYSTEMSTART = 6,
    TASK_EVENT_TRIGGER_AT_LOGON       = 7
} TASK_TRIGGER_TYPE, *PTASK_TRIGGER_TYPE;

Defines the type of trigger the task will use. This enumerated type is part of the TASK_TRIGGER structure. The trigger type determines when the task will run.

TASK_TIME_TRIGGER_ONCE
Trigger is set to run the task a single time.
TASK_TIME_TRIGGER_DAILY
Trigger is set to run the task on a daily interval.
TASK_TIME_TRIGGER_WEEKLY
Trigger is set to run the task on specific days of the week on a weekly interval.
TASK_TIME_TRIGGER_MONTHLYDATE
Trigger is set to run the task on a specific day(s) of the month.
TASK_TIME_TRIGGER_MONTHLYDOW
Trigger is set to run the task on specific days, weeks, and months.
TASK_EVENT_TRIGGER_ON_IDLE
Trigger is set to run the task when the system becomes idle (Windows 95 only).
TASK_EVENT_TRIGGER_AT_SYSTEMSTART
Trigger is set to run the task at system startup.
TASK_EVENT_TRIGGER_AT_LOGON
Trigger is set to run the task when a user logs on.


TASKPAGE

typedef enum  _TASKPAGE{
    TASKPAGE_TASK     = 0,
    TASKPAGE_SCHEDULE = 1,
    TASKPAGE_SETTINGS = 2
    }TASKPAGE;

Defines characteristics of a task object property. The enumeration values are used in the tpType parameter of the IProvideTaskPage::GetPage function.

TASKPAGE_TASK
Application name.
Parameters to be passed to the application.
Working directory.
Comment information.
Windows NT only Account name and password.
TASK_TRIGGER_FLAG_DISABLED flag.
TASKPAGE_SCHEDULE
Schedule properties for the task object. The user can create and delete task triggers from this page, and edit all of the properties for each of the triggers.
TASKPAGE_SETTINGS
TASK_FLAG_DELETE_WHEN_DONE flag.
MaxRunTime of the task.
Windows 95 only IdleWait.
Windows 95 only TASK_FLAG_START_ONLY_IF_IDLE flag.
Windows 95 only TASK_FLAG_KILL_ON_IDLE_END flag.
Windows 95 only TASK_FLAG_DONT_START_IF_ON_BATTERIES flag.
Windows 95 only TASK_FLAG_KILL_IF_GOING_ON_BATTERIES flag.


Interfaces

The interfaces and methods described in the following sections illustrate the necessary implementations of functionality available within the Task Scheduler. Many of these same task options are available to the user from the Scheduled Tasks user interface.

The collection of interfaces and methods available to the developer from Task Scheduler represents the programmatic techniques necessary to implement the functionality of task management.

IEnumWorkItems
IProvideTaskPage
IScheduledWorkItem
ITaskScheduler
ITask
ITaskTrigger


IEnumWorkItems::Clone

HRESULT Clone(
    IEnumWorkItems ** ppEnumWorkItems
);

Creates another enumerator that contains the same enumeration state as the current one. Using this method, a client can record a particular point in the enumeration sequence and return to that point later. The new enumerator supports the same interface as the original.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The argument is not valid.
    E_OUTOFMEMORY | There is not enough memory available.
    E_UNEXPECTED | An error occurred.
ppEnumWorkItems
Address of a pointer to an IEnumWorkItems interface that will be assigned to the newly created enumeration. If the method fails, this parameter is undefined.

Back to top


IEnumWorkItems

Applications use the methods of the IEnumWorkItems interface to enumerate tasks. The following list of methods is organized in vtable order.

IEnumWorkItems methods
Next
Skip
Reset
Clone


IEnumWorkItems::Next

HRESULT Next(
    ULONG celt,
    LPWSTR ** rgpwszNames,
    ULONG * pceltFetched
);

Retrieves the next celt tasks in the enumeration sequence. If there are fewer than the requested number of elements left in the sequence, the remaining elements are retrieved.

  • Returns one of the following values:
    S_OK | The number of tasks retrieved equals the number requested.
    S_FALSE | The number returned is less than the number requested (thus there are no more tasks to enumerate).
    E_INVALIDARG | A parameter is invalid.
    E_OUTOFMEMORY | Not enough memory is available.
celt
Number of tasks to retrieve.
rgpwszNames
Address of an array of pointers to character strings that contain the file names of the tasks returned from the enumeration sequence. These file names are taken from the Tasks folder and have the .job extension. You must free each LPWSTR in the array and the array itself using CoTaskMemFree.
pceltFetched
Address of a value that contains the number of tasks returned in rgpwszNames. If the celt parameter is 1, this parameter can be NULL.

Back to top


IEnumWorkItems::Reset

HRESULT Reset(void);

Resets the enumeration sequence to the beginning.

  • Returns S_OK if successful, or E_OUTOFMEMORY if there is not enough available memory.

A call to this method does not guarantee that the same set of tasks will be enumerated after the reset, because it depends on the collection being enumerated.

Back to top


IEnumWorkItems::Skip

HRESULT Skip(
    ULONG celt
);

Skips the next celt number of tasks in the enumeration sequence.

  • Returns one of the following values:
    S_OK | The number of elements skipped equals celt.
    S_FALSE | The number of elements remaining in the sequence is less than celt.
    E_INVALIDARG | celt is less than or equal to zero.
celt
Number of tasks to be skipped.

Back to top


IProvideTaskPage::GetPage

HRESULT IProvideTaskPage::GetPage(
    TASKPAGE tpType,
    BOOL  fPersistChanges,
    HPROPSHEETPAGE * phPage
);

Provides the ability to retrieve one or more property sheet pages associated with a task object.

  • Returns S_OK if the method was successful, or STG_E_NOTFILEBASEDSTORAGE if the task has not been saved to disk.
tpType
Specific page to return. The page type is one of the enumerated types of TASKPAGE defined as:
TASKPAGE_TASK | General page property.
TASKPAGE_SCHEDULE | Schedule properties for the task object.
TASKPAGE_SETTINGS | Settings properties for the task object.
fPersistChanges
If TRUE, the page updates the persisted task object automatically if there is a change made on release. If FALSE, the caller is responsible for persisting task object changes by calling IPersistFile::Save on the task object.
phPage
Returned page handle for the task object.

See also TASKPAGE

Back to top


IProvideTaskPage

Applications use the method of the IProvideTaskPage interface to have access to the task object's property sheet settings.

IProvideTaskPage method
GetPage


IScheduledWorkItem::CreateTrigger

HRESULT CreateTrigger(
    WORD * piNewTrigger,
    ITaskTrigger ** ppTrigger
);

Creates a task trigger.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
piNewTrigger
Address of a value that specifies the new trigger. piNewTrigger receives the new trigger index value. DeleteTrigger would take this value to delete the trigger.
ppTrigger
Address of a pointer to an ITaskTrigger interface.

See also IScheduledWorkItem::DeleteTrigger

Back to top


IScheduledWorkItem::DeleteTrigger

HRESULT DeleteTrigger(
    WORD iTrigger
);

Deletes a task trigger.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
iTrigger
Value that specifies the trigger to be deleted. The value associated with a trigger is established when a trigger is created by CreateTrigger.

See also IScheduledWorkItem::CreateTrigger

Back to top


IScheduledWorkItem::EditWorkItem

HRESULT EditWorkItem(
    HWND  hParent,
    DWORD dwReserved
);

Opens the configuration properties for the work item.

  • Returns one of the following values:
    S_OK | The operation was successful.
    STG_E_NOTFILEBASEDSTORAGE | The task object is not persistent.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
hParent
Handle to the parent window of the configuration properties window.
dwReserved
Reserved for internal use; this must be zero.

When you open the Properties page for a task from Windows®, the Task Scheduler calls this method to display the task's properties.

Back to top


IScheduledWorkItem::GetAccountInformation

HRESULT GetAccountInformation(
    LPWSTR * ppwszAccountName
);

Retrieves the account name for the task. This method is for Windows NT®; on Windows® 9x, this method will return SCHED_E_NO_SECURITY_SERVICES, indicating the Task Scheduler security services are not available. The Task Scheduler service must be running for this method to succeed.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
    SCHED_E_NO_SECURITY_SERVICES | Security services are available only on Windows NT®.
ppwszAccountName
Address of an LPWSTR that contains the account name for the current task.

The method that invokes GetAccountInformation is responsible for freeing the string using the CoTaskMemFree function.

See also IScheduledWorkItem::SetAccountInformation


IScheduledWorkItem::GetComment

HRESULT GetComment(
    LPWSTR * ppwszComment
);

Retrieves the comment for the work item.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
ppwszComment
Character string that contains the comment retrieved from the current work item.

Back to top


IScheduledWorkItem::GetCreator

HRESULT GetCreator(
    LPWSTR * ppwszCreator
);

Retrieves the work item's creator.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
ppwszCreator
Address of an LPWSTR that contains the current task's creator. The method that invokes GetCreator is responsible for freeing this string using the CoTaskMemFree function.

See also IScheduledWorkItem::SetCreator

Back to top


IScheduledWorkItem::GetErrorRetryCount IScheduledWorkItem::GetErrorRetryCount *
  * Previous Topic: IScheduledWorkItem::GetCreator
  * Next Topic: IScheduledWorkItem::GetErrorRetryInterval

IScheduledWorkItem::GetErrorRetryCount

HRESULT GetErrorRetryCount(
    WORD * pwRetryCount
);

Not currently implemented.


IScheduledWorkItem::GetErrorRetryInterval

HRESULT GetErrorRetryInterval(
    WORD * pwRetryInterval
);

Not currently implemented. Retrieves the time interval, in minutes, between task retries after an error occurs.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
    E_NOTIMPL | Not implemented.
pwRetryInterval
Address of a value that contains the time interval between retries of the current task after an error occurs.

See also IScheduledWorkItem::SetErrorRetryInterval

Back to top


IScheduledWorkItem::GetExitCode

HRESULT GetExitCode(
    DWORD * pdwExitCode
);

Retrieves the work item's last exit code.

  • Returns the error from the last attempt to start the work item. Possible values include:
    S_OK | The attempt to start the work item was successful.
    SCHED_S_TASK_HAS_NOT_RUN | No attempt has ever been made to start this work item.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
pdwExitCode
Address of a value that is set to the exit code that the work item returned when it last stopped running. If the work item has never been started, this will be set to zero.

Back to top


IScheduledWorkItem::GetFlags

HRESULT GetFlags(
    DWORD * pdwFlags
);

Returns the flags that modify the task's behavior.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
pdwFlags
Address of a value that contains the description of how the task behaves. For a list of the flags, see IScheduledWorkItem::SetFlags.

Back to top


IScheduledWorkItem::GetIdleWait

HRESULT GetIdleWait(
    WORD * pwIdleMinutes,
    WORD * pwDeadlineMinutes
);

Retrieves the task's idle wait time.

  • Returns S_OK if successful, or E_INVALIDARG if the argument is not valid.
pwIdleMinutes
Address of a value that contains the current task's idle wait time.
pwDeadlineMinutes
Address of a value that specifies the maximum number of minutes to wait for the idle time duration contained in pwIdleMinutes to occur before running the task.

If the task has the TASK_EVENT_TRIGGER_ON_IDLE trigger, the task runs when pwIdleMinutes have elapsed since the most recent keyboard or mouse event.

If the TASK_FLAG_START_ONLY_IF_IDLE flag is set, the task will run only after a period of pwDeadlineMinutes have elapsed with no mouse or keyboard activity. The Task Scheduler service will wait up to pwDeadlineMinutes past the scheduled start time of the task for the required pwIdleMinutes of idle time to elapse.

See also IScheduledWorkItem::SetIdleWait, Idle Triggers

Back to top


IScheduledWorkItem::GetMostRecentRunTime

HRESULT GetMostRecentRunTime(
    SYSTEMTIME * pstLastRun
);

Retrieves the most recent time the work item began running.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
    SCHED_S_TASK_HAS_NOT_RUN | The task has never run.
pstLastRun
Address of a SYSTEMTIME structure that contains the most recent time the current task ran.

See also IScheduledWorkItem::GetNextRunTime

Back to top


IScheduledWorkItem::GetNextRunTime

HRESULT GetNextRunTime(
    [in, out] SYSTEMTIME * pstNextRun
);

Retrieves the next time the work item will run.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
pstNextRun
Address of a SYSTEMTIME structure that contains the next time the work item will run.

Back to top


IScheduledWorkItem::GetRunTimes

HRESULT GetRunTimes(
    const LPSYSTEMTIME pstBegin,
    const LPSYSTEMTIME pstEnd,
    WORD * pCount,
    LPSYSTEMTIME * rgstTaskTimes
);

Retrieves the work item run times for a specified time period.

  • Returns one of the following values:
    S_OK | The requested number of run times was retrieved.
    S_FALSE | The method succeeded, but fewer than the requested number of run times was retrieved. The number of run times retrieved is contained in the value pointed to by pCount. If the number of run times retrieved is zero, there are also no event-based triggers that can cause the work item to be executed during the specified time period.
    SCHED_S_EVENT_TRIGGER | No run times exist for the specified time period, but event-based triggers exist that might cause the work item to run during the specified time period.
    SCHED_S_TASK_NO_VALID_TRIGGERS | The work item is enabled but has no valid triggers.
    SCHED_S_TASK_DISABLED | The work item is disabled.
    E_INVALIDARG | One or more of the arguments are invalid.
    E_OUTOFMEMORY | There is insufficient memory to compute the result.
pstBegin
Address of a SYSTEMTIME structure that contains the starting time of the time period to check. This value is inclusive.
pstEnd
Address of a SYSTEMTIME structure that contains the ending time of the time period to check. This value is exclusive. If NULL is passed for this value, the end time is infinite.
pCount
Address of a value that specifies the number of run times to retrieve. Before calling GetRunTimes, this value contains the number of run times being requested. This can be a number between 1 and TASK_MAX_RUN_TIMES. After GetRunTimes is called, this value contains the number of run times actually retrieved.
rgstTaskTimes
Address of an array of SYSTEMTIME structures. This array contains pCount run times. This array must be freed using the CoTaskMemFree function.

Back to top


IScheduledWorkItem::GetStatus

HRESULT GetStatus(
    HRESULT * phrStatus
);

Retrieves the status of the work item.

  • Returns S_OK if the operation was successful, or E_INVALIDARG if the arguments are not valid.
phrStatus
Address of a value that contains the status of the current work item. phrStatus can be set to one of the following values:
SCHED_S_TASK_READY | Task is ready to run at its next scheduled time.
SCHED_S_TASK_RUNNING | Task is currently running.
SCHED_S_TASK_NOT_SCHEDULED | One or more of the properties that are needed to run this task on a schedule have not been set.

Back to top


IScheduledWorkItem::GetTrigger

HRESULT GetTrigger(
    WORD iTrigger,
    ITaskTrigger ** ppTrigger
);

Retrieves a task trigger.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
iTrigger
Value that specifies which trigger to retrieve.
ppTrigger
Address of a pointer to an ITaskTrigger interface. This interface contains the retrieved trigger.

Back to top


IScheduledWorkItem::GetTriggerCount

HRESULT GetTriggerCount(
    WORD * plCount
);

Retrieves the number of triggers for the current task.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
plCount
Address of a value that contains the total count of all triggers that are currently associated with the task.

Back to top


IScheduledWorkItem::GetTriggerString

HRESULT GetTriggerString(
    WORD iTrigger,
    LPWSTR * ppwszTrigger
);

Retrieves a character string that describes the task trigger.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
iTrigger
Value that specifies which trigger to retrieve.
ppwszTrigger
Address of a character string that contains the retrieved trigger description.

Back to top


IScheduledWorkItem::GetWorkItemData

HRESULT GetWorkItemData(
    WORD * pcBytes,
    BYTE ** ppBytes
);

Retrieves application-defined data associated with the work item.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
pcBytes
Number of bytes copied.
ppBytes
Address of a BYTE pointer that contains user-defined data for the current task. The method that invokes GetWorkItemData is responsible for freeing this memory by using CoTaskMemFree.

See also IScheduledWorkItem::SetWorkItemData

Back to top


IScheduledWorkItem

Applications use the methods of the IScheduledWorkItem interface to control work items. The following list of methods is organized in vtable order.

IScheduledWorkItem methods
CreateTrigger
DeleteTrigger
GetTriggerCount
GetTrigger
GetTriggerString
GetRunTimes
GetNextRunTime
SetIdleWait
GetIdleWait
Run
Terminate
EditWorkItem
GetMostRecentRunTime
GetStatus
GetExitCode
SetComment
GetComment
SetCreator
GetCreator
SetWorkItemData
GetWorkItemData
SetErrorRetryCount
GetErrorRetryCount
SetErrorRetryInterval
GetErrorRetryInterval
SetFlags
GetFlags
SetAccountInformation
GetAccountInformation


IScheduledWorkItem::Run

HRESULT Run(void);

Runs the work item. The Task Scheduler service must be running for this method to succeed.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.

Back to top


IScheduledWorkItem::SetAccountInformation

HRESULT SetAccountInformation(
    LPCWSTR pwszAccountName,
    LPCWSTR pwszPassword
);

Sets the account name and password for the task. This method is for Windows NT®; on Windows® 9x, this method will return SCHED_E_NO_SECURITY_SERVICES, indicating the Task Scheduler security services are not available. The Task Scheduler service must be running for this method to succeed.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
    SCHED_E_NO_SECURITY_SERVICES | Security services are available only on Windows NT.
pwszAccountName
LPCWSTR that contains the account name. This account name is assigned to the current task.
pwszPassword
LPCWSTR that contains the account password. This password is assigned to the current task.

See also IScheduledWorkItem::GetAccountInformation


IScheduledWorkItem::SetComment

HRESULT SetComment(
    LPCWSTR pwszComment
);

Sets the comment for the work item.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
pwszComment
Character string containing the comment to assign to the current work item.

Back to top


IScheduledWorkItem::SetCreator

HRESULT SetCreator(
    LPCWSTR pwszCreator
);

Sets the work item's creator.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
pwszCreator
LPCWSTR that contains the work item's creator.

See also IScheduledWorkItem::GetCreator

Back to top


IScheduledWorkItem::SetErrorRetryCount

HRESULT SetErrorRetryCount(
    WORD wRetryCount
);

Not currently implemented. Sets the number of times the task will try to run again if an error occurs.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
    E_NOTIMPL | Not implemented.
wRetryCount
Value assigned as the number of error retries for the current task.

See also IScheduledWorkItem::GetErrorRetryCount

Back to top


IScheduledWorkItem::SetErrorRetryInterval

HRESULT SetErrorRetryInterval(
    WORD wRetryInterval
);

Not currently implemented. Sets the time interval, in minutes, between task retries after an error occurs.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
    E_NOTIMPL | Not implemented.
wRetryInterval
Value assigned as the interval between error retries for the current task.

See also IScheduledWorkItem::GetErrorRetryInterval

Back to top


IScheduledWorkItem::SetFlags

HRESULT SetFlags(
    DWORD dwFlags
);

Sets the flags that modify the task's behavior.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
dwFlags
Value that contains a combination of one or more of the following flags:
TASK_FLAG_INTERACTIVE
This task flag is used when converting Windows NT AT service jobs into tasks. The Windows NT AT service job refers to At.exe, the Windows NT command-line utility used for creating jobs for the Windows NT Schedule service. The Task Scheduler service replaces the Schedule service and is backward-compatible with it. This conversion occurs when the Task Scheduler is installed on Windows NT; for example, installing Internet Explorer 4.0, or upgrading to Windows NT 5. During the setup process, the Task Scheduler installation code searches the registry for jobs created for the AT service, and creates tasks that will accomplish the same operation.

For such converted jobs, the interactive flag is set if the task is intended to be displayed to the user. When this flag is not set, no task items are displayed in the Tasks folder, and no user interface associated with the task is presented to the user when the task is executed.

TASK_FLAG_DELETE_WHEN_DONE
Task will be deleted when there are no more scheduled run times.
TASK_FLAG_DISABLED
Task is disabled. This is useful to temporarily prevent a task from running at the scheduled time(s).
TASK_FLAG_HIDDEN
Task file is hidden. When the task begins execution, it runs in a hidden window.
TASK_FLAG_START_ONLY_IF_IDLE
Task begins only if the computer is not in use at the scheduled start time. Windows 95 only.
TASK_FLAG_KILL_ON_IDLE_END
Task terminates if the computer makes an idle to non-idle transition while the task is running. The computer is not considered idle until the IdleWait triggers' time elapses with no user input. Windows 95 only. For information regarding idle triggers, see Idle Triggers.
TASK_FLAG_RESTART_ON_IDLE_RESUME
Task starts again if the computer makes a non-idle to idle transition before all its triggers' dwMinutesDuration elapse. (Use this flag in conjunction with TASK_FLAG_KILL_ON_IDLE_END.) Windows 95 only.
TASK_FLAG_DONT_START_IF_ON_BATTERIES
Task does not start if its target computer is running on battery power. Windows 95 only.
TASK_FLAG_KILL_IF_GOING_ON_BATTERIES
Task ends and the associated application quits if the task's target computer switches to battery power. Windows 95 only.
TASK_FLAG_RUN_IF_CONNECTED_TO_INTERNET
Task runs only if there is currently a valid Internet connection. Note: This feature is currently not implemented.

See also IScheduledWorkItem::GetFlags

Back to top


IScheduledWorkItem::SetIdleWait

HRESULT SetIdleWait(
    WORD wIdleMinutes,
    WORD wDeadlineMinutes
);

Sets the idle wait time for the task.

  • Returns S_OK.
wIdleMinutes
Value of the task's idle wait time, in minutes.
wDeadlineMinutes
Value that specifies the maximum number of minutes to wait for the idle wait time duration contained in wIdleMinutes to occur before running the task.

If the task has the TASK_EVENT_TRIGGER_ON_IDLE trigger, the task runs when wIdleMinutes have elapsed since the most recent keyboard or mouse event.

If the TASK_FLAG_START_ONLY_IF_IDLE flag is set, the task runs only after a period of wIdleMinutes elapses with no mouse or keyboard activity. The Task Scheduler service will wait up to wDeadlineMinutes past the scheduled start time of the task for the required wIdleMinutes of idle time to elapse.

See also IScheduledWorkItem::GetIdleWait, Idle Triggers

Back to top


IScheduledWorkItem::SetWorkItemData

HRESULT SetWorkItemData(
    WORD cBytes,
    BYTE rgbData[]
);

Stores application-defined data associated with the work item.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
cBytes
Number of bytes in the data buffer. The caller allocates and frees this memory.
rgbData
Data to copy.

See also IScheduledWorkItem::GetWorkItemData

Back to top


IScheduledWorkItem::Terminate

HRESULT Terminate(void);

Ends the execution of the work item.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.

Back to top


ITask::GetApplicationName

HRESULT GetApplicationName(
    LPWSTR * ppwszApplicationName
);

Retrieves the name of the application that the task is associated with.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
ppwszApplicationName
Address of an LPWSTR that contains the name of the application the current task is associated with. The method that invokes GetApplicationName is responsible for freeing this string using the CoTaskMemFree function.

If you set the application name property to an executable file, you can set the parameters property to the command-line arguments to pass to that executable—for example, ApplicationName=notepad.exe and Parameters=foo.txt.

However, if you set the ApplicationName property to a non-executable file, the parameters property will be ignored, because the application name in this case is the parameter—for example, ApplicationName=foo.txt.

See also ITask::SetApplicationName

Back to top


ITask::GetMaxRunTime

HRESULT GetMaxRunTime(
    DWORD * pdwMaxRunTime
);

Retrieves the maximum time, in milliseconds, the task can run before terminating.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
pdwMaxRunTime
Address of a value that contains the maximum run time of the current task.

If the maximum run time is reached during the execution of a task, the Scheduling Agent first sends a WM_CLOSE message to the associated application. If the application hasn't exited within three minutes, TerminateProcess is run.

See also ITask::SetMaxRunTime

Back to top


ITask::GetParameters

HRESULT GetParameters(
    LPWSTR * ppwszParameters
);

Retrieves the task's command-line parameters.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
ppwszParameters
Address of an LPWSTR that contains the current task's parameters. The method that invokes GetParameters is responsible for freeing this string using the CoTaskMemFree function.

See also ITask::SetParameters

Back to top


ITask::GetPriority

HRESULT GetPriority(
    DWORD * pdwPriority
);

Retrieves the priority for the task.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
pdwPriority
Address of a DWORD that contains the priority for the current task. The priority value determines the frequency and length of a process' time slices. This applies only to Windows NT and has no effect in Windows 95. It is taken from the CreateProcess priority class and can be one of the following flags (in descending order of thread scheduling priority):
REALTIME_PRIORITY_CLASS
HIGH_PRIORITY_CLASS
NORMAL_PRIORITY_CLASS
IDLE_PRIORITY_CLASS

See also ITask::SetPriority

Back to top


ITask::GetTaskFlags

HRESULT GetTaskFlags(
    DWORD * pdwFlags
);

Returns the flags that modify the task's behavior.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
pdwFlags
Address of a value that contains the description of how the task behaves. For a list of the flags, see ITask::SetTaskFlags.

Back to top


ITask::GetWorkingDirectory

HRESULT GetWorkingDirectory(
    LPWSTR * ppwszWorkingDirectory
);

Retrieves the task's working directory.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
ppwszWorkingDirectory
Address of an LPWSTR that contains the task's working directory. The method that invokes GetWorkingDirectory is responsible for freeing this string using the CoTaskMemFree function.

See also ITask::SetWorkingDirectory

Back to top


ITask

Applications use the methods of the ITask interface to set and retrieve task information and to run and terminate tasks. The following list of methods is organized in vtable order.

ITask methods
SetApplicationName
GetApplicationName
SetParameters
GetParameters
SetWorkingDirectory
GetWorkingDirectory
SetPriority
GetPriority
SetTaskFlags
GetTaskFlags
SetMaxRunTime
GetMaxRunTime


ITask::SetApplicationName

HRESULT SetApplicationName(
    LPCWSTR pwszApplicationName
);

Assigns a specific application to the current task.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
pwszApplicationName
LPCWSTR that contains an application's name. To clear the application name, set pwszApplicationName to L"".

If you do not specify a path for the application, the Task Scheduler searches the environment path to find the correct path. If the application name specifies a program, it should use the .exe extension to ensure that the Scheduling Agent user interface properly displays the application's icon.

See also ITask::GetApplicationName

Back to top


ITask::SetMaxRunTime

HRESULT SetMaxRunTime(
    DWORD dwMaxRunTime
);

Sets the maximum time the task can run before terminating.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
dwMaxRunTime
Value assigned as the maximum run time, in milliseconds, for the current task.

If the maximum run time is reached during the execution of a task, the Scheduling Agent first sends a WM_CLOSE message to the associated application. If the application has not exited within three minutes, TerminateProcess is run.

See also ITask::GetMaxRunTime

Back to top


ITask::SetParameters

HRESULT SetParameters(
    LPCWSTR pwszParameters
);

Sets the command-line parameters for the task.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
pwszParameters
LPCWSTR that contains task parameters. These parameters are passed as command-line arguments to the application the task will run.

If the Application Name method contains a document to run by association, the Parameters methods are ignored. To clear the command-line parameter property, set pwszParameters to L"".

The application name and parameters properties are accessed through the Application Name Set and Get methods on the ITask interface. They are properties of a task object.

See also ITask::GetParameters

Back to top


ITask::SetPriority

HRESULT SetPriority(
    DWORD dwPriority
);

Sets the priority for the task.

  • Returns S_OK if successful, or E_INVALIDARG if the argument is not valid.
dwPriority
Value assigned as the priority for the current task. The priority value determines the frequency and length of a process' time slices. This applies only to Windows NT and has no effect in Windows 95. It is taken from the CreateProcess priority class and can be one of following flags (in descending order of thread scheduling priority):
REALTIME_PRIORITY_CLASS
HIGH_PRIORITY_CLASS
NORMAL_PRIORITY_CLASS
IDLE_PRIORITY_CLASS

See also ITask::GetPriority

Back to top


ITask::SetTaskFlags

HRESULT SetTaskFlags(
    DWORD dwFlags
);

Sets the flags that modify the task's behavior.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
dwFlags
Value that contains a combination of one or more of the following flags:
TASK_FLAG_INTERACTIVE
This task flag is used when converting Windows NT AT service jobs into tasks. The Windows NT AT service job refers to At.exe, the Windows NT command-line utility used for creating jobs for the Windows NT Schedule service. The Task Scheduler service replaces the Schedule service and is backward-compatible with it. This conversion occurs when the Task Scheduler is installed on Windows NT: for example, installing Internet Explorer 4.0, or upgrading to Windows NT 5. During the setup process, the Task Scheduler installation code searches the registry for jobs created for the AT service, and creates tasks that will accomplish the same operation.

For such converted jobs, the interactive flag is set if the task is intended to be displayed to the user. When this flag is not set, no task items are displayed in the Tasks folder, and no user interface associated with the task is presented to the user when the task is executed.

TASK_FLAG_DELETE_WHEN_DONE
Task will be deleted when there are no more scheduled run times.
TASK_FLAG_DISABLED
Task is disabled. This is useful to temporarily prevent a task from running at the scheduled time(s).
TASK_FLAG_HIDDEN
Task file is hidden. When the task begins execution, it runs in a hidden window.
TASK_FLAG_START_ONLY_IF_IDLE
Task begins only if the computer is not in use at the scheduled start time. Windows 95 only.
TASK_FLAG_KILL_ON_IDLE_END
Task terminates if the computer makes an idle to non-idle transition while the task is running. The computer is not considered idle until the IdleWait triggers' time elapses with no user input. Windows 95 only. For information regarding idle triggers, see Idle Triggers.
TASK_FLAG_DONT_START_IF_ON_BATTERIES
Task does not start if its target computer is running on battery power. Windows 95 only.
TASK_FLAG_KILL_IF_GOING_ON_BATTERIES
Task ends and the associated application quits if the task's target computer switches to battery power. Windows 95 only.
TASK_FLAG_RUN_IF_CONNECTED_TO_INTERNET
Not yet implemented.

See also ITask::GetTaskFlags

Back to top


ITask::SetWorkingDirectory

HRESULT SetWorkingDirectory(
    LPCWSTR pwszWorkingDirectory
);

Sets the working directory for the task.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
pwszWorkingDirectory
LPCWSTR that contains a directory path. The application starts with this directory as the current working directory. To clear the directory, set pwszWorkingDirectory to L"". If the working directory is set to L"", when the application is run, the current directory will be the directory in which the task scheduler service executable, Mstask.exe, resides.

See also ITask::GetWorkingDirectory

Back to top


ITaskScheduler::Activate

HRESULT Activate(
    LPCWSTR pwszName,
    REFIID riid,
    IUnknown ** ppunk
);

Returns an active interface to the specified task.

  • Returns one of the following values:
    S_OK | The method was successful.
    SCHED_E_UNKNOWN_OBJECT_VERSION | The task object version is either unsupported or invalid.
    E_INVALIDARG | pwszName is not valid.
    E_OUTOFMEMORY | A memory allocation failure occurred.
pwszName
LPCWSTR that specifies the name of the task to activate.
riid
Reference identifier of the interface being requested.
ppunk
Address of an interface pointer that receives the requested interface.

Back to top


ITaskScheduler::AddWorkItem

HRESULT AddWorkItem(
    LPCWSTR  pwszTaskName,
    IScheduledWorkItem * pWorkItem
);

Adds a task to the schedule of tasks. Unlike NewWorkItem, this method requires that you first create an object that supports the IScheduledWorkItem interface and pass its address in the pWorkItem parameter.

  • Returns one of the following values:
    S_OK | The operation was successful.
    ERROR_FILE_EXISTS | A task with the specified name already exists.
    E_INVALIDARG | One or more of the arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available to complete the operation.
pwszTaskName
LPCWSTR that specifies the name of the task to add. The task name must conform to Windows NT file-naming conventions but cannot include backslashes, because nesting within the task folder object is not allowed.
pWorkItem
Address of an interface pointer that receives the requested interface.

See also ITaskScheduler::NewWorkItem

Back to top


ITaskScheduler::Delete

HRESULT Delete(
    LPCWSTR pwszName
);

Deletes a task.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
pwszName
LPCWSTR that specifies the name of the task to delete.

Back to top


ITaskScheduler::Enum

HRESULT Enum(
    IEnumTasks ** ppEnumTasks
);

Retrieves a pointer to an OLE enumerator object that enumerates the tasks in the current task folder.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
ppEnumTasks
Address of a pointer to an IEnumWorkItems interface. This interface contains the enumeration context of the current task(s).

The current folder resides on the computer returned by GetTargetComputer, which defaults to the local computer if not previously set by a call to SetTargetComputer.

Back to top


ITaskScheduler::GetTargetComputer

HRESULT GetTargetComputer(
    LPWSTR * ppwszComputer
);

Returns the computer name on which ITaskScheduler is currently targeted.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
ppwszComputer
Address of an LPWSTR that contains the name of the target computer for the current task. This string is allocated by the method that invokes GetTargetComputer and is freed by the same method by using CoTaskMemFree.

Back to top


ITaskScheduler::IsOfType

HRESULT IsOfType(
    LPCWSTR  pwszName,
    REFIID   riid
);

Checks the object's type to verify that it supports a particular interface.

  • Returns S_OK if the object named by pwszName supports the interface specified in riid, or S_FALSE otherwise.
pwszName
LPCWSTR that specifies the name of the object to check.
riid
Identifier of the interface to be matched.

Back to top


ITaskScheduler

Applications use the methods of the ITaskScheduler interface to schedule tasks. The following list of methods is organized in vtable order.

ITaskScheduler methods
SetTargetComputer
GetTargetComputer
Enum
Activate
Delete
NewWorkItem
AddWorkItem
IsOfType


ITaskScheduler::NewWorkItem

HRESULT NewWorkItem(
    LPCWSTR    pwszTaskName,
    REFCLSID   rclsid,
    REFIID     riid,
    IUnknown   ** ppunk
);

Allocates space for a new task and retrieves its address. Unlike AddWorkItem, this function handles memory allocation automatically.

  • Returns one of the following values:
    S_OK | The operation was successful.
    ERROR_FILE_EXISTS | A task with the specified name already exists.
    E_INVALIDARG | One or more of the arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available to complete the operation.
pwszTaskName
LPCWSTR that specifies the new task's name. The task name must conform to Windows NT file-naming conventions but cannot include backslashes, because nesting within the task folder object is not allowed.
rclsid
Identifier of the class of work item to be created. The only supported class is CLSID_Ctask.
riid
Reference identifier of the interface being requested.
ppunk
Address of an interface pointer that receives the requested interface.

See also ITaskScheduler::AddWorkItem

Back to top


ITaskScheduler::SetTargetComputer

HRESULT SetTargetComputer(
    LPCWSTR pwszComputer
);

Selects the computer that the ITaskScheduler interface operates on. This allows remote task management and enumeration. The user must have administrative access on the remote computer to use this method. For more information on remote installation requirements, refer to Mstask.hlp.

  • Returns one of the following values:
    S_OK | The method was successful.
    SCHED_E_SERVICE_NOT_INSTALLED | The Task Scheduler service is not installed on the target computer.
    E_INVALIDARG | pwszComputer is not valid.
    E_OUTOFMEMORY | A memory allocation failure occurred.
pwszComputer
LPCWSTR that specifies the target computer for the current task. The computer name indicates that the local computer is the target computer; set this value to NULL or to the local computer's Universal Naming Convention (UNC) name.

Back to top


ITaskTrigger::GetTrigger

HRESULT GetTrigger(
    PTASK_TRIGGER pTrigger
);

Retrieves the current task trigger.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
pTrigger
Address of a TASK_TRIGGER structure that contains the current task trigger. You must set the cbTriggerSize member of the TASK_TRIGGER structure to be the size of the task trigger structure before passing it to this method.

See also ITaskTrigger::SetTrigger

Back to top


ITaskTrigger::GetTriggerString

HRESULT GetTriggerString(
    LPWSTR * ppwszTrigger
);

Retrieves the current task trigger in the form of a string. This string appears in the Scheduling Agent user interface in a form similar to "At 2PM every day, starting 5/11/97."

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
ppwszTrigger
Address of an LPWSTR that contains the description of the current task trigger. The method that invokes GetTriggerString is responsible for freeing this string using the CoTaskMemFree function.

Back to top


ITaskTrigger

Applications use the methods of the ITaskTrigger interface to access and set triggers for a task. Triggers specify task start times, repetition criteria, and other parameters. The following list of methods is organized in vtable order.

ITaskTrigger methods
SetTrigger
GetTrigger
GetTriggerString


ITaskTrigger::SetTrigger

HRESULT SetTrigger(
    const PTASK_TRIGGER pTrigger
);

Sets the task trigger values.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
pTrigger
Address of a TASK_TRIGGER structure containing the values that define the new task trigger.

See also ITaskTrigger::GetTrigger

Back to top


DAILY

typedef struct _DAILY {
    WORD DaysInterval;
} DAILY;

Defines the interval, in days, between invocations of a task. The TRIGGER_TYPE_UNION union uses an instance of this structure as part of the TASK_TRIGGER structure definition.

DaysInterval
Number of days between invocations of a task.


MONTHLYDATE

typedef struct _MONTHLYDATE {
    DWORD rgfDays;
    WORD rgfMonths;
} MONTHLYDATE;

Defines the day of the month the task will run. The TRIGGER_TYPE_UNION union uses an instance of this structure as part of the TASK_TRIGGER structure definition.

rgfDays
Value that describes the day of the month a task runs. This value is a bit field that specifies the day(s) the task will run. Bit 0 corresponds to the first of the month, bit 1 to the second, and so forth.
rgfMonths
Value that describes the month(s) when the task runs. This value is a combination of the following flags:
TASK_JANUARY | Task will run in January.
TASK_FEBRUARY | Task will run in February.
TASK_MARCH | Task will run in March.
TASK_APRIL | Task will run in April.
TASK_MAY | Task will run in May.
TASK_JUNE | Task will run in June.
TASK_JULY | Task will run in July.
TASK_AUGUST | Task will run in August.
TASK_SEPTEMBER | Task will run in September.
TASK_OCTOBER | Task will run in October.
TASK_NOVEMBER | Task will run in November.
TASK_DECEMBER | Task will run in December.

The following code fragment provides an example of how you can combine these flags. This example would run a task quarterly.

MONTHLYDATE example;
example.rgfDays = 1;
example.rgfMonths = TASK_JANUARY | TASK_APRIL | TASK_JULY | TASK_OCTOBER;


MONTHLYDOW

typedef struct _MONTHLYDOW {
    WORD wWhichWeek;
    WORD rgfDaysOfTheWeek;
    WORD rgfMonths;
} MONTHLYDOW;

(MONTHLY Day Of the Week) Defines the date(s) that the task runs by month, week, and day of week. The TRIGGER_TYPE_UNION union uses an instance of this structure as part of the TASK_TRIGGER structure definition.

wWhichWeek
Value that describes the week of the month when the task runs. This value is exclusive and is one of the following flags:
TASK_FIRST_WEEK | Task will run during the first week of the month.
TASK_SECOND_WEEK | Task will run during the second week of the month.
TASK_THIRD_WEEK | Task will run during the third week of the month.
TASK_FOURTH_WEEK | Task will run during the fourth week of the month.
TASK_LAST_WEEK | Task will run during the last week of the month.
rgfDaysOfTheWeek
Value that describes the day(s) of the week specified in wWhichWeek when the task runs. This value is a combination of the following flags:
TASK_SUNDAY | Task will run on Sunday.
TASK_MONDAY | Task will run on Monday.
TASK_TUESDAY | Task will run on Tuesday.
TASK_WEDNESDAY | Task will run on Wednesday.
TASK_THURSDAY | Task will run on Thursday.
TASK_FRIDAY | Task will run on Friday.
TASK_SATURDAY | Task will run on Saturday.
rgfMonths
Value that describes the month(s) when the task runs. This value is a combination of the following flags:
TASK_JANUARY | Task will run in January.
TASK_FEBRUARY | Task will run in February.
TASK_MARCH | Task will run in March.
TASK_APRIL | Task will run in April.
TASK_MAY | Task will run in May.
TASK_JUNE | Task will run in June.
TASK_JULY | Task will run in July.
TASK_AUGUST | Task will run in August.
TASK_SEPTEMBER | Task will run in September.
TASK_OCTOBER | Task will run in October.
TASK_NOVEMBER | Task will run in November.
TASK_DECEMBER | Task will run in December.

The following code fragment provides an example of how you can combine these flags. This example would run a task on Monday and Friday of the third week of every third month.

MONTHLYDOW example;
example.wWhichWeek = TASK_THIRD_WEEK;
example.rgfDaysOfTheWeek = TASK_FRIDAY | TASK_MONDAY;
example.rgfMonths = TASK_JANUARY | TASK_APRIL | TASK_JULY | TASK_OCTOBER;


Structures Structures *
  * Previous Topic: ITaskTrigger::SetTrigger
  * Next Topic: DAILY

Structures

This section describes the Task Scheduler structures.


TASK_TRIGGER

typedef struct _TASK_TRIGGER {
    WORD cbTriggerSize;
    WORD Reserved1;
    WORD wBeginYear;
    WORD wBeginMonth;
    WORD wBeginDay;
    WORD wEndYear;
    WORD wEndMonth;
    WORD wEndDay;
    WORD wStartHour;
    WORD wStartMinute;
    DWORD MinutesDuration;
    DWORD MinutesInterval;
    DWORD rgFlags;
    TASK_TRIGGER_TYPE TriggerType;
    TRIGGER_TYPE_UNION Type;
    WORD Reserved2;
    WORD wRandomMinutesInterval;
} TASK_TRIGGER, * PTASK_TRIGGER;

Defines the start time, end time, duration, and modification flags for a task.

cbTriggerSize
Size of this structure, in bytes (sizeof(TASK_TRIGGER)).
Reserved1
For internal use only; this value must be zero.
wBeginYear
Year that the task trigger activates. This value must be four digits (1997, not 97).
wBeginMonth
Month of the year in the wBeginYear member that the task trigger activates.
wBeginDay
Day of the month in the wBeginMonth member that the task trigger activates.
wEndYear
Year that the task trigger deactivates. This value must be four digits (1997, not 97).
wEndMonth
Month of the year in the wEndYear member that the task trigger deactivates.
wEndDay
Day of the month in the wEndMonth member that the task trigger deactivates.
wStartHour
Hour of the day the task runs. This value is on a 24-hour clock; hours go from 00 to 23.
wStartMinute
Minute of the hour in the wStartHour member that the task runs.
MinutesDuration
Number of minutes after the task starts that the trigger will remain active. For example, if you start a task at 8:00 A.M. and want to repeatedly start the task until 5:00 P.M., there would be 540 minutes in the duration.
MinutesInterval
Number of minutes between consecutive task executions. This number is counted from the start of the previous task. For example, to run a task every hour from 8:00 A.M. to 5:00 P.M., set this field to 60.
rgFlags
Value that describes the task trigger's behavior. This value is a combination of the following flags:
TASK_TRIGGER_FLAG_HAS_END_DATE
Trigger structure's end date is valid. If this flag is not set, the end date data is ignored and the trigger will be valid indefinitely.
TASK_TRIGGER_FLAG_KILL_AT_DURATION_END
Task will be terminated at the end of the active trigger's lifetime. At the duration end, the scheduling agent first sends a WM_CLOSE message to the associated application. If the application hasn't exited in three minutes, TerminateProcess runs. If more than one instance of a task is running, all instances are terminated.
TASK_TRIGGER_FLAG_DISABLED
Task trigger is inactive.
TriggerType
Value that determines the type of trigger for this task. This value is a member of the TASK_TRIGGER_TYPE enumerated type.
Type
Structure that determines the type of trigger for this task. This structure is a member of the TRIGGER_TYPE_UNION union.
Reserved2
For internal use only; this value must be zero.
wRandomMinutesInterval
Not currently used.


WEEKLY

typedef struct _WEEKLY {
    WORD WeeksInterval;
    WORD rgfDaysOfTheWeek;
} WEEKLY;

Defines the interval, in weeks, between invocations of a task. The TRIGGER_TYPE_UNION union uses an instance of this structure as part of the TASK_TRIGGER structure definition.

WeeksInterval
Number of weeks between invocations of a task.
rgfDaysOfTheWeek
Value that describes the days of the week the task runs. This value is a bit field and is a combination of the following flags:
TASK_SUNDAY | Task will run on Sunday.
TASK_MONDAY | Task will run on Monday.
TASK_TUESDAY | Task will run on Tuesday.
TASK_WEDNESDAY | Task will run on Wednesday.
TASK_THURSDAY | Task will run on Thursday.
TASK_FRIDAY | Task will run on Friday.
TASK_SATURDAY | Task will run on Saturday.

The following code fragment provides an example of how you can combine these flags. This example would run a task on every other Sunday, Wednesday, and Friday.

WEEKLY example;
example.WeeksInterval = 2;
example.rgfDaysOfTheWeek = TASK_SUNDAY | TASK_WEDNESDAY | TASK_FRIDAY;


TRIGGER_TYPE_UNION

typedef union _TRIGGER_TYPE_UNION {
    DAILY Daily;
    WEEKLY Weekly;
    MONTHLYDATE MonthlyDate;
    MONTHLYDOW MonthlyDOW;
} TRIGGER_TYPE_UNION;

Defines the task trigger's invocation schedule. This union is part of the TASK_TRIGGER structure.

Daily
Structure that specifies the number of days between invocation of a task. This member is a DAILY structure.
Weekly
Structure that specifies the number of weeks between invocations of a task, and day(s) of the week the task will run. This member is a WEEKLY structure.
MonthlyDate
Structure that specifies the month(s) and day(s) of the month a task will run. This member is a MONTHLYDATE structure.
MonthlyDOW
Structure that specifies the day(s) of the year a task runs by month(s), week of month, and day(s) of week. This member is a MONTHLYDOW structure.


Unions Unions *
  * Previous Topic: WEEKLY
  * Next Topic: TRIGGER_TYPE_UNION

Unions

This section describes the Task Scheduler union.

TRIGGER_TYPE_UNION


Web Publishing Overview

This section describes the Microsoft® Web Publishing Software Development Kit (SDK), including a description of the command-line options for the Web Publishing Wizard, Wpwiz.exe. Use this SDK to access Web Publishing functionality through your application.

For detailed descriptions of the interface methods and for code examples, see the Web Publishing Programmer's Reference. Note that the examples in the Web Publishing Programmer's Reference are not complete samples and often omit most error processing.

What's in the SDK

Web Publishing Sites

The Posting Information File

The Web Publishing API

The Web Publishing SPI

The File Upload Control

Web Publishing Wizard

What's in the SDK

The Web Publishing SDK includes the following:
The application programming interface (API). The API is designed for use by applications that want to include Web Publishing functionality. The API manages multiple publishing destinations (called sites) and calls the service provider interface (SPI) to do the work of transferring the files over the network. The API can support multiple service providers (implementations of the SPI), and provides mechanisms for selecting from among installed providers when setting up a new site.
The service provider interface (SPI). The SPI consists of a COM interface and several helper functions; the latter must be callable entry points in the DLL that services the COM interface.
The File Upload Control. This control packages the Web Publishing API's functionality in an ActiveX(tm) control, which can easily be included on HTML pages.

Web Publishing Sites

A site is a destination to which files can be published. Typically this is a computer connected to the Internet and running an HTTP server. The concept of a site in the Web Publishing API encompasses all information required in order to get files from the user's local computer onto the destination computer. The API handles management of the core set of information common to all varieties of sites, namely:

  • A friendly name.
  • The URL from which the files will be retrievable once they have been published (called the destination URL).
  • The service provider installed on the user's local computer that is used to transfer files to the destination computer.
  • A local base directory that corresponds to the destination URL. This is an optional feature of a site; if it is set it indicates how much of the path of a local file should be preserved when publishing to the destination computer. For example, if a site "MySite" has its local base directory set to C:\MYSITE and its destination URL set to http://www.mysite.com, then these example files would be posted as follows.
    Local file | Posted to
    c:\mysite\file.html | http://www.mysite.com/file.html
    c:\mysite\images\gifs\me.gif | http://www.mysite.com/images/gifs/me.gif

    If a file is posted to a site with a local base directory specified, and the file is not under the local base directory tree, it is posted directly to the destination URL.
    Local file | Posted to
    c:\site2\images\icons\redball.gif | http://www.mysite.com/redball.gif

When the preceding information is gathered and stored for a given destination computer, a site is said to be "created." WpCreateSite collects these four pieces of information, either from the parameters passed to it or possibly, in the case of the service provider, by querying the service providers installed on the system to see whether they can publish to the specified destination URL. The information is then stored in a registry key under HKCU\Software\Microsoft\WebPost\Sites named with the friendly name of the site.

It is likely that most service providers will require more than this minimal set of information in order to get files onto the destination computer. For instance, the Microsoft® FTP service provider requires the name of the FTP server, the subfolder on the server, and possibly a user name and password in order to upload files. Service providers are encouraged to store this extra information on the same site key used by the API. Aside from simple centralization, the advantage of keeping information there is that any parameter values specified in the posting information file on the destination computer (see The Posting Information File) are automatically saved under this key when the site is first configured, making those parameters easily available to the service provider and possibly eliminating the need to obtain technical information from the user.

The Posting Information File

Because of variations among Internet servers, Microsoft requests that Internet service providers (ISPs) include a posting information file on their Internet servers. This file contains details about the posting protocol and policy. The Web Publishing API uses the information in the file to help with the detection of the Web Publishing protocol.

The version 1.5 release supports a new mechanism that meets with the approval of the W3C, in addition to the old postinfo.htm from version 1.1. The new mechanism allows the ISP to place a <META NAME="POSTINFO" CONTENT="URL"> tag in the default page on their server. This tag specifies a URL to the posting information file. The URL can be any path (even another machine) with any name but must be enclosed in quotation marks.

The file is simply a text file with sections and keys. The version statement must be the first statement in the file, followed by section(s) defining the transfer types. Multiple protocols can be supported on the server. Each new protocol section must start with the transfer type in brackets and include keys required by that provider. The transfer types must appear in priority order. When the Web Publishing client binds to a site it will attempt to use the first protocol listed; if that is not available, then it will try the next, and so on The transfer type can be specified as either a program ID or a GUID, enclosed in brackets. The convention for a program ID is Webpost.ProviderDll, where ProviderDll is the actual file name of the provider. A GUID must include the standard braces within the brackets. The GUIDs for the installed providers can be found in the registry under HKLM\System\CurrentControlSet\Services\Webpost\Providers.

All blank lines will be ignored and the fields are not case sensitive. Case will be preserved on all quoted string values. The keys can appear in any order within a section. There is one supported parameter and that is the $USERNAME variable. The Web Publishing client will substitute the local user name for that value when read from the server. The following is a sample posting information file that could appear on a server:

Version=1.5

[WebPost.FTPWPP]
ServerName="Server"
Subfolder="ftpupl/$USERNAME"
DefaultPage="default.html"

[WebPost.CRSWPP]
ServerName="Server"

For a complete list of parameters for different service providers, including CRS, FTP, and HTTP, see Appendix C, Parameters, in the Web Publishing Programmer's Reference.

The Web Publishing API

The Web Publishing application programming interface (API) makes it possible for authoring tools to post Web pages to an Internet site with just one call to the WpPost function. In a typical scenario, an authoring tool's File menu would include a "Post to Web" command that, when clicked, causes the tool to call the WpPost function. This function starts a wizard that asks the user for a friendly name for the Internet site and the Uniform Resource Locator (URL) for the site. Next, the function connects to the Internet server at the given URL, determines the protocol to use for posting the Web pages, and then posts the requested files. For subsequent posting to the same site, this function remembers the details of how to connect to the site, and posts the files with little user intervention. Thus, the Web Publishing API maintains a friendly site name, remembers all the details involved in posting to that site, and allows the applications to easily post Web pages to a site or to the URL associated with that site.

As an alternative to the wizard, an authoring tool can let the user choose the Web site before calling WpPost by displaying a list of sites (plus a "New Site" item) obtained by a call to the WpListSites function. The list of sites could be in a nested menu that appears when the user clicks the "Post to Web" command.

Interface Definition

The Web Publishing API consists of the following methods.
Method | Description
WpBindToSite | Obtains a pointer to a service provider object supporting either the IWPSite interface or the IWPProvider interface.
WpCreateSite | Creates a new site entry in the registry.
WpCreateSiteEx | Creates a new site entry in the registry, using a user name and password.
WpDeleteSite | Deletes the information for a site from the registry.
WpDoesSiteExist | Determines whether or not the specified site exists.
WpEnumProviders | Enumerates the currently installed service providers.
WpGetErrorString | Translates an error code.
WpListSites | Lists the sites for which there is currently information in the registry.
WpPost | Posts one or more files or directories to the specified site.
WpPostEx | Posts one or more files or directories to the specified site, using a user name and password.
WpPostFile | Posts one file or directory to the specified site.

The Web Publishing SPI

The Web Publishing service provider interface (SPI) describes the interface each service provider must support to allow the core web publishing services to post content. The SPI DLLs are OLE COM servers provide the following methods and helper functions. The Web Publishing API functions and the Web Publishing Wizard route requests to a provider based on a site name or URL, and use the SPI functions to post the files.

Interface Definition

The Web Publishing SPI consists of the following methods.
Helper function | Description
WppBindToSite | Retrieves the address of an interface if the provider DLL owns the site name or the URL.
WppDeleteSite | Deletes a site name that has been configured.
Interface method | Description
AddWizardPages | Allows the provider DLLs to plug pages into the wizard invoked by the WpPost function.
DeleteFile | Deletes the given file from the destination site.
FindClose | Closes the specified search handle.
FindFirstFile | Searches a directory for a file whose name matches the specified file name on the destination site.
FindNextFile | Continues a file search from a previous call to the FindFirstFile function.
GetError | Retrieves additional information about an error.
GetParam | Retrieves a parameter value for this site.
GetSiteInfo | Retrieves the site information for the current object.
NetworkConnect | Connects to the Internet.
NetworkDisconnect | Disconnects from the Internet.
PostFiles | Posts files to the specified URL.
ServerLogin | Logs the user on to the Internet server.
ServerLogout | Logs the user out of the Internet server.
SetParam | Sets the value of a parameter for a given site.
SetProgressUpdateProc | Specifies the callback function.

Helper Functions

Each service provider DLL must export one helper function not available through the COM interface: WppBindToSite. This entry point will be called from WpBindToSite and WpPost in order to obtain a pointer to the service provider object. It will also be called from WpCreateSite.

If a service provider exports a WppDeleteSite entry point, it will be called from WpDeleteSite.

Note that one of the primary design changes in Web Publishing 1.5 is the shift of responsibility for maintaining site information from the individual service providers to the Web Publishing API. Providers should not maintain site-related state information independently of the Web Publishing API except when necessary. However, if separate record-keeping is necessary, a service provider is guaranteed under this model to be notified whenever sites are added, removed, or utilized for posting.

Self-Registration Responsibilities

Service provider DLLs are required to export a DllRegisterServer method that performs the following functions:

  1. Registers its object's CLSID according to standard COM procedure.
  2. Inserts a subkey for itself under HKLM\System\CurrentControlSet\Services\WebPost\Providers named with its CLSID and containing the following values.
    Value | Meaning
    Provider | A string that contains the name of the provider. This name is used in the wizard; it appears in the list box that contains the names of the providers.
    Path | A string that contains the path of the service provider DLL.
    Priority | A DWORD value that indicates the provider's priority. Zero is highest priority. Microsoft Web Publishing 1.5 service providers' priorities start at 0x00010000 and are 0x00000100 apart.
    PostInfoRequired(new) | If this DWORD value is non-zero, then this service provider requires a posting information file in order to obtain all the information necessary to post. If the posting information file cannot be retrieved, the attempt to create a site using this provider will fail.
  3. (Optional.) Calls WpCreateSite to add the sites it supports to the registry.

The File Upload Control

The File Upload Control is an ActiveX control that uses the Web Publishing API. It can be included on an HTML page to allow posting to a server. Typical applications would be for a file upload area, or for an ISP to allow easy uploading to a personal Web pages site. The control also provides all configuration information normally provided by the wizard.

When the user sees the control on a page, he or she can simply drag files onto it to have them instantly sent, or double-click to display a dialog allowing selection of the local files to be transmitted. Right-clicking the icon will bring up a property sheet for the site, which will allow the user to edit the parameters.

Note If you intend to use this control from Visual Basic® applications on machines where Internet Explorer is not installed, you will need the following binary files: OLEPRO32.DLL, MSVCRT40.DLL, MSVCIRT.DLL.

Interface Definition

The File Upload Control interface has the following methods.
Method | Description
AboutBox | Displays information about the File Upload Control.
CreatePermBinding | Creates a permanent site and binds to it.
CreateTempBinding | Creates a temporary site and binds to it.
FoundPostInfo | Checks whether a postinfo file was found on the target server.
SetBindingParam | Sets binding parameters.

If the site should be retained on the client machine after the post is complete, the CreatePermBinding method should be used. The CreatePermBinding method will allow the author to specify a site name, URL, and, optionally, a provider. The call will return a value indicating whether the site was created, the site already existed, or the call failed. The author also has the ability to determine whether the path information from the client will be preserved when passing the file to the server. There are three flags supported for this method: strip, preserve, and prompt. The strip option can be used in a raw file upload situation where only the files are desired. The preserve option will assume the path of the first file/directory sent will become the base directory for this site. The prompt option will display a dialog allowing the user to set the local base directory. This dialog will be preloaded with the path of the first file/directory but the user will be allowed to change it as needed.

If the site definition will only be used for a single session, the CreateTempBinding method should be called. The only UI required of the ActiveX control is the file selection dialog, which is only displayed if the user double-clicks the icon, a transferring files dialog similar to the one used in the wizard, and a dialog indicating the completion status (success or error). There is also a dialog that can be brought up on a right-click that allows the user to set the local base directory.

Web Publishing Wizard

This section describes the command-line options for the Web Publishing Wizard, Wpwiz.exe.

Syntax

Wpwiz [–w "FriendlyName"] [–u "URL"] [–n "UserName"] [–p "password"] [–s "Service"] [–f [flags]] path [...]
Parameters
-w "FriendlyName" | The friendly name to use for the site.
-u "URL" | The destination URL to use for the site.
-n "UserName" | The username to use for the site.
-p "Password" | The password to use for the site.
-s "Service" | The service provider to use for the site.
-f[flags] Force flags. By default the Wizard will skip any pages for which the required information has already been provided on the command line. These flags allow you to override this default behavior and force the Wizard to show whatever pages you specify.

There should not be a space between the "-f" and the list of page letter-identifiers. The letter-identifiers may appear in any order, and again should not be separated by spaces. The letter-identifiers are:
a | All pages (shorthand for "iswnup")
i | Introductory (welcome) page
s | Source paths page (where user specifies file/folder to be published)
w | Web server page (where user selects from list of existing friendly-named sites)
n | Name the web server pages (where user provides friendly name for new site)
u | URL page (where user provides URL for new site)
p | Provider-specific pages (i.e., FTP prompts for Server name and Subfolder)

-b | Disable auto-binding. This only applies when a new site is being created.
-i | Don't recurse into folder being published; only publish its immediate children.
path [path [path [...]]] | List of files to be published. Paths must be complete and absolute. Paths may be interspersed with flags.

Example

The following example invokes the Web Publishing wizard with the friendly name New Site, the URL http://myserver.com/myfolder, the user name anonymous, the password e-mail, with all flags and no auto-binding on the files Index.htm and Hello.htm. Note that the final path must be enclosed in double-quote marks since it contains a space.

C:\> wpwiz -w "New Site" -u "http://myserver.com/myfolder"
-n "anonymous" -p "e-mail" -s "FTP" -fa -b -i C:\Index.htm
"C:\HTML Files\Hello.htm"


Web Publishing Programmer's Reference

This section contains detailed descriptions of the interface methods and code examples for the Microsoft® Web Publishing Software Development Kit (SDK.) The examples in the Programmer's Reference are not complete samples and often omit most error processing.

Please read the Web Publishing Overview first for overview and general information about the Web Publishing SDK.

Note The Web Publishing interfaces (including the File Upload Control interface) cannot be used from a UI-less environment. For instance, if a pop-up dialog is created during a server-side run, the client never sees the dialog on its end and the process cannot complete.

Conventions

The Web Publishing API

The Web Publishing SPI

The File Upload Control Interface

Appendix A, Structures

Appendix B, Error Codes

Appendix C, Parameters


Microsoft Web Publishing SDK

This section provides all the information necessary to make use of the Microsoft® Web Publishing Software Development Kit (SDK). It details the specification of the Web Publishing API, the Web Publishing Service Provider interface, and the Web Publishing File Upload Control interface.

Web Publishing Overview

Web Publishing Programmer's Reference


AboutBox AboutBox *
  * Previous Topic: The File Upload Control Interface
  * Next Topic: CreatePermBinding

AboutBox

HRESULT AboutBox(void);

Displays a friendly message about the File Upload Control.


AddWizardPages

HRESULT AddWizardPages(
    [in]	LPVOID			pvFlags
    [in]	LPFNADDPROPSHEETPAGE	pfnAdd
    [in, out]	LPARAM			pParam
    );

Allows the provider DLLs to plug pages into the wizard invoked by the WpPost function.

pvFlags
The address of a LONG containing action flags. This parameter must be cast to an LPVOID in the call to AddWizardPages for backward compatibility. The only flag value supported is WPF_SHOWPAGE_PROVIDER, which indicates that the service provider should add its pages to the wizard whether or not it thinks that they are required.
pfnAdd
Address of a function that this Web Publishing service provider should use to add wizard pages. The declaration of this function-pointer type (LPFNADDPROPSHEETPAGE), is included in the header files of the Win32 SDK.
pParam
Address of a page identifier, an unsigned integer.

As input to this function, the low-order word is the dialog identifier of the page after the last page of the provider, and the high-order word is the dialog identifier of the page before the first page of the provider.

As output from this function, the low-order word is the dialog identifier of the provider's last page, and the high-order word is the dialog identifier of the provider's first page. If the provider has no pages, it should return zero as the page identifier.

As an example, in setting up a new site the wizard would provide the friendly site name and the site's URL and the provider DLLs would handle the rest of the site set up. The dialog identifier of the provider wizard page should be a value between the values of IDD_FIRST_PROV_PAGE and IDD_LAST_PROV_PAGE, as defined in the file WPPDEFS.H included with the stubbed service provider among the SDK samples.


The Web Publishing API

The Web Publishing API consists of the following methods.
Method | Description
WpBindToSite | Obtains a pointer to a service provider object supporting either the IWPSite interface or the IWPProvider interface.
WpCreateSite | Creates a new site entry in the registry.
WpCreateSiteEx | Creates a new site entry in the registry, using a user name and password.
WpDeleteSite | Deletes the information for a site from the registry.
WpDoesSiteExist | Determines whether or not the specified site exists.
WpEnumProviders | Enumerates the currently installed service providers.
WpGetErrorString | Translates an error code.
WpListSites | Lists the sites for which there is currently information in the registry.
WpPost | Posts one or more files or directories to the specified site.
WpPostEx | Posts one or more files or directories to the specified site, using a user name and password.
WpPostFile | Posts one file or directory to the specified site.


Commit

HRESULT Commit(void);

Ensures that all the files posted to this server with the PostFiles function are actually written to the Internet server.

If a callback function has been specified to the service provider with a previous call into SetProgressUpdateProc, the service provider should call the callback function while committing. See the description of SetProgressUpdateProc for more information.


Conventions

The following text formats are used throughout this document.
Bold text | Denotes a term or character to be typed literally, such as a predefined data type or function name (HWND or GetExtendedError.) You must type these terms exactly as shown.
Italic text | Denotes a placeholder or variable. You must provide the actual value. For example, the statement SetCursorPos(X, Y) requires you to substitute values for the X and Y parameters.
SMALL CAPITALS | Indicates the names of keys, key sequences, and key combinations—for example, ALT+SPACEBAR.
FULL CAPITALS | Indicates most type and structure names, which are also bold, and constants.
monospace | Sets off code examples and shows syntax spacing.
[] Encloses optional parameters.
| Separates an either/or choice.


CreatePermBinding

CreatePermBinding(
    [in]	BSTR	bstrBindingName
    [in]	BSTR	bstrDestUrl
    [in]	BSTR	bstrProvCLSID
    );

Creates a permanent site and binds to it.

bstrBindingName
Address of a null-terminated string that contains the site name. This may not be NULL or empty.
bstrDestUrl
Address of a null-terminated string that contains the destination URL for the site. This is where the files dropped on the File Upload Control will be posted. This may not be a NULL or empty.
bstrProvCLSID
Address of a null-terminated string that contains the CLSID of the provider that will handle this site. This may be NULL or empty, in which case the File Upload Control will attempt to find a posting information file or auto-bind to an appropriate provider.

The site information is persistent, that is, it will remain on the user's machine even after the browser is shut down.


CreateTempBinding

HRESULT CreateTempBinding(
    [in]	BSTR	bsDestUrl
    [in]	BSTR	bsProvCLSID
    );

Creates a temporary site and binds to it.

bsDestUrl
Address of a null-terminated string that contains the destination URL for the site. This is where the files dropped on the File Upload Control will be posted. This may not be NULL or empty.
bsProvCLSID
Address of a null-terminated string that contains the CLSID of the provider that will handle this site. This may be NULL or empty, in which case the File Upload Control will attempt to find a posting information file or auto-bind to an appropriate provider.

Garbage collection should take care of this site information when the user shuts down the browser.

Sample HTML Usage

<HTML>
<HEAD>
<TITLE>File Upload Control</TITLE>
</HEAD>

<BODY LEFTMARGIN=20 TOPMARGIN=20 BGCOLOR=#FFFFFF TEXT=#000000 LINK=#FF0066 VLINK=#330099 ALINK=#000000 language="VBS" onload="InitializeControl">

<FONT FACE="ARIAL" SIZE=2>

<CENTER>
<P><FONT SIZE=5><B>Welcome</B></FONT>
</CENTER>

<H3>File Upload</H3>
<P>
You can upload your html content using this control.
<OBJECT
    classid="clsid:886E7BF0-C867-11CF-B1AE-00AA00A3F2C3"
    id=FlUpl1
    width=100
    height=100
    align=textmiddle
    color=blue
    codebase=http://my_server/flupl/FlUpl.cab#Version=6,0,86,0

</OBJECT>
You may drag and drop files onto it. Or double click on it to get a FileOpen dialog.

<SCRIPT LANGUAGE="VBS">

Sub InitializeControl
    FlUpl1.CreateTempBinding "http://my_server", "{8B14B770-748C-11D0-A309-00C04FD7CFC5}"
End Sub
</SCRIPT>

<P ALIGN=CENTER><FONT SIZE=2><B>For more information on VB Script, visit the <A TARGET="_top" HREF="http://www.microsoft.com/vbscript/default.htm">VB Script site.</A></B></FONT>

</FONT>

</BODY>
</HTML>


DeleteFile

HRESULT DeleteFile(
    [in, string]	LPCWSTR	wsFile
    );

Deletes the given file from the destination site.

wsFile
Address of a null-terminated string that contains the name of the file to delete.


Appendix B, Error Codes

The following error codes are used in this SDK.

Web Publishing API

Error code | Meaning
WEBPOST_ERROR_AUTOBIND_FAILED | The Web Publishing API was unable to automatically determine which service provider to use for this site.
WEBPOST_ERROR_BAD_PROV_PTR | The Web Publishing API was not able to obtain a valid pointer to the requested service provider.
WEBPOST_ERROR_COCREATE_WIZARD | The Web Publishing API could not invoke the Web Publishing Wizard.
WEBPOST_ERROR_CREATE_SITE | An error occurred while the Web Publishing API was creating the requested site.
WEBPOST_ERROR_DELETE_SITE | An error occurred while the Web Publishing API was deleting the requested site.
WEBPOST_ERROR_ENUM_PROVS | An error occurred while the Web Publishing API was enumerating the providers on this system.
WEBPOST_ERROR_EXTENDED_ERROR | A Web Publishing extended error occurred. This means that the API received an error code that the API client may not be able to translate, so the API performed the translation and cached the error message for retrieval on a call to the WpGetErrorString method.
WEBPOST_ERROR_HTTP_GET_FAILED | Informational (non-failure) result indicating failure in the attempt to retrieve one of the published files with an HTTP GET. This error is only returned in cases where the files were all successfully uploaded.
WEBPOST_ERROR_INIT_FAILED | An error occurred while attempting to initialize the Web Publishing API DLL.
WEBPOST_ERROR_INVALID_POSTINFO | Informational (non-failure) result indicating that the postinfo file found on the server during site creation could not be parsed correctly. This error is only returned if the site creation is otherwise successful.
WEBPOST_ERROR_LIST_SITES | An error occurred while the Web Publishing API was enumerating the sites on this system.
WEBPOST_ERROR_NO_EXT_ERR_INFO | An extended error occurred in the Web Publishing API, but the error message could not be retrieved.
WEBPOST_ERROR_NO_POSTINFO | Informational (non-failure) result indicating that the postinfo file could not be retrieved during a site creation. This error is only returned if the site creation is otherwise successful.
WEBPOST_ERROR_POST_FILES | An error occurred while the Web Publishing API was attempting to post the requested files.
WEBPOST_ERROR_POSTINFO_REQUIRED | This service provider requires a postinfo file on the server, and none could be found.
WEBPOST_ERROR_PROV_CORRUPT | The Web Publishing API could not retrieve all of the required service provider information.
WEBPOST_ERROR_PROV_DLL | The Web Publishing API could not load the DLL for one of its service providers.
WEBPOST_ERROR_PROV_EP | The Web Publishing API could not locate a required entry point in one of its service providers.
WEBPOST_ERROR_PROV_NOT_IN_POSTINFO | The server to which you are trying to post does not indicate support for the service provider you have requested.
WEBPOST_ERROR_PROV_QI | The Web Publishing API was unable to determine what interface is exported by the specified service provider.
WEBPOST_ERROR_PROVCLSID_UNKNOWN | The Web Publishing API could not locate the service provider used to transfer files to this site.
WEBPOST_ERROR_SITE_CORRUPT | The Web Publishing API could not retrieve all of the required site information.
WEBPOST_ERROR_SITE_DOESNOTEXIST | The Web Publishing API could not delete the requested site because no site with the specified name exists.
WEBPOST_ERROR_SITE_EXISTS | The Web Publishing API could not create the requested site because a site with the same name already exists.
WEBPOST_ERROR_UNKNOWN | An unknown error occurred during Web Publishing.
WPWIZ_ERROR_COCREATE_WEBPOST | The Web Publishing Wizard could not create the Web Publishing implementation object.
WPWIZ_ERROR_FILE_NOT_FOUND | The local file(s) selected to be published could not be found.
WPWIZ_ERROR_INIT_FAILED | An error occurred during the initialization of the Web Publishing Wizard.
WPWIZ_ERROR_NO_PROVIDERS | The Web Publishing Wizard could not run because there are no service providers installed.
WPWIZ_ERROR_OUTOFMEMORY | The Wizard ran out of memory.
WPWIZ_ERROR_PROPSHEET_ERROR | The wizard received an error result back from the PropertySheet() call into the system.
WPWIZ_ERROR_PROV_QI | The Web Publishing Wizard could not determine which interface is exported by the requested service provider.
WPWIZ_ERROR_STATE_PTR | The Web Publishing Wizard could not retrieve a pointer to its state object.
WPWIZ_ERROR_UNKNOWN | An unknown error occurred.
WPWIZ_ERROR_WEBPOST_PTR | The Web Publishing Wizard cannot complete the operation because it does not have a pointer to the Web Publishing API implementation object.

Web Publishing SPI

Error code | Meaning
CRSWPP_BIND_FAILED | Could not bind to the site with the information specified.
CRSWPP_FAILED_AUTH | You do not have the necessary access privileges to post content to this CRS server.
CRSWPP_INVALID_POSTINFO_FILE | The postinfo file is invalid on the server you selected.
CRSWPP_NO_MATCHING_MAPURL | The CRS project you selected has no MAPURL.
CRSWPP_POSTINFO_NEEDED | Server does not have a postinfo file. Additional information is needed, please invoke my Wizard Pages to complete bind operation.
CRSWPP_PROJECT_BINDING_INCOMPLETE | An internal error (0x2205) has occurred in the CRS service provider.
CRSWPP_SECURITY_PACKAGE | The initialization of the security package failed.
CRSWPP_SECURITY_PACKAGE_NOT_FOUND | The security package(s) required by the server could not be found on your computer.
CRSWPP_SERVER_BINDING_INCOMPLETE | The site is not yet bound to a CRS server.
CRSWPP_SERVER_NOT_RESPONDING | The CRS server is not responding.
FTPWPP_ERROR_AUTHENTICATION_FAILED | The FTP service provider was unable to log on to the FTP server.
FTPWPP_ERROR_INETOPEN_FAILED | The FTP service provider was not able to connect to the Internet.
WPP_POST_POSTING_NO_RESPONSE_ERROR | Posting Server response is either missing or invalid. No status is available about the uploaded files.
WPP_POST_POSTING_SERVER_ERROR | Server returned a posting error.
WPP_POST_POSTING_URL_ERROR | The supplied posting URL is invalid.


The File Upload Control Interface

The File Upload control is an ActiveX control onto which users can drag and drop files or directories for posting to the server hosting the page with the control. The File Upload Control interface has the following methods.
Method | Description
AboutBox | Displays information about the File Upload Control.
CreatePermBinding | Creates a permanent site and binds to it.
CreateTempBinding | Creates a temporary site and binds to it.
FoundPostInfo | Checks whether a postinfo file was found on the target server.
SetBindingParam | Sets binding parameters.


FindClose

HRESULT FindClose(
    [in] 	HANDLE 	hSearchHandle
    );

Closes the specified search handle.

hSearchHandle
Search handle returned by a previous call to the FindFirstFile function.

The FindFirstFile and FindNextFile functions use the search handle to locate files with names that match a given name.


FindFirstFile

HRESULT FindFirstFile(
    [in, string] 	LPCWSTR			wsSearchFile
    [out] 		LPWIN32_FIND_DATAW 	pFindFileData
    [out] 		LPHANDLE		pSearchHandle
    );

Searches a directory for a file whose name matches the specified file name on the destination site identified by this object. It examines subdirectory names as well as file names.

wsSearchFile
Address of a null-terminated string that contains the file name to find.
pFindFileData
Address of a WIN32_FIND_DATA structure that receives information about the file or subdirectory that has been found.
pSearchHandle
Address of a variable that receives a handle that can be used for subsequent calls to the FindNextFile and FindClose functions.


FindNextFile

HRESULT FindNextFile(
    [in] 	HANDLE			hSearchHandle
    [out] 	LPWIN32_FIND_DATAW	pFindFileData
    );

Continues a file search from a previous call to the FindFirstFile function.

hSearchHandle
Search handle returned by a previous call to the FindFirstFile function.
pFindFileData
Address of a WIN32_FIND_DATA structure that receives information about the file or subdirectory that has been found.


FoundPostInfo

HRESULT FoundPostInfo(void);

Determines whether a postinfo file was found on the target server.

This property is set to true if during a CreateTempBinding or CreatePermBinding call a postinfo file was found on the server.

Example

REM This example demonstrates binding parameters required by the CRS
REM provider
Flupl.CreateTempBinding "<http://www.icp.com/hello>", "{FFCF1E40-7978-11D0-B1C9-00AA006DCDF4}"

If not Flupl.FoundPostInfo then
    Flupl.SetBindingParam "Servername", "www.crsserver.com <http://>"
    Flupl.SetBindingParam "Authentication", "MSN, NTLM"
Endif


GetError

HRESULT GetError(
    [out] 		LPDWORD	pdwErrorType
    [in, out] 	LPDWORD	pdwErrorCode
    [in, out] 	LPDWORD	pdwErrorBufLen
    [out, string] 	LPWSTR	wsError
    );

Retrieves additional information about an error.

pdwErrorType
Indicates the error type. Currently set to zero.
pdwErrorCode
Indicates the error code.
pdwErrorBufLen
Indicates the size, in bytes, of the wsError buffer. Set to the number of bytes written to wsError if the buffer was large enough, or to the required buffer size if the buffer was not large enough.
wsError
Address of a buffer that receives the error information.


GetParam

HRESULT GetParam(
    [in, string]	LPCWSTR	wsParameter
    [in, out] 		LPDWORD	pdwValueBufLen
    [out, string] 	LPWSTR	wsValue
    );

Retrieves a parameter value for this site.

wsParameter
Address of a null-terminated string that contains the name of a site parameter.
pdwValueBufLen
Address of a variable that receives the size of the wsValue buffer. If wsValue is NULL, or if the buffer length is short, this variable receives the size, in bytes, of the parameter name.
wsValue
Address of a buffer that receives the value of the parameter queried.


GetSiteInfo

HRESULT GetSiteInfo(
    [out]	LPWPSITEINFO 	pbSite
    [in, out] 	LPDWORD		pdwSiteBufLen
    );

Retrieves the site information for the current object.

Note With version 1.5, implementation of this function has become optional, since site management should be done with the Web Publishing API.

pbSite
Address of a buffer that receives a WPSITEINFO structure containing the site information.
pdwSiteBufLen
Address of a variable that contains the size, in bytes, of the pbSite buffer.


NetworkConnect

HRESULT NetworkConnect(
    [in, string]	LPCWSTR	wsUserName
    [in, string]	LPCWSTR	wsPassword
    );

Connects to the Internet.

wsUserName
Address of a null-terminated string that contains the user name for the Internet connection.
wsPassword
Address of a null-terminated string that contains the password for the Internet connection.


NetworkDisconnect

HRESULT NetworkDisconnect(void);

Disconnects from the Internet (hangs up if a dial-up connection was used.)


Appendix C, Parameters

The following tables list the parameters supported by each Microsoft service provider. When writing a posting information file for a server, as many parameters as possible should be specified for each service provider the server will support, in order to minimize the amount of information that must be entered by a user.

The DefaultPage parameter is handled by the Web Publishing API (as such it is not listed under the individual service providers.) It specifies the name to use when saving a file as the default page for a site (when indicated by the WPF_FIRST_FILE_AS_DEFAULT flag to WpPost.)

The service provider section of the posting information file must include the registration identifier. To get this string value, use the WpEnumProvidersmethod.

Content Replication System Service Provider

Parameter | Example value | Meaning
Authentication | NTLM | The name of the security package to use when authenticating against the server.
ServerName | myserver | The name of the CRS server.

FTP Service Provider

Note that if present, the special string "$USERNAME" will be replaced with the name of the account used to log on to the server during publishing. This string can be used in the ServerName and Subfolder values.

The ConnectTimeout, ConnectRetries, SendTimeout, and ReceiveTimeout, were made site parameters to allow dynamic adjustment of the waiting behavior on network calls. However, a typical postinfo file will probably not need to include these parameters. The values listed under "Example Value" for these four parameters are the defaults.
Parameter | Example value | Meaning
ServerName | myserver | The name of the FTP server.
Subfolder | home/users/$USERNAME | The path on the FTP server where files should be saved. Note that $USERNAME will be replaced with the "UserName" value.
ConnectTimeout | 60000 (msec) | The length of the timeout to use when connecting to the server.
ConnectRetries | 5 | The number of retries to make when connecting to the server.
SendTimeout | 60000 (msec) | The length of the timeout for all network packets sent.
ReceiveTimeout | 60000 (msec) | The length of the timeout for all network packets received.
BasePath - This value is obsolete. If present on a site key that was used with version 1.1 of the Web Publishing Wizard, it will be upgraded to "Subfolder" the first time the FTP provider binds to the site.
FtpServerName - This value is obsolete. If present on a site key that was used with version 1.1 of the Web Publishing Wizard, it will be upgraded to "ServerName" the first time the FTP provider binds to the site.

HTTP POST Service Provider

Parameter | Example value | Meaning
PostingURL | http://myserver/scripts/cpshost.dll?PUBLISH | The URL of the HTTP POST acceptor.
TargetURL | http://myserver/users | The URL where the uploaded files should be placed.


PostFiles

HRESULT PostFiles(
    [in] 		DWORD 	cLocalPaths
    [in, string] 	LPWSTR *	pwsLocalPaths
    [in, out] 		LPDWORD 	pdwURLBufLen
    [in, out, string]	LPWSTR 	wsURL
    [in] 		DWORD 	fdwFlags
    );

Posts files to the specified URL on the destination site identified by this object.

cLocalPaths
Number of elements in the pwsLocalPaths array.
pwsLocalPaths
Address of an array of null-terminated strings that contain the file names or directories to be posted on the Internet. If any of these strings point to a directory and the WPF_NO_RECURSIVE_POST flag is not set in fdwFlags, all the files in that directory are posted.
pdwURLBufLen
Address of a variable that indicates the length of the wsURL buffer. When the function returns, the variable contains the length, in bytes, of the that buffer.
wsURL
Optional. Address of a null-terminated string that contains the destination URL. If this parameter is NULL, the files are posted in the root URL for the site.

If this parameter is not NULL, the URL of the copied file, or the URL of the directory that the files were copied to, is returned in the buffer pointed to by this parameter.

fdwFlags
Action flags.
Value | Meaning
WPF_NO_RECURSIVE_POST | If any element in the pwsLocalPaths array points to a directory, do not post files recursively.

Changes for version 1.5:
Service providers are no longer required to support the posting of multiple files. It is not a violation of the interface contract for a service provider to return failure if cLocalPaths is greater than 1.
If a callback function has been specified to the service provider with a previous call into SetProgressUpdateProc, the service provider should call the callback function while posting. See the description of SetProgressUpdateProc for more information.

See also WpPost


ServerLogin

HRESULT ServerLogin(
    [in, string]	LPCWSTR	wsUserName
    [in, string]	LPCWSTR	wsPassword
    );

Logs the user on to the Internet server.

wsUserName
Address of a null-terminated string that contains the user name for the Internet server.
wsPassword
Address of a null-terminated string that contains the password for the Internet server.

The given user name and password are for the Internet server. They may or may not be the same as those used for the NetworkConnect function.


ServerLogout ServerLogout *
  * Previous Topic: ServerLogin
  * Next Topic: SetParam

ServerLogout

HRESULT ServerLogout(void);

Logs the user out of the Internet server.


SetBindingParam

SetBindingParam(
    [in]	BSTR	bstrParamName
    [in]	BSTR	bstrParamValue
    );

Sets the parameters of an incomplete binding in case a previous CreateTempBinding or CreatePermBinding call failed to find a postinfo file on the server.

bstrParamName
Address of a null-terminated string that contains the name of the provider-specific binding parameter to be set.
bstrParamValue
Address of a null-terminated string that contains the value to which the parameter should be set.

This method takes the name of the provider specific binding parameter and the value and sets it. This should be used only as a fallback mechanism in case the postinfo file is not found on the server.


SetParam

HRESULT SetParam(
    [in, string]	LPCWSTR	wsParameter
    [in, string]	LPCWSTR	wsValue
    );

Sets the value of a parameter for a given site.

wsParameter
Address of a null-terminated string that contains a parameter name.
wsValue
Address of a null-terminated string that contains the configuration parameter value.


SetProgressUpdateProc

HRESULT SetProgressUpdateProc(
    [in] 	LONG *	pfnProgressUpdateProc
    );

Specifies the callback function the provider should use to update the "Publishing Files" progress dialog displayed by the API.

pfnProgressUpdateProc
Function with the following declaration:
HRESULT CALLBACK *pfnProgressUpdateProc(
[in, string] 	LPCWSTR 	wsFileName
[in]			DWORD		dwNumBytes
    );

The type PFNPROGRESSUPDATEPROC declared in WPSPI.IDL encapsulates this declaration.

The service provider should cache the function pointer specified here so that it can call into the update procedure from PostFiles and Commit. (The progress bar is reset after all the PostFiles calls have been made, and fills a second time during the call to Commit.)

The Service Provider should call this function from both PostFiles and Commit to update the progress dialog as it posts and commits the files passed to it. WpPost will do a series of PostFiles calls, followed by a single call to Commit. The API keeps track of the total number of bytes being transferred, so on each call the service provider should just specify the file name to display and the number of bytes that have been posted or committed since the last call.

If the update procedure returns an error, the Service Provider must quit its current operation and return the error (as the result code from PostFiles or Commit.) This ensures that if the "Cancel" button is clicked by the user during publishing, it will be processed correctly.

A typical call to the callback procedure is as follows:

hResult = (*m_pfnProgressUpdateProc)(wsFileName, dwFileSize);

If the service provider wishes to change the file name displayed in the progress dialog without advancing the progress bar, it should make a call such as the following:

hResult = (*m_pfnProgressUpdateProc)(wsFileName, 0);


The Web Publishing SPI

The Web Publishing SPI consists of the following methods.
Helper function | Description
WppBindToSite | Retrieves the address of an interface if the provider DLL owns the site name or the URL.
WppDeleteSite | Deletes a configured site.
Interface method | Description
AddWizardPages | Allows the provider DLLs to plug pages into the wizard invoked by the WpPost function.
DeleteFile | Deletes the specified file from the destination site.
FindClose | Closes the specified search handle.
FindFirstFile | Searches a directory for a file whose name matches the specified file name on the destination site.
FindNextFile | Continues a file search from a previous call to the FindFirstFile method.
GetError | Retrieves additional information about an error.
GetParam | Retrieves a parameter value for this site.
GetSiteInfo | Retrieves the site information for the current object.
NetworkConnect | Connects to the Internet.
NetworkDisconnect | Disconnects from the Internet.
PostFiles | Posts files to the specified URL.
ServerLogin | Logs the user on to the Internet server.
ServerLogout | Logs the user out of the Internet server.
SetParam | Sets the value of a parameter for a given site.
SetProgressUpdateProc | Specifies the callback function.


Appendix A, Structures

WPPROVINFO
WPSITEINFO

Up Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


WpBindToSite

DWORD WpBindToSite(
    [in]		HWND	hWnd
    [in, string]	LPTSTR	szSiteName
    [in, string]	LPTSTR	szSiteURL
    [in]	DWORD		dwFlags
    [in]	DWORD		dwReserved
    [out]	LPVOID *	ppUnk
    );

Attempts to determine the provider responsible for servicing the specified site based upon szSiteName and/or szSiteURL.

  • Returns NO_ERROR if successful. Otherwise, returns an error code, which may be one of the following:
    E_INVALIDARG
    E_OUTOFMEMORY
    WEBPOST_ERROR_LIST_SITES
    WEBPOST_ERROR_SITE_CORRUPT
    WEBPOST_ERROR_PROVCLSID_UNKNOWN
    WEBPOST_ERROR_PROV_CORRUPT
    WEBPOST_ERROR_PROV_DLL
    WEBPOST_ERROR_PROV_EP
    WEBPOST_ERROR_BAD_PROV_PTR
    WEBPOST_ERROR_EXTENDED_ERROR
    WEBPOST_ERROR_NO_EXT_ERROR_INFO

    More information about these error codes can be found in Appendix B, Error Codes.

hWnd
Optional. Window handle to receive focus upon completion of this API call. May be NULL.
szSiteName
Posting site name. May be NULL if valid szSiteURL is given.
szSiteURL
Posting site URL. May be NULL if valid szSiteName is given.
dwFlags
Action flags. Possible values are shown in the following table.
Value | Meaning
WPF_NO_DIRECT_LOOKUP | Do not attempt to look up the site based on the posting site name. This has the same effect as a NULL or empty szSiteName.
WPF_NO_URL_LOOKUP | Do not attempt to look up the site based on the posting site URL. This has the same effect as a NULL or empty szSiteURL.
dwReserved
Reserved. Must be set to zero.
ppUnk
Address of an IUnknown pointer, which can be queried upon return to determine whether the service provider supports the old IWPSite or the new IWPProvider interface. May not be NULL.

The site lookup procedure works as follows:

  1. If szSiteName and szSiteURL are both either NULL or empty, return E_INVALIDARG.
  2. Registry lookup. If szSiteName is non-NULL/empty and WPF_NO_DIRECT_LOOKUP is not set:
    1. Get a site subkey.
    2. Check szSiteName for a match with the subkey name. If there is a match, get the site URL and call WppBindToSite into the indicated provider with the WPF_FORCE_BIND flag and return the interface pointer so obtained.
    3. If all subkeys have been enumerated, proceed to URL Lookup. Otherwise return to step 2-1.
  3. URL lookup. If szSiteURL is non-NULL/empty and WPF_NO_URL_LOOKUP is not set:
    1. Get a site subkey.
    2. Check whether the szSiteURL value of the subkey is a prefix of szSiteURL. If so, get the site name and call WppBindToSite into the indicated provider with the WPF_FORCE_BIND flag and return the interface pointer so obtained.
    3. If all subkeys have been enumerated, quit with error result. Otherwise return to step 3-1.

Examples
C/C++

{
    HRESULT hResult = NOERROR;
    void *pUnknown;

    hResult = WpBindToSite(NULL, "site1", NULL, 0, 0, &pUnknown);
}


WpCreateSite

DWORD WpCreateSite(
    [in, string]	LPTSTR	szSiteName
    [in, string]	LPTSTR	szSiteLocalBaseDir
    [in, string]	LPTSTR	szSiteURL
    [in, string]	LPTSTR	szProviderCLSID
    [in]		DWORD	dwFlags
    );

Creates a new site in the registry.

  • Returns NO_ERROR if successful. Otherwise, returns an error code, which may be one of the following:
    E_INVALIDARG
    E_OUTOFMEMORY
    WEBPOST_ERROR_INIT_FAILED
    WEBPOST_ERROR_CREATE_SITE
    WEBPOST_ERROR_INVALID_POSTINFO
    WEBPOST_ERROR_NO_POSTINFO
    WEBPOST_ERROR_PROV_DLL
    WEBPOST_ERROR_PROV_EP
    WEBPOST_ERROR_SITE_EXISTS
    WEBPOST_ERROR_EXTENDED_ERROR
    WEBPOST_ERROR_NO_EXT_ERROR_INFO
    WEBPOST_ERROR_POSTINFO_REQUIRED
    WEBPOST_ERROR_AUTOBIND_FAILED

    More information about these error codes can be found in Appendix B, Error Codes.

szSiteName
Posting site name.
szSiteLocalBaseDir
Optional. Local base directory for the site. If NULL, then the local base directory feature is not used for the site.
szSiteURL
Posting site URL.
szProviderCLSID
Optional. CLSID as string, of the provider that will handle this site. If NULL, then this method will search for a posting information (postinfo) file or attempt to auto-bind to an appropriate provider.
dwFlags
Optional.
WPF_USE_PROVIDER_PASSED If WpCreateSite has been called and returned WEBPOST_ERROR_PROV_NOT_IN_POSTINFO, use this flag to have WpCreateSiteExuse the provider specified in szProviderCLSID even if there is a postinfo file and it does not list this provider.

Examples
C/C++

{
    HRESULT hResult = NOERROR;

    hResult = WpCreateSite("site1", NULL, "http://site1", NULL, 0);
}


WpCreateSiteEx

DWORD WpCreateSiteEx(
    [in, string]	LPTSTR	szSiteName
    [in, string]	LPTSTR	szSiteLocalBaseDir
    [in, string]	LPTSTR	szSiteURL
    [in, string]	LPTSTR	szProviderCLSID
    [in, string]	LPTSTR	szUsername,
    [in, string]	LPSTR		szPassword,
    [in]		DWORD		dwFlags,
    [out]		Iunknown	**ppSPI,
    [out]		DWORD		*pdwCharSet
    );

Creates a new site in the registry, using a user name and password, and returns a pointer to the service provider interface.

  • Returns NO_ERROR if successful. Otherwise, returns an error code, which may be one of the following:
    E_INVALIDARG
    E_OUTOFMEMORY
    WEBPOST_ERROR_INIT_FAILED
    WEBPOST_ERROR_CREATE_SITE
    WEBPOST_ERROR_INVALID_POSTINFO
    WEBPOST_ERROR_NO_POSTINFO
    WEBPOST_ERROR_PROV_DLL
    WEBPOST_ERROR_PROV_EP
    WEBPOST_ERROR_SITE_EXISTS
    WEBPOST_ERROR_EXTENDED_ERROR
    WEBPOST_ERROR_NO_EXT_ERROR_INFO
    WEBPOST_ERROR_POSTINFO_REQUIRED
    WEBPOST_ERROR_AUTOBIND_FAILED

    More information about these error codes can be found in Appendix B, Error Codes.

szSiteName
Posting site name.
szSiteLocalBaseDir
Optional. Local base directory for the site. If NULL, then the local base directory feature is not used for the site.
szSiteURL
Posting site URL.
szProviderCLSID
Optional. CLSID as string, of the provider that will handle this site. If NULL, then this method will search for a posting information (postinfo) file or attempt to auto-bind to an appropriate provider.
szUsername
Optional. The user name to use when logging on to the remote servers. If NULL or incorrect, the user is prompted to supply a user name and password.
szPassword
Optional. The password to use when logging on to the remote servers. If NULL or incorrect, the user is prompted to supply a user name and password.
dwFlags
Optional.
WPF_USE_PROVIDER_PASSED If WpCreateSite has been called and returned WEBPOST_ERROR_PROV_NOT_IN_POSTINFO, use this flag to have WpCreateSiteExuse the provider specified in szProviderCLSID even if there is a postinfo file and it does not list this provider.
**ppSPI
Optional. If WpCreateSiteExreturns successfully, *pSPI should point to a IWPSiteA, IWPSiteW, or IWPProvider interface.

Examples
C/C=++

{
    HRESULT hResult = NOERROR;
    IUnknown *pUnkSPI = NULL;
    DWORD dwCharSet;

    hResult = WpCreateSiteEx(
        "site1",
        NULL,
        "http://site1",
        NULL,
        "CRSadmin",
        "ptmyhygmn",
        NULL,
        0,
        &pUnkSPI,
        &dwCharSet);
}


WpDeleteSite

DWORD WpDeleteSite(
    [in, string]	LPTSTR	szSiteName
    );

Deletes a site from the registry.

  • Returns NO_ERROR if successful. Otherwise, returns an error code, which may be one of the following:
    E_INVALIDARG
    WEBPOST_ERROR_INIT_FAILED
    WEBPOST_ERROR_SITE_DOESNOTEXIST
    WEBPOST_ERROR_PROV_EP
    WEBPOST_ERROR_DELETE_SITE
    WEBPOST_ERROR_EXTENDED_ERROR
    WEBPOST_ERROR_NO_EXT_ERROR_INFO

    More information about these error codes can be found in Appendix B, Error Codes.

szSiteName
Posting site name.

WpDeleteSite calls WppDeleteSite on the provider that owns the specified site.

Examples
C/C=++

{
    HRESULT hResult = NOERROR;

    hResult = WpDeleteSite("site1");
}


WpDoesSiteExist

DWORD WpDoesSiteExist(
    [in, string]	LPTSTR	szSiteName
    [out]		BOOL	*	pbSiteExists
    );

Checks to see whether a site with the specified name exists.

  • Returns NO_ERROR if successful. Otherwise, returns an error code, which may be one of the following:
    E_INVALIDARG
    WEBPOST_ERROR_INIT_FAILED

    More information about these error codes can be found in Appendix B, Error Codes.

szSiteName
Posting site name.
pbSiteExists
Returned as TRUE if site exists, FALSE otherwise.

Examples
C/C=++

{
    HRESULT hResult = NOERROR;
    BOOL b;

    hResult = WpDoesSiteExist("site1",&b);
}


WpEnumProviders

DWORD WpEnumProviders(
    [in, out]		LPDWORD		pdwProvidersBufLen
    [out]		LPWPPROVINFO	pProvidersBuffer
    [out]		LPDWORD		pdwNumProviders
    );

Retrieves the list of all currently registered providers.

  • Returns NO_ERROR if successful. Otherwise, returns an error code, which may be one of the following:
    E_INVALIDARG
    E_OUTOFMEMORY
    WEBPOST_ERROR_INIT_FAILED
    WEBPOST_ERROR_PROV_CORRUPT
    WEBPOST_ERROR_ENUM_PROVS

    More information about these error codes can be found in Appendix B, Error Codes.

pdwProvidersBufLen
Size, in bytes, of pProvidersBuffer. On return, contains the actual number of bytes used in pProvidersBuffer. If pProvidersBuffer is NULL or too small to hold all the providers, this parameter shows the necessary size of the buffer to allocate.
pProvidersBuffer
Receives an array of WPPROVINFO structures.
pdwNumProviders
Number of providers. This value is set whether or not pProvidersBuffer is NULL or points to a large enough buffer.

Examples
C/C=++

{
    HRESULT hResult = NOERROR;
    DWORD BufLen;
    DWORD Num;

    hResult = WpEnumProviders(&BufLen, NULL, &Num);
}


WpGetErrorString

DWORD WpGetErrorString(
    [in]		UINT		uErrCode
    [in, out]		LPTSTR	szOutputBuf
    [in, out]		DWORD *	pdwBuflen
    );

Provides a textual explanation of the specified error code.

  • Returns NO_ERROR if successful. If the error code could not be translated, returns an E_FAIL error code.
uErrCode
The error code to translate.
szOutputBuf
The error message as NULL-terminated string. If NULL or not large enough, then use the value returned in pdwBufLen to allocate the necessary buffer.
pdwBufLen
On entry, the size of buffer provided. On return, the required buffer size in bytes.

The error code is first looked up in Web Publishing's error message table, then in the Win32® system table. If the error code cannot be translated, the function returns E_FAIL and the buffer is filled with an "Unknown Error" message.

Examples
C/C=++

{
    HRESULT hResult = NOERROR;
    DWORD BufLen;

    hResult = WpGetErrorString(0, NULL, &BufLen);
}


WpListSites

DWORD WpListSites(
    [in, out]		LPDWORD		pdwSitesBufLen
    [out]		LPWPSITEINFO	pSitesBuffer
    [out]		LPDWORD		pdwNumSites
    );

Retrieves the list of all sites about which Web Publishing currently has information.

  • Returns NO_ERROR if successful. Otherwise, returns an error code, which may be one of the following:
    E_INVALIDARG
    E_OUTOFMEMORY
    WEBPOST_ERROR_INIT_FAILED
    WEBPOST_ERROR_SITE_CORRUPT
    WEBPOST_ERROR_LIST_SITES

    More information about these error codes can be found in Appendix B, Error Codes.

pdwSitesBufLen
Size, in bytes, of pSitesBuffer. On return, contains the actual number of bytes used in pSitesBuffer. If pSitesBuffer is NULL or too small to hold all the sites, this parameter shows the necessary size of the buffer to allocate.
pSitesBuffer
Receives an array of WPSITEINFO structures.
pdwNumSites
Number of sites. This value is set whether or not pdwSitesBuffer is NULL or points to a large enough buffer.

Examples
C/C=++

{
    HRESULT hResult = NOERROR;
    DWORD BufLen;
    DWORD Num;

    hResult = WpListSites(&BufLen, NULL, &Num);
}


WppBindToSite

LONG WppBindToSite(
    [in]		HWND 	hwnd
    [in, string]	LPCTSTR 	wsSiteName
    [in, string]	LPCTSTR 	wsURL
    [in]		REFIID 	riid
    [in]		DWORD 	fdwFlags
    [in]		DWORD 	dwReserved
    [out]		PVOID *	ppvObj
    );

Retrieves the address of an interface if the provider DLL owns the site name or the URL.

  • Returns ERROR_SUCCESS if successful or an error value otherwise.
hwnd
Handle of the window to which the focus returns when the wizard, if invoked, completes. This parameter can be NULL if the wizard is not invoked or if this function is called from a console application.
wsSiteName
Optional. Address of a null-terminated string that contains an Internet site name.
wsURL
Optional. Address of a null-terminated string that contains a URL.
riid
Interface identifier. All providers should support the IID_IWPSiteinterface identifier. Provider implementations that implement IWPProvider should also support the IID_IWPProvider ID.
fdwFlags
Action flags. Possible values are shown in the following table.
Value | Meaning
WPF_FORCE_BIND | The provider should not query the site to see whether it can post to it (that is, do not test whether the protocol used by the provider is supported by the server.)
dwReserved
Reserved, and must be set to zero (0).
ppvObj
Address of a variable to receive the interface address.

See a C++ sample provider template included with Web Publishing in the Internet Client SDK.


WppDeleteSite

LONG WppDeleteSite(
    [in, string] 	LPCTSTR 	szSiteName
    );

Deletes a configured site.

  • Returns ERROR_SUCCESS if successful or an error value otherwise.
szSiteName
Address of a null-terminated string that contains the site name.

See a C++ sample provider template included with Web Publishing in the Internet Client SDK.


WpPost

DWORD WpPost(
    [in]		HWND 	hWnd
    [in]		DWORD	dwNumLocalPaths
    [in]		LPTSTR *	pszLocalPaths
    [in, out]		LPDWORD	pdwSiteNameBufLen
    [in, out]		LPTSTR	szSiteName
    [in, out]		LPDWORD	pdwDestURLBufLen
    [in, out]		LPTSTR	szDestURL
    [in]		DWORD	dwFlags
    );

Posts files and directories to a desired site.

  • Returns NO_ERROR if successful. Otherwise, returns an error code, which may be one of the following:
    WEBPOST_ERROR_INIT_FAILED
    WEBPOST_ERROR_PROV_QI
    WEBPOST_ERROR_POST_FILES
    WEBPOST_ERROR_INIT_FILES
    WEBPOST_ERROR_COCREATE_WIZARD
    WEBPOST_ERROR_HTTP_GET_FAILED
    WEBPOST_ERROR_EXTENDED_ERROR
    WEBPOST_ERROR_NO_EXT_ERROR_INFO

    For further information on error codes, see Appendix B, Error Codes.

hWnd
Optional. Window handle to receive focus upon completion of this API call. May be NULL.
dwNumLocalPaths
Number of elements in the array pointed to by pszLocalPaths.
pszLocalPaths
String names of files or directories to be posted. If the string specifies a directory (and the WPF_NO_RECURSIVE_POST flag is not set in the dwFlags parameter), all the files in that directory are posted.
pdwSiteNameBufLen
Size, in bytes, of buffer szSiteName. On return, contains the actual number of bytes used in szSiteName. If szSiteName is NULL or too small, this parameter shows the necessary size of the buffer to allocate.
szSiteName
The posting site name. This parameter and the szDestURL parameter may not both be NULL or empty if the WPF_NO_WIZARD flag is set.
pdwDestURLBufLen
Size, in bytes, of buffer szDestURL. On return, contains the actual number of bytes used in szDestURL. If szDestURL is NULL or too small, this parameter shows the necessary size of the buffer to allocate.
szDestURL
The destination URL. If this parameter is non-NULL and of sufficient size, and the WPF_NO_WIZARD flag is not set, then on return it will contain the destination URL for the site.
dwFlags
Action flags. Possible values are shown in the following table.
Value | Meaning
WPF_FIRST_FILE_AS_DEFAULT | Take the first file specified in pszLocalPaths as the file that will be shown as the default page.
WPF_NO_RECURSIVE_POST | If any element in pszLocalPaths points to a directory, do not post files recursively.
WPF_NO_WIZARD | Do not prompt the user for any input.
WPF_NO_DIRECT_LOOKUP | Do not attempt to look up the site based on the site name. This has the same effect as a NULL or empty szSiteName.
WPF_NO_URL_LOOKUP | Do not attempt to look up the site based on the site URL. This has the same effect as a NULL or empty szSiteURL.
WPF_NO_PROGRESS_DLGS | Do not show the "Publishing files" progress bar during the transfer of files to the destination computer.
WPF_NO_UI | Predefined combination of WPF_NO_WIZARD and WPF_NO_PROGRESS_DLGS.
WPF_SHOWPAGE_WELCOME | Forces the wizard to display the initial "Publish Your Files on the Web" page. Normally this page is skipped if the only other page being displayed is the Finish page. Note that the WPF_NO_WIZARD flag overrides this one.
WPF_SHOWPAGE_SRCFILE | Forces the wizard to display the "Select a File or Folder" page. Normally this page is skipped if the path or paths to publish are specified in the call to WpPost. Note that the WPF_NO_WIZARD flag overrides this one.
WPF_SHOWPAGE_DESTSITE | Forces the wizard to display the "Select a Web Server" page. Normally this page is skipped if the site name is specified in the call to WpPost. Note that the WPF_NO_WIZARD flag overrides this one.
WPF_SHOWPAGE_PROVIDER | Forces the wizard to display any and all pages associated with the service provider. Note that it is the responsibility of service provider implementations to be compliant with this flag (see the specification of the AddWizardPages SPI function.) Note that the WPF_NO_WIZARD flag overrides this one.
WPF_SHOWPAGE_ALL | Predefined combination of WPF_SHOWPAGE_*. Note that the WPF_NO_WIZARD flag overrides this one.

The following tables explain how whether dwFlags has the WPF_NO_WIZARD flag set and the various values of the szSiteName and the szDestURL parameters affect what WpPost does.

dwFlags has the WPF_NO_WIZARD flag set
szDestURL == NULL | szDestURL == existing site Y | szDestURL is prefixed by an existing site Y | szDestURL is new
szSiteName == NULL | Returns E_INVALIDARG | Posts to site Y | Posts to site Y; publishes to URL szDestURL | Creates a new site
szSiteName == existing site X | Posts to site X | If X == Y, posts to that site; otherwise, returns E_INVALIDARG | If X == Y, posts to that site and publishes to to URL szDestURL; otherwise, returns E_INVALIDARG | Returns E_INVALIDARG
szSiteName is new | Returns E_INVALIDARG | Creates a new site | Creates a new site | Creates a new site

dwFlags does not have the WPF_NO_WIZARD flag set
szDestURL == NULL | szDestURL == existing site Y | szDestURL is prefixed by an existing site Y | szDestURL is new
szSiteName == NULL | Creates a new site; displays all Wizard pages | Posts to site Y; displays Welcome and Finish Wizard pages | Posts to site Y; publishes to URL szDestURL; displays Welcome and Finish Wizard pages | Creates a new site; displays all Wizard pages except URL
szSiteName == existing site X | Posts to site X; displays Welcome and Finish Wizard pages | Posts to site X; displays Welcome and Finish Wizard pages | Posts to site X; displays Welcome and Finish Wizard pages | Posts to site X; displays Welcome and Finish Wizard pages
szSiteName is new | Creates a new site; displays all Wizard pages except Name the Web Server | Creates a new site; displays all Wizard pages except Name the Web Server and URL | Creates a new site; displays all Wizard pages except Name the Web Server and URL | Creates a new site; displays all Wizard pages except Name the Web Server and URL

If the wizard is invoked (the WPF_NO_WIZARD flag is not set), the wizard will examine the information specified in the call to WpPost and display the minimum set of pages necessary to complete the publishing process (this minimum-UI behavior may be overridden with the WPF_SHOWPAGE flags.) If the user is prompted to enter the friendly name and/or URL for the site, this information is returned to the caller of WpPost in the buffers provided.

If the wizard is not invoked, WpPost calls WpBindToSite to get an interface pointer to the provider that owns the specified site. If the WpBindToSite call fails, WpPost tries to create the site by calling WpCreateSite. Note that WpPost passes the destination URL to WpBindToSiteand WpCreateSite. When calling WpCreateSite, it also passes NULL for the local base directory, indicating that this site does not use the local base directory feature and that all posts to this site should go to the root destination URL; and it passes NULL for the service provider, specifying that the service provider should be determined by auto-binding. If the site's provider cannot be determined from the site name passed to WpPost or an auto-bind, WpPost will fail.

Since WpPost relies on WpBindToSite to do site lookup, all site lookup functionality resides within WpBindToSite. The procedure followed when performing this lookup is detailed under WpBindToSite.

Examples
C/C=++

{
    HRESULT hResult = NOERROR;
    LPTSTR szLocalPaths = {"c:\\MyDir"};

    hResult = WpPost(NULL, 1, &szLocalPaths, 0, NULL, 0, NULL, 0);
}


WpPostEx

DWORD WpPostEx(
    [in]		HWND 	hWnd
    [in]		DWORD	dwNumLocalPaths
    [in]		LPTSTR *	pszLocalPaths
    [in, out]		LPDWORD	pdwSiteNameBufLen
    [in, out]		LPTSTR	szSiteName
    [in, out]		LPDWORD	pdwDestURLBufLen
    [in, out]		LPTSTR	szDestURL
    [in]		LPSTR		szUsername
    [in]		LPSTR		szPassword
    [in]		DWORD	dwFlags
    );

Posts files and directories to a desired site, using a user name and password.

  • Returns NO_ERROR if successful. Otherwise, returns an error code, which may be one of the following:
    WEBPOST_ERROR_INIT_FAILED
    WEBPOST_ERROR_PROV_QI
    WEBPOST_ERROR_POST_FILES
    WEBPOST_ERROR_INIT_FILES
    WEBPOST_ERROR_COCREATE_WIZARD
    WEBPOST_ERROR_HTTP_GET_FAILED
    WEBPOST_ERROR_EXTENDED_ERROR
    WEBPOST_ERROR_NO_EXT_ERROR_INFO

    For further information on error codes, see Appendix B, Error Codes.

hWnd
Optional. Window handle to receive focus upon completion of this API call. May be NULL.
dwNumLocalPaths
Number of elements in the array pointed to by pszLocalPaths.
pszLocalPaths
String names of files or directories to be posted. If the string specifies a directory (and the WPF_NO_RECURSIVE_POST flag is not set in the dwFlags parameter), all the files in that directory are posted.
pdwSiteNameBufLen
Size, in bytes, of buffer szSiteName. On return, contains the actual number of bytes used in szSiteName. If szSiteName is NULL or too small, this parameter shows the necessary size of the buffer to allocate.
szSiteName
The posting site name. This parameter and the szDestURL parameter may not both be NULL or empty if the WPF_NO_WIZARD flag is set. If this parameter is non-NULL and of sufficient size, and the WPF_NO_WIZARD flag is not set, then on return it will contain the site to which the files were posted.
pdwDestURLBufLen
Size, in bytes, of buffer szDestURL. On return, contains the actual number of bytes used in szDestURL. If szDestURL is NULL or too small, this parameter shows the necessary size of the buffer to allocate.
szDestURL
The destination URL. If this parameter is non-NULL and of sufficient size, and the WPF_NO_WIZARD flag is not set, then on return it will contain the destination URL for the site.
szUsername
Optional. The user name to use when logging on to the remote servers. If NULL or incorrect, the user is prompted to supply a user name and password.

QUESTION: Does WP prompt for both a user name and password if either the user name is NULL or incorrect or the password is NULL or incorrect (versus just prompting for only the missing information)? For example, if the user name is correct but the password is not correct, does WP prompt for only a password?

szPassword
Optional. The password to use when logging on to the remote servers. If NULL or incorrect, the user is prompted to supply a user name and password.
dwFlags
Action flags. Possible values are shown in the following table.
Value | Meaning
WPF_FIRST_FILE_AS_DEFAULT | Take the first file specified in pszLocalPaths as the file that will be shown as the default page.
WPF_NO_RECURSIVE_POST | If any element in pszLocalPaths points to a directory, do not post files recursively.
WPF_NO_WIZARD | Do not prompt the user for any input.
WPF_NO_DIRECT_LOOKUP | Do not attempt to look up the site based on the site name. This has the same effect as a NULL or empty szSiteName.
WPF_NO_URL_LOOKUP | Do not attempt to look up the site based on the site URL. This has the same effect as a NULL or empty szSiteURL.
WPF_NO_PROGRESS_DLGS | Do not show the "Publishing files" progress bar during the transfer of files to the destination computer.
WPF_NO_UI | Predefined combination of WPF_NO_WIZARD and WPF_NO_PROGRESS_DLGS.
WPF_SHOWPAGE_WELCOME | Forces the wizard to display the initial "Publish Your Files on the Web" page. Normally this page is skipped if the only other page being displayed is the Finish page. Note that the WPF_NO_WIZARD flag overrides this one.
WPF_SHOWPAGE_SRCFILE | Forces the wizard to display the "Select a File or Folder" page. Normally this page is skipped if the path or paths to publish are specified in the call to WpPost. Note that the WPF_NO_WIZARD flag overrides this one.
WPF_SHOWPAGE_DESTSITE | Forces the wizard to display the "Select a Web Server" page. Normally this page is skipped if the site name is specified in the call to WpPost. Note that the WPF_NO_WIZARD flag overrides this one.
WPF_SHOWPAGE_PROVIDER | Forces the wizard to display any and all pages associated with the service provider. Note that it is the responsibility of service provider implementations to be compliant with this flag (see the specification of the AddWizardPages SPI function.) Note that the WPF_NO_WIZARD flag overrides this one.
WPF_SHOWPAGE_ALL | Predefined combination of WPF_SHOWPAGE_*. Note that the WPF_NO_WIZARD flag overrides this one.

If the wizard is invoked (the WPF_NO_WIZARD flag is not set), the wizard will examine the information specified in the call to WpPost and display the minimum set of pages necessary to complete the publishing process (this minimum-UI behavior may be overridden with the WPF_SHOWPAGE flags.) If the user is prompted to enter the friendly name and/or URL for the site, this information is returned to the caller of WpPost in the buffers provided.

If the wizard is not invoked, WpPost calls WpBindToSite to get an interface pointer to the provider that owns the specified site. If the WpBindToSite call fails, WpPost tries to create the site by calling WpCreateSite. Note that WpPost passes the destination URL to WpBindToSiteand WpCreateSite. When calling WpCreateSite, it also passes NULL for the local base directory, indicating that this site does not use the local base directory feature and that all posts to this site should go to the root destination URL; and it passes NULL for the service provider, specifying that the service provider should be determined by auto-binding. If the site's provider cannot be determined from the site name passed to WpPost or an auto-bind, WpPost will fail.

Since WpPost relies on WpBindToSite to do site lookup, all site lookup functionality resides within WpBindToSite. The procedure followed when performing this lookup is detailed under WpBindToSite.

Examples
C/C=++

{
    HRESULT hResult = NOERROR;
    LPTSTR szLocalPaths = {"c:\\MyDir"};

    hResult = WpPost(
        NULL,
        1,
        &szLocalPaths,
        0,
        NULL,
        0,
        NULL,
        "anonynous",
        "e-mail",
        0);
}


WpPostFile

HRESULT WpPostFile(
    [in]		LONG	 	hWnd
    [in]		BSTR		bstrLocalPath
    [in, out]		LONG *	plSiteNameBufLen
    [in, out]		BSTR		bstrSiteName
    [in, out]		LONG *	plDestURLBufLen
    [in, out]		BSTR		bstrDestURL
    [in]		LONG		lFlags
    [out, retval]	LONG *	plRetCode
    );

Simply a version of WpPost accessible through WpObj's COM Interface. The functionality is identical to that described in WpPost except as follows:
WpPostFile can only accept a single file for posting (although that file may be a directory, in which case all files within it will be posted.)
The WPF_NO_WIZARD flag is disabled, and the WPF_SHOWPAGE_SRCFILE flag is automatically set. This is to ensure that users who may download a Web page that uses this method are always prompted before any files can be uploaded from their machine.

  • Return values are the same as WpPost.
hWnd
Same as WpPost.
bstrLocalPath
String name of a single file or directory to be posted. If the string specifies a directory (and the WPF_NO_RECURSIVE_POST flag is not set in the lFlags parameter), all the files in that directory are posted.
plSiteNameBufLen
Same as WpPost.
bstrSiteName
Same as WpPost.
plDestURLBufLen
Same as WpPost.
bstrDestURL
Same as WpPost.
lFlags
Same as WpPost.
plRetCode
Pointer to a long integer that receives the return code of the operation.


WPPROVINFO

typedef struct tagWPPROVINFO
{
    DWORD	dwSize;
    DWORD	dwFlags;
    DWORD	dwPriority;
    LPTSTR	lpszProviderName;
    LPTSTR	lpszProviderCLSID;
    LPTSTR	lpszDllPath;
}
WPPROVINFO, *LPWPPROVINFO;
dwSize
Size of the provider information structure in bytes, including the string buffers for the name, CLSID, and DLL path.
dwFlags
Provider flags. Not currently used.
dwPriority
Integer that indicates the provider's priority. 0 is highest priority.
lpszProviderName
Friendly name of the provider.
lpszProviderCLSID
CLSID of the provider implementation object.
lpszDllPath
Fully qualified path of the DLL that contains the COM server for the provider.


WPSITEINFO

typedef struct tagWPSITEINFO
{
DWORD	dwSize;
    DWORD	dwFlags;
    LPTSTR	lpszSiteName;
    LPTSTR	lpszSiteURL;
}
WPSITEINFO, *LPWPSITEINFO;
dwSize
Size of the site information structure in bytes, including the string buffers for the site name and URL.
dwFlags
Site flags. Not currently used.
lpszSiteName
Friendly name of the site.
lpszSiteURL
Destination URL for the site (location where posted files can be accessed.)


Microsoft Win32 Internet Functions Reference

This reference describes the functions, macros, structures, flags, and error codes associated with the Microsoft® Win32® Internet (WinInet) functions.

General Win32 Internet Functions

Automatic Dialing Functions

Uniform Resource Locator (URL) Functions

FTP Functions

Gopher Functions

HTTP Functions

Cookie Functions

Persistent URL Cache Functions

Macros

Data Types

Structures

API Flags

HTTP Status Codes

Option Flags

Error Messages


WinInet API

This section covers the Win32® Internet functions, which provide a high-level interface that abstracts the underlying protocols. This section also includes automatic dialing functions to handle dial-up connections.

Microsoft Win32 Internet Functions Overview

Microsoft Win32 Internet Functions Reference


API Flags

Many of the Win32 Internet functions accept a double-word array of flags as a parameter. The following is a brief description of the defined flags.

INTERNET_FLAG_ASYNC
Makes only asynchronous requests on handles descended from the handle returned from this function. Only the InternetOpen function uses this flag.
INTERNET_FLAG_CACHE_ASYNC
Allows a lazy cache write.
INTERNET_FLAG_CACHE_IF_NET_FAIL
Return the resource from the cache if the network request for the resource fails due to an ERROR_INTERNET_CONNECTION_RESET or ERROR_INTERNET_CANNOT_CONNECT. This flag is used by HttpOpenRequest.
INTERNET_FLAG_DONT_CACHE
Does not add the returned entity to the cache. Identical to the preferred value, INTERNET_FLAG_NO_CACHE_WRITE. This flag is used by GopherFindFirstFile, GopherOpenFile, FtpFindFirstFile, FtpGetFile, FtpOpenFile, FtpPutFile, HttpOpenRequest, and InternetOpenUrl.
INTERNET_FLAG_EXISTING_CONNECT
Attempts to use an existing InternetConnect object if one exists with the same attributes required to make the request. This is useful only with FTP operations, since FTP is the only protocol that typically performs multiple operations during the same session. The Win32 Internet API caches a single connection handle for each HINTERNET handle generated by InternetOpen. Only the InternetOpenUrl function uses this flag.
INTERNET_FLAG_FORMS_SUBMIT
Indicates that this is a forms submit.
INTERNET_FLAG_FROM_CACHE
Does not make network requests. All entities are returned from the cache. If the requested item is not in the cache, a suitable error, such as ERROR_FILE_NOT_FOUND, is returned. Only the InternetOpen function uses this flag.
INTERNET_FLAG_HYPERLINK
Forces a reload if there was no Expires time and no Last-Modified time returned from the server when determining whether to reload the item from the network. This flag can be used by GopherFindFirstFile, GopherOpenFile, FtpFindFirstFile, FtpGetFile, FtpOpenFile, FtpPutFile, HttpOpenRequest, and InternetOpenUrl.
INTERNET_FLAG_IGNORE_CERT_CN_INVALID
Disables Win32 Internet function checking of SSL/PCT-based certificates that are returned from the server against the host name given in the request. Win32 Internet functions use a simple check against certificates by comparing for matching host names and simple wildcarding rules. This flag can be used by HttpOpenRequest and InternetOpenUrl (for HTTP requests).
INTERNET_FLAG_IGNORE_CERT_DATE_INVALID
Disables Win32 Internet function checking of SSL/PCT-based certificates for proper validity dates. This flag can be used by HttpOpenRequest and InternetOpenUrl (for HTTP requests).
INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP
Disables the ability of the Win32 Internet functions to detect this special type of redirect. When this flag is used, Win32 Internet functions transparently allow redirects from HTTPS to HTTP URLs. This flag can be used by HttpOpenRequest and InternetOpenUrl (for HTTP requests).
INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS
Disables the ability of the Win32 Internet functions to detect this special type of redirect. When this flag is used, Win32 Internet functions transparently allow redirects from HTTP to HTTPS URLs. This flag can be used by HttpOpenRequest and InternetOpenUrl (for HTTP requests).
INTERNET_FLAG_KEEP_CONNECTION
Uses keep-alive semantics, if available, for the connection. This flag is used by HttpOpenRequest and InternetOpenUrl (for HTTP requests). This flag is required for Microsoft Network (MSN), NT LAN Manager (NTLM), and other types of authentication.
INTERNET_FLAG_MAKE_PERSISTENT
No longer supported.
INTERNET_FLAG_MUST_CACHE_REQUEST
Identical to the preferred value, INTERNET_FLAG_NEED_FILE. Causes a temporary file to be created if the file cannot be cached. This flag can be used by GopherFindFirstFile, GopherOpenFile, FtpFindFirstFile, FtpGetFile, FtpOpenFile, FtpPutFile, HttpOpenRequest, and InternetOpenUrl.
INTERNET_FLAG_NEED_FILE
Causes a temporary file to be created if the file cannot be cached. This flag can be used by GopherFindFirstFile, GopherOpenFile, FtpFindFirstFile, FtpGetFile, FtpOpenFile, FtpPutFile, HttpOpenRequest, and InternetOpenUrl.
INTERNET_FLAG_NO_AUTH
Does not attempt authentication automatically. This flag can be used by HttpOpenRequest and InternetOpenUrl (for HTTP requests).
INTERNET_FLAG_NO_AUTO_REDIRECT
Does not automatically handle redirection in HttpSendRequest. This flag can also be used by InternetOpenUrl for HTTP requests.
INTERNET_FLAG_NO_CACHE_WRITE
Does not add the returned entity to the cache. This flag is used by GopherFindFirstFile, GopherOpenFile, FtpFindFirstFile, FtpGetFile, FtpOpenFile, FtpPutFile, HttpOpenRequest, and InternetOpenUrl.
INTERNET_FLAG_NO_COOKIES
Does not automatically add cookie headers to requests, and does not automatically add returned cookies to the cookie database. This flag can be used by HttpOpenRequest and InternetOpenUrl (for HTTP requests).
INTERNET_FLAG_NO_UI
Disables the cookie dialog box. This flag can be used by HttpOpenRequest and InternetOpenUrl (HTTP requests only).
INTERNET_FLAG_OFFLINE
Identical to INTERNET_FLAG_FROM_CACHE. Does not make network requests. All entities are returned from the cache. If the requested item is not in the cache, a suitable error, such as ERROR_FILE_NOT_FOUND, is returned. Only the InternetOpen function uses this flag.
INTERNET_FLAG_PASSIVE
Uses passive FTP semantics. Only InternetConnect and InternetOpenUrl use this flag. InternetConnect uses this flag for FTP requests, and InternetOpenUrl uses this flag for FTP files and directories.
INTERNET_FLAG_PRAGMA_NOCACHE
Forces the request to be resolved by the origin server, even if a cached copy exists on the proxy. The InternetOpenUrl function (on HTTP and HTTPS requests only) and HttpOpenRequest functions use this flag.
INTERNET_FLAG_RAW_DATA
Returns the data as a GOPHER_FIND_DATA structure when retrieving Gopher directory information, or as a WIN32_FIND_DATA structure when retrieving FTP directory information. If this flag is not specified or if the call was made through a CERN proxy, InternetOpenUrl returns HTML version of the directory. Only the InternetOpenUrl function uses this flag.
INTERNET_FLAG_READ_PREFETCH
This flag is currently disabled.
INTERNET_FLAG_RELOAD
Forces a download of the requested file, object, or directory listing from the origin server, not from the cache. The GopherFindFirstFile, GopherOpenFile, FtpFindFirstFile, FtpGetFile, FtpOpenFile, FtpPutFile, HttpOpenRequest, and InternetOpenUrl functions utilize this flag.
INTERNET_FLAG_RESYNCHRONIZE
Reloads HTTP resources if the resource has been modified since the last time it was downloaded. All FTP and Gopher resources are reloaded. This flag can be used by GopherFindFirstFile, GopherOpenFile, FtpFindFirstFile, FtpGetFile, FtpOpenFile, FtpPutFile, HttpOpenRequest, and InternetOpenUrl.
INTERNET_FLAG_SECURE
Uses secure transaction semantics. This translates to using Secure Sockets Layer/Private Communications Technology (SSL/PCT) and is only meaningful in HTTP requests. This flag is used by HttpOpenRequest and InternetOpenUrl, but this is made redundant if "https://" appears in the URL.
INTERNET_FLAG_TRANSFER_ASCII
Transfers file as ASCII (FTP only). This flag can be used by FtpOpenFile, FtpGetFile, and FtpPutFile.
INTERNET_FLAG_TRANSFER_BINARY
Transfers file as binary (FTP only). This flag can be used by FtpOpenFile, FtpGetFile, and FtpPutFile.
WININET_API_FLAG_ASYNC
Forces asynchronous operations.
WININET_API_FLAG_SYNC
Forces synchronous operations.
WININET_API_FLAG_USE_CONTEXT
Forces the API to use the context value, even if it is set to zero.


Error Messages

The Win32 Internet functions return Win32 error messages where appropriate. The following error messages are specific to the Win32 Internet functions.

INTERNET_ERROR_BASE
Base value of the Internet error codes.
ERROR_FTP_DROPPED
The FTP operation was not completed because the session was aborted.

ERROR_FTP_TRANSFER_IN_PROGRESS
The requested operation cannot be made on the FTP session handle because an operation is already in progress.

ERROR_GOPHER_ATTRIBUTE_NOT_FOUND
The requested attribute could not be located.

ERROR_GOPHER_DATA_ERROR
An error was detected while receiving data from the Gopher server.

ERROR_GOPHER_END_OF_DATA
The end of the data has been reached.

ERROR_GOPHER_INCORRECT_LOCATOR_TYPE
The type of the locator is not correct for this operation.

ERROR_GOPHER_INVALID_LOCATOR
The supplied locator is not valid.

ERROR_GOPHER_NOT_FILE
The request must be made for a file locator.

ERROR_GOPHER_NOT_GOPHER_PLUS
The requested operation can only be made against a Gopher+ server, or with a locator that specifies a Gopher+ operation.

ERROR_GOPHER_PROTOCOL_ERROR
An error was detected while parsing data returned from the Gopher server.

ERROR_GOPHER_UNKNOWN_LOCATOR
The locator type is unknown.

ERROR_HTTP_DOWNLEVEL_SERVER
The server did not return any headers.

ERROR_HTTP_HEADER_ALREADY_EXISTS
The header could not be added because it already exists.

ERROR_HTTP_HEADER_NOT_FOUND
The requested header could not be located.

ERROR_HTTP_INVALID_HEADER
The supplied header is invalid.

ERROR_HTTP_INVALID_QUERY_REQUEST
The request made to HttpQueryInfo is invalid.

ERROR_HTTP_REDIRECT_FAILED
The redirection failed because either the scheme changed (for example, HTTP to FTP) or all attempts made to redirect failed (default is five attempts).

ERROR_HTTP_REDIRECT_NEEDS_CONFIRMATION
The redirection requires user confirmation.

ERROR_HTTP_INVALID_SERVER_RESPONSE
The server response could not be parsed.

ERROR_INTERNET_ASYNC_THREAD_FAILED
The application could not start an asynchronous thread.

ERROR_INTERNET_BAD_OPTION_LENGTH
The length of an option supplied to InternetQueryOption or InternetSetOption is incorrect for the type of option specified.

ERROR_INTERNET_BAD_AUTO_PROXY_SCRIPT
There was an error in the automatic proxy configuration script.

ERROR_INTERNET_BAD_REGISTRY_PARAMETER
A required registry value was located but is an incorrect type or has an invalid value.

ERROR_INTERNET_CANNOT_CONNECT
The attempt to connect to the server failed.

ERROR_INTERNET_CHG_POST_IS_NON_SECURE
The application is posting and attempting to change multiple lines of text on a server that is not secure.

ERROR_INTERNET_CLIENT_AUTH_CERT_NEEDED
The server is requesting client authentication.

ERROR_INTERNET_CLIENT_AUTH_NOT_SETUP
Client authorization is not set up on this computer.

ERROR_INTERNET_CONNECTION_ABORTED
The connection with the server has been terminated.

ERROR_INTERNET_CONNECTION_RESET
The connection with the server has been reset.

ERROR_INTERNET_DIALOG_PENDING
Another thread has a password dialog in progress.

ERROR_INTERNET_DISCONNECTED
The Internet connection has been lost.

ERROR_INTERNET_EXTENDED_ERROR
An extended error was returned from the server. This is typically a string or buffer containing a verbose error message. Call InternetGetLastResponseInfo to retrieve the error text.

ERROR_INTERNET_FAILED_DUETOSECURITYCHECK
The function failed due to a security check.

ERROR_INTERNET_FORCE_RETRY
The Win32 Internet function needs to redo the request.

ERROR_INTERNET_HANDLE_EXISTS
The request failed because the handle already exists.

ERROR_INTERNET_HTTP_TO_HTTPS_ON_REDIR
The application is moving from a non-SSL to an SSL connection because of a redirect.

ERROR_INTERNET_HTTPS_TO_HTTP_ON_REDIR
The application is moving from an SSL to an non-SSL connection because of a redirect.

ERROR_INTERNET_INCORRECT_FORMAT
The format of the request is invalid.

ERROR_INTERNET_INCORRECT_HANDLE_STATE
The requested operation cannot be carried out because the handle supplied is not in the correct state.

ERROR_INTERNET_INCORRECT_HANDLE_TYPE
The type of handle supplied is incorrect for this operation.

ERROR_INTERNET_INCORRECT_PASSWORD
The request to connect and log on to an FTP server could not be completed because the supplied password is incorrect.

ERROR_INTERNET_INCORRECT_USER_NAME
The request to connect and log on to an FTP server could not be completed because the supplied user name is incorrect.

ERROR_INTERNET_INSERT_CDROM
The request requires a CD-ROM to be inserted in the CD-ROM drive to locate the resource requested.

ERROR_INTERNET_INTERNAL_ERROR
An internal error has occurred.

ERROR_INTERNET_INVALID_CA
The function is unfamiliar with the Certificate Authority that generated the server's certificate.

ERROR_INTERNET_INVALID_OPERATION
The requested operation is invalid.

ERROR_INTERNET_INVALID_OPTION
A request to InternetQueryOption or InternetSetOption specified an invalid option value.

ERROR_INTERNET_INVALID_PROXY_REQUEST
The request to the proxy was invalid.

ERROR_INTERNET_INVALID_URL
The URL is invalid.

ERROR_INTERNET_ITEM_NOT_FOUND
The requested item could not be located.

ERROR_INTERNET_LOGIN_FAILURE
The request to connect and log on to an FTP server failed.

ERROR_INTERNET_MIXED_SECURITY
The content is not entirely secure. Some of the content being viewed may have come from unsecured servers.

ERROR_INTERNET_NAME_NOT_RESOLVED
The server name could not be resolved.

ERROR_INTERNET_NEED_UI
A user interface or other blocking operation has been requested.

ERROR_INTERNET_NO_CALLBACK
An asynchronous request could not be made because a callback function has not been set.

ERROR_INTERNET_NO_CONTEXT
An asynchronous request could not be made because a zero context value was supplied.

ERROR_INTERNET_NO_DIRECT_ACCESS
Direct network access cannot be made at this time.

ERROR_INTERNET_NOT_PROXY_REQUEST
The request cannot be made via a proxy.

ERROR_INTERNET_OFFLINE
Identical to the preferred value ERROR_INTERNET_DISCONNECTED.

ERROR_INTERNET_OPERATION_CANCELLED
The operation was canceled, usually because the handle on which the request was operating was closed before the operation completed.

ERROR_INTERNET_OPTION_NOT_SETTABLE
The requested option cannot be set, only queried.

ERROR_INTERNET_OUT_OF_HANDLES
No more handles could be generated at this time.

ERROR_INTERNET_POST_IS_NON_SECURE
The application is posting data to a sever that is not secure.

ERROR_INTERNET_PROTOCOL_NOT_FOUND
The requested protocol could not be located.

ERROR_INTERNET_PROXY_SERVER_UNREACHABLE
The designated proxy server cannot be reached.

ERROR_INTERNET_REDIRECT_SCHEME_CHANGE
The function could not handle the redirection, because the scheme changed (for example, HTTP to FTP).

ERROR_INTERNET_REGISTRY_VALUE_NOT_FOUND
A required registry value could not be located.

ERROR_INTERNET_REQUEST_PENDING
The required operation could not be completed because one or more requests are pending.

ERROR_INTERNET_SEC_CERT_CN_INVALID
SSL certificate common name (host name field) is incorrect—for example, if you entered www.server.com and the common name on the certificate says www.different.com.

ERROR_INTERNET_SEC_CERT_DATE_INVALID
SSL certificate date that was received from the server is bad. The certificate is expired.

ERROR_INTERNET_SEC_CERT_REVOKED
SSL certificate was revoked.

ERROR_INTERNET_SEC_INVALID_CERT
SSL certificate is invalid.

ERROR_INTERNET_SECURITY_CHANNEL_ERROR
The application experienced an internal error loading the SSL libraries.

ERROR_INTERNET_SERVER_UNREACHABLE
The Web site or server indicated is unreachable.

ERROR_INTERNET_SHUTDOWN
The Win32 Internet function support is being shut down or unloaded.

ERROR_INTERNET_TCPIP_NOT_INSTALLED
The required protocol stack is not loaded and the application cannot start WinSock.

ERROR_INTERNET_TIMEOUT
The request has timed out.

ERROR_INTERNET_UNABLE_TO_CACHE_FILE
The function was unable to cache the file.

ERROR_INTERNET_UNABLE_TO_DOWNLOAD_SCRIPT
The automatic proxy configuration script could not be downloaded. The INTERNET_FLAG_MUST_CACHE_REQUEST flag was set.

ERROR_INTERNET_UNRECOGNIZED_SCHEME
The URL scheme could not be recognized, or is not supported.

ERROR_INVALID_HANDLE
The handle that was passed to the API has been either invalidated or closed. (Win32 error code)

ERROR_NO_MORE_FILES
No more files have been found. (Win32 error code)

ERROR_NO_MORE_ITEMS
No more items have been found. (Win32 error code)


Option Flags

The following list contains the options supported by InternetQueryOption and InternetSetOption.

INTERNET_OPTION_ASYNC
Not currently implemented.

INTERNET_OPTION_ASYNC_PRIORITY
Not currently implemented.

INTERNET_OPTION_CACHE_STREAM_HANDLE
No longer supported.

INTERNET_OPTION_CALLBACK
Returns or sets the address of the callback function defined for this handle. This option can be used on all HINTERNET handles. Used by InternetQueryOption and InternetSetOption.

INTERNET_OPTION_CALLBACK_FILTER
Not currently implemented

INTERNET_OPTION_CONNECT_BACKOFF
Not currently implemented.

INTERNET_OPTION_CONNECT_LIMIT
Not currently implemented.

INTERNET_OPTION_CONNECT_RETRIES
Returns or sets the retry count to use for Internet connection requests. If a connection attempt still fails after the specified number of tries, the request is canceled. The default is five retries. This option can be used on any HINTERNET handle, including a NULL handle. Used by InternetQueryOption and InternetSetOption.

INTERNET_OPTION_CONNECT_TIME
Not currently implemented.

INTERNET_OPTION_CONNECT_TIMEOUT
Returns or sets the time-out value, in milliseconds, to use for Internet connection requests. If a connection request takes longer than this time-out value, the request is canceled. This option can be used on any HINTERNET handle, including a NULL handle. Used by InternetQueryOption and InternetSetOption.

INTERNET_OPTION_CONNECTED_STATE
Returns or sets the connected state. Used by InternetQueryOption and InternetSetOption.

INTERNET_OPTION_CONTEXT_VALUE
Returns or sets the context value associated with this Internet handle. This option can be used on any HINTERNET handle. Used by InternetQueryOption and InternetSetOption. Previously, this set the context value to the address stored in the DWORD(lpBuffer) pointer. This has been corrected so that the value stored in the buffer will be used and the INTERNET_OPTION_CONTEXT_VALUE flag will be reassigned a new value. The old value, 10, has been preserved so that applications written for the old behavior are still supported.

INTERNET_OPTION_CONTROL_RECEIVE_TIMEOUT
Identical to INTERNET_OPTION_RECEIVE_TIMEOUT. Used by InternetQueryOption and InternetSetOption.

INTERNET_OPTION_CONTROL_SEND_TIMEOUT
Identical to INTERNET_OPTION_SEND_TIMEOUT. Used by InternetQueryOption and InternetSetOption.

INTERNET_OPTION_DATA_RECEIVE_TIMEOUT
Returns or sets the time-out value, in milliseconds, to use for Internet data download requests. If a data receive request takes longer than this time-out value, the request is canceled. Used by InternetQueryOption and InternetSetOption.

INTERNET_OPTION_DATA_SEND_TIMEOUT
Returns or sets the time-out value, in milliseconds, to use for Internet data send requests. If a data send request takes longer than this time-out value, the request is canceled. Used by InternetQueryOption and InternetSetOption.

INTERNET_OPTION_DATAFILE_NAME
Returns the name of the file backing a downloaded entity. This flag is valid after InternetOpenUrl, FtpOpenFile, GopherOpenFile, or HttpOpenRequest has completed. Used by InternetQueryOption and InternetSetOption.

INTERNET_OPTION_DISCONNECTED_TIMEOUT
Not currently implemented.

INTERNET_OPTION_END_BROWSER_SESSION
Flushes entries not in use from the password cache on the hard drive. Also resets the cache time used when the synchronization mode is once-per-session. Used by InternetSetOption.

INTERNET_OPTION_ERROR_MASK
Not currently implemented.

INTERNET_OPTION_EXTENDED_ERROR
Returns the Windows Sockets error message that was mapped to the ERROR_INTERNET_ error messages last returned in this thread context. This option is used on a NULL HINTERNET handle by InternetQueryOption.

INTERNET_OPTION_HANDLE_TYPE
Returns the type of the Internet handle passed in. Used by InternetQueryOption on any HINTERNET handle. Possible return values include:

INTERNET_HANDLE_TYPE_CONNECT_FTP
INTERNET_HANDLE_TYPE_CONNECT_GOPHER
INTERNET_HANDLE_TYPE_CONNECT_HTTP
INTERNET_HANDLE_TYPE_FTP_FILE
INTERNET_HANDLE_TYPE_FTP_FILE_HTML
INTERNET_HANDLE_TYPE_FTP_FIND
INTERNET_HANDLE_TYPE_FTP_FIND_HTML
INTERNET_HANDLE_TYPE_GOPHER_FILE
INTERNET_HANDLE_TYPE_GOPHER_FILE_HTML
INTERNET_HANDLE_TYPE_GOPHER_FIND
INTERNET_HANDLE_TYPE_GOPHER_FIND_HTML
INTERNET_HANDLE_TYPE_HTTP_REQUEST
INTERNET_HANDLE_TYPE_INTERNET

INTERNET_OPTION_HTTP_VERSION
Returns or sets the HTTP version being supported. Must be used on a NULL handle. An HTTP_VERSION_INFO structure is used to set or get the version information. Used by InternetQueryOption and InternetSetOption.

INTERNET_OPTION_IDLE_STATE
Not currently implemented.

INTERNET_OPTION_KEEP_CONNECTION
Not currently implemented.

INTERNET_OPTION_LISTEN_TIMEOUT
Not currently implemented.

INTERNET_OPTION_OFFLINE_MODE
Not currently implemented.

INTERNET_OPTION_OFFLINE_SEMANTICS
Not currently implemented.

INTERNET_OPTION_PARENT_HANDLE
Returns the parent handle to this handle. This option can be used on any HINTERNET handle by InternetQueryOption.

INTERNET_OPTION_PASSWORD
Returns or sets the password associated with a handle returned by InternetConnect. Used by InternetQueryOption and InternetSetOption.

INTERNET_OPTION_POLICY
Not currently implemented.

INTERNET_OPTION_PROXY
Returns or sets the proxy information on an existing InternetOpen handle when the HINTERNET handle is not NULL. If the HINTERNET handle is NULL, the function sets or queries the global proxy information. The lpBuffer parameter is an INTERNET_PROXY_INFO structure that contains the proxy information. This option can be used on the HINTERNET handle returned by InternetOpen. Used by InternetQueryOption and InternetSetOption.

INTERNET_OPTION_PROXY_PASSWORD
Returns or sets the password currently being used to access the proxy. Used by InternetQueryOption and InternetSetOption.

INTERNET_OPTION_PROXY_USERNAME
Returns or sets the user name currently being used to access the proxy. Used by InternetQueryOption and InternetSetOption.

INTERNET_OPTION_READ_BUFFER_SIZE
Returns or sets the size of the read buffer. This option can be used on HINTERNET handles returned by FtpOpenFile, FtpFindFirstFile, and InternetConnect (FTP session only). Used by InternetQueryOption and InternetSetOption.

INTERNET_OPTION_RECEIVE_THROUGHPUT
Not currently implemented.

INTERNET_OPTION_RECEIVE_TIMEOUT
Returns or sets the time-out value, in milliseconds, to receive a response to a request. If the response takes longer than this time-out value, the request is canceled. This option can be used on any HINTERNET handle, including a NULL handle. Used by InternetQueryOption and InternetSetOption.

INTERNET_OPTION_REFRESH
Returns or sets the value that determines if the proxy information can be reread from the registry for a handle. The value TRUE indicates that the proxy information can be reread from the registry for a handle. This option can be used on the HINTERNET handle returned by InternetOpen. Used by InternetQueryOption and InternetSetOption.

INTERNET_OPTION_REQUEST_FLAGS
Returns special status flags about the current download in progress. Used by InternetQueryOption. The flag can be one of the following values:

INTERNET_REQFLAG_ASYNC | Not currently implemented.
INTERNET_REQFLAG_FROM_CACHE | Response came from the cache.
INTERNET_REQFLAG_NO_HEADERS | Original response contained no headers.
INTERNET_REQFLAG_PASSIVE | Not currently implemented.
INTERNET_REQFLAG_VIA_PROXY | Request was made through a proxy.

INTERNET_OPTION_REQUEST_PRIORITY
Returns or sets the priority of requests competing for a connection on an HTTP handle. Used by InternetQueryOption and InternetSetOption.

INTERNET_OPTION_SECONDARY_CACHE_KEY
Returns or sets the secondary cache key. Used by InternetQueryOption and InternetSetOption.

INTERNET_OPTION_SECURITY_CERTIFICATE
Returns the certificate for an SSL/PCT (Secure Sockets Layer/Private Communications Technology) server into a formatted string. Used by InternetQueryOption.

INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT
Returns the certificate for an SSL/PCT server into the INTERNET_CERTIFICATE_INFO structure. Used by InternetQueryOption.

INTERNET_OPTION_SECURITY_FLAGS
Returns the security flags for a handle. Used by InternetQueryOption. Can be a combination of these values:

SECURITY_FLAG_128BIT
Identical to the preferred value SECURITY_FLAG_STRENGTH_STRONG. Only returned in a call to InternetQueryOption.
SECURITY_FLAG_40BIT
Identical to the preferred value SECURITY_FLAG_STRENGTH_WEAK. Only returned in a call to InternetQueryOption.
SECURITY_FLAG_56BIT
Identical to the preferred value SECURITY_FLAG_STRENGTH_MEDIUM. Only returned in a call to InternetQueryOption.
SECURITY_FLAG_IETFSSL4
Not currently implemented.
SECURITY_FLAG_IGNORE_CERT_CN_INVALID
Ignores the ERROR_INTERNET_SEC_CERT_CN_INVALID error message.
SECURITY_FLAG_IGNORE_CERT_DATE_INVALID
Ignores the ERROR_INTERNET_SEC_CERT_DATE_INVALID error message.
SECURITY_FLAG_IGNORE_REDIRECT_TO_HTTP
Ignores the ERROR_INTERNET_HTTPS_TO_HTTP_ON_REDIR error message.
SECURITY_FLAG_IGNORE_REDIRECT_TO_HTTPS
Ignores the ERROR_INTERNET_HTTP_TO_HTTPS_ON_REDIR error message.
SECURITY_FLAG_IGNORE_REVOCATION
Ignores certificate revocation problems.
SECURITY_FLAG_IGNORE_UNKNOWN_CA
Ignore unknown certificate authority problems.
SECURITY_FLAG_IGNORE_WRONG_USAGE
Ignore incorrect usage problems.
SECURITY_FLAG_NORMALBITNESS
Identical to the value SECURITY_FLAG_STRENGTH_WEAK. Only returned in a call to InternetQueryOption.
SECURITY_FLAG_PCT
Not currently implemented.
SECURITY_FLAG_PCT4
Not currently implemented.
SECURITY_FLAG_SECURE
Uses secure transfers. Only returned in a call to InternetQueryOption.
SECURITY_FLAG_SSL
Not currently implemented.
SECURITY_FLAG_SSL3
Not currently implemented.
SECURITY_FLAG_STRENGTH_MEDIUM
Uses medium (56 bit) encryption. Only returned in a call to InternetQueryOption.
SECURITY_FLAG_STRENGTH_STRONG
Uses strong (128 bit) encryption. Only returned in a call to InternetQueryOption.
SECURITY_FLAG_STRENGTH_WEAK
Uses weak (40 bit) encryption. Only returned in a call to InternetQueryOption.
SECURITY_FLAG_UNKNOWNBIT
The bit size used in the encryption is unknown. Only returned in a call to InternetQueryOption.
INTERNET_OPTION_SECURITY_KEY_BITNESS
Returns the bit size of the encryption key. The larger the number, the greater the encryption strength being used. Used by InternetQueryOption.

INTERNET_OPTION_SECURITY_SELECT_CLIENT_CERT
Sets the client certification. Used by InternetSetOption.

INTERNET_OPTION_SEND_THROUGHPUT
Not currently implemented.

INTERNET_OPTION_SEND_TIMEOUT
Returns or sets the time-out value, in milliseconds, to send a request. If the send takes longer than this time-out value, the send is canceled. This option can be used on any HINTERNET handle, including a NULL handle. Used by InternetQueryOption and InternetSetOption.

INTERNET_OPTION_SETTINGS_CHANGED
Informs WinInet that the registry settings have been changed, so that it will check the settings on the next call to InternetConnect. Used by InternetSetOption.

INTERNET_OPTION_URL
Returns the full URL of a downloaded resource. If the original URL contained any extra information (such as search strings or anchors) or if the call was redirected, the URL returned will differ from the original. This option is valid on HINTERNET handles returned by InternetOpenUrl, FtpOpenFile, GopherOpenFile, or HttpOpenRequest. Used by InternetQueryOption.

INTERNET_OPTION_USER_AGENT
Returns or sets the user agent string on handles supplied by InternetOpen and used in subsequent HttpSendRequest functions, as long as it is not overridden by a header added by HttpAddRequestHeaders or HttpSendRequest. Used by InternetQueryOption and InternetSetOption.

INTERNET_OPTION_USERNAME
Returns or sets the user name associated with a handle returned by InternetConnect. Used by InternetQueryOption and InternetSetOption.

INTERNET_OPTION_VERSION
Returns the version number of Wininet.dll. The lpBuffer parameter is the address of an INTERNET_VERSION_INFO structure. This option can be used on a NULL HINTERNET handle. Used by InternetQueryOption.

INTERNET_OPTION_WRITE_BUFFER_SIZE
Returns or sets the size of the write buffer. This option can be used on HINTERNET handles returned by FtpOpenFile and InternetConnect (FTP session only). Used by InternetQueryOption and InternetSetOption.


HTTP Status Codes

The following list contains the values and corresponding constants for the HTTP status codes returned by servers on the Internet.
Constant | Value | Description
HTTP_STATUS_OK | 200 | The request completed successfully.
HTTP_STATUS_CREATED | 201 | The request has been fulfilled and resulted in the creation of a new resource.
HTTP_STATUS_ACCEPTED | 202 | The request has been accepted for processing , but the processing has not been completed.
HTTP_STATUS_PARTIAL | 203 | The returned meta information in the entity-header is not the definitive set available from the origin server.
HTTP_STATUS_NO_CONTENT | 204 | The server has fulfilled the request, but there is no new information to send back.
HTTP_STATUS_RESET_CONTENT | 205 | The request has been completed, and the client program should reset the document view that caused the request to be sent to allow the user to easily initiate another input action.
HTTP_STATUS_PARTIAL_CONTENT | 206 | The server has fulfilled the partial GET request for the resource.
HTTP_STATUS_AMBIGUOUS | 300 | The server couldn't decide what to return.
HTTP_STATUS_MOVED | 301 | The requested resource has been assigned to a new permanent URI, and any future references to this resource should be done using one of the returned URIs.
HTTP_STATUS_REDIRECT | 302 | The requested resource resides temporarily under a different URI.
HTTP_STATUS_REDIRECT_METHOD | 303 | The response to the request can be found under a different URI and should be retrieved using a GET method on that resource.
HTTP_STATUS_NOT_MODIFIED | 304 | The requested resource has not been modified.
HTTP_STATUS_USE_PROXY | 305 | The requested resource must be accessed through the proxy given by the location field.
HTTP_STATUS_REDIRECT_KEEP_VERB | 307 | The redirected request keeps the same verb. HTTP/1.1 behavior.
HTTP_STATUS_BAD_REQUEST | 400 | The request could not be processed by the server due to invalid syntax.
HTTP_STATUS_DENIED | 401 | The requested resource requires user authentication.
HTTP_STATUS_PAYMENT_REQ | 402 | Not currently implemented in the HTTP protocol.
HTTP_STATUS_FORBIDDEN | 403 | The server understood the request, but is refusing to fulfill it.
HTTP_STATUS_NOT_FOUND | 404 | The server has not found anything matching the requested URI.
HTTP_STATUS_BAD_METHOD | 405 | The method used is not allowed.
HTTP_STATUS_NONE_ACCEPTABLE | 406 | No responses acceptable to the client were found.
HTTP_STATUS_PROXY_AUTH_REQ | 407 | Proxy authentication required.
HTTP_STATUS_REQUEST_TIMEOUT | 408 | The server timed out waiting for the request.
HTTP_STATUS_CONFLICT | 409 | The request could not be completed due to a conflict with the current state of the resource. The user should resubmit with more information.
HTTP_STATUS_GONE | 410 | The requested resource is no longer available at the server, and no forwarding address is known.
HTTP_STATUS_LENGTH_REQUIRED | 411 | The server refuses to accept the request without a defined content length.
HTTP_STATUS_PRECOND_FAILED | 412 | The precondition given in one or more of the request header fields evaluted to false when it was tested on the server.
HTTP_STATUS_REQUEST_TOO_LARGE | 413 | The server is refusing to process a request because the request entity is larger than the server is willing or able to process.
HTTP_STATUS_URI_TOO_LONG | 414 | The server is refusing to service the request because the request URI is longer than the server is willing to interpret.
HTTP_STATUS_UNSUPPORTED_MEDIA | 415 | The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method.
HTTP_STATUS_SERVER_ERROR | 500 | The server encountered an unexpected condition that prevented it from fulfilling the request.
HTTP_STATUS_NOT_SUPPORTED | 501 | The server does not support the functionality required to fulfill the request.
HTTP_STATUS_BAD_GATEWAY | 502 | The server, while acting as a gateway or proxy, received an invalid response from the upstream server it accessed in attempting to fulfill the request.
HTTP_STATUS_SERVICE_UNAVAIL | 503 | The service is temporarily overloaded.
HTTP_STATUS_GATEWAY_TIMEOUT | 504 | The request was timed out waiting for a gateway.
HTTP_STATUS_VERSION_NOT_SUP | 505 | The server does not support, or refuses to support, the HTTP protocol version that was used in the request message.


Data Types

The following section contains the type definitions used by the Win32 Internet functions.
INTERNET_STATUS_CALLBACK


INTERNET_STATUS_CALLBACK

VOID (CALLBACK * INTERNET_STATUS_CALLBACK)(
    IN HINTERNET hInternet,
    IN DWORD dwContext,
    IN DWORD dwInternetStatus,
    IN LPVOID lpvStatusInformation,
    IN DWORD dwStatusInformationLength
);

Type used for an application-defined status callback function.

hInternet
Handle for which the callback function is being called.
dwContext
Application-defined context value associated with hInternet.
dwInternetStatus
Status code that indicates why the callback function is being called. Can be one of the following values:
INTERNET_STATUS_CLOSING_CONNECTION
Closing the connection to the server. The lpvStatusInformation parameter is NULL.
INTERNET_STATUS_CONNECTED_TO_SERVER
Successfully connected to the socket address (SOCKADDR) pointed to by lpvStatusInformation.
INTERNET_STATUS_CONNECTING_TO_SERVER
Connecting to the socket address (SOCKADDR) pointed to by lpvStatusInformation.
INTERNET_STATUS_CONNECTION_CLOSED
Successfully closed the connection to the server. The lpvStatusInformation parameter is NULL.
INTERNET_STATUS_CTL_RESPONSE_RECEIVED
Not currently implemented.
INTERNET_STATUS_HANDLE_CLOSING
This handle value is now terminated.
INTERNET_STATUS_HANDLE_CREATED
Used by InternetConnect to indicate it has created the new handle. This lets the application call InternetCloseHandle from another thread, if the connect is taking too long.
INTERNET_STATUS_INTERMEDIATE_RESPONSE
Received an intermediate (100 level) status code message from the server.
INTERNET_STATUS_NAME_RESOLVED
Successfully found the IP address of the name contained in lpvStatusInformation.
INTERNET_STATUS_PREFETCH
Not currently implemented.
INTERNET_STATUS_RECEIVING_RESPONSE
Waiting for the server to respond to a request. The lpvStatusInformation parameter is NULL.
INTERNET_STATUS_REDIRECT
An HTTP request is about to automatically redirect the request. The lpvStatusInformation parameter points to the new URL. At this point, the application can read any data returned by the server with the redirect response, and can query the response headers. It can also cancel the operation by closing the handle. This callback is not made if the original request specified INTERNET_FLAG_NO_AUTO_REDIRECT.
INTERNET_STATUS_REQUEST_COMPLETE
An asynchronous operation has been completed. See InternetOpen for details on INTERNET_FLAG_ASYNC.
INTERNET_STATUS_REQUEST_SENT
Successfully sent the information request to the server. The lpvStatusInformation parameter points to a DWORD containing the number of bytes sent.
INTERNET_STATUS_RESOLVING_NAME
Looking up the IP address of the name contained in lpvStatusInformation.
INTERNET_STATUS_RESPONSE_RECEIVED
Successfully received a response from the server. The lpvStatusInformation parameter points to a DWORD containing the number of bytes received.
INTERNET_STATUS_SENDING_REQUEST
Sending the information request to the server. The lpvStatusInformation parameter is NULL.
INTERNET_STATUS_STATE_CHANGE
Moved between a secure (HTTPS) and a nonsecure (HTTP) site. Can be one of the following values:
INTERNET_STATE_ONLINE | Online state (mutually exclusive with offline).
INTERNET_STATE_OFFLINE | Offline because no network connection could be established.
INTERNET_STATE_OFFLINE_USER | Offline by user request.
INTERNET_STATE_IDLE | No network requests are being made by WinInet.
INTERNET_STATE_BUSY | Network requests are being made by WinInet.
lpvStatusInformation
Address of a buffer that contains information pertinent to this call to the callback function.
dwStatusInformationLength
Size of the lpvStatusInformation buffer.

The lpvStatusInformation parameter points to an INTERNET_ASYNC_RESULT structure. The dwStatusInformationLength parameter contains the final completion status of the asynchronous function. If this is ERROR_INTERNET_EXTENDED_ERROR, the application can retrieve the server error information by using InternetGetLastResponseInfo.

In the case of INTERNET_STATUS_REQUEST_COMPLETE, lpvStatusInformation is the address of an INTERNET_ASYNC_RESULT structure.

An application uses the callback function to indicate the progress of synchronous and asynchronous functions, and to indicate the completion of an asynchronous request.

Because callbacks are made during processing of the request, the application should spend as little time as possible in the callback function to avoid degrading data throughput on the network. For example, displaying a dialog box in a callback function may be such a lengthy operation that the server terminates the request.

The callback function can be called in a thread context different from the thread that initiated the request.


Automatic Dialing Functions

The functions described in this section handle dial-up access to the Internet.
InternetAutodial
InternetAutodialHangup
InternetDial
InternetGetConnectedState
InternetGoOnline
InternetHangUp
InternetSetDialState


Persistent URL Cache Functions

This section describes the functions used by applications that need persistent caching services. These functions allow an application to save data in the local file system for subsequent use, such as in situations where access to the data is over a low bandwidth link, or the access is not available at all. The calling program that inserts data into the persistent cache assigns a source name that is used to do operations such as retrieve the data, set and get some properties on the data, and delete data.

The protocols implemented in Win32 Internet functions use the cache functions to provide persistent caching and offline browsing. Unless explicitly specified not to cache through the INTERNET_FLAG_NO_CACHE_WRITE flag, Win32 Internet functions cache all data downloaded from the network. The responses to POST data are not cached.
CommitUrlCacheEntry
CreateUrlCacheEntry
CreateUrlCacheGroup
DeleteUrlCacheEntry
DeleteUrlCacheEntry
FindCloseUrlCache
FindFirstUrlCacheEntry
FindFirstUrlCacheEntryEx
FindNextUrlCacheEntry
FindNextUrlCacheEntryEx
GetUrlCacheEntryInfo
GetUrlCacheEntryInfoEx
ReadUrlCacheEntryStream
RetrieveUrlCacheEntryFile
RetrieveUrlCacheEntryStream
SetUrlCacheEntryGroup
SetUrlCacheEntryInfo
UnlockUrlCacheEntryFile
UnlockUrlCacheEntryStream


CommitUrlCacheEntry

BOOL CommitUrlCacheEntry(
    IN LPCSTR lpszUrlName,
    IN LPCSTR lpszLocalFileName,
    IN FILETIME ExpireTime,
    IN FILETIME LastModifiedTime,
    IN DWORD CacheEntryType,
    IN LPCBYTE lpHeaderInfo,
    IN DWORD dwHeaderSize,
    IN LPCSTR lpszFileExtension,
    IN DWORD dwReserved
    );

Caches data in the specified file in the cache storage and associates it with the given URL.

  • Returns TRUE if successful, or FALSE otherwise. To get extended error information, call GetLastError. Possible error values include:
    ERROR_DISK_FULL | The cache storage is full.
    ERROR_FILE_NOT_FOUND | The specified local file is not found.
lpszUrlName
Address of a string that contains the source name of the cache entry. The name string must be unique, and should not contain any escape characters.
lpszLocalFileName
Address of a string that contains the name of the local file that is being cached. This should be the same name as that returned by CreateUrlCacheEntry.
ExpireTime
FILETIME structure that contains the expire date and time (GMT) of the file that is being cached. If the expire date and time is unknown, set this parameter to zero.
LastModifiedTime
FILETIME structure that contains the last modified date and time (GMT) of the URL that is being cached. If the last modified date and time is unknown, set this parameter to zero.
CacheEntryType
Cache type bitmask. Currently, the cache entry type values have not been finalized, so this value does not serve a real purpose at this point, except for STICK_CACHE_ENTRY. Can be a combination of the following values:
COOKIE_CACHE_ENTRY
NORMAL_CACHE_ENTRY
OCX_CACHE_ENTRY
SPARSE_CACHE_ENTRY
STABLE_CACHE_ENTRY
STICKY_CACHE_ENTRY
TRACK_CACHE_ENTRY
TRACK_OFFLINE_CACHE_ENTRY
TRACK_ONLINE_CACHE_ENTRY
URLHISTORY_CACHE_ENTRY

The STICKY_CACHE_ENTRY type is used to make cache entries exempt from scavenging. The default exempt time for entries set using CommitUrlCacheEntry is one day. The exempt time can be changed using the SetUrlCacheEntryInfo function.

lpHeaderInfo
Address of the header information. If this parameter is not NULL, the header information is treated as extended attributes of the URL and is returned in the INTERNET_CACHE_ENTRY_INFO structure.
dwHeaderSize
Size of the header information. If lpHeaderInfo is not NULL, this value is assumed to indicate the size of the header information. An application can maintain headers as part of the data and provide dwHeaderSize together with a NULL value for lpHeaderInfo.
lpszFileExtension
Address of a buffer that contains information maintained in the cache database for future use. In this version of Win32 Internet functions, this information is not used.
dwReserved
Reserved. If redirection has taken place, this parameter should contain the address of a string containing the original URL. Otherwise, must be set to zero.

If the cache storage is full, CommitUrlCacheEntry invokes cache cleanup to make space for this new file. If the cache entry already exists, the function overwrites the entry if it is not in use. An entry is in use when it has been retrieved with either RetrieveUrlCacheEntryStream or RetrieveUrlCacheEntryFile.

Clients who add entries to the cache should set the headers to at least "HTTP/1.0 200 OK\r\n\r\n"; otherwise, Microsoft Internet Explorer and other WinInet clients will disregard the entry.


Cookie Functions

Cookies are the means by which, under HTTP protocol, a server or a script can maintain state information on the client workstation. The Win32 Internet functions have implemented a persistent cookie database for this purpose. Cookie functions are provided for users of Win32 Internet functions to set cookies into, and access them from, the cookie database. The caller of these functions should be familiar with cookies as outlined in ftp://ds.internic.net/internet-drafts/draft-ietf-http-state-mgmt-*.txt. Please note that the implementation of these functions is evolving; be cautious when using them.
InternetGetCookie
InternetSetCookie


CreateUrlCacheEntry

BOOL CreateUrlCacheEntry(
    IN LPCSTR lpszUrlName,
    IN DWORD dwExpectedFileSize,
    IN LPCSTR lpszFileExtension,
    OUT LPSTR lpszFileName,
    IN DWORD dwReserved
);

Creates a local file name for saving the cache entry corresponding to the source name and the file extension.

  • Returns TRUE if successful, or FALSE otherwise. To get extended error information, call GetLastError.
lpszUrlName
String value that contains the name of the URL. The string should not contain any escape characters.
dwExpectedFileSize
Unsigned long integer value that contains the expected size of the file needed to store the data corresponding to the source entity. If the expected size is unknown, set this value to zero.
lpszFileExtension
String that contains an extension name of the file in the local storage.
lpszFileName
Address of a buffer that receives the file name. The buffer should be large enough (MAX_PATH) to store the path of the created file.
dwReserved
Reserved; must be zero.

After CreateUrlCacheEntry is called, the application can write directly into the file in local storage. When the file is completely received, the caller should call CommitUrlCacheEntry to commit the entry in the cache.


CreateUrlCacheGroup

GROUPID CreateUrlCacheGroup (
    IN DWORD dwFlags,
    IN LPVOID lpReserved
);

Generates cache group identifications.

  • Returns a valid GROUPID if successful, or FALSE otherwise. To get specific error information, use GetLastError.
dwFlags
DWORD value that contains the flags to control the creation of the cache group. No flags are currently implemented. Must be set to zero.
lpReserved
Reserved. Must be set to NULL.


DeleteUrlCacheEntry

BOOL DeleteUrlCacheEntry(
    IN LPCSTR lpszUrlName
);

Removes the file associated with the source name from the cache, if the file exists.

  • Returns TRUE if successful, or FALSE otherwise. To get extended error information, call GetLastError. Possible error values include:
    ERROR_ACCESS_DENIED | The file is locked or in use. The entry will be marked and will be deleted when the file is unlocked.
    ERROR_FILE_NOT_FOUND | The file is not in the cache.
lpszUrlName
Address of a string that contains the name of the source corresponding to the cache entry.


DeleteUrlCacheGroup

BOOLAPI DeleteUrlCacheGroup (
    IN GROUPID GroupId,
    IN DWORD dwFlags,
    IN LPVOID lpReserved
);

Releases a GROUPID and any associated state in the cache index file.

  • Returns TRUE if successful, or FALSE otherwise. To get specific error information, use GetLastError.
GroupId
GROUPID value that is associated with the cache group to be released.
dwFlags
DWORD value containing the flags to control the cache group deletion. No flags are currently implemented. Must be set to zero.
lpReserved
Reserved. Must be set to NULL.


FindCloseUrlCache

BOOL FindCloseUrlCache(
    IN HANDLE hEnumHandle
);

Closes the specified enumeration handle.

  • Returns TRUE if successful, or FALSE otherwise. To get extended error information, call GetLastError.
hEnumHandle
Handle returned by a previous call to the FindFirstUrlCacheEntry function.


FindFirstUrlCacheEntry

HANDLE FindFirstUrlCacheEntry (
    IN LPCSTR lpszUrlSearchPattern,
    OUT LPINTERNET_CACHE_ENTRY_INFO lpFirstCacheEntryInfo,
    IN OUT LPDWORD lpdwFirstCacheEntryInfoBufferSize
);

Begins the enumeration of the cache.

  • Returns a handle that the application can use in the FindNextUrlCacheEntry function to retrieve subsequent entries in the cache. If the function fails, the return value is NULL. To get extended error information, call GetLastError.

    ERROR_INSUFFICIENT_BUFFER indicates that the size of lpFirstCacheEntryInfo as specified by lpdwFirstCacheEntryInfoBufferSize is not sufficient to contain all the information. The value returned in lpdwFirstCacheEntryInfoBufferSize indicates the buffer size necessary to contain all the information.

lpszUrlSearchPattern
Address of a string that contains the source name pattern to search for. Can be set to "cookie:" or "visited:" to enumerate the cookies and URL History entries in the cache. If this parameter is NULL, the function uses *.*.
lpFirstCacheEntryInfo
Address of an INTERNET_CACHE_ENTRY_INFO structure.
lpdwFirstCacheEntryInfoBufferSize
Address of a variable that specifies the size of the lpFirstCacheEntryInfo buffer. When the function returns, the variable contains the number of bytes copied to the buffer, or the required size of the buffer.

FindFirstUrlCacheEntry and FindNextUrlCacheEntry return variable size information. If ERROR_INSUFFICIENT_BUFFER is returned, the application should allocate a buffer of the size specified by lpdwFirstCacheEntryInfoBufferSize. For more information, see Appendix B: Using Buffers in the Win32 Internet Functions Overview.


FindFirstUrlCacheEntryEx

HANDLE FindFirstUrlCacheEntryEx (
    IN LPCSTR lpszUrlSearchPattern,
    IN DWORD dwFlags,
    IN DWORD dwFilter,
    IN GROUPID GroupId
    OUT LPINTERNET_CACHE_ENTRY_INFO  lpFirstCacheEntryInfo,
    IN OUT LPDWORD lpdwFirstCacheEntryInfoBufferSize,
    OUT LPVOID lpGroupAttributes,
    IN OUT LPDWORD pcbGroupAttributes,
    IN LPVOID lpReserved
);

Starts a filtered enumeration of the cache.

  • Returns a valid handle if successful, or NULL otherwise. To get specific error information, use GetLastError. If the function finds no matching files, GetLastError returns ERROR_NO_MORE_FILES.
lpszUrlSearchPattern
String value containing the search pattern. Search patterns are currently not supported, so the value must be set to NULL to indicate all entries with the matching GROUPID.
dwFlags
DWORD value containing the flags controlling the enumeration. No flags are currently implemented. Must be set to zero.
dwFilter
DWORD value that indicates the cache entry types that are allowed. Can be any combination of cache entry types:
NORMAL_CACHE_ENTRY | Normal cache entry; can be deleted to recover space for new entries.
SPARSE_CACHE_ENTRY | Not currently implemented.
STABLE_CACHE_ENTRY | Not currently implemented.
STICKY_CACHE_ENTRY | Not currently implemented.

The following list contains the values that indicate what is being cached. Can be one of the following values:
COOKIE_CACHE_ENTRY | Cookie cache entry.
OCX_CACHE_ENTRY | Not currently implemented.
URLHISTORY_CACHE_ENTRY | Visited link cache entry.

GroupId
GROUPID value indicating the cache group to enumerate. Set the value to zero to enumerate all entries that are not grouped.
lpFirstCacheEntryInfo
Address of the buffer to hold the INTERNET_CACHE_ENTRY_INFO structure that the cache entry information will be stored in.
lpdwFirstCacheEntryInfoBufferSize
Address of a DWORD value that indicates the size of lpFirstCacheEntryInfo.
lpGroupAttributes
Must be set to NULL.
pcbGroupAttributes
Must be set to NULL.
lpReserved
Reserved. Must be set to NULL.

At the end of the enumeration, the application should call FindCloseUrlCache.


FindNextUrlCacheEntry

BOOL FindNextUrlCacheEntry(
    IN HANDLE hEnumHandle,
    OUT LPINTERNET_CACHE_ENTRY_INFO lpNextCacheEntryInfo,
    IN OUT LPWORD lpdwNextCacheEntryInfoBufferSize
);

Retrieves the next entry in the cache.

  • Returns TRUE if successful, or FALSE otherwise. To get extended error information, call GetLastError. Possible error values include:
    ERROR_INSUFFICIENT_BUFFER | The size of lpNextCacheEntryInfo as specified by lpdwNextCacheEntryInfoBufferSize is not sufficient to contain all the information. The value returned in lpdwNextCacheEntryInfoBufferSize indicates the buffer size necessary to contain all the information.
    ERROR_NO_MORE_ITEMS | The enumeration completed.
hEnumHandle
Enumeration handle obtained from a previous call to FindFirstUrlCacheEntry.
lpNextCacheEntryInfo
Address of an INTERNET_CACHE_ENTRY_INFO structure that receives information about the cache entry.
lpdwNextCacheEntryInfoBufferSize
Address of a variable that specifies the size of the lpNextCacheEntryInfo buffer. When the function returns, the variable contains the number of bytes copied to the buffer, or the required size of the buffer.


FindNextUrlCacheEntryEx

BOOLAPI FindNextUrlCacheEntryEx (
    IN HANDLE hEnumHandle,
    OUT LPINTERNET_CACHE_ENTRY_INFO lpFirstCacheEntryInfo,
    IN OUT LPDWORD lpdwFirstCacheEntryInfoBufferSize,
    OUT LPVOID lpGroupAttributes,
    IN OUT LPDWORD pcbGroupAttributes,
    IN LPVOID lpReserved
);

Finds the next cache entry in a cache enumeration started by FindFirstUrlCacheEntryEx.

  • Returns TRUE if successful, FALSE otherwise. To get specific error information, use GetLastError.
hEnumHandle
HANDLE type value returned by FindFirstUrlCacheEntryEx, which started a cache enumeration.
lpFirstCacheEntryInfo
Address of the buffer to hold the INTERNET_CACHE_ENTRY_INFO structure that the cache entry information will be stored in.
lpdwFirstCacheEntryInfoBufferSize
Address of a DWORD value that indicates the size of the buffer.
lpGroupAttributes
Must be set to NULL.
pcbGroupAttributes
Must be set to NULL.
lpReserved
Reserved. Must be set to NULL.

At the end of the enumeration, the application should call FindCloseUrlCache.


FTP Functions

The FTP functions deal with FTP file and directory manipulation and navigation. Applications that use a CERN proxy exclusively must use the InternetOpenUrl function because CERN proxies do not support FTP. For more information on how to use InternetOpenUrl, see Accessing URLs directly.
FtpCreateDirectory
FtpDeleteFile
FtpFindFirstFile
FtpGetCurrentDirectory
FtpGetFile
FtpOpenFile
FtpPutFile
FtpRemoveDirectory
FtpRenameFile
FtpSetCurrentDirectory


FtpCreateDirectory

BOOL FtpCreateDirectory(
    IN HINTERNET hFtpSession,
    IN LPCSTR lpszDirectory
);

Creates a new directory on the FTP server.

  • Returns TRUE if successful, or FALSE otherwise. To get a specific error message, call GetLastError. If the error message indicates that the FTP server denied the request to create a directory, use InternetGetLastResponseInfo to determine why.
hFtpSession
Valid handle to an FTP session. This handle must have been returned from a previous call to InternetConnect.
lpszDirectory
Address of a null-terminated string that contains the name of the directory to create on the remote system. This can be either a fully qualified path or a name relative to the current directory.

An application should use FtpGetCurrentDirectory to determine the remote site's current working directory, instead of assuming that the remote system uses a hierarchical naming scheme for directories.

The lpszDirectory parameter can be either partially or fully qualified file names relative to the current directory. A backslash (\) or forward slash (/) can be used as the directory separator for either name. FtpCreateDirectory translates the directory name separators to the appropriate character before they are used.


FtpDeleteFile

BOOL FtpDeleteFile(
    IN HINTERNET hFtpSession,
    IN LPCSTR lpszFileName
);

Deletes a file stored on the FTP server.

  • Returns TRUE if successful, or FALSE otherwise. To get a specific error message, call GetLastError.
hFtpSession
Valid handle to an FTP session. This handle must have been returned from a previous call to InternetConnect.
lpszFileName
Address of a null-terminated string that contains the name of the file to delete on the remote system.

The lpszFile parameter can be either partially or fully qualified file names relative to the current directory. A backslash (\) or forward slash (/) can be used as the directory separator for either name. FtpDeleteFile translates the directory name separators to the appropriate character before they are used.


FtpFindFirstFile

HINTERNET FtpFindFirstFile(
    IN HINTERNET hFtpSession,
    IN LPCSTR lpszSearchFile,
    OUT LPWIN32_FIND_DATA lpFindFileData,
    IN DWORD dwFlags,
    IN DWORD dwContext
);

Searches the specified directory of the given FTP session. File and directory entries are returned to the application in the WIN32_FIND_DATA structure.

  • Returns a valid handle for the request if the directory enumeration was started successfully; otherwise, returns NULL. To get a specific error message, call GetLastError. If the function finds no matching files, GetLastError returns ERROR_NO_MORE_FILES.
hFtpSession
Valid handle to an FTP session returned from InternetConnect.
lpszSearchFile
Address of a null-terminated string that specifies a valid directory path or file name for the FTP server's file system. The string can contain wildcards, but no blank spaces are allowed. If the value of lpszSearchFile is NULL or if it is an empty string, it will find the first file in the current directory on the server.
lpFindFileData
Address of a WIN32_FIND_DATA structure that receives information about the found file or directory.
dwFlags
Application-defined value that associates this search with any application. Can be one of the following values:
INTERNET_FLAG_DONT_CACHE
Does not add the returned entity to the cache. Identical to the preferred value, INTERNET_FLAG_NO_CACHE_WRITE.
INTERNET_FLAG_HYPERLINK
Forces a reload if there was no Expires time and no Last-Modified time returned from the server when determining whether to reload the item from the network.
INTERNET_FLAG_MAKE_PERSISTENT
No longer supported.
INTERNET_FLAG_MUST_CACHE_REQUEST
Causes a temporary file to be created if the file cannot be cached. Identical to the preferred value, INTERNET_FLAG_NEED_FILE.
INTERNET_FLAG_NEED_FILE
Causes a temporary file to be created if the file cannot be cached.
INTERNET_FLAG_NO_CACHE_WRITE
Does not add the returned entity to the cache.
INTERNET_FLAG_RELOAD
Forces a download of the requested file, object, or directory listing from the origin server, not from the cache.
INTERNET_FLAG_RESYNCHRONIZE
Causes the FTP resource to be reloaded from the server.
dwContext
Application-defined value that associates this search with any application data. This parameter is used only if the application has already called InternetSetStatusCallback to set up a status callback function.

This function enumerates both files and directories.

FtpFindFirstFile is similar to the Win32 FindFirstFile function. Note, however, that only one FtpFindFirstFile can occur at a time within a given FTP session. The enumerations, therefore, are correlated with the FTP session handle. This is because the FTP protocol allows only a single directory enumeration per session.

After calling FtpFindFirstFile and until calling InternetCloseHandle, the application cannot call FtpFindFirstFile again on the given FTP session handle. If a call is made to FtpFindFirstFile on that handle, the function will fail with ERROR_FTP_TRANSFER_IN_PROGRESS.

After beginning a directory enumeration with FtpFindFirstFile, the InternetFindNextFile function can be used to continue the enumeration.

The InternetCloseHandle function is used to close the handle returned from FtpFindFirstFile. If InternetCloseHandle closes the handle before InternetFindNextFile fails with ERROR_NO_MORE_FILES, the directory enumeration will be terminated.

Because the FTP protocol provides no standard means of enumerating, some of the common information about files, such as file creation date and time, is not always available or correct. When this happens, FtpFindFirstFile and InternetFindNextFile fill in unavailable information with a best guess based on available information. For example, creation and last access dates will often be the same as the file's modification date.

The application cannot call FtpFindFirstFile between calls to FtpOpenFile and InternetCloseHandle.

See also InternetSetStatusCallback


FtpGetCurrentDirectory

BOOL FtpGetCurrentDirectory(
    IN HINTERNET hFtpSession,
    OUT LPSTR lpszCurrentDirectory,
    IN OUT LPDWORD lpdwCurrentDirectory
);

Retrieves the current directory for the specified FTP session.

  • Returns TRUE if successful, or FALSE otherwise. To get the specific error message, call GetLastError.
hFtpSession
Valid handle to an FTP session.
lpszCurrentDirectory
Address of a buffer that receives the current directory string, which specifies the absolute path to the current directory. The string is null terminated.
lpdwCurrentDirectory
Address of a variable that specifies the length, in characters, of the buffer for the current directory string. The buffer length must include room for a terminating null character. Using a length of MAX_PATH is sufficient for all paths. When the function returns, the variable receives the number of characters copied into the buffer.

If the lpszCurrentDirectory buffer is not large enough, lpdwCurrentDirectory receives the number of bytes required to retrieve the full, current directory name.


FtpGetFile

BOOL FtpGetFile(
    IN HINTERNET hFtpSession,
    IN LPCSTR lpszRemoteFile,
    IN LPCSTR lpszNewFile,
    IN BOOL fFailIfExists,
    IN DWORD dwLocalFlagsAndAttributes,
    IN DWORD dwInternetFlags,
    IN DWORD dwContext
);

Retrieves a file from the FTP server and stores it under the specified file name, creating a new local file in the process.

  • Returns TRUE if successful, or FALSE otherwise. To get a specific error message, call GetLastError.
hFtpSession
Valid handle to an FTP session.
lpszRemoteFile
Address of a null-terminated string that contains the name of the file to retrieve from the remote system.
lpszNewFile
Address of a null-terminated string that contains the name of the file to create on the local system.
fFailIfExists
Boolean flag that indicates whether the function should proceed if a local file of the specified name already exists. If fFailIfExists is TRUE and the local file exists, FtpGetFile fails.
dwLocalFlagsAndAttributes
File attributes for the new file. Can be any combination of the FILE_ATTRIBUTE_* flags used by the CreateFile function. For more information on FILE_ATTRIBUTE_* attributes, see CreateFile in the Platform SDK.
dwInternetFlags
Flags that control how the function will handle the file download. The first set of flag values indicates the conditions under which the transfer occurs. These transfer type flags can be used in combination with the second set of flags that control caching. The application can select one of these transfer type values:
FTP_TRANSFER_TYPE_ASCII
Transfers the file using FTP's ASCII (Type A) transfer method. Control and formatting information is converted to local equivalents.
FTP_TRANSFER_TYPE_BINARY
Transfers the file using FTP's Image (Type I) transfer method. The file is transferred exactly as it exists with no changes. This is the default transfer method.
FTP_TRANSFER_TYPE_UNKNOWN
Defaults to FTP_TRANSFER_TYPE_BINARY.
INTERNET_FLAG_TRANSFER_ASCII
Transfers the file as ASCII.
INTERNET_FLAG_TRANSFER_BINARY
Transfers the file as binary.
The following flags determine how the caching of this file will be done. Any combination of the following flags can be used with the transfer type flag. The possible values are:
INTERNET_FLAG_DONT_CACHE
Does not add the returned entity to the cache. Identical to the preferred value, INTERNET_FLAG_NO_CACHE_WRITE.
INTERNET_FLAG_HYPERLINK
Forces a reload if there was no Expires time and no Last-Modified time returned from the server when determining whether to reload the item from the network.
INTERNET_FLAG_MAKE_PERSISTENT
No longer supported.
INTERNET_FLAG_MUST_CACHE_REQUEST
Causes a temporary file to be created if the file cannot be cached. Identical to the preferred value, INTERNET_FLAG_NEED_FILE.
INTERNET_FLAG_NEED_FILE
Causes a temporary file to be created if the file cannot be cached.
INTERNET_FLAG_NO_CACHE_WRITE
Does not add the returned entity to the cache.
INTERNET_FLAG_RELOAD
Forces a download of the requested file, object, or directory listing from the origin server, not from the cache.
INTERNET_FLAG_RESYNCHRONIZE
Causes the FTP resource to be reloaded from the server.
dwContext
Application-defined value that associates this search with any application data. This is used only if the application has already called InternetSetStatusCallback to set up a status callback function.

FtpGetFile is a high-level routine that handles all the bookkeeping and overhead associated with reading a file from an FTP server and storing it locally. An application that needs to retrieve file data only or that requires close control over the file transfer should use the FtpOpenFile and InternetReadFile functions.

If the dwTransferType parameter specifies FILE_TRANSFER_TYPE_ASCII, translation of the file data converts control and formatting characters to local equivalents. The default transfer is binary mode, where the file is downloaded in the same format as it is stored on the server.

Both lpszRemoteFile and lpszNewFile can be either partially or fully qualified file names relative to the current directory. A backslash (\) or forward slash (/) can be used as the directory separator for either name. FtpGetFile translates the directory name separators to the appropriate character before they are used.


FtpOpenFile

HINTERNET FtpOpenFile(
    IN HINTERNET hFtpSession,
    IN LPCSTR lpszFileName,
    IN DWORD fdwAccess,
    IN DWORD dwFlags,
    IN DWORD dwContext
);

Initiates access to a remote file for writing or reading.

  • Returns a handle if successful, or NULL otherwise. To get a specific error message, call GetLastError.
hFtpSession
Valid handle to an FTP session.
lpszFileName
Address of a null-terminated string that contains the name of the file to access on the remote system.
fdwAccess
Value that determines how the file will be accessed. This can be GENERIC_READ or GENERIC_WRITE, but not both.
dwFlags
Conditions under which the transfers occur. The application should select one transfer type and any of the flags that control how the caching of the file will be controlled. The transfer type can be any one of the following values:
FTP_TRANSFER_TYPE_ASCII
Transfers the file using FTP's ASCII (Type A) transfer method. Control and formatting information is converted to local equivalents.
FTP_TRANSFER_TYPE_BINARY
Transfers the file using FTP's Image (Type I) transfer method. The file is transferred exactly as it exists with no changes. This is the default transfer method.
FTP_TRANSFER_TYPE_UNKNOWN
Defaults to FTP_TRANSFER_TYPE_BINARY.
INTERNET_FLAG_TRANSFER_ASCII
Transfers the file as ASCII.
INTERNET_FLAG_TRANSFER_BINARY
Transfers the file as binary.

The following values are used to control the caching of the file. The application can use one or more of the following values:

INTERNET_FLAG_DONT_CACHE
Does not cache the data, either locally or in any gateways. Identical to the preferred value, INTERNET_FLAG_NO_CACHE_WRITE.
INTERNET_FLAG_HYPERLINK
Forces a reload if there was no Expires time and no Last-Modified time returned from the server when determining whether to reload the item from the network.
INTERNET_FLAG_MAKE_PERSISTENT
No longer supported.
INTERNET_FLAG_MUST_CACHE_REQUEST
Causes a temporary file to be created if the file cannot be cached. Identical to the preferred value, INTERNET_FLAG_NEED_FILE.
INTERNET_FLAG_NEED_FILE
Causes a temporary file to be created if the file cannot be cached.
INTERNET_FLAG_NO_CACHE_WRITE
Does not cache the data, either locally or in any gateways.
INTERNET_FLAG_RELOAD
Forces a download of the requested file, object, or directory listing from the origin server, not from the cache.
INTERNET_FLAG_RESYNCHRONIZE
Causes the FTP resource to be reloaded from the server.
dwContext
Application-defined value that associates this search with any application data. This is only used if the application has already called InternetSetStatusCallback to set up a status callback function.

FtpOpenFile should be used in the following situations:

  • An application has data it needs to send to an FTP server to be created as a file on the FTP server, but the application does not have a local file containing the data. After the file is opened with FtpOpenFile, the application uses InternetWriteFile to send the FTP file data to the server.
  • An application needs to retrieve a file from the server into application-controlled memory, instead of writing the file to disk. The application uses InternetReadFile after using FtpOpenFile to open the file.
  • An application needs a fine level of control over a file transfer. For example, the application may need to display a progress indicator when downloading a file to indicate to the user that the file transfer is or is not proceeding correctly.

After calling FtpOpenFile and until calling InternetCloseHandle, all other calls to FTP functions on the same FTP session handle will fail and set the error message to ERROR_FTP_TRANSFER_IN_PROGRESS.

Only one file can be open in a single FTP session. Therefore, no file handle is returned and the application simply uses the FTP session handle when necessary.

The lpszFile parameter can be either partially or fully qualified file names relative to the current directory. A backslash (\) or forward slash (/) can be used as the directory separator for either name. FtpOpenFile translates the directory name separators to the appropriate character before they are used.

The InternetCloseHandle function is used to close the handle returned from FtpOpenFile. If InternetCloseHandle closes the handle before all the data has been transferred, the transfer is terminated.


FtpPutFile

BOOL FtpPutFile(
    IN HINTERNET hFtpSession,
    IN LPCSTR lpszLocalFile,
    IN LPCSTR lpszNewRemoteFile,
    IN DWORD dwFlags,
    IN DWORD dwContext
);

Stores a file on the FTP server.

  • Returns TRUE if successful, or FALSE otherwise. To get a specific error message, call GetLastError.
hFtpSession
Valid handle to an FTP session.
lpszLocalFile
Address of a null-terminated string that contains the name of the file to send from the local system.
lpszNewRemoteFile
Address of a null-terminated string that contains the name of the file to create on the remote system.
dwFlags
Conditions under which the transfer occurs. Can be any combination of the following values:
INTERNET_FLAG_DONT_CACHE
Does not add the returned entity to the cache. Identical to the preferred value, INTERNET_FLAG_NO_CACHE_WRITE.
INTERNET_FLAG_HYPERLINK
Forces a reload if there was no Expires time and no Last-Modified time returned from the server when determining whether to reload the item from the network.
INTERNET_FLAG_MAKE_PERSISTENT
No longer supported.
INTERNET_FLAG_MUST_CACHE_REQUEST
Causes a temporary file to be created if the file cannot be cached. Identical to the preferred value, INTERNET_FLAG_NEED_FILE.
INTERNET_FLAG_NEED_FILE
Causes a temporary file to be created if the file cannot be cached.
INTERNET_FLAG_NO_CACHE_WRITE
Does not add the returned entity to the cache.
INTERNET_FLAG_RELOAD
Forces a download of the requested file, object, or directory listing from the origin server, not from the cache.
INTERNET_FLAG_RESYNCHRONIZE
Performs a conditional download of the file.
INTERNET_FLAG_TRANSFER_ASCII
Transfers the file as ASCII.
INTERNET_FLAG_TRANSFER_BINARY
Transfers the file as binary.
dwContext
Application-defined value that associates this search with any application data. This parameter is used only if the application has already called InternetSetStatusCallback to set up a status callback.

FtpPutFile is a high-level routine that handles all the bookkeeping and overhead associated with reading a file locally and storing it on an FTP server. An application that needs to send file data only, or that requires close control over the file transfer, should use the FtpOpenFile and InternetWriteFile functions.

If the dwTransferType parameter specifies FILE_TRANSFER_TYPE_ASCII, translation of the file data converts control and formatting characters to local equivalents.

Both lpszNewRemoteFile and lpszLocalFile can be either partially or fully qualified file names relative to the current directory. A backslash (\) or forward slash (/) can be used as the directory separator for either name. FtpPutFile translates the directory name separators to the appropriate character before they are used.


FtpRemoveDirectory

BOOL FtpRemoveDirectory(
    IN HINTERNET hFtpSession,
    IN LPCSTR lpszDirectory
);

Removes the specified directory on the FTP server.

  • Returns TRUE if successful, or FALSE otherwise. To get the specific error message, call GetLastError. If the error message indicates that the FTP server denied the request to remove a directory, use InternetGetLastResponseInfo to determine why.
hFtpSession
Valid handle to an FTP session.
lpszDirectory
Address of a null-terminated string that contains the name of the directory to remove on the remote system. This can be either a fully qualified path or a name relative to the current directory.

An application should use FtpGetCurrentDirectory to determine the remote site's current working directory, instead of assuming that the remote system uses a hierarchical naming scheme for directories.

The lpszDirectory parameter can be either partially or fully qualified file names relative to the current directory. A backslash (\) or forward slash (/) can be used as the directory separator for either name. FtpRemoveDirectory translates the directory name separators to the appropriate character before they are used.


FtpRenameFile

BOOL FtpRenameFile(
    IN HINTERNET hFtpSession,
    IN LPCSTR lpszExisting,
    IN LPCSTR lpszNew
);

Renames a file stored on the FTP server.

  • Returns TRUE if successful, or FALSE otherwise. To get a specific error message, call GetLastError.
hFtpSession
Valid handle to an FTP session.
lpszExisting
Address of a null-terminated string that contains the name of the file that will have its name changed on the remote FTP server.
lpszNew
Address of a null-terminated string that contains the new name for the remote file.

The lpszExisting and lpszNew parameters can be either partially or fully qualified file names relative to the current directory. A backslash (\) or forward slash (/) can be used as the directory separator for either name. FtpRenameFile translates the directory name separators to the appropriate character before they are used.


FtpSetCurrentDirectory

BOOL FtpSetCurrentDirectory(
    IN HINTERNET hFtpSession,
    IN LPCSTR lpszDirectory
);

Changes to a different working directory on the FTP server.

  • Returns TRUE if successful, or FALSE otherwise. To get the specific error message, call GetLastError. If the error message indicates that the FTP server denied the request to change a directory, use InternetGetLastResponseInfo to determine why.
hFtpSession
Valid handle to an FTP session.
lpszDirectory
Address of a null-terminated string that contains the name of the directory to change to on the remote system. This can be either a fully qualified path or a name relative to the current directory.

An application should use FtpGetCurrentDirectory to determine the remote site's current working directory, instead of assuming that the remote system uses a hierarchical naming scheme for directories.

The lpszDirectory parameter can be either partially or fully qualified file names relative to the current directory. A backslash (\) or forward slash (/) can be used as the directory separator for either name. FtpSetCurrentDirectory translates the directory name separators to the appropriate character before they are used.


General Win32 Internet Functions

The general Win32 Internet functions described in this section perform basic Internet file manipulations.
InternetAttemptConnect
InternetCheckConnection
InternetCloseHandle
InternetConfirmZoneCrossing
InternetConnect
InternetErrorDlg
InternetFindNextFile
InternetGetLastResponseInfo
InternetLockRequestFile
InternetOpen
InternetQueryDataAvailable
InternetQueryOption
InternetReadFile
InternetReadFileEx
InternetSetFilePointer
InternetSetOption
InternetSetOptionEx
InternetSetStatusCallback
InternetTimeFromSystemTime
InternetTimeToSystemTime
InternetUnlockRequestFile
InternetWriteFile


GetUrlCacheEntryInfo

BOOL GetUrlCacheEntryInfo(
    IN LPCSTR lpszUrlName,
    IN LPINTERNET_CACHE_ENTRY_INFO lpCacheEntryInfo,
    IN OUT LPDWORD lpdwCacheEntryInfoBufferSize
);

Retrieves information about a cache entry.

  • Returns TRUE if successful, or FALSE otherwise. To get extended error information, call GetLastError. Possible error values include:
    ERROR_FILE_NOT_FOUND | The specified cache entry is not found in the cache.
    ERROR_INSUFFICIENT_BUFFER | The size of lpCacheEntryInfo as specified by lpdwCacheEntryInfoBufferSize is not sufficient to contain all the information. The value returned in lpdwCacheEntryInfoBufferSize indicates the buffer size necessary to contain all the information.
lpszUrlName
Address of a string that contains the name of the cache entry. The name string should not contain any escape characters.
lpCacheEntryInfo
Address of an INTERNET_CACHE_ENTRY_INFO structure that receives information about the cache entry.
lpdwCacheEntryInfoBufferSize
Address of a variable that specifies the size of the lpCacheEntryInfo buffer. When the function returns, the variable contains the number of bytes copied to the buffer, or the required size of the buffer.

GetUrlCacheEntryInfo does not do any URL parsing, so a URL containing an anchor (#) will not be found in the cache, even if the resource is cached. For example, if the URL http://example.com/example.htm#sample was passed, the function would return ERROR_FILE_NOT_FOUND even if http://example.com/example.htm is in the cache.


GetUrlCacheEntryInfoEx

BOOL GetUrlCacheEntryInfoEx(
    IN LPCSTR lpszUrl,
    OUT LPINTERNET_CACHE_ENTRY_INFO lpCacheEntryInfo,
    IN OUT LPDWORD lpdwCacheEntryInfoBufSize,
    OUT LPSTR lpszReserved,
    IN OUT LPDWORD lpdwReserved,
    LPVOID lpReserved,
    DWORD dwFlags
);

Searches for the URL after translating any cached redirections that would be applied in offline mode by HttpSendRequest.

  • Returns TRUE if the URL was located, or FALSE otherwise. Call GetLastError for specific error information. Possible errors include:
    ERROR_FILE_NOT_FOUND | The URL, after taking any cached redirections into account, was not found in the cache index.
    ERROR_INSUFFICIENT_BUFFER | One or more of the buffers (lpCacheEntryInfo and lpszRedirectUrl) supplied was not large enough to hold the requested information. The size of the buffer needed will be returned to lpdwCacheEntryInfoBufSize and lpdwRedirectUrlSize.
lpszUrl
Address of a string that contains the name of the cache entry. The name string should not contain any escape characters.
lpCacheEntryInfo
Address of an INTERNET_CACHE_ENTRY_INFO structure that receives information about the cache entry.
lpdwCacheEntryInfoBufSize
Address of a variable that specifies the size of the lpCacheEntryInfo buffer. When the function returns, the variable contains the number of bytes copied to the buffer, or the required size of the buffer.
lpszReserved
Reserved. Must be set to NULL.
lpdwReserved
Reserved. Must be set to NULL.
lpReserved
Reserved. Must be set to NULL.
dwFlags
Reserved. Must be set to zero.


Gopher Functions

The Gopher functions described in this section control the creation and use of the Internet Gopher utilities.
GopherAttributeEnumerator
GopherCreateLocator
GopherFindFirstFile
GopherGetAttribute
GopherGetLocatorType
GopherOpenFile


GopherAttributeEnumerator

BOOL GopherAttributeEnumerator(
    LPGOPHER_ATTRIBUTE_TYPE lpAttributeInformation,
    DWORD dwError
);

Defines a callback function that processes attribute information from a Gopher server. This callback function is installed by a call to the GopherGetAttribute function.

  • Returns TRUE to continue the enumeration, or FALSE to immediately stop it. This function is primarily used for returning the results of a Gopher+ ASK item.
lpAttributeInformation
Address of a buffer that contains a single GOPHER_ATTRIBUTE_TYPE structure. The lpBuffer parameter to GopherGetAttribute is used for storing this structure. The lpBuffer size must be equal to or greater than the value of MIN_GOPHER_ATTRIBUTE_LENGTH.
dwError
Error value. This parameter is NO_ERROR if the attribute was parsed and written to the buffer successfully. If a problem was encountered, an error value is returned.


GopherCreateLocator

BOOL GopherCreateLocator(
    IN LPCSTR lpszHost,
    IN INTERNET_PORT nServerPort,
    IN LPCSTR lpszDisplayString,
    IN LPCSTR lpszSelectorString,
    IN DWORD dwGopherType,
    OUT LPCSTR lpszLocator,
    IN OUT LPDWORD lpdwBufferLength
);

Creates a Gopher or Gopher+ locator string from its component parts.

  • Returns TRUE if successful, or FALSE otherwise. To get extended error information, call GetLastError or InternetGetLastResponseInfo.
lpszHost
Address of a string that contains the name of the host, or a dotted-decimal IP address (such as 198.105.232.1).
nServerPort
Number of the port on which the Gopher server at lpszHost lives, in host byte order. If nServerPort is INTERNET_INVALID_PORT_NUMBER, the default Gopher port is read from the \etc\services file.
lpszDisplayString
Gopher document or directory to be displayed. If this parameter is NULL, the function returns the default directory for the Gopher server.
lpszSelectorString
Address of the selector string to send to the Gopher server in order to retrieve information. This parameter can be NULL.
dwGopherType
Value that specifies whether lpszSelectorString refers to a directory or document, and whether the request is Gopher+ or Gopher. The default value, GOPHER_TYPE_DIRECTORY, is used if the value of dwGopherType is zero. Can be one of the following values:
GOPHER_TYPE_ASK | Ask+ item.
GOPHER_TYPE_BINARY | Binary file.
GOPHER_TYPE_BITMAP | Bitmap file.
GOPHER_TYPE_CALENDAR | Calendar file.
GOPHER_TYPE_CSO | CSO telephone book server.
GOPHER_TYPE_DIRECTORY | Directory of additional Gopher items.
GOPHER_TYPE_DOS_ARCHIVE | MS-DOS® archive file.
GOPHER_TYPE_ERROR | Indicator of an error condition.
GOPHER_TYPE_GIF | GIF graphics file.
GOPHER_TYPE_GOPHER_PLUS | Gopher+ item.
GOPHER_TYPE_HTML | HTML document.
GOPHER_TYPE_IMAGE | Image file.
GOPHER_TYPE_INDEX_SERVER | Index server.
GOPHER_TYPE_INLINE | Inline file.
GOPHER_TYPE_MAC_BINHEX | Macintosh file in BINHEX format.
GOPHER_TYPE_MOVIE | Movie file.
GOPHER_TYPE_PDF | PDF file.
GOPHER_TYPE_REDUNDANT | Indicator of a duplicated server. The information contained within is a duplicate of the primary server. The primary server is defined as the last directory entry that did not have a GOPHER_TYPE_REDUNDANT type.
GOPHER_TYPE_SOUND | Sound file.
GOPHER_TYPE_TELNET | Telnet server.
GOPHER_TYPE_TEXT_FILE | ASCII text file.
GOPHER_TYPE_TN3270 | TN3270 server.
GOPHER_TYPE_UNIX_UUENCODED | UUENCODED file.
GOPHER_TYPE_UNKNOWN | Item type is unknown.
lpszLocator
Address of a buffer that receives the locator string. If lpszLocator is NULL, lpdwBufferLength receives the needed buffer length, but the function performs no other processing.
lpdwBufferLength
Length of the lpszLocator buffer. When the function returns, this parameter receives the number of bytes written to the lpszLocator buffer. If GetLastError returns ERROR_INSUFFICIENT_BUFFER, this parameter receives the number of bytes required to form the locator successfully.

To retrieve information from a Gopher server, an application must first get a Gopher "locator" from the Gopher server.

The locator, which the application should treat as an opaque token, is normally used for calls to the GopherFindFirstFile function to retrieve a specific piece of information.


GopherFindFirstFile

HINTERNET GopherFindFirstFile(
    IN HINTERNET hGopherSession,
    IN LPCSTR lpszLocator,
    IN LPCSTR lpszSearchString,
    OUT LPGOPHER_FIND_DATA lpFindData,
    IN DWORD dwFlags,
    IN DWORD dwContext
);

Uses a Gopher locator and some search criteria to create a session with the server and locate the requested documents, binary files, index servers, or directory trees.

  • Returns a valid search handle if successful, or NULL otherwise. To get extended error information, call GetLastError or InternetGetLastResponseInfo.
hGopherSession
Handle to a Gopher session returned by InternetConnect.
lpszLocator
Name of the item to locate. Can be one of the following items:
  • Gopher locator returned by a previous call to this function or the InternetFindNextFile function.
  • NULL pointer or zero-length string indicating that the topmost information from a Gopher server is being returned.
  • Locator created by the GopherCreateLocator function.
lpszSearchString
Address of a buffer that contains the strings to search, if this request is to an index server. Otherwise, this parameter should be NULL.
lpFindData
Address of a GOPHER_FIND_DATA structure that receives the information retrieved by this function.
dwFlags
Action flag that can be a combination of the following values:
INTERNET_FLAG_DONT_CACHE
Does not add the returned entity to the cache. Identical to the preferred value, INTERNET_FLAG_NO_CACHE_WRITE.
INTERNET_FLAG_HYPERLINK
Forces a reload if there was no Expires time and no Last-Modified time returned from the server when determining whether to reload the item from the network.
INTERNET_FLAG_MAKE_PERSISTENT
No longer supported.
INTERNET_FLAG_MUST_CACHE_REQUEST
Causes a temporary file to be created if the file cannot be cached. Identical to the preferred value, INTERNET_FLAG_NEED_FILE.
INTERNET_FLAG_NEED_FILE
Causes a temporary file to be created if the file cannot be cached.
INTERNET_FLAG_NO_CACHE_WRITE
Does not add the returned entity to the cache.
INTERNET_FLAG_RELOAD
Forces a download of the requested file, object, or directory listing from the origin server, not from the cache.
INTERNET_FLAG_RESYNCHRONIZE
Reloads the FTP resource.
dwContext
Application-defined value that associates this search with any application data.

GopherFindFirstFile closely resembles the Win32 FindFirstFile function. It creates a connection with a Gopher server, and then returns a single structure containing information about the first Gopher object referenced by the locator string.

After calling GopherFindFirstFile to retrieve the first Gopher object in an enumeration, an application can use the InternetFindNextFile function to retrieve subsequent Gopher objects.

Use the InternetCloseHandle function to close the handle returned from GopherFindFirstFile. If there are any pending operations described by the handle when the application calls InternetCloseHandle, they are canceled or marked as closed pending. Any open sessions are terminated, and any data waiting for the caller is discarded. In addition, any allocated buffers are freed.


GopherGetAttribute

BOOL GopherGetAttribute(
    IN HINTERNET hGopherSession,
    IN LPCSTR lpszLocator,
    IN LPCSTR lpszAttributeName,
    OUT LPBYTE lpBuffer,
    IN DWORD dwBufferLength,
    OUT LPDWORD lpdwCharactersReturned,
    IN GOPHER_ATTRIBUTE_ENUMERATOR lpfnEnumerator,
    IN DWORD dwContext
);

Allows an application to retrieve specific attribute information from the server.

  • Returns TRUE if the request is satisfied, or FALSE otherwise. To get extended error information, call GetLastError or InternetGetLastResponseInfo.
hGopherSession
Handle to a Gopher session returned by InternetConnect.
lpszLocator
Address of a string that identifies the item at the Gopher server on which to return attribute information.
lpszAttributeName
Address of a space-delimited string specifying the names of attributes to return. If lpszAttributeName is NULL, GopherGetAttribute returns information about all attributes.
lpBuffer
Address of an application-defined buffer from which attribute information is retrieved.
dwBufferLength
Size, in bytes, of the lpBuffer buffer.
lpdwCharactersReturned
Number of characters read into the lpBuffer buffer.
lpfnEnumerator
Address of a callback function that enumerates each attribute of the locator. This parameter is optional. If it is NULL, all the Gopher attribute information is placed into lpBuffer. If lpfnEnumerator is specified, the callback function is called once for each attribute of the object.
The callback function receives the address of a single GOPHER_ATTRIBUTE_TYPE structure with each call. The enumeration callback function allows the application to avoid having to parse the Gopher attribute information.
dwContext
Application-defined value that associates this operation with any application data.

Generally, applications call this function after calling GopherFindFirstFile or InternetFindNextFile.

The size of the lpBuffer parameter must be equal to or greater than the value of MIN_GOPHER_ATTRIBUTE_LENGTH (currently defined in Wininet.h as 256 bytes).


GopherGetLocatorType

BOOL GopherGetLocatorType(
    IN LPCSTR lpszLocator,
    OUT LPDWORD lpdwGopherType
);

Parses a Gopher locator and determines its attributes.

  • Returns TRUE if successful, or FALSE otherwise. To get extended error information, call GetLastError.
lpszLocator
Address of the Gopher locator string to parse.
lpdwGopherType
Address of a variable that receives the type of the locator. The type is a bitmask that consists of a combination of the following values:
GOPHER_TYPE_ASK | Ask+ item.
GOPHER_TYPE_BINARY | Binary file.
GOPHER_TYPE_BITMAP | Bitmap file.
GOPHER_TYPE_CALENDAR | Calendar file.
GOPHER_TYPE_CSO | CSO telephone book server.
GOPHER_TYPE_DIRECTORY | Directory of additional Gopher items.
GOPHER_TYPE_DOS_ARCHIVE | MS-DOS archive file.
GOPHER_TYPE_ERROR | Indicator of an error condition.
GOPHER_TYPE_GIF | GIF graphics file.
GOPHER_TYPE_GOPHER_PLUS | Gopher+ item.
GOPHER_TYPE_HTML | HTML document.
GOPHER_TYPE_IMAGE | Image file.
GOPHER_TYPE_INDEX_SERVER | Index server.
GOPHER_TYPE_INLINE | Inline file.
GOPHER_TYPE_MAC_BINHEX | Macintosh file in BINHEX format.
GOPHER_TYPE_MOVIE | Movie file.
GOPHER_TYPE_PDF | PDF file.
GOPHER_TYPE_REDUNDANT | Indicator of a duplicated server. The information contained within is a duplicate of the primary server. The primary server is defined as the last directory entry that did not have a GOPHER_TYPE_REDUNDANT type.
GOPHER_TYPE_SOUND | Sound file.
GOPHER_TYPE_TELNET | Telnet server.
GOPHER_TYPE_TEXT_FILE | ASCII text file.
GOPHER_TYPE_TN3270 | TN3270 server.
GOPHER_TYPE_UNIX_UUENCODED | UUENCODED file.
GOPHER_TYPE_UNKNOWN | Item type is unknown.

GopherGetLocatorType returns information about the item referenced by a Gopher locator. Note that it is possible for multiple attributes to be set on a file. For example, both GOPHER_TYPE_TEXT_FILE and GOPHER_TYPE_GOPHER_PLUS are set for a text file stored on a Gopher+ server.


GopherOpenFile

HINTERNET GopherOpenFile(
    IN HINTERNET hGopherSession,
    IN LPCSTR lpszLocator,
    IN LPCSTR lpszView,
    IN DWORD dwFlags,
    IN DWORD dwContext
);

Begins reading a Gopher data file from a Gopher server.

  • Returns a handle if successful, or NULL if the file cannot be opened. To get extended error information, call GetLastError or InternetGetLastResponseInfo.
hGopherSession
Handle to a Gopher session returned by InternetConnect.
lpszLocator
Address of a string that identifies the file to open. Generally, this locator is returned from a call to GopherFindFirstFile or InternetFindNextFile. Because the Gopher protocol has no concept of a current directory, the locator is always fully qualified.
lpszView
Address of a string that describes the view to open if several views of the file exist at the server. If lpszView is NULL, the function uses the default file view.
dwFlags
Conditions under which subsequent transfers occur. Can be any combination of the following values:
INTERNET_FLAG_DONT_CACHE
Does not add the returned entity to the cache. Identical to the preferred value, INTERNET_FLAG_NO_CACHE_WRITE.
INTERNET_FLAG_HYPERLINK
Forces a reload if there was no Expires time and no Last-Modified time returned from the server when determining whether to reload the item from the network.
INTERNET_FLAG_MAKE_PERSISTENT
No longer supported.
INTERNET_FLAG_MUST_CACHE_REQUEST
Causes a temporary file to be created if the file cannot be cached. Identical to the preferred value, INTERNET_FLAG_NEED_FILE.
INTERNET_FLAG_NEED_FILE
Causes a temporary file to be created if the file cannot be cached.
INTERNET_FLAG_NO_CACHE_WRITE
Does not add the returned entity to the cache.
INTERNET_FLAG_RELOAD
Forces a download of the requested file, object, or directory listing from the origin server, not from the cache.
INTERNET_FLAG_RESYNCHRONIZE
Causes the Gopher resource to be reloaded from the server.
dwContext
Application-defined value that associates this operation with any application data.

GopherOpenFile opens a file at a Gopher server. Because a file cannot actually be opened or locked at a server, this function simply associates location information with a handle that an application can use for file-based operations such as InternetReadFile or GopherGetAttribute.

Use the InternetCloseHandle function to close the handle returned from GopherOpenFile. If there are any pending operations described by the handle when the application calls InternetCloseHandle, they are canceled or marked as closed pending. Any open sessions are terminated, and any data waiting for the caller is discarded. In addition, any allocated buffers are freed.

See also InternetOpenUrl


HTTP Functions

The HTTP functions described in this section control the transmission and content of HTTP requests.
HttpAddRequestHeaders
HttpEndRequest
HttpOpenRequest
HttpQueryInfo
HttpSendRequest
HttpSendRequestEx


HttpAddRequestHeaders

BOOL HttpAddRequestHeaders(
    IN HINTERNET hHttpRequest,
    IN LPCSTR lpszHeaders,
    IN DWORD dwHeadersLength,
    IN DWORD dwModifiers
);

Adds one or more HTTP request headers to the HTTP request handle.

  • Returns TRUE if successful, or FALSE otherwise. To get extended error information, call GetLastError.
hHttpRequest
Open HTTP request handle returned by HttpOpenRequest.
lpszHeaders
Headers to append to the request. Each header must be terminated by a CR/LF (carriage return/line feed) pair.
dwHeadersLength
Length, in characters, of lpszHeaders. If this parameter is -1L, the function assumes that lpszHeaders is zero-terminated (ASCIIZ), and the length is computed.
dwModifiers
Values used to modify the semantics of this function. Can be a combination of the following values:
HTTP_ADDREQ_FLAG_ADD
Adds the header if it does not exist. Used with HTTP_ADDREQ_FLAG_REPLACE.
HTTP_ADDREQ_FLAG_ADD_IF_NEW
Adds the header only if it does not already exist; otherwise, an error is returned.
HTTP_ADDREQ_FLAG_COALESCE
Coalesces headers of the same name.
HTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA
Coalesces headers of the same name. For example, adding "Accept: text/*" followed by "Accept: audio/*" with this flag results in the formation of the single header "Accept: text/*, audio/*". This causes the first header found to be coalesced. It is up to the calling application to ensure a cohesive scheme with respect to coalesced/separate headers.
HTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON
Coalesces headers of the same name using a semicolon.
HTTP_ADDREQ_FLAG_REPLACE
Replaces or removes a header. If the header value is empty and the header is found, it is removed. If not empty, the header value is replaced.

HttpAddRequestHeaders appends additional, free-format headers to the HTTP request handle and is intended for use by sophisticated clients that need detailed control over the exact request sent to the HTTP server.

Note that for basic HttpAddRequestHeaders, the application can pass in multiple headers in a single buffer. If the application is trying to remove or replace a header, only one header can be supplied in lpszHeaders.

See also HttpSendRequest


HttpEndRequest

HttpEndRequest(
    IN HINTERNET hRequest,
    OUT LPINTERNET_BUFFERS lpBuffersOut,
    IN DWORD dwFlags,
    IN DWORD dwContext
    );

Ends an HTTP request.

  • Returns TRUE if successful, or FALSE otherwise. To get extended error information, call GetLastError.
hRequest
HINTERNET handle returned by HttpOpenRequest and sent by HttpSendRequestEx.
lpBuffersOut
Address of an INTERNET_BUFFERS structure.
dwFlags
Can be one of the following values:
HSR_ASYNC | Identical to WININET_API_FLAG_ASYNC.
HSR_SYNC | Identical to WININET_API_FLAG_SYNC.
HSR_USE_CONTEXT | Identical to WININET_API_FLAG_USE_CONTEXT.
HSR_INITIATE | Iterative operation (completed by HttpEndRequest).
HSR_DOWNLOAD | Download resource to file.
HSR_CHUNKED | Send chunked data.
dwContext
Double-word variable that contains the context value to use in asynchronous operations.


HttpOpenRequest

HINTERNET HttpOpenRequest(
    IN HINTERNET hHttpSession,
    IN LPCSTR lpszVerb,
    IN LPCSTR lpszObjectName,
    IN LPCSTR lpszVersion,
    IN LPCSTR lpszReferer,
    IN LPCSTR FAR * lpszAcceptTypes,
    IN DWORD dwFlags,
    IN DWORD dwContext
);

Opens an HTTP request handle.

  • Returns a valid (non-NULL) HTTP request handle if successful, or NULL otherwise. To get extended error information, call GetLastError.
hHttpSession
Handle to an HTTP session returned by InternetConnect.
lpszVerb
Address of a string that contains the verb to use in the request. If this parameter is NULL, the function uses "GET" as the verb.
lpszObjectName
Address of a string that contains the name of the target object of the specified verb. This is generally a file name, an executable module, or a search specifier.
lpszVersion
Address of a string that contains the HTTP version. If this parameter is NULL, the function uses "HTTP/1.0" as the version.
lpszReferer
Address of a string that specifies the address (URL) of the document from which the URL in the request (lpszObjectName) was obtained. If this parameter is NULL, no "referrer" is specified.
lpszAcceptTypes
Address of a null-terminated array of LPCSTR pointers indicating content types accepted by the client. If this parameter is NULL, no types are accepted by the client. Servers interpret a lack of accept types to indicate that the client accepts only documents of type "text/*" (that is, only text documents, and not pictures or other binary files).
dwFlags
Internet flag values. Can be any of the following values:
INTERNET_FLAG_CACHE_IF_NET_FAIL
Return the resource from the cache if the network request for the resource fails due to an ERROR_INTERNET_CONNECTION_RESET or ERROR_INTERNET_CANNOT_CONNECT.
INTERNET_FLAG_DONT_CACHE
Does not add the returned entity to the cache. Identical to the preferred value, INTERNET_FLAG_NO_CACHE_WRITE.
INTERNET_FLAG_HYPERLINK
Forces a reload if there was no Expires time and no Last-Modified time returned from the server when determining whether to reload the item from the network.
INTERNET_FLAG_IGNORE_CERT_CN_INVALID
Disables Win32 Internet function checking of SSL/PCT-based certificates that are returned from the server against the host name given in the request. Win32 Internet functions use a simple check against certificates by comparing for matching host names and simple wildcarding rules.
INTERNET_FLAG_IGNORE_CERT_DATE_INVALID
Disables Win32 Internet function checking of SSL/PCT-based certificates for proper validity dates.
INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP
Disables the ability of the Win32 Internet functions to detect this special type of redirect. When this flag is used, Win32 Internet functions transparently allow redirects from HTTPS to HTTP URLs.
INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS
Disables the ability of the Win32 Internet functions to detect this special type of redirect. When this flag is used, Win32 Internet functions transparently allow redirects from HTTP to HTTPS URLs.
INTERNET_FLAG_KEEP_CONNECTION
Uses keep-alive semantics, if available, for the connection. This flag is required for Microsoft Network (MSN), NT LAN Manager (NTLM), and other types of authentication.
INTERNET_FLAG_MAKE_PERSISTENT
No longer supported.
INTERNET_FLAG_MUST_CACHE_REQUEST
Causes a temporary file to be created if the file cannot be cached. Identical to the preferred value, INTERNET_FLAG_NEED_FILE.
INTERNET_FLAG_NEED_FILE
Causes a temporary file to be created if the file cannot be cached.
INTERNET_FLAG_NO_AUTH
Does not attempt authentication automatically.
INTERNET_FLAG_NO_AUTO_REDIRECT
Does not automatically handle redirection in HttpSendRequest.
INTERNET_FLAG_NO_CACHE_WRITE
Does not add the returned entity to the cache.
INTERNET_FLAG_NO_COOKIES
Does not automatically add cookie headers to requests, and does not automatically add returned cookies to the cookie database.
INTERNET_FLAG_NO_UI
Disables the cookie dialog box.
INTERNET_FLAG_PRAGMA_NOCACHE
Forces the request to be resolved by the origin server, even if a cached copy exists on the proxy.
INTERNET_FLAG_READ_PREFETCH
This flag is currently disabled.
INTERNET_FLAG_RELOAD
Forces a download of the requested file, object, or directory listing from the origin server, not from the cache.
INTERNET_FLAG_RESYNCHRONIZE
Reloads HTTP resources if the resource has been modified since the last time it was downloaded.
INTERNET_FLAG_SECURE
Uses SSL/PCT transaction semantics.
dwContext
Application-defined value that associates this operation with any application data.

HttpOpenRequest creates a new HTTP request handle and stores the specified parameters in that handle. An HTTP request handle holds a request to be sent to an HTTP server and contains all RFC822/MIME/HTTP headers to be sent as part of the request.

Use the InternetCloseHandle function to close the handle returned by HttpOpenRequest. InternetCloseHandle cancels all outstanding I/O on the handle.

The lpszReferer parameter to InternetOpen is used as the referrer for the HTTP request.

See also HttpAddRequestHeaders, HttpQueryInfo, InternetReadFile


HttpQueryInfo

BOOL HttpQueryInfo(
    IN HINTERNET hHttpRequest,
    IN DWORD dwInfoLevel,
    IN LPVOID lpvBuffer,
    IN LPDWORD lpdwBufferLength,
    IN OUT LPDWORD lpdwIndex,
);

Queries for information about an HTTP request.

  • Returns TRUE if successful, or FALSE otherwise. To get extended error information, call GetLastError.
hHttpRequest
Open HTTP request handle returned by HttpOpenRequest or InternetOpenUrl.
dwInfoLevel
Combination of the attribute to query and the flags that modify the request. The attributes can be any of the following values:
HTTP_QUERY_ACCEPT
Retrieves the acceptable media types for the response.
HTTP_QUERY_ACCEPT_CHARSET
Retrieves the acceptable character sets for the response.
HTTP_QUERY_ACCEPT_ENCODING
Retrieves the acceptable content-coding values for the response.
HTTP_QUERY_ACCEPT_LANGUAGE
Retrieves the acceptable natural languages for the response.
HTTP_QUERY_ACCEPT_RANGES
Retrieves the types of range requests that are accepted for a resource.
HTTP_QUERY_AGE
Retrieves the Age response-header field, which contains the sender's estimate of the amount of time since the response was generated at the origin server.
HTTP_QUERY_ALLOW
Receives the methods supported by the server.
HTTP_QUERY_AUTHORIZATION
Retrieves the authorization credentials used for a request.
HTTP_QUERY_CACHE_CONTROL
Retrieves the cache control directives.
HTTP_QUERY_CONNECTION
Retrieves any options that are specified for a particular connection and must not be communicated by proxies over further connections.
HTTP_QUERY_COOKIE
Retrieves any cookies associated with the request.
HTTP_QUERY_CONTENT_BASE
Retrieves the base URI for resolving relative URLs within the entity.
HTTP_QUERY_CONTENT_DESCRIPTION
Obsolete. Maintained for legacy application compatibility only.
HTTP_QUERY_CONTENT_DISPOSITION
Obsolete. Maintained for legacy application compatibility only.
HTTP_QUERY_CONTENT_ENCODING
Receives any additional content codings that have been applied to the entire resource.
HTTP_QUERY_CONTENT_ID
Receives the content identification.
HTTP_QUERY_CONTENT_LANGUAGE
Receives the language that the content is in.
HTTP_QUERY_CONTENT_LENGTH
Receives the size of the resource, in bytes.
HTTP_QUERY_CONTENT_LOCATION
Retrieves the resource location for the entity enclosed in the message.
HTTP_QUERY_CONTENT_MD5
Retrieves a MD5 digest of the entity-body for the purpose of providing an end-to-end message integrity check (MIC) for the entity-body. For more information, see RFC1864, The Content-MD5 Header Field, at http://ds.internic.net/rfc/rfc1864.txt External Link for more information.
HTTP_QUERY_CONTENT_RANGE
Retrieves the location in the full entity-body where the partial entity-body should be inserted and the total size of the full entity-body.
HTTP_QUERY_CONTENT_TRANSFER_ENCODING
Receives the additional content coding that has been applied to the resource.
HTTP_QUERY_CONTENT_TYPE
Receives the content type of the resource (such as text/html).
HTTP_QUERY_COST
No longer implemented.
HTTP_QUERY_DATE
Receives the date and time at which the message was originated.
HTTP_QUERY_DERIVED_FROM
No longer supported.
HTTP_QUERY_ETAG
Retrieves the entity tag for the associated entity.
HTTP_QUERY_EXPIRES
Receives the date and time after which the resource should be considered outdated.
HTTP_QUERY_FORWARDED
Obsolete. Maintained for legacy application compatibility only.
HTTP_QUERY_FROM
Retrieves the e-mail address for the human user who controls the requesting user agent if the From header is given.
HTTP_QUERY_HOST
Retrieves the Internet host and port number of the resource being requested.
HTTP_QUERY_IF_MATCH
Retrieves the contents of the If-Match request-header field.
HTTP_QUERY_IF_MODIFIED_SINCE
Retrieves the contents of the If-Modified-Since header.
HTTP_QUERY_IF_NONE_MATCH
Retrieves the contents of the If-None-Match request-header field.
HTTP_QUERY_IF_RANGE
Retrieves the contents of the If-Range request-header field. This header allows the client application to check if the entity related to a partial copy of the entity in the client application's cache has not been updated. If the entity has not been updated, send the parts that the client application is missing. If the entity has been updated, send the entire updated entity.
HTTP_QUERY_IF_UNMODIFIED_SINCE
Retrieves the contents of the If-Unmodified-Since request-header field.
HTTP_QUERY_LINK
Obsolete. Maintained for legacy application compatibility only.
HTTP_QUERY_LAST_MODIFIED
Receives the date and time at which the server believes the resource was last modified.
HTTP_QUERY_LOCATION
Retrieves the absolute URI used in a Location response-header.
HTTP_QUERY_MAX
Retrieves the maximum value of an HTTP_QUERY_* value.
HTTP_QUERY_MAX_FORWARDS
Retrieves the number of proxies or gateways that can forward the request to the next inbound server.
HTTP_QUERY_MESSAGE_ID
No longer implemented.
HTTP_QUERY_MIME_VERSION
Receives the version of the MIME protocol that was used to construct the message.
HTTP_QUERY_ORIG_URI
Obsolete. Maintained for legacy application compatibility only.
HTTP_QUERY_PRAGMA
Receives the implementation-specific directives that may apply to any recipient along the request/response chain.
HTTP_QUERY_PROXY_AUTHENTICATE
Retrieves the authentication scheme and realm returned by the proxy.
HTTP_QUERY_PROXY_AUTHORIZATION
Retrieves the header that is used to identify the user to a proxy that requires authentication.
HTTP_QUERY_PUBLIC
Receives methods available at this server.
HTTP_QUERY_RANGE
Retrieves the byte range of an entity.
HTTP_QUERY_RAW_HEADERS
Receives all the headers returned by the server. Each header is terminated by "\0". An additional "\0" terminates the list of headers.
HTTP_QUERY_RAW_HEADERS_CRLF
Receives all the headers returned by the server. Each header is separated by a carriage return/line feed (CR/LF) sequence.
HTTP_QUERY_REFERER
Receives the URI of the resource where the requested URI was obtained.
HTTP_QUERY_REFRESH
Obsolete. Maintained for legacy application compatibility only.
HTTP_QUERY_REQUEST_METHOD
Receives the verb that is being used in the request, typically GET or POST.
HTTP_QUERY_RETRY_AFTER
Retrieves the amount of time the service is expected to be unavailable.
HTTP_QUERY_SERVER
Retrieves information about the software used by the origin server to handle the request.
HTTP_QUERY_SET_COOKIE
Receives the value of the cookie set for the request.
HTTP_QUERY_STATUS_CODE
Receives the status code returned by the server. For a list of possible values, see HTTP Status Codes.
HTTP_QUERY_STATUS_TEXT
Receives any additional text returned by the server on the response line.
HTTP_QUERY_TITLE
Obsolete. Maintained for legacy application compatibility only.
HTTP_QUERY_TRANSFER_ENCODING
Retrieves the type of transformation that has been applied to the message body so it can be safely transferred between the sender and recipient.
HTTP_QUERY_UPGRADE
Retrieves the additional communication protocols that are supported by the server.
HTTP_QUERY_URI
Receives some or all of the Uniform Resource Identifiers (URIs) by which the Request-URI resource can be identified.
HTTP_QUERY_USER_AGENT
Retrieves information about the user agent that made the request.
HTTP_QUERY_VARY
Retrieves the header that indicates that the entity was selected from a number of available representations of the response using server-driven negotiation.
HTTP_QUERY_VERSION
Receives the last response code returned by the server.
HTTP_QUERY_VIA
Retrieves the intermediate protocols and recipients between the user agent and the server on requests, and between the origin server and the client on responses.
HTTP_QUERY_WARNING
Retrieves additional information about the status of a response that may not be reflected by the response status code.
HTTP_QUERY_WWW_AUTHENTICATE
Retrieves the authentication scheme and realm returned by the server.

The following modifiers can be used with the information values:

HTTP_QUERY_CUSTOM
Causes HttpQueryInfo to search for the header name specified in lpvBuffer and store the header information in lpvBuffer.
HTTP_QUERY_FLAG_COALESCE
Combines the values from headers with the same name into the output buffer.
HTTP_QUERY_FLAG_NUMBER
Returns the data as a 32-bit number for headers whose value is a number, such as the status code.
HTTP_QUERY_FLAG_REQUEST_HEADERS
Queries request headers only.
HTTP_QUERY_FLAG_SYSTEMTIME
Returns the header value as a standard Win32 SYSTEMTIME structure, which does not require the application to parse the data. Use for headers whose value is a date/time string, such as "Last-Modified-Time".
lpvBuffer
Address of the buffer that receives the information.
lpdwBufferLength
Address of a value that contains the length of the data buffer. When the function returns, this parameter contains the address of a value specifying the length of the information written to the buffer. When the function returns strings, the following rules apply:
  • If the function succeeds, lpdwBufferLength specifies the length of the string, in characters, minus 1 for the terminating null.
  • If the function fails and ERROR_INSUFFICIENT_BUFFER is returned, lpdwBufferLength specifies the number of bytes that the application must allocate to receive the string.
lpdwIndex
Address of a zero-based header index used to enumerate multiple headers with the same name. When calling the function, this parameter is the index of the specified header to return. When the function returns, this parameter is the index of the next header. If the next index cannot be found, ERROR_HTTP_HEADER_NOT_FOUND is returned.

HttpQueryInfo is used to return response or request headers from an HTTP request.

You can retrieve different types of data from HttpQueryInfo:

  • strings (default)
  • SYSTEMTIME (for Data: Expires:, headers)
  • DWORD (for STATUS_CODE, CONTENT_LENGTH, and so on if HTTP_QUERY_INFO_NUMBER has been used)

See also HttpOpenRequest


HttpSendRequest

BOOL HttpSendRequest(
    IN HINTERNET hHttpRequest,
    IN LPCSTR lpszHeaders,
    IN DWORD dwHeadersLength,
    IN LPVOID lpOptional,
    DWORD dwOptionalLength
);

Sends the specified request to the HTTP server.

  • Returns TRUE if successful, or FALSE otherwise. To get extended error information, call GetLastError.
hHttpRequest
Open HTTP request handle returned by HttpOpenRequest.
lpszHeaders
Additional headers to be appended to the request. This parameter can be NULL if there are no additional headers to append.
dwHeadersLength
Length, in characters, of the additional headers. If this parameter is -1L and lpszHeaders is not NULL, the function assumes that lpszHeaders is zero-terminated (ASCIIZ), and the length is calculated.
lpOptional
Address of any optional data to send immediately after the request headers. This parameter is generally used for POST and PUT operations. The optional data can be the resource or information being posted to the server. This parameter can be NULL if there is no optional data to send.
dwOptionalLength
Length, in bytes, of the optional data. This parameter can be zero if there is no optional data to send.

HttpSendRequest sends the specified request to the HTTP server and allows the client to specify additional headers to send along with the request.

The function also lets the client specify optional data to send to the HTTP server immediately following the request headers. This feature is generally used for "write" operations such as PUT and POST.

After the request is sent, the status code and response headers from the HTTP server are read. These headers are maintained internally and are available to client applications through the HttpQueryInfo function.

An application can use the same HTTP request handle in multiple calls to HttpSendRequest, but the application must read all data returned from the previous call before calling the function again.

See also InternetReadFile


HttpSendRequestEx

BOOL HttpSendRequestEx(
    IN HINTERNET hRequest,
    IN LPINTERNET_BUFFERS lpBuffersIn,
    OUT LPINTERNET_BUFFERS lpBuffersOut,
    IN DWORD dwFlags,
    IN DWORD dwContext
);

Sends the specified request to the HTTP server.

  • Returns TRUE if successful, or FALSE otherwise. To get extended error information, call GetLastError.
hRequest
HINTERNET handle returned by HttpOpenRequest.
lpBuffersIn
Optional. Address of an INTERNET_BUFFERS structure.
lpBuffersOut
Optional. Address of an INTERNET_BUFFERS structure.
dwFlags
Can be one of the following values:
HSR_ASYNC | Identical to WININET_API_FLAG_ASYNC.
HSR_SYNC | Identical to WININET_API_FLAG_SYNC.
HSR_USE_CONTEXT | Identical to WININET_API_FLAG_USE_CONTEXT.
HSR_INITIATE | Iterative operation (completed by HttpEndRequest).
HSR_DOWNLOAD | Download resource to file.
HSR_CHUNKED | Send chunked data.
dwContext
DWORD variable that contains the context value to use in asynchronous operations.


InternetAttemptConnect

DWORD InternetAttemptConnect(
    IN DWORD dwReserved
);

Attempts to make a connection to the Internet.

  • Returns ERROR_SUCCESS if successful, or a Win32 error value otherwise.
dwReserved
Reserved; must be zero.

This function allows an application to first attempt to connect before issuing any requests. A client program can use this to evoke the dialup dialog box. If the attempt fails, the application should enter offline mode.


InternetAutodial

BOOL InternetAutodial(
    IN DWORD dwFlags,
    IN DWORD dwReserved
);

Automatically causes the modem to dial the default Internet connection.

  • Returns TRUE if successful, or FALSE otherwise.
dwFlags
Double-word value that contains the flags controlling this operation. Can be one of the following values:
INTERNET_AUTODIAL_FORCE_ONLINE | Forces an online Internet connection.
INTERNET_AUTODIAL_FORCE_UNATTENDED | Forces an unattended Internet dial-up.
dwReserved
Reserved. Must be set to zero.


InternetAutodialHangup

BOOL InternetAutodialHangup(
    IN DWORD dwReserved
);

Disconnects an automatic dial-up connection.

  • Returns TRUE if successful, or FALSE otherwise.
dwReserved
Reserved. Must be set to zero.


InternetCanonicalizeUrl

BOOL InternetCanonicalizeUrl(
    IN LPCSTR lpszUrl,
    OUT LPSTR lpszBuffer,
    IN OUT LPDWORD lpdwBufferLength,
    IN DWORD dwFlags
);

Canonicalizes a URL, which includes converting unsafe characters and spaces into escape sequences.

  • Returns TRUE if successful, or FALSE otherwise. To get extended error information, call GetLastError. Possible errors include:
    ERROR_BAD_PATHNAME | The URL could not be canonicalized.
    ERROR_INSUFFICIENT_BUFFER | Canonicalized URL is too large to fit in the buffer provided. The *lpdwBufferLength parameter is set to the size, in bytes, of the buffer required to hold the resultant, canonicalized URL.
    ERROR_INTERNET_INVALID_URL | The format of the URL is invalid.
    ERROR_INVALID_PARAMETER | Bad string, buffer, buffer size, or flags parameter.
lpszUrl
Address of the input URL to canonicalize.
lpszBuffer
Address of the buffer that receives the resulting canonicalized URL.
lpdwBufferLength
Length, in bytes, of the lpszBuffer buffer. If the function succeeds, this parameter receives the length of the lpszBuffer buffer—the length does not include the terminating null. If the function fails, this parameter receives the required length, in bytes, of the lpszBuffer buffer—the required length includes the terminating null.
dwFlags
Flags that control canonicalization. Can be one of the following values:
ICU_BROWSER_MODE | Does not encode or decode characters after "#" or "?", and does not remove trailing white space after "?". If this value is not specified, the entire URL is encoded, and trailing white space is removed.
ICU_DECODE | Converts all %XX sequences to characters, including escape sequences, before the URL is parsed.
ICU_ENCODE_SPACES_ONLY | Encodes spaces only.
ICU_NO_ENCODE | Does not convert unsafe characters to escape sequences.
ICU_NO_META | Does not remove meta sequences (such as "." and "..") from the URL.

If no flags are specified (dwFlags = 0), the function converts all unsafe characters and meta sequences (such as \.,\ .., and \...) to escape sequences.

InternetCanonicalizeUrl always encodes by default, even if the ICU_DECODE flag has been specified. To decode without re-encoding, use ICU_DECODE | ICU_NO_ENCODE. If the ICU_DECODE flag is used without ICU_NO_ENCODE, the URL is decoded before being parsed; unsafe characters then are re-encoded after parsing. This function will handle arbitrary protocol schemes, but to do so it must make inferences from the unsafe character set.

The application calling InternetCanonicalizeUrl should track the usage of this function on a particular URL. If unsafe characters in a URL have been converted to escape sequences, using InternetCanonicalizeUrl again on the URL (with no flags) will cause the escape sequences to be converted to another escape sequence. For example, a blank space in a URL would be converted to the escape sequence "%20". Calling InternetCanonicalizeUrl again on the URL would cause the escape sequence "%20" to be converted to the escape sequence "%2520", because the "%" sign is an unsafe character that is reserved for escape sequences and is replaced by the function with the escape sequence "%25".


InternetCheckConnection

BOOL InternetCheckConnection(
    IN LPCSTR lpszUrl,
    IN DWORD dwFlags,
    IN DWORD dwReserved
);

Allows an application to check if a connection to the Internet can be established.

  • Returns TRUE if a connection is made successfully, or FALSE otherwise. Use GetLastError to retrieve the error code. ERROR_NOT_CONNECTED is returned by GetLastError if a connection cannot be made or if the sockets database is unconditionally offline.
lpszUrl
Address of a string containing the Uniform Resource Locator (URL) to use to check the connection. This value can be set to NULL.
dwFlags
Unsigned long integer value containing the flag values. FLAG_ICC_FORCE_CONNECTION is the only flag that is currently available. If this flag is set, it forces a connection. A sockets connection is attempted in the following order:
  • If lpszUrl is non-NULL, the host value is extracted from it and used to ping that specific host.
  • If lpszUrl is NULL and there is an entry in WinInet's internal server database for the nearest sever, the host value is extracted from the entry and used to ping that server.
dwReserved
Reserved, must be zero.


InternetCloseHandle

BOOL InternetCloseHandle(
    IN HINTERNET hInet
);

Closes a single Internet handle.

  • Returns TRUE if the handle is successfully closed, or FALSE otherwise. To get extended error information, call GetLastError.
hInet
Valid Internet handle to be closed.

The function terminates any pending operations on the handle and discards any outstanding data. If a thread is blocking a call to Wininet.dll, another thread in the application can call InternetCloseHandle on the Internet handle being used by the first thread to cancel the operation and unblock the first thread.

If there is a status callback registered for the handle being closed and the handle was created with a non-NULL context value, an INTERNET_STATUS_HANDLE_CLOSING callback will be made. This indication will be the last callback made from a handle and indicates that the handle is being destroyed.

If asynchronous requests are pending for the handle or any of its child handles, the handle cannot be closed immediately, but it will be invalidated. Any new requests attempted using the handle will return with an ERROR_INVALID_HANDLE notification. The asynchronous requests will complete with INTERNET_STATUS_REQUEST_COMPLETE. Applications must be prepared to receive any INTERNET_STATUS_REQUEST_COMPLETE indications on the handle before the final INTERNET_STATUS_HANDLE_CLOSING indication is made, which indicates that the handle is completely closed.

An application can call GetLastError to determine if requests are pending. If GetLastError returns ERROR_IO_PENDING, there were outstanding requests when the handle was closed.

See also FtpFindFirstFile, FtpOpenFile, GopherFindFirstFile, HttpOpenRequest, InternetConnect


InternetCombineUrl

BOOL InternetCombineUrl(
    IN LPCSTR lpszBaseUrl,
    IN LPCSTR lpszRelativeUrl,
    OUT LPSTR lpszBuffer,
    IN OUT LPDWORD lpdwBufferLength,
    IN DWORD dwFlags
);

Combines a base and relative URL into a single URL. The resultant URL will be canonicalized (see InternetCanonicalizeUrl).

  • Returns TRUE if successful, or FALSE otherwise. To get extended error information, call GetLastError. Possible errors include:
    ERROR_BAD_PATHNAME | The URLs could not be combined.
    ERROR_INSUFFICIENT_BUFFER | The buffer supplied to the function was insufficient or NULL. The DWORD indicated by the lpdwBufferLength parameter will contain the number of bytes required to hold the resultant, combined URL.
    ERROR_INTERNET_INVALID_URL | The format of the URL is invalid.
    ERROR_INVALID_PARAMETER | Bad string, buffer, buffer size, or flags parameter.
lpszBaseUrl
Address of the base URL to be combined.
lpszRelativeUrl
Address of the relative URL to be combined.
lpszBuffer
Address of a buffer that receives the resulting URL.
lpdwBufferLength
Size, in bytes, of the lpszBuffer buffer. If the function succeeds, this parameter receives the length, in characters, of the resultant combined URL—the length does not include the null terminator. If the function fails, this parameter receives the length, in bytes, of the required buffer—the length includes the null terminator.
dwFlags
Flags controlling the operation of the function. Can be one of the following values:
ICU_BROWSER_MODE | Does not encode or decode characters after "#" or "?", and does not remove trailing white space after "?". If this value is not specified, the entire URL is encoded and trailing white space is removed.
ICU_DECODE | Converts all %XX sequences to characters, including escape sequences, before the URL is parsed.
ICU_ENCODE_SPACES_ONLY | Encodes spaces only.
ICU_NO_ENCODE | Does not convert unsafe characters to escape sequences.
ICU_NO_META | Does not remove meta sequences (such as "." and "..") from the URL.


InternetConfirmZoneCrossing

DWORD InternetConfirmZoneCrossing(
    IN HWND hWnd,
    IN LPSTR szUrlPrev,
    IN LPSTR szUrlNew,
    IN BOOL bPost
);

Checks for changes between secure and nonsecure URLs. When a change occurs in security between two URLs, an application should allow the user to acknowledge this change, typically by displaying a dialog box.

  • Returns one of the following values:
    ERROR_SUCCESS | The user confirmed that it was okay to continue or there was no user input needed.
    ERROR_CANCELLED | The user canceled the request.
    ERROR_NOT_ENOUGH_MEMORY | There is not enough memory to carry out the request.
hWnd
Handle to the parent window for any needed dialog box.
szUrlPrev
URL that was viewed before the current request was made.
szUrlNew
New URL that the user has requested to view.
bPost
TRUE if a post is being made in this request. This flag is ignored in this release.


InternetConnect

HINTERNET InternetConnect(
    IN HINTERNET hInternetSession,
    IN LPCSTR lpszServerName,
    IN INTERNET_PORT nServerPort,
    IN LPCSTR lpszUsername,
    IN LPCSTR lpszPassword,
    IN DWORD dwService,
    IN DWORD dwFlags,
    IN DWORD dwContext
);

Opens an FTP, Gopher, or HTTP session for a given site.

  • Returns a valid handle to the FTP, Gopher, or HTTP session if the connection is successful, or NULL otherwise. To get extended error information, call GetLastError. An application can also use InternetGetLastResponseInfo to determine why access to the service was denied.
hInternetSession
Handle to the current Internet session. The handle must have been returned by a previous call to InternetOpen.
lpszServerName
Address of a null-terminated string that contains the host name of an Internet server. Alternately, the string can contain the IP number of the site in ASCII dotted-decimal format (for example, 11.0.1.45).
nServerPort
Number of the TCP/IP port on the server to connect to. Can be one of the values in the following list. These flags set only the port that will be used. The service is set by the value of dwService.
INTERNET_DEFAULT_FTP_PORT | Uses the default port for FTP servers (port 21).
INTERNET_DEFAULT_GOPHER_PORT | Uses the default port for Gopher servers (port 70).
INTERNET_DEFAULT_HTTP_PORT | Uses the default port for HTTP servers (port 80).
INTERNET_DEFAULT_HTTPS_PORT | Uses the default port for HTTPS servers (port 443).
INTERNET_DEFAULT_SOCKS_PORT | Uses the default port for SOCKS firewall servers (port 1080).
INTERNET_INVALID_PORT_NUMBER | Uses the default port for the service specified by dwService.
lpszUsername
Address of a null-terminated string that contains the name of the user to log on. If this parameter is NULL, the function uses an appropriate default, except for HTTP; a NULL parameter in HTTP causes the server to return an error. For the FTP protocol, the default is "anonymous".
lpszPassword
Address of a null-terminated string that contains the password to use to log on. If both lpszPassword and lpszUsername are NULL, the function uses the default "anonymous" password. In the case of FTP, the default password is the user's e-mail name. If lpszPassword is NULL, but lpszUsername is not NULL, the function uses a blank password. The following table describes the behavior for the four possible settings of lpszUsername and lpszPassword.
lpszUsername | lpszPassword | User name sent to FTP server | Password sent to FTP server
NULL | NULL | "anonymous" | User's e-mail name
Non-NULL string NULL lpszUsername ""
NULL | Non-NULL string | ERROR | ERROR
Non-NULL string | Non-NULL string | lpszUsername | lpszPassword
dwService
Type of service to access. Can be one of the following values:
INTERNET_SERVICE_FTP | FTP service.
INTERNET_SERVICE_GOPHER | Gopher service.
INTERNET_SERVICE_HTTP | HTTP service.
dwFlags
Flags specific to the service used. When the value of dwService is INTERNET_SERVICE_FTP, INTERNET_FLAG_PASSIVE causes the application to use passive FTP semantics.
dwContext
Application-defined value that is used to identify the application context for the returned handle in callbacks.

The InternetConnect function is required before communicating with any Internet service.

Having a connect function for all protocols, even those that do not use persistent connections, lets an application communicate common information about several requests by using a single function call. In addition, this allows for future versions of Internet protocols that do not require a connection to be established for every client request.

For FTP sites, InternetConnect actually establishes a connection with the server; for others, such as Gopher, the actual connection is not established until the application requests a specific transaction.

For maximum efficiency, applications using the Gopher and HTTP protocols should try to minimize calls to InternetConnect and avoid calling this function for every transaction requested by the user. One way to accomplish this is to keep a small cache of handles returned from InternetConnect; when the user makes a request to a previously accessed server, that session handle is still available.

An application that needs to display multiline text information sent by an FTP server can use InternetGetLastResponseInfo to retrieve the text.

For FTP connections, if lpszUsername is NULL, InternetConnect sends the string "anonymous" as the user name. If lpszPassword is NULL, InternetConnect attempts to use the user's e-mail name as the password.

To close the handle returned from InternetConnect, the application should call InternetCloseHandle. This function disconnects the client from the server and frees all resources associated with the connection.


InternetCrackUrl

BOOL InternetCrackUrl(
    IN LPCSTR lpszUrl,
    IN DWORD dwUrlLength,
    IN DWORD dwFlags,
    IN OUT LPURL_COMPONENTS lpUrlComponents
);

Cracks a URL into its component parts.

  • Returns TRUE if the function succeeds, or FALSE otherwise. To get extended error information, call GetLastError.
lpszUrl
Address of a string that contains the canonical URL to crack.
dwUrlLength
Length of the lpszUrl string, or zero if lpszUrl is an ASCIIZ string.
dwFlags
Flags controlling the operation. Can be one of the following values:
ICU_DECODE | Converts encoded characters back to their normal form. This can be used only if the user provides buffers in the URL_COMPONENTS structure to copy the components into.
ICU_ESCAPE | Converts all escape sequences (%xx) to their corresponding characters. This can be used only if the user provides buffers in the URL_COMPONENTS structure to copy the components into.
lpUrlComponents
Address of a URL_COMPONENTS structure that receives the URL components.

The required components are indicated by members of the URL_COMPONENTS structure. Each component has a pointer to the value and has a member that stores the length of the stored value. If both the value and the length for a component are equal to zero, that component is not returned. If the pointer to the value of the component is NULL and the value of its corresponding length member is nonzero, the address of the first character of the corresponding component in the lpszUrl string is stored in the pointer, and the length of the component is stored in the length member.

If the pointer contains the address of the user-supplied buffer, the length member must contain the size of the buffer. InternetCrackUrl copies the component into the buffer, and the length member is set to the length of the copied component, minus 1 for the trailing string terminator.

For InternetCrackUrl to work properly, the size of the URL_COMPONENTS structure must be stored in the dwStructSize member.

See also FtpOpenFile, InternetCloseHandle, InternetFindNextFile, InternetSetStatusCallback


InternetCreateUrl

BOOL InternetCreateUrl(
    IN LPURL_COMPONENTS lpUrlComponents,
    IN DWORD dwFlags,
    OUT LPSTR lpszUrl,
    IN OUT LPDWORD lpdwUrlLength
);

Creates a URL from its component parts.

  • Returns TRUE if the function succeeds, or FALSE otherwise. To get extended error information, call GetLastError.
lpUrlComponents
Address of a URL_COMPONENTS structure that contains the components from which to create the URL.
dwFlags
Flags that control the operation of this function. Can be a combination of these values:
ICU_ESCAPE | Converts all escape sequences (%xx) to their corresponding characters.
ICU_USERNAME | When adding the user name, uses the name that was specified at logon time.
lpszUrl
Address of a buffer that receives the URL.
lpdwUrlLength
Length, in bytes, of the lpszUrl buffer. When the function returns, this parameter receives the length, in bytes, of the URL string, minus 1 for the terminating character. If GetLastError returns ERROR_INSUFFICIENT_BUFFER, this parameter receives the number of bytes required to hold the created URL.


InternetDial

DWORD InternetDial(
    IN HWND hwndParent,
    IN LPTSTR lpszConnectoid,
    IN DWORD dwFlags,
    OUT LPDWORD lpdwConnection,
    IN DWORD dwReserved
);

Initiates a connection to the Internet using a modem connection.

hwndParent
Handle to the parent window.
lpszConnectoid
String value containing the name of the dial-up connection to use.
dwFlags
Double-word value that contains the flags to use. Can be one of the following values:
INTERNET_AUTODIAL_FORCE_ONLINE | Forces an online connection.
INTERNET_AUTODIAL_FORCE_UNATTENDED | Forces an unattended Internet dial-up.
INTERNET_DIAL_UNATTENDED | Connects to the Internet through a modem, without displaying a user interface.
lpdwConnection
Address of a double-word value containing the number associated to the connection.
dwReserved
Reserved. Must be set to zero.


InternetErrorDlg

DWORD InternetErrorDlg(
    IN HWND hWnd,
    IN OUT HINTERNET hInternet,
    IN DWORD dwError,
    IN DWORD dwFlags,
    IN OUT LPVOID *lppvData
);

Displays a dialog box for the error that is passed to InternetErrorDlg, if an appropriate dialog box exists. If the FLAGS_ERROR_UI_FILTER_FOR_ERRORS flag is used, the function also checks the headers for any hidden errors and displays a dialog box if needed.

  • Returns ERROR_SUCCESS, ERROR_CANCELLED, or ERROR_INTERNET_FORCE_RETRY.
hWnd
Handle to the parent window for any needed dialog box. This parameter can be NULL if no dialog box is needed.
hInternet
Handle to the Internet connection used in the call to HttpSendRequest.
dwError
Error value for which to display a dialog box. Can be one of the following values:
ERROR_INTERNET_HTTP_TO_HTTPS_ON_REDIR
Notifies the user of the zone crossing to and from a secure site.
ERROR_INTERNET_INCORRECT_PASSWORD
Displays a dialog box for obtaining the user's name and password. (On Microsoft Windows® 95, the function first attempts to use any cached authentication information for the server being accessed, before displaying a dialog box.)
ERROR_INTERNET_INVALID_CA
Notifies the user that the Win32 Internet function does not recognize the certificate authority that generated the certificate for this Secure Sockets Layer (SSL) site.
ERROR_INTERNET_POST_IS_NON_SECURE
Displays a warning about posting data to the server through a nonsecure connection.
ERROR_INTERNET_SEC_CERT_CN_INVALID
Indicates that the SSL certificate Common Name (hostname field) is incorrect. Displays an Invalid SSL Common Name dialog box, and lets the user view the incorrect certificate. Also allows the user to select a certificate in response to a server request.
ERROR_INTERNET_SEC_CERT_DATE_INVALID
Tells the user that the SSL certificate has expired.
dwFlags
Action flags. Can be a combination of these values:
FLAGS_ERROR_UI_FILTER_FOR_ERRORS
Scans the returned headers for errors. Call after using HttpSendRequest. This option detects any hidden errors, such as an authentication error.
FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS
If the function succeeds, stores the results of the dialog box in the Internet handle.
FLAGS_ERROR_UI_FLAGS_GENERATE_DATA
Queries the Internet handle for needed information. The function constructs the appropriate data structure for the error. (For example, for Cert CN failures, the function grabs the certificate.)
FLAGS_ERROR_UI_SERIALIZE_DIALOGS
Serializes authentication dialog boxes for concurrent requests on a password cache entry. The lppvData parameter should contain the address of a pointer to an INTERNET_AUTHNOTIFY_DATA structure, and the client should implement a thread-safe, nonblocking callback function.
lppvData
Address of a data structure. The structure can be different for each error that needs to be handled.

Authentication errors are hidden, since the call to HttpSendRequest will complete successfully, but the status code would indicate that the proxy or server requires authentication. The FLAGS_ERROR_UI_FILTER_FOR_ERRORS flag causes the function to search the headers for status codes that indicate that user input is needed.


InternetFindNextFile

BOOL InternetFindNextFile(
    IN HINTERNET hFind,
    OUT LPVOID lpvFindData
);

Continues a file search started as a result of a previous call to FtpFindFirstFile or GopherFindFirstFile.

  • Returns TRUE if the function succeeds, or FALSE otherwise. To get extended error information, call GetLastError. If the function finds no matching files, GetLastError returns ERROR_NO_MORE_FILES.
hFind
Valid handle returned from either FtpFindFirstFile or GopherFindFirstFile, or InternetOpenUrl (directories only).
lpvFindData
Address of the buffer that receives information about the found file or directory. The format of the information placed in the buffer depends on the protocol in use. The FTP protocol returns a WIN32_FIND_DATA structure, and the Gopher protocol returns a GOPHER_FIND_DATA structure.


InternetGetConnectedState

BOOL InternetGetConnectedState(
    OUT LPDWORD lpdwFlags,
    IN DWORD dwReserved
);

Retrieves the connected state of the local system.

  • Returns TRUE if there is an Internet connection, FALSE otherwise.
lpdwFlags
Address of a double-word variable where the connection description should be returned. Can be a combination of the following values:
INTERNET_CONNECTION_MODEM | Local system uses a modem to connect to the Internet.
INTERNET_CONNECTION_LAN | Local system uses a local area network to connect to the Internet.
INTERNET_CONNECTION_PROXY | Local system uses a proxy server to connect to the Internet.
INTERNET_CONNECTION_MODEM_BUSY | Local system's modem is busy with a non-Internet connection.
dwReserved
Reserved. Must be set to zero.


InternetGetCookie

BOOL InternetGetCookie(
    IN  LPCSTR lpszUrlName,
    IN  LPCSTR lpszCookieName,
    OUT LPSTR lpszCookieData,
    IN OUT LPDWORD  lpdwSize
);

Returns the cookie for the specified URL.

  • Returns TRUE if successful, or FALSE otherwise. To get the specific error value, call GetLastError. The following error values apply to InternetGetCookie:
    ERROR_NO_MORE_ITEMS | There is no cookie for the specified URL and all its parents.
    ERROR_INSUFFICIENT_BUFFER | The value passed in lpdwSize is insufficient to copy all the cookie data. The value returned in lpdwSize is the size of the buffer necessary to get all the data.
lpszUrlName
Address of a string that contains the URL to get cookies for.
lpszCookieName
Address of the name of the cookie to get for the specified URL. This has not been implemented in this release.
lpszCookieData
Address of the buffer that receives the cookie data. This value can be NULL.
lpdwSize
Address of a variable that specifies the size of the lpszCookieData buffer. If the function succeeds, the buffer receives the amount of data copied to the lpszCookieData buffer. If lpszCookieData is NULL, this parameter receives a value that specifies the size of the buffer necessary to copy all the cookie data.

InternetGetCookie does not require a call to InternetOpen. InternetGetCookie checks in the windows\cookies directory for cookies and searches memory for any cookies that do not have an expiration date, since these cookies are not written to any files. Rules for creating cookie files are internal to Win32 Internet functions and may change in the future.


InternetGetLastResponseInfo

BOOL InternetGetLastResponseInfo(
    OUT LPDWORD lpdwError,
    OUT LPSTR lpszBuffer,
    IN OUT LPDWORD lpdwBufferLength
);

Retrieves the last Win32 Internet function error description or server response on the thread calling this function.

  • Returns TRUE if error text was successfully written to the buffer, or FALSE otherwise. To get extended error information, call GetLastError. If the buffer is too small to hold all the error text, GetLastError returns ERROR_INSUFFICIENT_BUFFER, and the lpdwBufferLength parameter contains the minimum buffer size required to return all the error text.
lpdwError
Address of a variable that receives an error message pertaining to the operation that failed.
lpszBuffer
Address of a buffer that receives the error text.
lpdwBufferLength
Size of the lpszBuffer buffer. When the function returns, this parameter contains the size of the string written to the buffer.

The FTP and Gopher protocols can return additional text information along with most errors. This extended error information can be retrieved by using the InternetGetLastResponseInfo function whenever GetLastError returns ERROR_INTERNET_EXTENDED_ERROR (occurring after an unsuccessful function call).

The buffer pointed to by lpszBuffer must be large enough to hold both the error string and a zero terminator at the end of the string. However, note that the value returned in lpdwBufferLength does not include the terminating zero.

InternetGetLastResponseInfo can be called multiple times until another Win32 Internet function is called on this thread. When another function is called, the internal buffer that is storing the last response information is cleared.


InternetGoOnline

BOOL InternetGoOnline(
    IN LPTSTR lpszURL,
    IN HWND hwndParent,
    IN DWORD dwReserved
);

Prompts the user for permission to initiate connection to a URL.

  • Returns TRUE if successful, or FALSE otherwise.
lpszURL
String value containing the URL of the Web site to connect to.
hwndParent
Handle to the parent window.
dwReserved
Reserved. Must be set to zero.


InternetHangUp

DWORD InternetHangUp(
    IN DWORD dwConnection,
    IN DWORD dwReserved
);

Instructs the modem to disconnect from the Internet.

dwConnection
Double-word value that contains the number assigned to the connection to be disconnected.
dwReserved
Reserved. Must be set to zero.


InternetLockRequestFile

BOOL InternetLockRequestFile (
    IN HINTERNET hInternet,
    OUT HANDLE *lphLockReqHandle
);

Allows the user to place a lock on the file that is being used.

  • Returns TRUE if successful, or FALSE otherwise. To get a specific error message, use GetLastError.
hInternet
HINTERNET handle returned by FtpOpenFile, GopherOpenFile, HttpOpenRequest, or InternetOpenUrl.
lphLockReqHandle
Address of a handle to store the lock request handle.

If the HINTERNET handle passed to hInternet was created using INTERNET_FLAG_NO_CACHE_WRITE or INTERNET_FLAG_DONT_CACHE, the function creates a temporary file with the extension TMP, unless it is an HTTPS resource. If the handle was created using INTERNET_FLAG_NO_CACHE_WRITE or INTERNET_FLAG_DONT_CACHE and it is accessing an HTTPS resource, InternetLockRequestFile fails.

See also InternetUnlockRequestFile


InternetOpen

HINTERNET InternetOpen(
    IN LPCSTR lpszAgent,
    IN DWORD dwAccessType,
    IN LPCSTR lpszProxyName,
    IN LPCSTR lpszProxyBypass,
    IN DWORD dwFlags
);

Initializes an application's use of the Win32 Internet functions.

  • Returns a valid handle that the application passes on to subsequent Win32 Internet functions. If InternetOpen fails, it returns NULL. To get a specific error message, call GetLastError.
lpszAgent
Address of a string that contains the name of the application or entity calling the Internet functions (for example, Microsoft Internet Explorer). This name is used as the user agent in the HTTP protocol.
dwAccessType
Type of access required. Can be one of the following values:
INTERNET_OPEN_TYPE_DIRECT
Resolves all host names locally.
INTERNET_OPEN_TYPE_PRECONFIG
Retrieves the proxy or direct configuration from the registry.
INTERNET_OPEN_TYPE_PRECONFIG_WITH_NO_AUTOPROXY
Retrieves the proxy or direct configuration from the registry and prevents the use of a startup JScript or Internet Setup (INS) file.
INTERNET_OPEN_TYPE_PROXY
Passes requests to the proxy unless a proxy bypass list is supplied and the name to be resolved bypasses the proxy. In this case, the function uses INTERNET_OPEN_TYPE_DIRECT.
lpszProxyName
Address of a string that contains the name of the proxy server (or servers) to use if proxy access was specified. If this parameter is NULL, the function reads proxy information from the registry. Do not use an empty string, because InternetOpen will use it as the proxy name. The Win32 Internet functions only recognize CERN type proxies (HTTP only) and the TIS FTP gateway (FTP only). If Microsoft Internet Explorer is installed, the Win32 Internet functions also support SOCKS proxies. FTP and Gopher requests can be made through a CERN type proxy either by changing them to an HTTP request or by using InternetOpenUrl.
lpszProxyBypass
Address of an optional list of host names or IP addresses, or both, that should not be routed through the proxy. The list can contain wildcards. Do not use an empty string, because InternetOpen will use it as the proxy bypass list. If this parameter specifies the "<local>" macro as the only entry, the function bypasses any host name that does not contain a period. If this parameter is NULL, the function reads the bypass list from the registry.
dwFlags
Flags that indicate various options affecting the behavior of the function. Can be a combination of these values:
INTERNET_FLAG_ASYNC
INTERNET_FLAG_FROM_CACHE
INTERNET_FLAG_OFFLINE

InternetOpen is the first Win32 Internet function called by an application. It tells the Internet DLL to initialize internal data structures and prepare for future calls from the application. When the application finishes using the Internet functions, it should call InternetCloseHandle to free the handle and any associated resources.

The application can make any number of calls to InternetOpen, although a single call is normally sufficient. The application might need to have separate behaviors defined for each InternetOpen instance, such as different proxy servers configured for each.


InternetOpenUrl

HINTERNET InternetOpenUrl(
    IN HINTERNET hInternetSession,
    IN LPCSTR lpszUrl,
    IN LPCSTR lpszHeaders,
    IN DWORD dwHeadersLength,
    IN DWORD dwFlags,
    IN DWORD dwContext
);

Begins reading a complete FTP, Gopher, or HTTP URL. Use InternetCanonicalizeUrl first if the URL being used contains a relative URL and a base URL separated by blank spaces.

  • Returns a valid handle to the FTP, Gopher, or HTTP URL if the connection is successfully established, or NULL if the connection fails. To get a specific error message, call GetLastError. To determine why access to the service was denied, call InternetGetLastResponseInfo.
hInternetSession
Handle to the current Internet session. The handle must have been returned by a previous call to InternetOpen.
lpszUrl
Address of a string that contains the URL to begin reading. Only URLs beginning with ftp:, gopher:, http:, or https: are supported.
lpszHeaders
Address of a string that contains the headers to be sent to the HTTP server. (For more information, see the description of the lpszHeaders parameter in the HttpSendRequest function.)
dwHeadersLength
Length, in characters, of the additional headers. If this parameter is -1L and lpszHeaders is not NULL, lpszHeaders is assumed to be zero-terminated (ASCIIZ) and the length is calculated.
dwFlags
Action flags. Can be one of the following values:
INTERNET_FLAG_DONT_CACHE
Does not cache the data, either locally or in any gateways. Identical to the preferred value, INTERNET_FLAG_NO_CACHE_WRITE.
INTERNET_FLAG_EXISTING_CONNECT
If possible, reuses the existing connections to the server for new requests generated by InternetOpenUrl instead of creating a new session for each request. This flag is useful only for FTP connections, since FTP is the only protocol that typically performs multiple operations during the same session. The Win32 Internet API caches a single connection handle for each HINTERNET handle generated by InternetOpen.
INTERNET_FLAG_HYPERLINK
Forces a reload if there was no Expires time and no Last-Modified time returned from the server when determining whether to reload the item from the network.
INTERNET_FLAG_IGNORE_CERT_CN_INVALID
Disables Win32 Internet function checking of SSL/PCT-based certificates that are returned from the server against the host name given in the request. Win32 Internet functions use a simple check against certificates by comparing for matching host names and simple wildcarding rules for HTTP requests.
INTERNET_FLAG_IGNORE_CERT_DATE_INVALID
Disables Win32 Internet function checking of SSL/PCT-based certificates for proper validity dates for HTTP requests.
INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP
Disables the ability of the Win32 Internet functions to detect this special type of redirect. When this flag is used, Win32 Internet functions transparently allow redirects from HTTPS to HTTP URLs.
INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS
Disables the ability of the Win32 Internet functions to detect this special type of redirect. When this flag is used, Win32 Internet functions transparently allow redirects from HTTP to HTTPS URLs.
INTERNET_FLAG_KEEP_CONNECTION
Uses keep-alive semantics, if available, for the connection for HTTP requests. This flag is required for Microsoft Network (MSN), NT LAN Manager (NTLM), and other types of authentication.
INTERNET_FLAG_MAKE_PERSISTENT
No longer supported.
INTERNET_FLAG_MUST_CACHE_REQUEST
Causes a temporary file to be created if the file cannot be cached. Identical to the preferred value, INTERNET_FLAG_NEED_FILE.
INTERNET_FLAG_NEED_FILE
Causes a temporary file to be created if the file cannot be cached.
INTERNET_FLAG_NO_AUTH
Does not attempt authentication automatically for HTTP requests.
INTERNET_FLAG_NO_AUTO_REDIRECT
Does not automatically handle redirection for HTTP requests only.
INTERNET_FLAG_NO_CACHE_WRITE
Does not cache the data, either locally or in any gateways.
INTERNET_FLAG_NO_COOKIES
Does not automatically add cookie headers to requests, and does not automatically add returned cookies to the cookie database for HTTP requests.
INTERNET_FLAG_NO_UI
Disables the cookie dialog box.
INTERNET_FLAG_PASSIVE
Uses passive FTP semantics for FTP files and directories.
INTERNET_FLAG_RAW_DATA
Returns the data as a GOPHER_FIND_DATA structure when retrieving Gopher directory information, or as a WIN32_FIND_DATA structure when retrieving FTP directory information. If this flag is not specified or if the call was made through a CERN proxy, InternetOpenUrl returns an HTML version of the directory.
INTERNET_FLAG_PRAGMA_NOCACHE
Forces the request to be resolved by the origin server, even if a cached copy exists on the proxy.
INTERNET_FLAG_READ_PREFETCH
This flag is currently disabled.
INTERNET_FLAG_RELOAD
Gets the data from the wire even if it is locally cached.
INTERNET_FLAG_RESYNCHRONIZE
Reloads HTTP resources if the resource has been modified since the last time it was downloaded. All FTP and Gopher resources are reloaded.
INTERNET_FLAG_SECURE
Requests secure transactions on the wire with SSL or PCT. This flag applies to HTTP requests only.
dwContext
Application-defined value that is passed, along with the returned handle, to any callback functions.

This is a general function that an application can use to retrieve data over any of the protocols that the Win32 Internet functions support. This function is particularly useful when the application does not need to access the particulars of a protocol, but only requires the data corresponding to a URL. The InternetOpenUrl function parses the URL string, establishes a connection to the server, and prepares to download the data identified by the URL. The application can then use InternetReadFile (for files) or InternetFindNextFile (for directories) to retrieve the URL data. It is not necessary to call InternetConnect before InternetOpenUrl.

InternetOpenUrl disables Gopher on ports less than 1024, except for port 70 (the standard Gopher port) and port 105 (typically used for Central Services Organization [CSO] name searches).

Use InternetCloseHandle to close the handle returned from InternetOpenUrl. However, note that closing the handle before all the URL data has been read results in the connection being terminated.


InternetQueryDataAvailable

BOOL InternetQueryDataAvailable(
    IN HINTERNET hFile,
    OUT LPDWORD lpdwNumberOfBytesAvailable,
    IN DWORD dwFlags,
    IN DWORD dwContext
);

Queries the amount of data available.

  • Returns TRUE if the function succeeds, or FALSE otherwise. To get extended error information, call GetLastError. If the function finds no matching files, GetLastError returns ERROR_NO_MORE_FILES.
hFile
Valid Internet file handle, as returned by InternetOpenUrl, FtpOpenFile, GopherOpenFile, or HttpOpenRequest.
lpdwNumberOfBytesAvailable
Optional. Address of a variable that receives the number of available bytes.
dwFlags
Reserved; must be zero.
dwContext
Reserved; must be zero.

This function returns the number of bytes of data that are available to be read immediately by a subsequent call to InternetReadFile. If there is currently no data available and the end of the file has not been reached, the request waits until data becomes available. The amount of data remaining will not be recalculated until all available data indicated by the call to InternetQueryDataAvailable is read.

For HINTERNET handles created by HttpOpenRequest and sent by HttpSendRequestEx, a call to HttpEndRequest must be made on the handle before InternetQueryDataAvailable can be used.


InternetQueryOption

BOOL InternetQueryOption(
    IN HINTERNET hInternet,
    IN DWORD dwOption,
    OUT LPVOID lpBuffer,
    IN OUT LPDWORD lpdwBufferLength
);

Queries an Internet option on the specified handle.

  • Returns TRUE if successful, or FALSE otherwise. To get a specific error message, call GetLastError.
hInternet
Internet handle on which to query information.
dwOption
Internet option to query. Can be one of the Option Flags values.
lpBuffer
Address of a buffer that receives the option setting.
lpdwBufferLength
Address of a variable that contains the length of lpBuffer. When the function returns, the variable receives the length of the data placed into lpBuffer. If GetLastError returns ERROR_INSUFFICIENT_BUFFER, this parameter receives the number of bytes required to hold the created URL.

See also FtpGetFile, FtpPutFile, InternetConnect, InternetOpen, InternetSetOption


InternetReadFile

BOOL InternetReadFile(
    IN HINTERNET hFile,
    IN LPVOID lpBuffer,
    IN DWORD dwNumberOfBytesToRead,
    OUT LPDWORD lpNumberOfBytesRead
);

Reads data from a handle opened by the InternetOpenUrl, FtpOpenFile, GopherOpenFile, or HttpOpenRequest function.

  • Returns TRUE if successful, or FALSE otherwise. To get extended error information, call GetLastError. An application can also use InternetGetLastResponseInfo when necessary.
hFile
Valid handle returned from a previous call to InternetOpenUrl, FtpOpenFile, GopherOpenFile, or HttpOpenRequest.
lpBuffer
Address of a buffer that receives the data read.
dwNumberOfBytesToRead
Number of bytes to read.
lpNumberOfBytesRead
Address of a variable that receives the number of bytes read. InternetReadFile sets this value to zero before doing any work or error checking.

If the return value is TRUE and the number of bytes read is zero, the transfer has been completed and there are no more bytes to read on the handle. This is analogous to reaching EOF in a local file. Call InternetCloseHandle to free the connection to the server.

The buffer pointed to by lpBuffer is not always filled by calls to InternetReadFile (sufficient data might not have arrived from the server). When reading HTML data, for the first read posted, the buffer must be large enough to hold the HTML headers. When reading HTML-encoded directory entries, the buffer must be large enough to hold at least one complete entry.

When the item being read is also being cached by a Win32 Internet function, the application must ensure that a read is made for end-of-file so the cache file is committed correctly.

This function always fulfills the user's request. If more data is requested than is available, the function waits until enough data to complete the request is available. The only time that less data is returned than requested is when the end of the file has been reached.

This function can also be used to retrieve FTP and Gopher directory listings as an HTML document on a handle opened by InternetOpenUrl. The INTERNET_FLAG_RAW_DATA value must not have been specified in the call to InternetOpenUrl.

If the HINTERNET handle stored in hFile was created by HttpOpenRequest and sent by HttpSendRequestEx, a call to HttpEndRequest must be made on the handle before InternetReadFile is used.


InternetReadFileEx

InternetReadFileEx(
    IN HINTERNET hFile,
    OUT LPINTERNET_BUFFERS lpBuffersOut,
    IN DWORD dwFlags,
    IN DWORD dwContext
);

Reads data from a handle opened by the InternetOpenUrl, FtpOpenFile, GopherOpenFile, or HttpOpenRequest function.

  • Returns TRUE if successful, or FALSE otherwise. To get extended error information, call GetLastError. An application can also use InternetGetLastResponseInfo when necessary.
hFile
HINTERNET handle returned by the InternetOpenUrl, FtpOpenFile, GopherOpenFile, or HttpOpenRequest function.
lpBuffersOut
Address of an INTERNET_BUFFERS structure that contains the data downloaded.
dwFlags
DWORD variable that contains the flags controlling the download. Can be one of the following values:
IRF_ASYNC | Identical to WININET_API_FLAG_ASYNC.
IRF_SYNC | Identical to WININET_API_FLAG_SYNC.
IRF_USE_CONTEXT | Identical to WININET_API_FLAG_USE_CONTEXT.
IRF_NO_WAIT | Do not wait for data. If there is data available, the function returns either the amount of data requested or the amount of data available (whichever is smaller).
dwContext
DWORD variable that contains the context value used for asynchronous operations.


InternetSetCookie

BOOL InternetSetCookie(
    IN LPCSTR lpszUrlName,
    IN LPCSTR lpszCookieName,
    IN LPCSTR lpszCookieData
);

Sets a cookie on the specified URL.

  • Returns TRUE if successful, or FALSE otherwise. To get the specific error message, call GetLastError.
lpszUrlName
Address of a null-terminated string that specifies the URL for which the cookie should be set.
lpszCookieName
Address of a string that contains the name to associate with the cookie. If this parameter is NULL, no name is associated with the cookie.
lpszCookieData
Address of the actual data to associate with the URL.

Creating a new cookie might cause a dialog box to appear on the screen if the appropriate registry value, AllowCookies, is set. There is no way to change the registry value from a Win32 Internet function.


InternetSetDialState

BOOL InternetSetDialState(
    IN LPCSTR lpszConnectoid,
    IN DWORD dwState,
    IN DWORD dwReserved
);

Sets the modem dialing state.

  • Returns TRUE if successful, or FALSE otherwise.
lpszConnectoid
String value that contains the name of the dial-up connection.
dwState
Double-word value that indicates the state to set the dial-up connection to. Currently, the only defined value is INTERNET_DIALSTATE_DISCONNECTED.
dwReserved
Reserved. Must be set to zero.


InternetSetFilePointer

DWORD InternetSetFilePointer(
    IN HINTERNET hFile,
    IN LONG lDistanceToMove,
    IN PVOID pReserved,
    IN DWORD dwMoveMethod,
    IN DWORD dwContext
);

Sets a file position for InternetReadFile. This is a synchronous call; however, subsequent calls to InternetReadFile may block or return pending if the data is not available from the cache and the server does not support random access.

  • Returns the current file position if the function succeeds, or -1 otherwise.
hFile
Valid handle returned from a previous call to InternetOpenUrl (on an HTTP or HTTPS URL) or HttpOpenRequest (using the GET or HEAD method and passed to HttpSendRequest or HttpSendRequestEx). This handle must not have been created with the INTERNET_FLAG_DONT_CACHE or INTERNET_FLAG_NO_CACHE_WRITE value set.
lDistanceToMove
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.
pReserved
Reserved; must be NULL.
dwMoveMethod
Starting point for the file pointer move. Can be one of the following values:
FILE_BEGIN | The starting point is zero or the beginning of the file. If FILE_BEGIN is specified, lDistanceToMove 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. This method fails if the content length is unknown.
dwContext
Reserved; must be zero.

This function cannot be used once the end of file has been reached by InternetReadFile.

For HINTERNET handles created by HttpOpenRequest and sent by HttpSendRequestEx, a call to HttpEndRequest must be made on the handle before InternetSetFilePointer is used.

InternetSetFilePointer cannot be used reliably if the content length is unknown and with chunked transfers.


InternetSetOption

BOOL InternetSetOption(
    IN HINTERNET hInternet,
    IN DWORD dwOption,
    IN LPVOID lpBuffer,
    IN DWORD dwBufferLength
);

Sets an Internet option.

  • Returns TRUE if successful, or FALSE otherwise. To get a specific error message, call GetLastError.
hInternet
Internet handle on which to set information.
dwOption
Internet option to set. Can be one of the Option Flags values.
lpBuffer
Address of a buffer that contains the option setting.
dwBufferLength
Length of the lpBuffer buffer.

See also FtpGetFile, FtpPutFile, InternetConnect, InternetOpen, InternetQueryOption


InternetSetOptionEx InternetSetOptionEx *
  * Previous Topic: InternetSetOption
  * Next Topic: InternetSetStatusCallback

InternetSetOptionEx

Not currently implemented.


InternetSetStatusCallback

INTERNET_STATUS_CALLBACK InternetSetStatusCallback(
    IN HINTERNET hInternet,
    IN INTERNET_STATUS_CALLBACK lpfnInternetCallback
);

Sets up a callback function that Win32 Internet functions can call as progress is made during an operation.

  • Returns the previously defined status callback function if successful, NULL if there was no previously defined status callback function, or INTERNET_INVALID_STATUS_CALLBACK if the callback function is not valid.
hInternet
Handle for which the callback is to be set.
lpfnInternetCallback
Address of the callback function to call when progress is made, or to return NULL to remove the existing callback function. For more information about the callback function, see INTERNET_STATUS_CALLBACK.

Both synchronous and asynchronous functions use the callback function to indicate the progress of the request, such as resolving a name, connecting to a server, and so on. The callback function is required for an asynchronous operation. The asynchronous request will call back to the application with INTERNET_STATUS_REQUEST_COMPLETE to indicate the request has been completed.

A callback function can be set on any handle, and is inherited by derived handles. A callback function can be changed using InternetSetStatusCallback, providing there are no pending requests that need to use the previous callback value. Note, however, that changing the callback function on a handle does not change the callbacks on derived handles, such as that returned by InternetConnect. You must change the callback function at each level.

Many of the Win32 Internet functions perform several operations on the network. Each operation can take time to complete, and each can fail.

It is sometimes desirable to display status information during a long-term operation. You can display status information by setting up an Internet status callback function that cannot be removed as long as any callbacks or any asynchronous functions are pending.

After initiating InternetSetStatusCallback, the callback function can be accessed from within any Win32 Internet function for monitoring time-intensive network operations.


InternetTimeFromSystemTime

BOOL InternetTimeFromSystemTime(
    IN  CONST SYSTEMTIME *pst,
    IN  DWORD dwRFC,
    OUT LPSTR lpszTime,
    IN  DWORD cbTime
);

Formats a date and time according to the specified RFC format (as specified in the HTTP version 1.0 specification).

  • Returns TRUE if the function succeeds, or FALSE otherwise. To get extended error information, call GetLastError.
pst
Address of a SYSTEMTIME structure that contains the date and time to format.
dwRFC
RFC format used. Currently, the only valid format is INTERNET_RFC1123_FORMAT.
lpszTime
Address of a buffer that receives the formatted date and time. The buffer should be of size INTERNET_RFC1123_BUFSIZE.
cbTime
Size, in bytes, of the lpszTime buffer.


InternetTimeToSystemTime

BOOL InternetTimeToSystemTime(
    IN LPCSTR lpszTime,
    OUT SYSTEMTIME *pst,
    IN DWORD dwReserved
);

Takes an HTTP time/date string and converts it to a SYSTEMTIME structure.

  • Returns TRUE if the string was converted, or FALSE otherwise. To get extended error information, call GetLastError.
lpszTime
Address of a null-terminated date/time string to convert.
pst
Address of the pointer to the converted time.
dwReserved
Reserved; must be zero.


InternetUnlockRequestFile

BOOL InternetUnlockRequestFile (
    IN HANDLE hLockHandle
);

Unlocks a file that was locked using InternetLockRequestFile.

  • Returns TRUE if successful, or FALSE otherwise. To get a specific error message, use GetLastError.
hLockHandle
Lock request handle that was returned by InternetLockRequestFile.


InternetWriteFile

BOOL InternetWriteFile(
    IN HINTERNET hFile,
    IN LPCVOID lpBuffer,
    IN DWORD dwNumberOfBytesToWrite,
    OUT LPDWORD lpdwNumberOfBytesWritten
);

Writes data to an open Internet file.

  • Returns TRUE if the function succeeds, or FALSE otherwise. To get extended error information, call GetLastError. An application can also use InternetGetLastResponseInfo when necessary.
hFile
Valid handle returned from a previous call to FtpOpenFile or an HINTERNET handle sent by HttpSendRequestEx.
lpBuffer
Address of a buffer that contains the data to be written to the file.
dwNumberOfBytesToWrite
Number of bytes to write to the file.
lpdwNumberOfBytesWritten
Address of a variable that receives the number of bytes written to the buffer. InternetWriteFile sets this value to zero before doing any work or error checking.

When the application is sending data, it must call InternetCloseHandle to end the data transfer.


ReadUrlCacheEntryStream

BOOL ReadUrlCacheEntryStream(
    IN HANDLE hUrlCacheStream,
    IN  DWORD dwLocation,
    IN OUT LPVOID lpBuffer,
    IN OUT LPDWORD lpdwLen,
    IN DWORD dwReserved
    );

Reads the cached data from a stream that has been opened using the RetrieveUrlCacheEntryStream function.

  • Returns TRUE if successful, or FALSE otherwise. To get extended error information, call GetLastError.
hUrlCacheStream
Handle that was returned by the RetrieveUrlCacheEntryStream function.
dwLocation
Offset to read from.
lpBuffer
Address of a buffer that receives the data.
lpdwLen
Address of a variable that specifies the length of the lpBuffer buffer. When the function returns, the variable contains the number of bytes copied to the buffer, or the required size of the buffer.
dwReserved
Reserved; must be zero.

If the buffer size is not sufficient, GetLastError returns ERROR_INSUFFICIENT_BUFFER, and sets lpdwLen to the size necessary to contain all the information.


RetrieveUrlCacheEntryFile

BOOL RetrieveUrlCacheEntryFile(
    IN LPCSTR lpszUrlName,
    OUT LPINTERNET_CACHE_ENTRY_INFO lpCacheEntryInfo,
    IN OUT LPDWORD lpdwCacheEntryInfoBufferSize,
    IN DWORD dwReserved
    );

Retrieves a cache entry from the cache in the form of a file.

  • Returns TRUE if successful, or FALSE otherwise. To get extended error information, call GetLastError. Possible error values include:
    ERROR_FILE_NOT_FOUND | The cache entry specified by the source name is not found in the cache storage.
    ERROR_INSUFFICIENT_BUFFER | The size of the lpCacheEntryInfo buffer as specified by lpdwCacheEntryInfoBufferSize is not sufficient to contain all the information. The value returned in lpdwCacheEntryInfoBufferSize indicates the buffer size necessary to get all the information.
lpszUrlName
Source name of the cache entry. This must be a unique name. The name string should not contain any escape characters.
lpCacheEntryInfo
Address of a cache entry information buffer. If the buffer is not sufficient to accommodate all the information associated with the URL, one or more of the embedded pointers will be NULL.
lpdwCacheEntryInfoBufferSize
Address of a variable that specifies the size of the lpCacheEntryInfo buffer. When the function returns, the variable contains the size of the actual buffer used or required. The caller should check the return value in this parameter. If the return size is less than or equal to the size passed in, all the relevant data has been returned.
dwReserved
Reserved; must be zero.

RetrieveUrlCacheEntryFile does not do any URL parsing, so a URL containing an anchor (#) will not be found in the cache, even if the resource is cached. For example, if the URL, http://example.com/example.htm#sample, was passed, the function would return ERROR_FILE_NOT_FOUND even if http://example.com/example.htm is in the cache.

If an extension was provided while calling CommitUrlCacheEntry, the file will have the specified extension. If the entry is not available in the cache, this function returns ERROR_FILE_NOT_FOUND; otherwise, it returns the name of the local file. The caller is given only read permission to the local file, so the caller should not attempt to write or delete the file.

The file is locked for the caller when it is retrieved; the caller should unlock the file after it has been used up. The cache manager automatically unlocks the locked files after a certain interval. While the file is locked, the cache manager will not remove the file from the cache. It is important to note that this function may be efficient or expensive, depending on the internal implementation of the cache. For instance, if the URL data is stored in a packed file that contains data for other URLs, the cache will make a copy of the data to a file in a temporary directory maintained by the cache. The cache will eventually delete the copy. It is recommended that this function be used only in situations where a file name is needed to launch an application. RetrieveUrlCacheEntryStream and associated stream functions should be used in most cases.


RetrieveUrlCacheEntryStream

HANDLE RetrieveUrlCacheEntryStream(
    IN LPCSTR lpszUrlName,
    OUT LPINTERNET_CACHE_ENTRY_INFO lpCacheEntryInfo,
    IN OUT LPDWORD lpdwCacheEntryInfoBufferSize,
    IN BOOL fRandomRead,
    IN DWORD dwReserved
    );

Provides the most efficient and implementation-independent way of accessing the cache data.

  • Returns a valid handle for use in the ReadUrlCacheEntryStream and UnlockUrlCacheEntryStream functions if successful, or NULL otherwise. To get extended error information, call GetLastError. Possible error values include:
    ERROR_FILE_NOT_FOUND | The cache entry specified by the source name is not found in the cache storage.
    ERROR_INSUFFICIENT_BUFFER | The size of lpCacheEntryInfo as specified by lpdwCacheEntryInfoBufferSize is not sufficient to contain all the information. The value returned in lpdwCacheEntryInfoBufferSize indicates the buffer size necessary to contain all the information.
lpszUrlName
Address of a string that contains the source name of the cache entry. This must be a unique name. The name string should not contain any escape characters.
lpCacheEntryInfo
Address of an INTERNET_CACHE_ENTRY_INFO structure that receives information about the cache entry.
lpdwCacheEntryInfoBufferSize
Address of a variable that specifies the size of the lpCacheEntryInfo buffer. When the function returns, the variable receives the number of bytes copied to the buffer, or the required size of the buffer.
fRandomRead
Flag to indicate whether the stream is open for random access. Set the flag to TRUE to open the stream for random access.
dwReserved
Reserved; must be zero.

RetrieveUrlCacheEntryStream does not do any URL parsing, so a URL containing an anchor (#) will not be found in the cache, even if the resource is cached. For example, if the URL, http://example.com/example.htm#sample, was passed, the function would return ERROR_FILE_NOT_FOUND even if http://example.com/example.htm is in the cache.

Cache clients that do not need URL data in the form of a file should use this function to access the data for a particular URL.


SetUrlCacheEntryGroup

BOOLAPI SetUrlCacheEntryGroup (
    IN LPCSTR lpszUrlName,
    IN DWORD dwFlags,
    IN GROUPID GroupId,
    IN LPBYTE pbGroupAttributes,
    IN DWORD cbGroupAttributes,
    IN LPVOID lpReserved
);

Adds entries to or removes entries from a cache group.

  • Returns TRUE if successful, or FALSE otherwise.
lpszUrlName
String value that contains the URL of the cached resource.
dwFlags
DWORD value that determines whether the entry is added to or removed from a cache group. Can be one of the following values:
INTERNET_CACHE_GROUP_ADD | Adds the cache entry to the cache group.
INTERNET_CACHE_GROUP_REMOVE | Removes the entry from the cache group.
GroupId
GROUPID value that indicates the cache group that the entry will be added to or removed from.
pbGroupAttributes
Must be set to NULL.
cbGroupAttributes
Must be set to zero.
lpReserved
Reserved. Must be set to NULL.

A cache entry can belong to more than one cache group.


SetUrlCacheEntryInfo

BOOL SetUrlCacheEntryInfo(
    IN LPCSTR lpszUrlName,
    IN LPINTERNET_CACHE_ENTRY_INFO lpCacheEntryInfo,
    IN DWORD dwFieldControl
);

Sets the specified members of the INTERNET_CACHE_ENTRY_INFO structure.

  • Returns TRUE if successful, or FALSE otherwise. To get extended error information, call GetLastError. Possible error values include:
    ERROR_FILE_NOT_FOUND | The specified cache entry is not found in the cache.
    ERROR_INVALID_PARAMETER | The value(s) to be set is invalid.
lpszUrlName
Address of a string that contains the name of the cache entry. The name string should not contain any escape characters.
lpCacheEntryInfo
Address of an INTERNET_CACHE_ENTRY_INFO structure containing the values to be assigned to the cache entry designated by lpszUrlName.
dwFieldControl
Bitmask that indicates the members that are to be set. Can be a combination of the following values:
CACHE_ENTRY_ACCTIME_FC | Sets the last access time.
CACHE_ENTRY_ATTRIBUTE_FC | Sets the cache entry type.
CACHE_ENTRY_EXEMPT_DELTA_FC | Sets the exempt delta.
CACHE_ENTRY_EXPTIME_FC | Sets the expire time.
CACHE_ENTRY_HEADERINFO_FC | Sets the header info.
CACHE_ENTRY_HITRATE_FC | Sets the hit rate.
CACHE_ENTRY_MODTIME_FC | Sets the last modified time.
CACHE_ENTRY_SYNCTIME_FC | Sets the last sync time.


UnlockUrlCacheEntryFile

BOOL UnlockUrlCacheEntryFile(
    IN LPCSTR lpszUrlName,
    IN DWORD dwReserved
    );

Unlocks the cache entry that was locked while the file was retrieved for use from the cache.

  • Returns TRUE if successful, or FALSE otherwise. To get extended error information, call GetLastError. ERROR_FILE_NOT_FOUND indicates that the cache entry specified by the source name is not found in the cache storage.
lpszUrlName
Address of a string that contains the source name of the cache entry that is being unlocked. The name string should not contain any escape characters.
dwReserved
Reserved; must be zero.

The application should not access the file after calling this function.

When this function returns, the cache manager is free to delete the cache entry.


UnlockUrlCacheEntryStream

BOOL UnlockUrlCacheEntryStream(
    IN HANDLE hUrlCacheStream,
    IN DWORD dwReserved
);

Closes the stream that has been retrieved using the RetrieveUrlCacheEntryStream function.

  • Returns TRUE if successful, or FALSE otherwise. To get extended error information, call GetLastError.
hUrlCacheStream
Handle that was returned by the RetrieveUrlCacheEntryStream function.
dwReserved
Reserved; must be zero.


Uniform Resource Locator (URL) Functions

The URL functions deal with URL manipulation and access. These functions operate in a task-oriented manner. The content and format of the URL that is being used by the function is not verified. Usage of these functions should be tracked by the calling application to ensure that the data is in the format intended. For example, InternetCanonicalizeUrl would convert the unsafe character "%" into the escape sequence "%25" when using no flags. If InternetCanonicalizeUrl is used on the canonicalized URL, the escape sequence "%25" would be converted into the escape sequence "%2525", which would not work properly.
InternetCanonicalizeUrl
InternetCombineUrl
InternetCrackUrl
InternetCreateUrl
InternetOpenUrl


InternetConnectUrl

InternetConnectUrl (hInternet, lpszUrl, dwFlags, dwContext) \
    InternetConnect(hInternet, lpszUrl, INTERNET_INVALID_PORT_NUMBER, NULL, NULL,
        INTERNET_SERVICE_URL, dwFlags, dwContext)

Allows the use of a URL instead of supplying the component parts to InternetConnect

hInternet
HINTERNET handle returned by InternetOpen.
lpszUrl
String value containing the URL to connect to.
dwFlags
Flags specific to the service used. When the value of dwService is INTERNET_SERVICE_FTP, INTERNET_FLAG_PASSIVE causes the application to use passive FTP semantics.
dwContext
Application-defined value that is used to identify the application context for the returned handle in callbacks.


Macros

This section describes the macros included with the Win32 Internet functions.
InternetConnectUrl


Appendix A: HINTERNET Handles

This section contains information about the handles that are used by the Win32 Internet functions and the hierarchy that they work in.

About HINTERNET Handles

The handles that are created and used by the Win32 Internet functions are called HINTERNETs. The Win32 Internet functions return HINTERNET handles that are not interchangeable with the base Win32 handles, so they cannot be used with Win32 functions such as ReadFile or CloseHandle. Similarly, base Win32 handles cannot be used with the Win32 Internet functions. For example, a handle returned by CreateFile cannot be passed to InternetReadFile.

The InternetCloseHandle function closes handles of type HINTERNET. Note that handle values are recycled quickly; therefore, if a handle is closed and a new handle is generated immediately, there is a good chance that the new handle will have the same value as the handle just closed.

Handle Hierarchy

The HINTERNET handles are maintained in a tree hierarchy. The handle returned by the InternetOpen function is the root node. Handles returned by the InternetConnect function occupy the next level. Handles returned by the FtpFindFirstFile, FtpOpenFile, GopherFindFirstFile, GopherOpenFile, and HttpOpenRequest functions are the leaf nodes.

The following diagram illustrates the hierarchy of the HINTERNET handles. Each box in the diagram represents a Win32 Internet function that returns an HINTERNET handle.

Functions That Create Handles

At the top level is the InternetOpen function, which creates the root HINTERNET handle. The next level contains the InternetOpenUrl and InternetConnect functions. The functions that use the HINTERNET handle returned by InternetConnect make up the last level.

The following diagram shows the functions that are dependent on the HINTERNET handle created by InternetOpenUrl. The shaded boxes represent functions that return HINTERNET handles, while the plain boxes represent functions that use the HINTERNET handle created by the associated function.

Functions That Use The InternetOpenUrl Handle

InternetQueryDataAvailable, InternetReadFile, and InternetSetFilePointer use the HINTERNET handle created by InternetOpenUrl.

FTP hierarchy

The following diagram shows the FTP functions that are dependent on the FTP session HINTERNET handle returned by InternetConnect. The shaded boxes represent functions that return HINTERNET handles, while the plain boxes represent functions that use the HINTERNET handle created by the function on which they depend.

Functions That Use The FTP Session Handle

FtpCreateDirectory, FtpDeleteFile, FtpGetCurrentDirectory, FtpGetFile, FtpPutFile, FtpRemoveDirectory, FtpRenameFile, and FtpSetCurrentDirectory all use the HINTERNET handle created by InternetConnect.

The following diagram shows the two FTP functions that return HINTERNET handles and the functions that are dependent on the HINTERNET handles created by them. The shaded boxes represent functions that return HINTERNET handles, while the plain boxes represent functions that use the HINTERNET handle created by the function on which they depend.

Functions that use the handle from FtpOpen and FtpFindFirstFile

InternetFindNextFile is dependent on the HINTERNET handle created by FtpFindFirstFile, while InternetReadFile and InternetWriteFile use the HINTERNET handle created by FtpOpenFile.

Gopher hierarchy

The following diagram shows the Win32 Internet functions used for the Gopher protocol. The shaded boxes represent functions that return HINTERNET handles, while the plain boxes represent functions that use the HINTERNET handle created by the function on which they depend.

Gopher Related Functions

GopherGetAttribute is dependent on the HINTERNET handle created by InternetConnect. InternetFindNextFile uses the HINTERNET handle created by GopherFindFirstFile. The handle created by GopherOpenFile is used by InternetReadFile and InternetQueryDataAvailable.

HTTP hierarchy

The following diagram shows the relationships of the Win32 Internet functions that are used for the HTTP protocol. The shaded boxes represent functions that return HINTERNET handles, while the plain boxes represent functions that use the HINTERNET handle created by the function on which they depend.

Functions that use the handle from HttpOpenRequest

HttpAddRequestHeaders, HttpQueryInfo, HttpSendRequest, HttpSendRequestEx, and InternetErrorDlg are dependent on the HINTERNET handle created by HttpOpenRequest.

The following diagram shows the Win32 Internet functions that use the HINTERNET handle created by HttpOpenRequest after it is sent by HttpSendRequest. The shaded boxes represent functions that return HINTERNET handles, while the plain boxes represent functions that use the HINTERNET handle created by the function on which they depend.

Functions that use the handle after HttpSendRequest

After HttpSendRequest has been used on the handle returned by HttpOpenRequest, InternetQueryDataAvailable, InternetReadFile, and InternetSetFilePointer can be used on that handle.

Functions that use the handle after HttpSendRequestEx

After HttpSendRequestEx has been used on the handle returned by HttpOpenRequest, HttpEndRequest, InternetReadFileEx, and InternetWriteFile can be used on that handle. After HttpEndRequest has been used, InternetQueryDataAvailable, InternetReadFile, and InternetSetFilePointer can be used on that handle.


Appendix B: Using Buffers

Functions that return strings contain an input lpszBuffer parameter and an lpdwBufferLength parameter. Although lpszBuffer can be NULL, lpdwBufferLength must be a valid pointer to a double-word (DWORD) variable. If the input buffer pointed to by lpszBuffer is either too small to hold the output string or NULL, the function returns a failure indication and GetLastError returns ERROR_INSUFFICIENT_BUFFER. The variable pointed to by lpdwBufferLength contains a number that represents the number of bytes the function requires to return the requested string, including the NULL terminator. The application should allocate a buffer of this size, set the variable pointed to by lpdwBufferLength to this value, and resubmit the request. If the buffer size is sufficient to receive the requested string, the string is copied to the output buffer with a NULL terminator and the function returns a success indication. The variable pointed to by lpdwBufferLength now contains the number of characters stored in the buffer, excluding the NULL terminator.


Appendix C: Handling Errors

The Win32 function GetLastError is used to get the error code for all of the Win32 Internet functions. If ERROR_INTERNET_EXTENDED_ERROR is returned, there is a string or buffer containing a verbose error message. Call the InternetGetLastResponseInfo function to retrieve the extended error text.

To get the error text for a normal Win32 Internet error, use the Win32 function FormatMessage, and pass it an HMODULE handle to the Wininet.dll using the Win32 function GetModuleHandle.

The following is an example of a function to handle Win32 Internet function errors.

BOOL WINAPI ErrorOut ( HWND hErr, DWORD dError, TCHAR * szCallFunc)
{
TCHAR szTemp[356] = "", *szBuffer=NULL, *szBufferFinal = NULL;
        DWORD  dwIntError , dwLength = 0;
        char strName[256]="";

        FormatMessage(FORMAT_MESSAGE_FROM_HMODULE,
        GetModuleHandle("wininet.dll"),dError,0,
(LPSTR)strName,256,NULL);
wsprintf (szTemp,  "%s error code: %d\nMessage: %s\n",
szCallFunc, dError, strName);
        int response;

        if (dError == ERROR_INTERNET_EXTENDED_ERROR)
        {
                InternetGetLastResponseInfo (&dwIntError, NULL, &dwLength);
                if (dwLength)
                {
                        if ( !(szBuffer = (TCHAR *) LocalAlloc ( LPTR,  dwLength) ) )
                        {
                                lstrcat (szTemp, TEXT ( "Unable to allocate memory to display
                                         Internet error code. Error code: ") );
                                lstrcat (szTemp, TEXT (_itoa (GetLastError(), szBuffer, 10)  ) );
                                lstrcat (szTemp, TEXT ("\n") );
                                response = MessageBox(hErr, (LPSTR)szTemp,"Error",MB_OK);
                                return FALSE;
                        }
                        if (!InternetGetLastResponseInfo (&dwIntError, (LPTSTR) szBuffer,
                            &dwLength))
                        {
                                lstrcat (szTemp, TEXT ( "Unable to get Internet error. Error code: ") );
                                lstrcat (szTemp, TEXT (_itoa (GetLastError(), szBuffer, 10)  ) );
                                lstrcat (szTemp, TEXT ("\n") );
                                response = MessageBox(hErr, (LPSTR)szTemp,"Error",MB_OK);
                                return FALSE;
                        }
                        if ( !(szBufferFinal = (TCHAR *) LocalAlloc ( LPTR,
                               (strlen (szBuffer) +strlen (szTemp) + 1)  ) )  )
                        {
                                lstrcat (szTemp, TEXT ( "Unable to allocate memory. Error code: ") );
                                lstrcat (szTemp, TEXT (_itoa (GetLastError(), szBuffer, 10)  ) );
                                lstrcat (szTemp, TEXT ("\n") );
                                response = MessageBox(hErr, (LPSTR)szTemp,"Error",MB_OK);
                                return FALSE;
                        }
                        lstrcpy (szBufferFinal, szTemp);
                        lstrcat (szBufferFinal, szBuffer);
                        LocalFree (szBuffer);
                        response = MessageBox(hErr, (LPSTR)szBufferFinal,"Error",MB_OK);
                        LocalFree (szBufferFinal);
                }
        }
        else
    {
                response = MessageBox(hErr, (LPSTR)szTemp,"Error",MB_OK);
        }

    return response;
}


Handling Authentication

Some proxies and servers require authentication before allowing access to resources on the Internet. The Win32 Internet functions support server and proxy authentication for HTTP sessions. Authentication of Gopher and FTP servers must be handled by InternetConnect. Currently, there is no support available for FTP gateway authentication.

About HTTP Authentication

If authentication is required, the client program receives a status code of 401 (if the server requires authentication) or 407 (if the proxy requires authentication). Along with the status code, the proxy or server sends one or more authenticate response headers—Proxy-Authenticate (for proxy authentication) or WWW-Authenticate (for server authentication).

Each authenticate response header contains an available authentication scheme and a realm. If multiple authentication schemes are supported, the server returns multiple authenticate response headers. The realm value is case sensitive and defines a protection space on the proxy or server. For example, the header "WWW-Authenticate: Basic Realm="example"" would be an example of a header returned when server authentication is needed.

The client program that sent the request can authenticate itself by including an Authorization header field with the request. The Authorization header would contain the authentication scheme and the appropriate response required by that scheme. For example, the header "Authorization: Basic <username:password>" would be added to the request and resent to the server if the client received the authenticate response header "WWW-Authenticate: Basic Realm="example"".

There are two general kinds of authentication schemes:

  • Basic authentication scheme, where the user name and password are sent over in cleartext to the server.
  • Challenge-response schemes, which allows for a challenge-response format.

The Basic authentication scheme is based on the model that a client must authenticate itself with a user name and password for each realm. The server services the request if it is resent with an Authorization header that includes a valid user name and password.

Challenge-response schemes allow for more secure authentication. If a request requires authentication using a challenge-response scheme, the appropriate status code and Authenticate headers are returned to the client. The client then needs to resend the request with a negotiate. The server would return an appropriate status code with a challenge, and the client would then need to resend the request with the proper response to get the requested service.

The following table contains the authentication schemes that are used with the Win32 Internet functions, the authentication type, the DLLs that support them, and a description of the scheme.
Scheme | Type | DLL | Description
Basic (cleartext) | basic | Wininet.dll | Uses a base64 encoded string that contains the user name and password.
NT LAN Manager (NTLM) | challenge-response | Winsspi.dll | A challenge-response scheme that bases the challenge on the user name.
Microsoft Network (MSN) | challenge-response | Msnsspc.dll | The Microsoft Network's authentication scheme.
Distributed Password Authentication (DPA) | challenge-response | Msapsspc.dll | Similar to MSN authentication and will also be used by the Microsoft Network.
Remote Passphrase Authentication (RPA) | CompuServe | Rpawinet.dll, da.dll | CompuServe's authentication scheme. For more information, see http://www.compuserve.com/rpa/rpadoco.htm.

For anything other than Basic authentication, the registry keys must be set up in addition to installing the appropriate DLL(s). For more information on setting these registry keys, see Registering authentication keys.

If authentication is required, the INTERNET_FLAG_KEEP_CONNECTION flag should be used in the call to HttpOpenRequest. The INTERNET_FLAG_KEEP_CONNECTION flag is required for NTLM and other types of authentication in order to maintain the connection while completing the authentication process. If the connection is not maintained, the authentication process must be restarted with the proxy or server.

The Win32 Internet functions InternetOpenUrl and HttpSendRequest complete successfully even when authentication is required. The difference is, the information returned in the header files and InternetReadFile would receive an HTML page informing the user of the status code.

Registering authentication keys

INTERNET_OPEN_TYPE_PRECONFIG looks at the registry values ProxyEnable, ProxyServer, and ProxyOverride. These values are located under HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings.

For authentication schemes other than Basic, a key needs to be added to the registry under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Security. A string value, DLLFile, should contain the name of the DLL that supports the authentication scheme, and a DWORD value, Flags, should be set with the appropriate value. The following list shows the possible values for the Flags value.

PLUGIN_AUTH_FLAGS_UNIQUE_CONTEXT_PER_TCPIP (value=0x01)
Each TCP/IP socket will contain a different context. Otherwise, a new context will be passed for each realm or block URL template.
PLUGIN_AUTH_FLAGS_CAN_HANDLE_UI (value=0x02)
This DLL can handle its own user input.
PLUGIN_AUTH_FLAGS_CAN_HANDLE_NO_PASSWD (value=0x04)
This DLL might be capable of doing an authentication without prompting the user for a password.
PLUGIN_AUTH_FLAGS_NO_REALM (value=0x08)
This DLL does not use a standard HTTP realm string. Any data that appears to be a realm will be scheme-specific information.
PLUGIN_AUTH_FLAGS_KEEP_ALIVE_NOT_REQUIRED (value=0x10)
This DLL does not require a persistent connection for its challenge-response sequence.

For example, to add NTLM authentication, the key NTLM would need to be added to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Security. Under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Security\NTLM, the string value, DLLFile, and a DWORD value, Flags, would need to be added. DLLFile would need to be set to winsspi.dll, and Flags would need to be set to 0x08.

Server authentication

When a server receives a request that requires authentication, the server returns a 401 status code message. In that message, the server should include one or more WWW-Authenticate response headers. These headers include the authentication methods the server has available. The Win32 Internet functions pick the first method they recognize.

Basic authentication provides weak security unless the channel is first link-encrypted with SSL or PCT.

The InternetErrorDlg function can be used to obtain the user name and password information from the user, or a customized user interface can be designed to obtain the information.

A custom interface can use the InternetSetOption function to set the INTERNET_OPTION_PASSWORD and INTERNET_OPTION_USERNAME values and then resend the request to the server.

Proxy authentication

When a client attempts to use a proxy that requires authentication, the proxy returns a 407 status code message to the client. In that message, the proxy should include one or more Proxy-Authenticate response headers. These headers include the authentication methods available from the proxy. The Win32 Internet functions pick the first method they recognize.

The InternetErrorDlg function can be used to obtain the user name and password information from the user, or a customized user interface can be designed.

A custom interface can use the InternetSetOption function to set the INTERNET_OPTION_PROXY_PASSWORD and INTERNET_OPTION_PROXY_USERNAME values and then resend the request to the proxy.

If no proxy user name and password are set, the Win32 Internet functions attempt to use the user name and password for the server. This behavior allows clients to implement the same customized user interface that is used to handle server authentication.

Handling HTTP Authentication

HTTP authentication can be handled with either InternetErrorDlg or a customized function that uses InternetSetOption or adds its own authentication headers. InternetErrorDlg can examine the headers associated with an HINTERNET handle to find hidden errors, such as status codes from a proxy or server. InternetSetOption can be used to set the user name and password for the proxy and server. For MSN and DPA authentication, InternetErrorDlg must be used to set the user name and password.

For any customized function that adds its own WWW-Authenticate or Proxy-Authenticate headers, the INTERNET_FLAG_NO_AUTH flag should be set to disable WinInet's authentication.

The following example shows how InternetErrorDlg can be used to handle HTTP authentication.

HINTERNET hOpenHandle,  hConnectHandle, hResourceHandle;
DWORD dwError, dwErrorCode;

hOpenHandle = InternetOpen("Example", INTERNET_OPEN_TYPE_PRECONFIG,
                           NULL, NULL, 0);

hConnectHandle = InternetConnect(hOpenHandle, "www.server.com",
                                 INTERNET_INVALID_PORT_NUMBER, NULL,
                                 NULL, INTERNET_SERVICE_HTTP,0,0);

hResourceHandle = HttpOpenRequest(hConnectHandle, "GET", "/premium/default.htm",
                                  NULL, NULL, NULL,
                                  INTERNET_FLAG_KEEP_CONNECTION, 0);

resend:

HttpSendRequest(hResourceHandle, NULL, 0, NULL, 0);

//  dwErrorCode stores the error code associated with the call to HttpSendRequest.

dwErrorCode = hResourceHandle ? ERROR_SUCCESS : GetLastError();

dwError = InternetErrorDlg(hwnd, hResourceHandle, dwErrorCode,
                           FLAGS_ERROR_UI_FILTER_FOR_ERRORS |
                           FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS |
                           FLAGS_ERROR_UI_FLAGS_GENERATE_DATA,
                           NULL);

if (dwError == ERROR_INTERNET_FORCE_RETRY)
    goto resend;

//  Insert code to read the information from the hResourceHandle at this point.

In the example, dwErrorCode is used to store any errors associated with the call to HttpSendRequest. HttpSendRequest will complete successfully, even if the proxy or server requires authentication. When the FLAGS_ERROR_UI_FILTER_FOR_ERRORS flag is passed to InternetErrorDlg, the function checks the headers for any hidden errors. These hidden errors would include any requests for authentication. InternetErrorDlg displays the appropriate dialog box to prompt the user for the necessary information. The FLAGS_ERROR_UI_FLAGS_GENERATE_DATA and FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS flags should also be passed to InternetErrorDlg, so that the function constructs the appropriate data structure for the error and stores the results of the dialog box in the HINTERNET handle.

The following example shows how authentication could be handled using InternetSetOption.

HINTERNET hOpenHandle,  hResourceHandle;
DWORD dwError, dwStatus;
DWORD dwStatusSize = sizeof(dwStatus);
char strUsername[64], strPassword[64];

hOpenHandle = InternetOpen("Example", INTERNET_OPEN_TYPE_PRECONFIG,
                           NULL, NULL, 0);
hConnectHandle = InternetConnect(hOpenHandle, "www.server.com",
                                 INTERNET_INVALID_PORT_NUMBER, NULL,
                                 NULL, INTERNET_SERVICE_HTTP,0,0);

hResourceHandle = HttpOpenRequest(hConnectHandle, "GET", "/premium/default.htm",
                                  NULL, NULL, NULL,
                                  INTERNET_FLAG_KEEP_CONNECTION, 0);

resend:

HttpSendRequest(hResourceHandle, NULL, 0, NULL, 0);

HttpQueryInfo(hResourceHandle, HTTP_QUERY_FLAG_NUMBER |
              HTTP_QUERY_STATUS_CODE, &dwStatus, &dwStatusSize, NULL);

switch (dwStatus)
{
    case HTTP_STATUS_PROXY_AUTH_REQ:    //Proxy Authentication Required
        // Insert code to set strUsername and strPassword
        InternetSetOption(hResourceHandle, INTERNET_OPTION_PROXY_USERNAME,
                          strUsername, strlen(strUsername)+1);
        InternetSetOption(hResourceHandle, INTERNET_OPTION_PROXY_PASSWORD,
                          strPassword, strlen(strPassword)+1);
        break;
    case HTTP_STATUS_DENIED:     //Server Authentication Required
        // Insert code to set strUsername and strPassword
        InternetSetOption(hResourceHandle, INTERNET_OPTION_USERNAME,
                          strUsername, strlen(strUsername)+1);
        InternetSetOption(hResourceHandle, INTERNET_OPTION_PASSWORD,
                          strPassword, strlen(strPassword)+1);
        break;
}

//  Insert code to read the information from the hResourceHandle at this point.


Caching

The Win32 Internet functions have simple, yet flexible, built-in caching support. Any data retrieved from the network is cached on the hard disk and retrieved for subsequent requests. The application using the Win32 Internet functions can control the caching on each request. For HTTP requests from the server, most headers received are also cached. When an HTTP request is satisfied from the cache, the cached headers are also returned to the caller. This makes data download from Win32 Internet functions seamless, whether it is coming from the cache or from the network.

Unlike previous versions of the Win32 Internet functions, the current and future versions do not have an upper limit on the cache entry size. Applications must properly allocate a buffer in order to get the desired results when using the persistent URL caching functions. For more information, see Appendix B: Using Buffers.

Using Flags to Control Caching

The Win32 Internet function flags allow an application to control when and how it uses the cache. These flags can be used alone or in combination with the dwFlags parameter in functions that access information or resources on the Internet. The Win32 Internet functions store all data downloaded from the Internet by default.

The following flags can be used with the Win32 Internet functions to control caching:
INTERNET_FLAG_DONT_CACHE | Does not cache the data, either locally or in any gateways. Identical to the preferred value, INTERNET_FLAG_NO_CACHE_WRITE.
INTERNET_FLAG_HYPERLINK | Forces the application to reload a resource if no expire time and no last-modified time was returned when the resource was stored in the cache.
INTERNET_FLAG_MAKE_PERSISTENT | No longer supported.
INTERNET_FLAG_MUST_CACHE_REQUEST | Causes a temporary file to be created if the file cannot be cached. Identical to the preferred value, INTERNET_FLAG_NEED_FILE.
INTERNET_FLAG_NEED_FILE | Causes a temporary file to be created if the file cannot be cached.
INTERNET_FLAG_NO_CACHE_WRITE | Rejects any attempt by the function to store data downloaded from the Internet in the cache. This flag is necessary if the application does not want any downloaded resources to be stored locally.
INTERNET_FLAG_OFFLINE | Prevents the application from making requests to the network. All requests are resolved using the resources stored in the cache. If the resource is not in the cache, a suitable error, such as ERROR_FILE_NOT_FOUND, is returned.
INTERNET_FLAG_RELOAD | Forces the function to retrieve the requested resource directly from the Internet. The information that is downloaded is stored in the cache.
INTERNET_FLAG_RESYNCHRONIZE | Causes an application to perform a conditional download of the resource from the Internet. If the version stored in the cache is current, the information is downloaded from the cache. Otherwise, the information is reloaded from the server.

Persistent Caching Functions

Clients that need persistent caching services use the persistent caching functions to allow their applications to save data in the local file system for subsequent use, such as in situations where a low-bandwidth link limits access to the data, or the access is not available at all. The calling program that inserts data into the persistent cache assigns a source name that is used to perform operations, including retrieving, setting and getting some properties, and deleting the data.

The Win32 Internet function protocols use the cache functions to provide persistent caching and offline browsing. Unless the INTERNET_FLAG_NO_CACHE_WRITE flag explicitly specifies no caching, Win32 Internet functions cache all data downloaded from the network. The responses to POST data are not cached.

Using the Persistent URL Cache Functions

The following persistent URL cache functions allow an application to access and manipulate information stored in the cache.
Function | Description
CommitUrlCacheEntry | Caches data in the specified file in the cache storage and associates it with the given URL.
CreateUrlCacheEntry | Allocates the requested cache storage and creates a local file name for saving the cache entry corresponding to the source name.
CreateUrlCacheGroup | Generates a cache group identification.
DeleteUrlCacheEntry | Removes the file associated with the source name from the cache, if the file exists.
DeleteUrlCacheGroup | Releases a GROUPID and any associated state in the cache index file.
FindCloseUrlCache | Closes the specified enumeration handle.
FindFirstUrlCacheEntry | Begins the enumeration of the cache.
FindFirstUrlCacheEntryEx | Begins a filtered enumeration of the cache.
FindNextUrlCacheEntry | Retrieves the next entry in the cache.
FindNextUrlCacheEntryEx | Retrieves the next entry in a filtered cache enumeration.
GetUrlCacheEntryInfo | Retrieves information about a cache entry.
GetUrlCacheEntryInfoEx | Searches for the URL after translating any cached redirections that would be applied in offline mode by HttpSendRequest.
ReadUrlCacheEntryStream | Reads the cached data from a stream that has been opened using RetrieveUrlCacheEntryStream.
RetrieveUrlCacheEntryFile | Retrieves a cache entry from the cache in the form of a file.
RetrieveUrlCacheEntryStream | Provides the most efficient and implementation-independent way of accessing the cache data.
SetUrlCacheEntryGroup | Adds or removes entries from a cache group.
SetUrlCacheEntryInfo | Sets the specified members of the INTERNET_CACHE_ENTRY_INFO structure.
UnlockUrlCacheEntryFile | Unlocks the cache entry that was locked while the file was retrieved for use from the cache.
UnlockUrlCacheEntryStream | Closes the stream that has been retrieved using RetrieveUrlCacheEntryStream.

Enumerating the cache

The FindFirstUrlCacheEntry and FindNextUrlCacheEntry functions enumerate the information stored in the cache. FindFirstUrlCacheEntry starts the enumeration by taking a search pattern, a buffer, and a buffer size to create a handle and return the first cache entry. FindNextUrlCacheEntry takes the handle created by FindFirstUrlCacheEntry, a buffer, and a buffer size to return the next cache entry.

Both functions store an INTERNET_CACHE_ENTRY_INFO structure in the buffer. The size of this structure varies for each entry. If the buffer size passed to either function is insufficient, the function fails and GetLastError returns ERROR_INSUFFICIENT_BUFFER. The buffer size variable contains the buffer size that was needed to retrieve that cache entry. A buffer of the size indicated by the buffer size variable should be allocated, and the function should be called again with the new buffer.

The INTERNET_CACHE_ENTRY_INFO structure contains the structure size; URL of the cached information; local file name; cache entry type; use count; hit rate; size; last modified, expire, last access, and last synchronized times; header information and header information size; and file extension.

FindFirstUrlCacheEntry takes a search pattern, a buffer that stores the INTERNET_CACHE_ENTRY_INFO structure, and the buffer size. Currently, only the default search pattern, which returns all cache entries, is implemented.

After the cache is enumerated, the application should call FindCloseUrlCache to close the cache enumeration handle.

The following example displays the URL of each entry in the cache into a list box, IDC_CacheList. It uses MAX_CACHE_ENTRY_INFO_SIZE to initially allocate a buffer, since the Microsoft Internet Explorer 3.0 version of WinInet did not enumerate the cache properly otherwise. Internet Explorer 4.0 does enumerate the cache properly and there is no cache size limit. All applications that run on computers with the Internet Explorer 4.0 version of WinInet must allocate a buffer of the size required. For more information, see Appendix B: Using Buffers.

int WINAPI EnumerateCacheOld(HWND hX)
{
    DWORD dwEntrySize;
    LPINTERNET_CACHE_ENTRY_INFO lpCacheEntry;
    DWORD MAX_CACHE_ENTRY_INFO_SIZE=4096;
    HANDLE hCacheDir;
    int nCount=0;

    SendDlgItemMessage(hX,IDC_CacheList,LB_RESETCONTENT,0,0);

    SetCursor(LoadCursor(NULL,IDC_WAIT));

    dwEntrySize = MAX_CACHE_ENTRY_INFO_SIZE;
    lpCacheEntry = (LPINTERNET_CACHE_ENTRY_INFO) new char[dwEntrySize];
    lpCacheEntry->dwStructSize = dwEntrySize;

again:

    if (!(hCacheDir = FindFirstUrlCacheEntry(NULL,lpCacheEntry,&dwEntrySize)))
    {
        delete[]lpCacheEntry;
        switch(GetLastError())
        {
            case ERROR_NO_MORE_ITEMS:
                char tempout[80];
                sprintf(tempout,"The number of cache entries = %d \n",nCount);
                MessageBox(hX,tempout,"Cache Enumeration",MB_OK);
                FindCloseUrlCache(hCacheDir);
                SetCursor(LoadCursor(NULL,IDC_ARROW));
                return TRUE;
                break;
                        case ERROR_INSUFFICIENT_BUFFER:
                                lpCacheEntry = (LPINTERNET_CACHE_ENTRY_INFO)
                                                new char[dwEntrySize];
                                lpCacheEntry->dwStructSize = dwEntrySize;
                                goto again;
                                break;
                        default:
                                ErrorOut(hX,GetLastError(),"FindNextUrlCacheEntry Init");
                                FindCloseUrlCache(hCacheDir);
                                SetCursor(LoadCursor(NULL,IDC_ARROW));
                                return FALSE;
                }
        }

SendDlgItemMessage(hX,IDC_CacheList,LB_ADDSTRING,
                                0,(LPARAM)(lpCacheEntry->lpszSourceUrlName));
        nCount++;
        delete (lpCacheEntry);

        do
        {
                dwEntrySize = MAX_CACHE_ENTRY_INFO_SIZE;
                lpCacheEntry = (LPINTERNET_CACHE_ENTRY_INFO) new char[dwEntrySize];
                lpCacheEntry->dwStructSize = dwEntrySize;

retry:
                if (!FindNextUrlCacheEntry(hCacheDir,lpCacheEntry, &dwEntrySize))
                {
                        delete[]lpCacheEntry;
                        switch(GetLastError())
                        {
                                case ERROR_NO_MORE_ITEMS:
                                        char tempout[80];
                                        sprintf(tempout,"The number of cache entries =
                                                %d \n",nCount);
                                        MessageBox(hX,tempout,"Cache Enumeration",MB_OK);
                                        FindCloseUrlCache(hCacheDir);
                                        return TRUE;
                                        break;
                                case ERROR_INSUFFICIENT_BUFFER:
                                        lpCacheEntry = (LPINTERNET_CACHE_ENTRY_INFO)
                                                        new char[dwEntrySize];
                                        lpCacheEntry->dwStructSize = dwEntrySize;
                                        goto retry;
                                        break;
                                default:
                                        ErrorOut(hX,GetLastError(),"FindNextUrlCacheEntry Init");
                                        FindCloseUrlCache(hCacheDir);
                                        return FALSE;
                        }
                }

SendDlgItemMessage(hX,IDC_CacheList,LB_ADDSTRING,
                                        0,(LPARAM)(lpCacheEntry->lpszSourceUrlName));
                nCount++;
                delete[] lpCacheEntry;

        }
        while (TRUE);

        SetCursor(LoadCursor(NULL,IDC_ARROW));
        return TRUE;

}

Retrieving cache entry information

The GetUrlCacheEntryInfo function allows you to retrieve the INTERNET_CACHE_ENTRY_INFO structure for the specified URL. This structure contains the structure size; URL of the cached information; local file name; cache entry type; use count; hit rate; size; last modified, expire, last access, and last synchronized times; header information and header information size; and file extension.

GetUrlCacheEntryInfo accepts a URL, a buffer for an INTERNET_CACHE_ENTRY_INFO structure, and the buffer size. If the URL is found, the information is copied into the buffer. Otherwise, the function fails and GetLastError returns ERROR_FILE_NOT_FOUND. If the buffer size is insufficient to store the cache entry information, the function fails and GetLastError returns ERROR_INSUFFICIENT_BUFFER. The size required to retrieve the information is stored in the buffer size variable.

GetUrlCacheEntryInfo does not do any URL parsing, so a URL containing an anchor (#) will not be found in the cache, even if the resource is cached. For example, if the URL, http://example.com/example.htm#sample, was passed, the function would return ERROR_FILE_NOT_FOUND even if http://example.com/example.htm is in the cache.

The following example retrieves the cache entry information for the specified URL. The function then displays the header information in the IDC_CacheDump edit box.

int WINAPI GetCacheEntryInfo(HWND hX,LPSTR lpszUrl)
{
        DWORD dwEntrySize=0;
        LPINTERNET_CACHE_ENTRY_INFO lpCacheEntry;

        char strTemp[80];
        DWORD dwTemp;

        SetCursor(LoadCursor(NULL,IDC_WAIT));
        if (!GetUrlCacheEntryInfo(lpszUrl,NULL,&dwEntrySize))
        {
                if (GetLastError()!=ERROR_INSUFFICIENT_BUFFER)
                {
                        ErrorOut(hX,GetLastError(),"GetUrlCacheEntryInfo");
                        SetCursor(LoadCursor(NULL,IDC_ARROW));
                        return FALSE;
                }
                else
                        lpCacheEntry = (LPINTERNET_CACHE_ENTRY_INFO)
                                        new char[dwEntrySize];
        }
        else
                return FALSE;    //should not be successful w/ NULL buffer and 0 size.

        if (!GetUrlCacheEntryInfo(lpszUrl,lpCacheEntry,&dwEntrySize))
        {
                ErrorOut(hX,GetLastError(),"GetUrlCacheEntryInfo");
                SetCursor(LoadCursor(NULL,IDC_ARROW));
                return FALSE;
        }
        else
        {
                if ((lpCacheEntry->dwHeaderInfoSize)!=0)
                {
                        LPSTR(lpCacheEntry->lpHeaderInfo)[lpCacheEntry->dwHeaderInfoSize]='\0';
                        SetDlgItemText(hX,IDC_Headers,LPSTR(lpCacheEntry->lpHeaderInfo));
                }
                else
                {
                        SetDlgItemText(hX,IDC_Headers,"None");
                }

SetCursor(LoadCursor(NULL,IDC_ARROW));
                return TRUE;
        }

}

Creating a cache entry

An application uses the CreateUrlCacheEntry and CommitUrlCacheEntry functions to create a cache entry.

CreateUrlCacheEntry accepts the URL, expected file size, and file extension. The function then creates a local file name for saving the cache entry corresponding to the URL and file extension.

Using the local file name, write the data into the local file using standard C/C++ functions or Win32 functions. After the data has been written to the local file, the application should call CommitUrlCacheEntry.

CommitUrlCacheEntry accepts the URL; local file name; expire and last modified times; cache entry type; header information and header information size; and file extension. The function then caches data in the file specified in the cache storage and associates it with the given URL.

The following example uses the local file name, created by a previous call to CreateUrlCacheEntry, stored in the text box, IDC_LocalFile, to store the text from the text box, IDC_CacheDump, in the cache entry. After the data has been written to the file using fopen, fprintf, and fclose, the entry is committed using CommitUrlCacheEntry.

int WINAPI CommitEntry(HWND hX)
{
        LPSTR lpszUrl, lpszExt, lpszFileName;
        LPSTR lpszData,lpszSize;
        DWORD dwSize;
        DWORD dwEntryType=0;
        FILE *lpfCacheEntry;
        LPFILETIME lpdtmExpire, lpdtmLastModified;
        LPSYSTEMTIME lpdtmSysTime;

        if(SendDlgItemMessage(hX,IDC_RBNormal,BM_GETCHECK,0,0))
                dwEntryType = dwEntryType + NORMAL_CACHE_ENTRY;
        else
                if(SendDlgItemMessage(hX,IDC_RBStable, BM_GETCHECK,0,0))
                        dwEntryType = dwEntryType + STABLE_CACHE_ENTRY;
                else
                        if(SendDlgItemMessage(hX,IDC_RBSticky, BM_GETCHECK,0,0))
                                dwEntryType = dwEntryType + STICKY_CACHE_ENTRY;
                        else
                                if(SendDlgItemMessage(hX,IDC_RBSparse, BM_GETCHECK,0,0))
                                        dwEntryType = dwEntryType + SPARSE_CACHE_ENTRY;

        if(SendDlgItemMessage(hX,IDC_RBOCX, BM_GETCHECK,0,0))
                dwEntryType = dwEntryType + OCX_CACHE_ENTRY;
        else
                if(SendDlgItemMessage(hX,IDC_RBCookie, BM_GETCHECK,0,0))
                        dwEntryType = dwEntryType + COOKIE_CACHE_ENTRY;
                else
                        if(SendDlgItemMessage(hX,IDC_RBUrl, BM_GETCHECK,0,0))
                                dwEntryType = dwEntryType + URLHISTORY_CACHE_ENTRY;

        if(SendDlgItemMessage(hX,IDC_RBNone, BM_GETCHECK,0,0))
        {
                dwEntryType=0;
        }

        lpdtmSysTime = new SYSTEMTIME;
        lpdtmExpire = new FILETIME;
        lpdtmLastModified = new FILETIME;

        GetLocalTime(lpdtmSysTime);
        SystemTimeToFileTime(lpdtmSysTime,lpdtmExpire);
        SystemTimeToFileTime(lpdtmSysTime,lpdtmLastModified);
        delete(lpdtmSysTime);

        lpszUrl = new char[MAX_PATH];
        lpszFileName = new char[MAX_PATH];
        lpszExt = new char[5];
        lpszSize = new char[10];

        GetDlgItemText(hX,IDC_SourceURL,lpszUrl,MAX_PATH);
        GetDlgItemText(hX,IDC_LocalFile,lpszFileName,MAX_PATH);
        GetDlgItemText(hX,IDC_FileExt,lpszExt,5);

        GetDlgItemText(hX,IDC_SizeLow,lpszSize,5);
        dwSize = (DWORD)atol(lpszSize);
        delete(lpszSize);

        if (dwSize==0)
        {
                if((MessageBox(hX,"Incorrect File Size.\nUsing 8000 characters, Okay?\n",
                        "Commit Entry",MB_YESNO))==IDYES)
                {
                        dwSize = 8000;
                }
                else
                {
                        return FALSE;
                }
        }

        lpszData = new char[dwSize];
        GetDlgItemText(hX,IDC_CacheDump,lpszData,dwSize);

        lpfCacheEntry = fopen(lpszFileName,"w");
        fprintf(lpfCacheEntry,"%s",lpszData);
        fclose(lpfCacheEntry);
        delete(lpszData);

        if (!CommitUrlCacheEntry(lpszUrl, lpszFileName, *lpdtmExpire,
                *lpdtmLastModified, dwEntryType,NULL,0,lpszExt,0))
        {
                ErrorOut(hX,GetLastError(),"Commit Cache Entry");
                delete(lpszUrl);
                delete(lpszFileName);
                delete(lpszExt);
                delete(lpdtmExpire);
                delete(lpdtmLastModified);
                return FALSE;
        }
        else
        {
                delete(lpszUrl);
                delete(lpszFileName);
                delete(lpszExt);
                delete(lpdtmExpire);
                delete(lpdtmLastModified);
                return TRUE;
        }
}

Deleting a cache entry

The DeleteUrlCacheEntry function takes a URL and removes the cache file associated with it. If the cache file does not exist, the function fails and GetLastError returns ERROR_FILE_NOT_FOUND. If the cache file is currently locked or in use, the function fails and GetLastError returns ERROR_ACCESS_DENIED, and the file will be deleted when unlocked.

Retrieving a cache entry stream

RetrieveUrlCacheEntryStream, ReadUrlCacheEntryStream, and UnlockUrlCacheEntryStream retrieve the resources stored in the cache.

RetrieveUrlCacheEntryStream accepts a URL, a buffer that stores the INTERNET_CACHE_ENTRY_INFO structure, the buffer size, and a Boolean value to determine if random reads are allowed. If the cache file is found, the function then creates a handle to the file.

RetrieveUrlCacheEntryStream does not do any URL parsing, so a URL containing an anchor (#) will not be found in the cache, even if the resource is cached. For example, if the URL, http://example.com/example.htm#sample, was passed, the function would return ERROR_FILE_NOT_FOUND even if http://example.com/example.htm is in the cache.

ReadUrlCacheEntryStream uses the handle created by RetrieveUrlCacheEntryStream, a file offset, a buffer, and a buffer size variable. If the buffer size is insufficient to hold the amount of data available, the function fails and GetLastError returns ERROR_INSUFFICIENT_BUFFER. The buffer size variable is set to the size necessary to download the resource.

After the cache file is retrieved, the application must call UnlockUrlCacheEntryStream to close the handle that was created by RetrieveUrlCacheEntryStream.

The following example retrieves the information stored in the cache entry for the specified URL. The function displays text resources in the IDC_CacheDump edit box. Other resources are not displayed.

int WINAPI RetrieveStream(HWND hX, LPSTR lpszUrl)
{
    LPINTERNET_CACHE_ENTRY_INFO lpCacheEntry;
    DWORD dwEntrySize=0,dwStreamSize=0;
    HANDLE hStream;
    LPSTR lpszOut;

    RetrieveUrlCacheEntryStream(lpszUrl,NULL, &dwEntrySize, TRUE, 0);
    lpCacheEntry = LPINTERNET_CACHE_ENTRY_INFO(new char[dwEntrySize]);
    if (!(hStream = RetrieveUrlCacheEntryStream(lpszUrl,lpCacheEntry,
        &dwEntrySize, TRUE, 0)))
    {
        ErrorOut(hX,GetLastError(),"RetrieveUrlCacheEntryStream");
        return FALSE;
    }
    else
    {
        dwStreamSize = lpCacheEntry->dwSizeLow;
        lpszOut = new char[dwStreamSize];
        if (!ReadUrlCacheEntryStream(hStream,0,LPVOID(lpszOut),&dwStreamSize,
            0))
        {
            ErrorOut(hX,GetLastError(),"ReadUrlCacheEntryStream");
            return FALSE;
        }
        else
        {
            lpszOut[dwStreamSize]='\0';
            SetDlgItemText(hX,IDC_CacheDump,lpszOut);
            return TRUE;
        }
    }

    delete (lpCacheEntry);
    delete (lpszOut);

    if (!UnlockUrlCacheEntryStream(hStream,0))
    {
        ErrorOut(hX,GetLastError(),"UnlockUrlCacheEntryStream");
        return FALSE;
    }
    else
        return TRUE;
}

Retrieving cache entry files

For applications that require the file name of a resource in order to launch, the Win32 Internet API provides the RetrieveUrlCacheEntryFile and UnlockUrlCacheEntryFile functions. Applications that do not require the file name should use the RetrieveUrlCacheEntryStream, ReadUrlCacheEntryStream, and UnlockUrlCacheEntryStream functions to retrieve the information in the cache.

RetrieveUrlCacheEntryStream does not do any URL parsing, so a URL containing an anchor (#) will not be found in the cache, even if the resource is cached. For example, if the URL, http://example.com/example.htm#sample, was passed, the function would return ERROR_FILE_NOT_FOUND even if http://example.com/example.htm is in the cache.

RetrieveUrlCacheEntryFile accepts a URL, a buffer that stores the INTERNET_CACHE_ENTRY_INFO structure, and the buffer size. The function is retrieved and locked for the caller.

After the information in the file has been used, the application should call UnlockUrlCacheEntryFile to unlock the file.

Cache groups

Support for cache groups has been added to the Win32 Internet functions. To create a cache group, the CreateUrlCacheGroup function must be called to generate a GROUPID for the cache group. Entries can be added to the cache group by supplying the cache entry's URL and the INTERNET_CACHE_GROUP_ADD flag to the SetUrlCacheEntryGroup function. To remove a cache entry from a group, pass the cache entry's URL and the INTERNET_CACHE_GROUP_REMOVE flag to SetUrlCacheEntryGroup.

The FindFirstUrlCacheEntryEx and FindNextUrlCacheEntryEx functions can be used to enumerate the entries in a specified cache group. After the enumeration is complete, the function should call FindCloseUrlCache.

Handling Structures with Variable Size Information

The cache can contain variable size information for each URL stored. This is reflected in the INTERNET_CACHE_ENTRY_INFO structure. When the cache functions return this structure, they create a buffer that is always the size of INTERNET_CACHE_ENTRY_INFO plus any variable size information. If a pointer member is not NULL, it points to the memory area immediately after the structure. While copying the returned buffer from a function into another buffer, the pointer members should be fixed to point to the appropriate place in the new buffer, as the following example shows.

lpDstCEInfo->lpszSourceUrlName =
    (LPINTERNET_CACHE_ENTRY_INFO) ((LPBYTE) lpSrcCEInfo +
        ((DWORD) (lpOldCEInfo->lpszSourceUrlName) - (DWORD) lpOldCEInfo))

Some cache functions fail with the ERROR_INSUFFICIENT_BUFFER error message if you specify a buffer that is too small to contain the cache-entry information retrieved by the function. In this case, the function also returns the required size of the buffer. You can then allocate a buffer of the appropriate size and call the function again.


Common Functions

The different Internet protocols (such as FTP, HTTP, and Gopher) use several of the same Win32 Internet functions to handle information on the Internet. These common functions handle their tasks in a consistent manner, regardless of the particular protocol to which they are being applied. Applications can use these functions to create general-purpose functions that handle tasks across the different protocols (such as reading files for FTP, HTTP, and Gopher protocols).

The common functions handle the following tasks:

  • Downloading resources from the Internet can be handled by the InternetReadFile, InternetSetFilePointer, InternetFindNextFile, and InternetQueryDataAvailable functions.
  • Setting up asynchronous operations is handled by the InternetSetStatusCallback.
  • Viewing and changing options is handled by the InternetSetOption and InternetQueryOption functions.
  • Closing all types of HINTERNET handles is handled by the InternetCloseHandle function.
  • Placing and removing locks on resources being used with InternetLockRequestFile and InternetUnlockRequestFile.

Using Common Functions

The following table lists the common functions included in the Win32 Internet functions. The common functions can be used on different types of HINTERNET handles or can be used during different types of sessions.
Function | Description
InternetFindNextFile | Continues file enumeration or search. Requires a handle created by the FtpFindFirstFile, GopherFindFirstFile, or InternetOpenUrl function.
InternetLockRequestFile | Allows the user to place a lock on the file that is being used. This function requires a handle returned by the FtpOpenFile, GopherOpenFile, HttpOpenRequest, or InternetOpenUrl function.
InternetQueryDataAvailable | Queries the amount of data available. Requires a handle created by the FtpOpenFile, GopherOpenFile, or HttpOpenRequest function.
InternetQueryOption | Queries the setting of an Internet option.
InternetReadFile | Reads URL data. Requires a handle created by the InternetOpenUrl, FtpOpenFile, GopherOpenFile, or HttpOpenRequest function.
InternetSetFilePointer | Sets the position for the next read in a file. Requires a handle created by InternetOpenUrl (on an HTTP URL only) or a handle created by HttpOpenRequest using the GET method.
InternetSetOption | Sets an Internet option.
InternetSetStatusCallback | Sets a callback function that is called with status information. Assigns a callback function to the designated HINTERNET handle and all handles derived from it.
InternetUnlockRequestFile | Unlocks a file that was locked using the InternetLockRequestFile function.

Reading files, finding the next file, manipulating options, and setting up asynchronous operations are common to various protocols and HINTERNET handle types.

Reading files

The InternetReadFile function is used to download resources from an HINTERNET handle returned by the InternetOpenUrl, FtpOpenFile, GopherOpenFile, or HttpOpenRequest function.

InternetReadFile accepts a void pointer variable that contains the address of a buffer and a pointer to a double-word (DWORD) variable that contains the length of the buffer. It returns the data in the buffer and the amount of data downloaded into the buffer.

The Win32 Internet functions provide two techniques to download an entire resource:

  • Using the InternetQueryDataAvailable function.
  • Using the return values of InternetReadFile.

InternetQueryDataAvailable takes the HINTERNET handle created by InternetOpenUrl, FtpOpenFile, GopherOpenFile, or HttpOpenRequest (after HttpSendRequest has been called on the handle) and returns the number of bytes available. The application should allocate a buffer equal to the number of bytes available +1 for the NULL terminator, and use that buffer with InternetReadFile. This method does not always work because InternetQueryDataAvailable is checking the file size listed in the header and not the actual file. The information in the header file could be outdated or the header file could be missing, since it is not currently required under all standards.

The following example reads the contents of the resource accessed by the hResource handle and displayed in the edit box indicated by intCtrlID.

int WINAPI Dumper(HWND hX, int intCtrlID, HINTERNET hResource)
{
     LPSTR     lpszData;          // buffer for the data
     DWORD     dwSize;               // size of the data available
     DWORD     dwDownloaded;     // size of the downloaded data
     DWORD     dwSizeSum=0;     // size of the data in the textbox
     LPSTR     lpszHolding;     // buffer to merge the textbox data and buffer

     // Set the cursor to an hourglass.
     SetCursor(LoadCursor(NULL,IDC_WAIT));

     // This loop handles reading the data.
     do
     {
          // The call to InternetQueryDataAvailable determines the amount of
          // data available to download.
          if (!InternetQueryDataAvailable(hResource,&dwSize,0,0))
          {
               ErrorOut(hX,GetLastError(),"InternetReadFile");
               SetCursor(LoadCursor(NULL,IDC_ARROW));
               return FALSE;
          }
          else
          {
               // Allocates a buffer of the size returned by InternetQueryDataAvailable
               lpszData = new char[dwSize+1];

               // Reads the data from the HINTERNET handle.
               if(!InternetReadFile(hResource,(LPVOID)lpszData,dwSize,&dwDownloaded))
               {
                    ErrorOut(hX,GetLastError(),"InternetReadFile");
                    delete[] lpszData;
                    break;
               }
               else
               {
                    // Adds a null terminator to the end of the data buffer
                    lpszData[dwDownloaded]='\0';

                    // Allocates the holding buffer
                    lpszHolding = new char[dwSizeSum + dwDownloaded + 1];

                    // Checks if there has been any data written to the textbox
                    if (dwSizeSum != 0)
                    {
                         // Retrieves the data stored in the textbox if any
                         GetDlgItemText(hX,intCtrlID,(LPSTR)lpszHolding,dwSizeSum);

                         // Adds a null terminator at the end of the textbox data
                         lpszHolding[dwSizeSum]='\0';
                    }
                    else
                    {
                         // Make the holding buffer an empty string.
                         lpszHolding[0]='\0';
                    }

                    // Adds the new data to the holding buffer
                    strcat(lpszHolding,lpszData);

                    // Writes the holding buffer to the textbox
                    SetDlgItemText(hX,intCtrlID,(LPSTR)lpszHolding);

                    // Delete the two buffers
                    delete[] lpszHolding;
                    delete[] lpszData;

                    // Add the size of the downloaded data to the textbox data size
                    dwSizeSum = dwSizeSum + dwDownloaded + 1;

                    // Check the size of the remaining data.  If it is zero, break.
                    if (dwDownloaded == 0)
                         break;
               }
          }
     }
     while(TRUE);

     // Close the HINTERNET handle
     InternetCloseHandle(hResource);

     // Set the cursor back to an arrow
     SetCursor(LoadCursor(NULL,IDC_ARROW));

     // Return
     return TRUE;
}

InternetReadFile returns zero bytes read and completes successfully when all available data has been read. This allows an application to use InternetReadFile in a loop to download the data and exit when it returns zero bytes read and completes successfully.

The following example reads the resource from the Internet and displays the resource in the edit box indicated by intCtrlID. The HINTERNET handle, hResource, has been returned by InternetOpenUrl, FtpOpenFile, GopherOpenFile, or HttpOpenRequest (after being sent by HttpSendRequest).

int WINAPI Dump(HWND hX, int intCtrlID, HINTERNET hResource)
{

     DWORD dwSize = 0;
     LPSTR lpszData;
     LPSTR lpszOutPut;
     LPSTR lpszHolding;
     int nCounter = 1;
     int nBufferSize = 0;
     DWORD BigSize = 8000;

     // Set the cursor to an hourglass
     SetCursor(LoadCursor(NULL,IDC_WAIT));

     // Begin the loop that reads the data
     do
     {
          // Allocate the buffer
          lpszData =new char[BigSize+1];

          // Read the data
          if(!InternetReadFile(hResource,(LPVOID)lpszData,BigSize,&dwSize))
          {
               ErrorOut(hX,GetLastError(),"InternetReadFile");
               delete []lpszData;
               break;
          }
          else
          {
               // Add a null terminator to the end of the buffer
               lpszData[dwSize]='\0';

               // Check if all of the data has been read.  This should never
               // get called on the first time through the loop.
               if (dwSize == 0)
               {
                    // Write the final data to the textbox
                    SetDlgItemText(hX,intCtrlID,lpszHolding);

                    // Delete the existing buffers.
                    delete [] lpszData;
                    delete [] lpszHolding;
                    break;
               }

               // Determine the buffer size to hold the new data and the data
               // already written to the textbox (if any).
               nBufferSize = (nCounter*BigSize)+1;

               // Increment the number of buffers read
               nCounter++;

               // Allocate the output buffer
               lpszOutPut = new char[nBufferSize];

               // Make sure the buffer is not the initial buffer
               if(nBufferSize != int(BigSize+1))
               {
                    // Copy the data in the holding buffer
                    strcpy(lpszOutPut,lpszHolding);

                    // Concatenate the new buffer with the output buffer
                    strcat(lpszOutPut,lpszData);

                    // Delete the holding buffer
                    delete [] lpszHolding;
               }
               else
               {
                    // Copy the data buffer
                    strcpy(lpszOutPut, lpszData);
               }

               // Allocate a holding buffer
               lpszHolding = new char[nBufferSize];

               // Copy the output buffer into the holding buffer
               memcpy(lpszHolding,lpszOutPut,nBufferSize);

               // Delete the other buffers
               delete [] lpszData;
               delete [] lpszOutPut;

          }

     }
     while (TRUE);

     // Close the HINTERNET handle
     InternetCloseHandle(hResource);

     // Set the cursor back to an arrow
     SetCursor(LoadCursor(NULL,IDC_ARROW));

     // Return
     return TRUE;
}

Finding the next file

The InternetFindNextFile function is used to find the next file in a file search, using the search parameters and HINTERNET handle from either FtpFindFirstFile, GopherFindFirstFile, or InternetOpenUrl.

To complete a file search, continue to call InternetFindNextFile using the HINTERNET handle returned by FtpFindFirstFile, GopherFindFirstFile, or InternetOpenUrl until the function fails with the extended error message ERROR_NO_MORE_FILES. To get the extended error information, call the GetLastError function.

The following example displays the contents of an FTP directory in the list box, IDC_FTPList. The HINTERNET handle, hSecondary, is a handle returned by the InternetConnect function after it establishes an FTP session.

bool WINAPI DisplayDir(HWND hX, int lstDirectory, HINTERNET hConnect,
                            DWORD dwFlag)
{
     WIN32_FIND_DATA pDirInfo;
     HINTERNET hDir;
     char DirList[MAX_PATH];

     // Set the cursor to an hourglass
     SetCursor(LoadCursor(NULL,IDC_WAIT));

     // Reset the list box
     SendDlgItemMessage(hX, lstDirectory,LB_RESETCONTENT,0,0);

     // Find the first file
     if ( !(hDir = FtpFindFirstFile (hConnect, TEXT ("*.*"), &pDirInfo,
                                             dwFlag, 0) ))
     {
          // Check if the error was because there were no files
          if (GetLastError()  == ERROR_NO_MORE_FILES)
          {
               // Alert user
               MessageBox(hX,"There are no files here!!!","Display Dir",MB_OK);

               // Close the HINTERNET handle
               InternetCloseHandle(hDir);

               // Set the cursor back to an arrow
               SetCursor(LoadCursor(NULL,IDC_ARROW));

               // Return
               return TRUE;
          }
          else
          {
               // Call error handler
               ErrorOut (hX, GetLastError (), "FindFirst error: ");

               // Close the HINTERNET handle
               InternetCloseHandle(hDir);

               // Set the cursor back to an arrow
               SetCursor(LoadCursor(NULL,IDC_ARROW));

               // Return
               return FALSE;
          }
     }
     else
     {

          // Write the filename to a string
          sprintf(DirList, pDirInfo.cFileName);

          // Check the type of file
          if (pDirInfo.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY)
          {
               // Add <DIR> to indicate that this is a directory to the user
               strcat(DirList," <DIR> ");
          }

          // Add the filename (or directory) to the listbox
          SendDlgItemMessage(hX,lstDirectory,LB_ADDSTRING,0,(LPARAM)DirList);

     }

     do
     {
          // Find the next file
          if (!InternetFindNextFile (hDir, &pDirInfo))
          {
               // Check if there are no more files left
               if ( GetLastError() == ERROR_NO_MORE_FILES )
               {
                    // Close the HINTERNET handle
                    InternetCloseHandle(hDir);

                    // Set the cursor back to an arrow
                    SetCursor(LoadCursor(NULL,IDC_ARROW));

                    // Return
                    return TRUE;
               }
               else
               {
                    // Handle the error
                    ErrorOut (hX,GetLastError(), "InternetFindNextFile");

                    // Close the HINTERNET handle
                    InternetCloseHandle(hDir);

                    // Set the cursor back to an arrow
                    SetCursor(LoadCursor(NULL,IDC_ARROW));

                    // Return
                    return FALSE;
               }
           }
           else
           {
               // Write the filename to a string
               sprintf(DirList, pDirInfo.cFileName);

               // Check the type of file
               if (pDirInfo.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY)
               {
                    // Add <DIR> to indicate that this is a directory to the user
                    strcat(DirList," <DIR> ");
               }

               // Add the filename (or directory) to the listbox
               SendDlgItemMessage(hX,lstDirectory,LB_ADDSTRING,0,(LPARAM)DirList);
           }
     }
     while ( TRUE);

}

Manipulating options

InternetSetOption and InternetQueryOption are used to manipulate the Win32 Internet API options.

InternetSetOption accepts a double-word value that indicates the option to set, a buffer to hold the option setting, and a pointer that contains the address of the variable containing the length of the buffer.

InternetQueryOption accepts a double-word value that indicates the option to query, a buffer to hold the option setting, and a pointer that contains the address of the variable containing the length of the buffer.

Setting up asynchronous operations

By default, the Win32 Internet functions operate synchronously. An application can request asynchronous operation by setting the INTERNET_FLAG_ASYNC flag in the call to the InternetOpen function. All future calls made against handles derived from the handle returned from InternetOpen will be made asynchronously.

The rationale for asynchronous versus synchronous operation is to allow a single-threaded application to maximize its utilization of the CPU without having to wait for network I/O to complete. Therefore, depending on the request, the operation might complete synchronously or asynchronously. The application should check the return code. If a function returns FALSE or NULL, and GetLastError returns ERROR_IO_PENDING, the request has been made asynchronously, and the application will be called back with INTERNET_STATUS_REQUEST_COMPLETE when the function has completed.

For an application to be able to make requests asynchronously, it must set the INTERNET_FLAG_ASYNC flag in the call to InternetOpen, it must register a valid callback function, and it must supply a nonzero context value.

To begin asynchronous operation, the application must set the INTERNET_FLAG_ASYNC flag in its call to InternetOpen. It must then register a valid callback function, using InternetSetStatusCallback.

After a callback function is registered for a handle, all operations on that handle can generate status indications, provided that the context value that was supplied when the handle was created was not zero. Providing a zero context value forces an operation to complete synchronously, even though INTERNET_FLAG_ASYNC was specified in InternetOpen.

Status indications are mainly intended to give the application feedback about the operation's progress and are mainly concerned with network operations, such as resolving a host name, connecting to a server, and receiving data. Three special-purpose status indications can be made for a handle:

  • INTERNET_STATUS_HANDLE_CLOSING is the last status indication that is made for a handle.
  • INTERNET_STATUS_HANDLE_CREATED indicates when the handle is initially created.
  • INTERNET_STATUS_REQUEST_COMPLETE indicates when an asynchronous operation completes.

The application must check the INTERNET_ASYNC_RESULT structure to determine whether the operation succeeded or failed after receiving an INTERNET_STATUS_REQUEST_COMPLETE indication.

The following sample shows an example of a callback function and a call to InternetSetStatusCallback to register the function as the callback function.

void
CALLBACK
CInternet::InternetCallback(
    HINTERNET hInternet,
    DWORD dwcontext,
    DWORD dwInternetStatus,
    LPVOID lpvStatusInformation,
    DWORD dwStatusInformationLength
)
{

// Insert code here.

};

INTERNET_STATUS_CALLBACK dwISC;

dwISC = InternetSetStatusCallback(   hInternet,
        (INTERNET_STATUS_CALLBACK) InternetCallback);

Closing HINTERNET handles

All HINTERNET handles can be closed by using the InternetCloseHandle function. Client applications must close all HINTERNET handles derrived from the HINTERNET handle to be closed before calling InternetCloseHandle. For more information about HINTERNET handles and the handle hierarchy, see Appendix A: HINTERNET Handles.

The following example illustrates the handle hierarchy for the Win32 Internet functions.

HINTERNET hRootHandle, hOpenUrlHandle;

hRootHandle = InternetOpen("Example", INTERNET_OPEN_TYPE_DIRECT, NULL,
    NULL, 0);

hOpenUrlHandle = InternetOpenUrl(hRootHandle,
    "http://www.server.com/default.htm", NULL, 0,
    INTERNET_FLAG_RAW_DATA,0);

// Close the handle created by InternetOpenUrl, so that the InternetOpen handle can be closed.
InternetCloseHandle(hOpenUrlHandle);

// Close the handle created by InternetOpen
InternetCloseHandle(hRootHandle);

Locking and unlocking resources

The InternetLockRequestFile function allows an application to ensure that the cached resource associated with the HINTERNET handle passed to it will not disappear from the cache. If another download tries to commit a resource that has the same URL as the locked file, the cache avoids removing the file by doing a safe delete. After the application calls the InternetUnlockRequestFile function, the cache is given permission to delete the file.

If the INTERNET_FLAG_NO_CACHE_WRITE or INTERNET_FLAG_DONT_CACHE flag has been set, InternetLockRequestFile creates a temporary file with the extension TMP, unless the handle is connected to an HTTPS resource. If the function is accessing an HTTPS resource and INTERNET_FLAG_NO_CACHE_WRITE (or INTERNET_FLAG_DONT_CACHE) has been set, InternetLockRequestFile fails.


Cookie Functions

Under HTTP protocol, a server or a script uses cookies to maintain state information on the client workstation. The Win32 Internet functions have implemented a persistent cookie database for this purpose. The Win32 Internet cookie functions are used to set cookies into and access cookies from the cookie database.

The Win32 Internet functions InternetSetCookie and InternetGetCookie manipulate cookies. The caller of these functions should be familiar with cookies as outlined in ftp://ds.internic.net/internet-drafts/draft-ietf-http-state-mgmt-*.txt. Please note that the implementation of these functions is evolving; be cautious when using them.

Using Cookie Functions

Two functions allow an application to create or retrieve cookies in the cookie database.
Function | Description
InternetGetCookie | Returns cookies for the specified URL and all its parent URLs.
InternetSetCookie | Sets a cookie on the specified URL.

Getting a cookie

InternetGetCookie returns the cookies for the specified URL and all its parent URLs.

No call to InternetOpen is required to use this function. InternetGetCookie looks for cookies with no expiration dates in the windows\cookies directory and searches for unexpired cookies that are not written to any files in memory.

Setting a cookie

InternetSetCookie sets a cookie on the specified URL.


Enabling Internet Functionality

To compile programs that utilize the Win32 Internet functions, the header file, Wininet.h, must be in the include directory, and the library file, Wininet.lib, must be in the library directory of the C/C++ compiler being used.

Before using the Win32 Internet functions, the application should attempt to make a connection to the Internet by using the InternetAttemptConnect function. This function calls the dial-up dialog box to initiate a connection to the Internet or check if a connection already exists. If this function fails, the application can enter offline mode, which allows it to access information that was cached during previous connections to the Internet.

The InternetCheckConnection function can be used to check the connection to the Internet. It attempts to ping the server designated by the Uniform Resource Locator (URL) that is passed to the function. If the FLAG_ICC_FORCE_CONNECTION flag is set and NULL was given as the URL, the function checks to see if there is an entry in the WinInet server database for the nearest server. If one exists, the function pings that server.

To begin using the Win32 Internet functions, use the InternetOpen function to establish the characteristics of the Internet connection being used. InternetOpen creates the root HINTERNET handle that is used to establish HTTP, FTP, and Gopher sessions. InternetOpen does not test the connection to the Internet to verify that the characteristics passed to the function are correct.

Use the InternetConnect function to create a specific session. InternetConnect initializes an FTP, Gopher, or HTTP session for the specified site using the arguments passed to it and creates an HINTERNET handle that is a branch off the root handle. InternetConnect does not attempt to access or establish a connection to the specified site, except in the case of an FTP session. FtpFindFirstFile, FtpOpenFile, GopherFindFirstFile, GopherOpenFile, and HttpOpenRequest functions use the handle created by InternetConnect to establish a connection to the specified site.

The following diagram illustrates the hierarchy of the HINTERNET handles.

HINTERNET handles hierarchy

The InternetOpen function, which creates the root HINTERNET handle, is at the top level. The next level contains the InternetOpenUrl function and the InternetConnect function. The functions that use the HINTERNET handle returned by InternetConnect make up the last level. For more information about HINTERNET handles and the handle hierarchy, see Appendix A: HINTERNET Handles.

Using InternetOpen

To enable a connection to the Internet, a root HINTERNET handle must be created by using InternetOpen. Information about the user agent (the application calling the Internet functions), the type of access to the Internet, the proxy names, the hosts and addresses that bypass the proxy, and the behavior are passed to InternetOpen.

Setting the user agent

The lpszAgent parameter of InternetOpen should be given a string that contains the name of the application or entity accessing the Internet. This string is used as the user agent in the HTTP protocol. For example, Internet Explorer uses "Microsoft Internet Explorer".

Setting access types

InternetOpen supports three access types:

  • Use INTERNET_OPEN_TYPE_DIRECT if the system on which the application is running uses a direct connection to the Internet. The lpszProxyName and lpszProxyBypass parameters of InternetOpen are not used and should be set to NULL.
  • Use INTERNET_OPEN_TYPE_PROXY if the system on which the application is running uses one or more proxy servers to access the Internet. InternetOpen uses the proxy servers indicated by lpszProxyName and bypasses the proxy for any host names or IP addresses specified by lpszProxyBypass.
  • Use INTERNET_OPEN_TYPE_PRECONFIG to instruct your application to retrieve the configuration from the registry.

INTERNET_OPEN_TYPE_PRECONFIG looks at the registry values ProxyEnable, ProxyServer, and ProxyOverride. These values are located under HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings.

If ProxyEnable is zero, the application uses INTERNET_OPEN_TYPE_DIRECT. Otherwise, the application uses INTERNET_OPEN_TYPE_PROXY and uses the ProxyServer and ProxyOverride information.

The Win32 Internet functions provide support for SOCKS type proxies only if Microsoft Internet Explorer is installed. The installation of Internet Explorer installs the Wsock32n.dll, which the Win32 Internet functions need to support SOCKS proxies. The Wsock32n.dll is not redistributable.

Listing proxy servers

The Win32 Internet functions recognize two types of proxies: CERN type proxies (HTTP only) and TIS FTP proxies (FTP only). If Internet Explorer is installed, the Win32 Internet functions also support SOCKS type proxies. InternetConnect assumes, by default, that the specified proxy is a CERN proxy. If the access type is set to INTERNET_OPEN_TYPE_DIRECT or INTERNET_OPEN_TYPE_PRECONFIG, the lpszProxyName parameter of InternetOpen should be set to NULL. Otherwise, the value passed to lpszProxyName must contain the proxies in a space-delimited string. The proxy listings can contain the port number that is used to access the proxy.

To list a proxy for a specific protocol, the string must follow the format "<protocol>=<protocol>://<proxy_name>". The valid protocols are http, https, ftp, and gopher. For example, to list an FTP proxy, a valid string would be "ftp=ftp://ftp_proxy_name:21", where "ftp_proxy_name" is the name of the FTP proxy and "21" is the port number that must be used to access the proxy. If the proxy uses the default port number for that protocol, the port number can be omitted. If a proxy name is listed by itself, it is used as the default proxy for any protocols that do not have a specific proxy specified. For example, "http=http://http_proxy other" would use "http_proxy" for any HTTP operations, while all other protocols (such as FTP and Gopher) would use "other".

Listing the proxy bypass

Host names or IP addresses that are known locally can be listed in the proxy bypass. This list can contain wildcards, "*", which cause the application to bypass the proxy server for addresses that fit the specified pattern. To list multiple addresses and host names, separate them with blank spaces in the proxy bypass string. If the "<local>" macro is specified, the function bypasses any host name that does not contain a period.

The following example shows sample calls to InternetOpen using different proxy bypass strings. The comments above each call describe what effect the bypass string has on the host names that are accessed from the HINTERNET handle it creates.

/* bypass the proxy for any host name that does not
    contain a period */
hInternetRoot = InternetOpen("WinInet Example",
    INTERNET_OPEN_TYPE_PROXY,"proxy","<local>", 0);

/* bypass the proxy for any host name that starts with the
    letters "ms" */
hInternetRoot = InternetOpen("WinInet Example",
    INTERNET_OPEN_TYPE_PROXY,"proxy","ms*", 0);

/* bypass the proxy for any host name that contains "int",
    such as "internet" and "painter" */
hInternetRoot = InternetOpen("WinInet Example",
    INTERNET_OPEN_TYPE_PROXY,"proxy","*int*", 0);

/* bypass the proxy for the host name "example" and any
    host name that contains "test" */
hInternetRoot = InternetOpen("WinInet Example",
    INTERNET_OPEN_TYPE_PROXY,"proxy","example *test*", 0);

Using InternetConnect

To begin a Gopher, FTP, or HTTP session, the InternetConnect function must create a handle off the root handle returned by the InternetOpen function. InternetConnect sets the server address, port number, user name, password, and type of service.

InternetConnect uses the root HINTERNET handle created by InternetOpen to establish a session handle. If the INTERNET_FLAG_ASYNC flag was set in the call to InternetOpen, the call to InternetConnect should include a nonzero context value.

The server name can be a constant string or a variable containing a string value of type LPSTR. This string can contain either the host name (for example, www.servername.com) or IP number of the site in ASCII dotted-decimal format (for example, 11.0.1.45).

The server port is the TCP/IP port number to connect to on the server. InternetConnect uses the default port for the selected service type if the INTERNET_INVALID_PORT_NUMBER value is used. There are four server port defaults included with the Win32 Internet functions.
Value | Meaning
INTERNET_DEFAULT_FTP_PORT | Use the default port for FTP servers (port 21).
INTERNET_DEFAULT_GOPHER_PORT | Use the default port for Gopher servers (port 70).
INTERNET_DEFAULT_HTTP_PORT | Use the default port for HTTP servers (port 80).
INTERNET_DEFAULT_HTTPS_PORT | Use the default port for HTTPS servers (port 443).
INTERNET_DEFAULT_SOCKS_PORT | Uses the default port for SOCKS firewall servers (port 1080).

Defining the user name and password

The user name is the address of a NULL-terminated string that contains the name of the user to log on. If this parameter is NULL, the function uses an appropriate default, except for HTTP; a NULL parameter in HTTP causes the server to return an error. For the FTP protocol, the default is anonymous.

The password is the address of a NULL-terminated string that contains the password to use to log on. If both lpszUsername and lpszPassword are NULL, the function uses the default anonymous password. In the case of FTP, the default anonymous password is the user's e-mail name. If lpszUsername is not NULL and lpszPassword is NULL, the function uses a blank password. There are four possible settings of lpszUsername and lpszPassword, which produce the behaviors shown in the following table.
lpszUsername | lpszPassword | User name sent to FTP server | Password sent to FTP server
NULL | NULL | "anonymous" | User's e-mail name
Non-NULL string NULL lpszUsername ""
NULL | Non-NULL string | ERROR | ERROR
Non-NULL string | Non-NULL string | lpszUsername | lpszPassword

This information can be changed by using the InternetSetOption and InternetErrorDlg functions. InternetSetOption changes the user name and password values, while InternetErrorDlg displays a dialog box requesting the proper user name and password.

Defining the session

To define the session that is being established, InternetConnect must have the service type, flags, and context value set.

There are three service types available to InternetConnect: INTERNET_SERVICE_FTP, INTERNET_SERVICE_GOPHER, and INTERNET_SERVICE_HTTP. INTERNET_SERVICE_HTTP is used for both HTTP and HTTPS sessions.

INTERNET_FLAG_PASSIVE is the only service-specific flag used by the Win32 Internet functions. This flag can be set when the service type is INTERNET_SERVICE_FTP in order to use passive FTP semantics.

For all synchronous operations, the value of dwContext should be set to zero. If asynchronous operations were established by setting the INTERNET_FLAG_ASYNC flag in the call to InternetOpen, a nonzero value should be supplied for dwContext. For more information on asynchronous operations, see Setting up asynchronous operations.

For FTP sessions, InternetConnect tries to establish a connection to the server on the Internet. HTTP and Gopher sessions do not establish a connection until a function attempts to get information from the server.


Establishing a Dial-Up Connection to the Internet

The Win32 Internet functions include seven functions that handle modem connections.
Function | Description
InternetAutodial | Initiates an unattended dial-up connection.
InternetAutodialHangup | Disconnects a modem connection initiated by InternetAutodial.
InternetDial | Initiates a dial-up connection.
InternetGetConnectedState | Retrieves the current state of the Internet connection.
InternetHangUp | Disconnects a modem connect initiated by InternetDial.
InternetGoOnline | Prompts the user for permission to initiate a dial-up connection to the given URL.
InternetSetDialState | Sets the current state of the Internet connection.

Detailed information on how to use these functions will be included in a future version of this documentation.


FTP Sessions

The Win32 Internet functions can be used to provide applications with the ability to navigate and manipulate directories and files on an FTP server. Applications that use a CERN proxy exclusively must use the InternetOpenUrl function because CERN proxies do not support FTP. For more information on how to use InternetOpenUrl, see Accessing URLs directly.

To begin an FTP session, use InternetConnect to create the valid FTP session handle to be used by the FTP functions provided with the Win32 Internet functions.

The Win32 Internet functions provide the capability to navigate between directories; enumerate, create, remove, and rename directories; and rename, upload, download, and delete files on an FTP server.

Navigation is provided by the FtpGetCurrentDirectory and FtpSetCurrentDirectory functions. These functions utilize the FTP session handle created by a previous call to InternetConnect to determine which directory the application is currently in or to change to a different subdirectory.

Directory enumeration is performed by using the FtpFindFirstFile and InternetFindNextFile functions. FtpFindFirstFile uses the FTP session handle created by InternetConnect to find the first file that matches the given search criteria and returns a handle to continue the directory enumeration. InternetFindNextFile uses the handle returned by FtpFindFirstFile to return the next file that matches the original search criteria. The application should continue to call InternetFindNextFile until there are no more files left in the directory.

New directories are created by using the FtpCreateDirectory function. This function uses the FTP session handle created by InternetConnect and creates the directory specified by the string passed to the function. The string can contain a directory name relative to the current directory, or a fully qualified directory path.

To rename either files or directories, the application can call FtpRenameFile. This function replaces the original name with the new name passed to the function. The name of the file or directory can be relative to the current directory, or a fully qualified name.

To upload or place files on an FTP server, the application can use either FtpPutFile or FtpOpenFile (along with InternetWriteFile). FtpPutFile can be used if the file already exists locally, while FtpOpenFile and InternetWriteFile can be used if data needs to be written to a file on the FTP server.

To download or get files, the application can use either FtpGetFile or FtpOpenFile (with InternetReadFile). FtpGetFile is used to retrieve a file from an FTP server and store it locally, while FtpOpenFile and InternetReadFile can be used to control where the downloaded information is going (for example, it could be used to display the information in an edit box).

Deleting files on an FTP server is done by using the FtpDeleteFile function. This function removes a file name that is either relative to the current directory or a fully qualified file name from the FTP server. FtpDeleteFile requires an FTP session handle returned by InternetConnect.

FTP Function Handles

The FTP functions require certain types of HINTERNET handles to work properly. These handles must be created in a set order, starting with the root handle created by InternetOpen. InternetConnect can then create an FTP session handle.

The following diagram shows the FTP functions that are dependent on the FTP session handle returned by InternetConnect. The shaded boxes represent functions that return HINTERNET handles, while the plain boxes represent functions that use the HINTERNET handle created by the function on which they depend.

FTP functions dependent on FTP session handle returned by InternetConnect

The following diagram shows the two FTP functions that return HINTERNET handles and the functions that are dependent on the HINTERNET handles created by them. The shaded boxes represent functions that return HINTERNET handles, while the plain boxes represent functions that use the HINTERNET handle created by the function on which they depend.

FTP functions that return HINTERNET handles

For more information about HINTERNET handles and the handle hierarchy, see Appendix A: HINTERNET Handles.

Using the Win32 Internet Functions for FTP Sessions

The following Win32 Internet functions are used during FTP sessions. These functions are not recognized by CERN proxies. Applications that must function through CERN proxies should use InternetOpenUrl and access the resources directly. For more information on direct resource access, see Accessing URLs directly.
Function | Description
FtpCreateDirectory | Creates a new directory on the server. This function requires a handle created by InternetConnect.
FtpDeleteFile | Deletes a file from the server. This function requires a handle created by InternetConnect.
FtpFindFirstFile | Starts file enumeration or file search in the current directory. This function requires a handle created by InternetConnect.
FtpGetCurrentDirectory | Returns the client's current directory on the server. This function requires a handle created by InternetConnect.
FtpGetFile | Retrieves a file from the server. This function requires a handle created by InternetConnect.
FtpOpenFile | Initiates access to a file on the server for either reading or writing. This function requires a handle created by InternetConnect.
FtpPutFile | Writes a file to the server. This function requires a handle created by InternetConnect.
FtpRemoveDirectory | Deletes a directory on the server. This function requires a handle created by InternetConnect.
FtpRenameFile | Renames a file on the server. This function requires a handle created by InternetConnect.
FtpSetCurrentDirectory | Changes the client's current directory on the server. This function requires a handle created by InternetConnect.
InternetWriteFile | Writes data to an open file on the server. This function requires a handle created by FtpOpenFile.

Starting an FTP session

The application establishes an FTP session by calling InternetConnect on a handle created by InternetOpen. InternetConnect needs the server name, FTP port number, user name, password, and service type (which must be set to INTERNET_SERVICE_FTP). For passive FTP semantics, the application must also set the INTERNET_FLAG_PASSIVE flag.

The INTERNET_DEFAULT_FTP_PORT and INTERNET_INVALID_PORT_NUMBER values can be used for the FTP port number. INTERNET_DEFAULT_FTP_PORT uses the default FTP port, but the service type still must be set. INTERNET_INVALID_PORT_NUMBER uses the default value for the indicated service type.

The values for the user name and password can be set to NULL. If both values are set to NULL, InternetConnect uses "anonymous" for the user name, and the user's e-mail address for the password. If only the password is set to NULL, the user name passed to InternetConnect is used for the user name, and an empty string is used for the password. If both values are not NULL, the user name and password given to InternetConnect are used.

Enumerating directories

Enumeration of a directory on an FTP server requires the creation of a handle by FtpFindFirstFile. This handle is a branch of the FTP session handle created by InternetConnect. FtpFindFirstFile locates the first file or directory on the server and returns it in a WIN32_FIND_DATA structure. Use InternetFindNextFile until it returns ERROR_NO_MORE_FILES. This method finds all subsequent files and directories on the server. For more information on InternetFindNextFile, see Finding the next file.

To determine if the file retrieved by FtpFindFirstFile or InternetFindNextFile is a directory, check the dwFileAttributes member of the WIN32_FIND_DATA structure to see if it is equal to FILE_ATTRIBUTE_DIRECTORY.

If the application makes changes on the FTP server or if the FTP server undergoes changes frequently, the INTERNET_FLAG_NO_CACHE_WRITE and INTERNET_FLAG_RELOAD flags should be set in FtpFindFirstFile. These flags ensure that the directory information being retrieved from the FTP server is current.

After the application completes the directory enumeration, a call to InternetCloseHandle must be made on the handle created by FtpFindFirstFile. Until that handle is closed, the application cannot call FtpFindFirstFile again on the session handle created by InternetConnect. If a call to FtpFindFirstFile is made on the same session handle before the previous call to the same function is closed, the function fails, returning ERROR_FTP_TRANSFER_IN_PROGRESS.

The following example displays the contents of an FTP directory in the list box, IDC_FTPList. The HINTERNET handle, hSecondary, is a handle returned by the InternetConnect function after it establishes an FTP session.

int WINAPI DisplayDir(HWND hX, DWORD dwFlags)
{
    WIN32_FIND_DATA pDirInfo;
    HINTERNET hDir;
    DWORD dError;
    char DirList[MAX_PATH];
    DWORD dwTemp=MAX_PATH;
    LPDWORD temp =&dwTemp;
    LPVOID lpOption;
    DWORD dwSize;
    LPDWORD lpdwSize = &dwSize;

SendDlgItemMessage(hX,IDC_FTPList,LB_RESETCONTENT,0,0);
    if ( !(hDir = FtpFindFirstFile (hSecondary, TEXT ("*.*"), &pDirInfo,
        dwFlags, 0) ))
        if (GetLastError()  == ERROR_NO_MORE_FILES)
        {
            MessageBox(hX,"There are no files here!!!","Display Dir",MB_OK);
            InternetCloseHandle(hDir);
            return 1;
        }
        else
        {
            ErrorOut (hX, GetLastError (), "FindFirst error: ");
            InternetCloseHandle(hDir);
            return 0;
        }

        sprintf(DirList, pDirInfo.cFileName);
        if (pDirInfo.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY)
            strcat(DirList," <DIR> ");

        SendDlgItemMessage(hX,IDC_FTPList,LB_ADDSTRING,0,(LPARAM)DirList);

    dError = NO_ERROR;
    do
    {
         if (!InternetFindNextFile (hDir, &pDirInfo))
         {
             dError = GetLastError();
             if ( dError == ERROR_NO_MORE_FILES )
             {
                 InternetCloseHandle(hDir);
                 return 1;
             }
             else
             {
                 ErrorOut (hX,GetLastError(), "InternetFindNextFile");
                 InternetCloseHandle(hDir);
                 return 0;
             }
         }
         else
         {
            sprintf(DirList, pDirInfo.cFileName);
            if (pDirInfo.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY)
                strcat(DirList," <DIR> ");
            SendDlgItemMessage(hX,IDC_FTPList,LB_ADDSTRING,0,
                (LPARAM)DirList);
         }
    }
    while ( TRUE);

    if (!InternetCloseHandle(hDir) )
    {
        InternetCloseHandle(hDir);
        ErrorOut (hX,GetLastError(), "InternetCloseHandle error");
        return 0;
    }
    else
        return 1;

}

Navigating directories

The Win32 Internet functions FtpGetCurrentDirectory and FtpSetCurrentDirectory handle directory navigation.

FtpGetCurrentDirectory returns the application's current directory on the FTP server. The directory path from the root directory on the FTP server is included.

FtpSetCurrentDirectory changes the working directory on the server. The directory information passed to FtpSetCurrentDirectory can be either a partially or fully qualified path name relative to the current directory. For example, if the application is currently in the directory "public/info" and the path is "ftp/example", FtpSetCurrentDirectory changes the current directory to "public/info/ftp/example".

The following example uses an FTP session handle, hSecondary, returned by InternetConnect. The new directory name is stored in the edit box, IDC_FTPEdit2. Before the actual change is made, the function gets the current directory and stores it in the same edit box. DisplayDir is another function that is designed to enumerate the directory.

int WINAPI ChangeDir(HWND hX)
{
    DWORD testsz = 320;
    LPSTR lpszUrlBuffer;            // buffer to hold the URL
    LPSTR lpszDirList;

    lpszUrlBuffer = new char[testsz];
    GetDlgItemText(hX,IDC_FTPEdit2,(LPSTR)lpszUrlBuffer,testsz);
    lpszDirList = new char[testsz];
    if (!FtpGetCurrentDirectory(hSecondary,(LPSTR)lpszDirList,&testsz))
    {
        ErrorOut(hX,GetLastError(),"Change Dir");
    }
    else
        SetDlgItemText(hX,IDC_FTPEdit2,(LPSTR)lpszDirList);

    delete(lpszDirList);

    if (!(FtpSetCurrentDirectory(hSecondary,lpszUrlBuffer)))
    {
        ErrorOut(hX,GetLastError(),"InternetConnect");
        delete(lpszUrlBuffer);
        SetDlgItemText(hX,IDC_FTPEdit2,(LPSTR)lpszUrlBuffer);
        DisplayDir(hX,INTERNET_FLAG_RELOAD);
        return 0;
    }
    else
    {
        delete(lpszUrlBuffer);
        return DisplayDir(hX,0);
    }
}

Manipulating directories on an FTP server

The Win32 Internet functions provide the capability to create and remove directories on an FTP server to which the application has the necessary privileges. If the application must log on to a server with a specific user name and password, the values can be used in InternetConnect when creating the FTP session handle.

The FtpCreateDirectory function takes a valid FTP session handle and a NULL-terminated string that contains either a fully qualified path or a name relative to the current directory and creates a directory on the FTP server.

The following example shows two separate calls to FtpCreateDirectory. In both examples, hFtpSession is the session handle created by the InternetConnect function, and the root directory is the current directory.

FtpCreateDirectory(hFtpSession, "test");
/* this will create the directory "test" in the current directory
    (which is the root directory) */

FtpCreateDirectory(hFtpSession, "\test\example");
/* this will create the directory "example" in the test directory */

The FtpRemoveDirectory function takes a valid FTP session handle and a NULL-terminated string that contains either a fully qualified path or a name relative to the current directory and removes that directory from the FTP server.

The following example shows two sample calls to FtpRemoveDirectory. In both calls, hFtpSession is the session handle created by the InternetConnect function, and the root directory is the current directory. There is a directory called "test" in the root directory and a directory called "example" in the "test" directory.

FtpRemoveDirectory(hFtpSession,"\test\example");
/* removes the "example" directory and any files or directories contained in it
    from the "test" directory */

FtpRemoveDirectory(hFtpSession, "test");
/* removes the "test" directory and any files or directories contained in it
    from the root directory */

The following example creates the directory indicated by the string stored in the edit box, IDC_FTPEdit2. The HINTERNET handle, hSecondary, was created by InternetConnect after establishing an FTP session. DisplayDir is another function that is designed to enumerate the directory.

int WINAPI CreateDir(HWND hX)
{
    char strInFile[80];

    GetDlgItemText(hX,IDC_FTPEdit2,strInFile,80);

    if (strlen(strInFile)==0)
    {
        MessageBox(hX,"Directory Name Must Be Specified","Create Dir",MB_OK);
        return 0;
    }
    else
    {
        if(!FtpCreateDirectory(hSecondary,strInFile))
        {
            ErrorOut(hX,GetLastError(),"Create Dir");
            return 0;
        }
        else
        {
            return DisplayDir(hX,INTERNET_FLAG_RELOAD);
        }
    }
}

The following example deletes the directory indicated by the edit box, IDC_FTPEdit2. The HINTERNET handle, hSecondary, was created by InternetConnect after establishing an FTP session. DisplayDir is another function that is designed to enumerate the directory.

int WINAPI RemoveDir(HWND hX)
{
    char strInFile[80];

    GetDlgItemText(hX,IDC_FTPEdit2,strInFile,80);

    if (strlen(strInFile)==0)
    {
        MessageBox(hX,"Directory Name Must Be Specified!","Remove Dir",MB_OK);
        return 0;
    }
    else
    {
        if(!FtpRemoveDirectory(hSecondary,strInFile))
        {
            ErrorOut(hX,GetLastError(),"Remove Dir");
            return 0;
        }
        else
        {
            MessageBox(hX,"Directory Deleted", "Remove Dir", MB_OK);
            return DisplayDir(hX,INTERNET_FLAG_RELOAD);
        }
    }
}

Getting files on an FTP server

The Win32 Internet functions offer three methods for retrieving files from an FTP server:

  • Using InternetOpenUrl and InternetReadFile.
  • Using FtpOpenFile and InternetReadFile.
  • Using FtpGetFile.

For more information about using the InternetReadFile function, see Reading files.

If the URL of the file is available, the application can call InternetOpenUrl to connect to that URL and then use InternetReadFile to control the download of the file. This setup allows the application to control the download more tightly and is ideal for situations where no other operations need to be made on the FTP server. For more information on how to directly access resources, see Accessing URLs directly.

If the application has established an FTP session handle to the server with InternetConnect, the application can call FtpOpenFile with the existing file name and with a new name for the locally stored file. The application can then use InternetReadFile to download the file. This allows the application to control the download more tightly and keep the connection to the FTP server, so more commands can be executed.

If the application does not need to tightly control the download, the application can use FtpGetFile with the FTP session handle, remote file name, and local file name to retrieve the file. FtpGetFile performs all the bookkeeping and overhead associated with reading a file from an FTP server and storing it locally.

The following example retrieves the file indicated by the IDC_FTPEdit2 edit box and stores it locally using the file name specified by the IDC_FTPEdit3 edit box. The HINTERNET handle, hSecondary, was created by InternetConnect after establishing an FTP session. DisplayDir is another function that is designed to enumerate the directory.

int WINAPI GetFile(HWND hX)
{
    char strInFile[80];
    char strOutFile[80];
    int intTransType;

    GetDlgItemText(hX,IDC_FTPEdit3,strOutFile,80);
    GetDlgItemText(hX,IDC_FTPEdit2,strInFile,80);

    if ((strlen(strOutFile)==0) | (strlen(strInFile)==0))
    {
        MessageBox(hX,"Target File or Destination File Missing","Get File",
            MB_OK);
        return 0;
    }
    else
    {
        intTransType = MessageBox(hX,
            "Do you want to download in ASCII (Default:Binary)?",
            "Get File",MB_YESNO);
        if (intTransType==IDYES)
        {
            if(!FtpGetFile(hSecondary,strInFile,strOutFile,FALSE,
                FILE_ATTRIBUTE_NORMAL,FTP_TRANSFER_TYPE_ASCII |
                INTERNET_FLAG_NO_CACHE_WRITE,0))
            {
                ErrorOut(hX,GetLastError(),"Get File");
                DisplayDir(hX,INTERNET_FLAG_RELOAD);
                return 0;
            }
            else
            {
                MessageBox(hX,"ASCII Transfer Complete","Get File",MB_OK);
                return 1;
            }
        }
        else
        {
            if(!FtpGetFile(hSecondary,strInFile,strOutFile,FALSE,
                FILE_ATTRIBUTE_NORMAL, FTP_TRANSFER_TYPE_BINARY |
                INTERNET_FLAG_RELOAD,0))
            {
                ErrorOut(hX,GetLastError(),"Get File");
                return 0;
            }
            else
            {
                MessageBox(hX,"Binary Transfer Complete","Get File",MB_OK);
                return 1;
            }
        }
    }
}

Placing files on an FTP server

An application can use two methods to place a file on an FTP server using the Win32 Internet functions:

  • Use the FtpOpenFile function with the InternetWriteFile function.
  • Use FtpPutFile.

An application that must send data to an FTP server, but does not have a local file containing all the data, should use FtpOpenFile to create and open a file on the FTP server. The application then can use InternetWriteFile to upload the information to the file.

If the file already exists locally, the application can use FtpPutFile to upload the file to the FTP server. FtpPutFile performs all the overhead that goes with uploading a local file to a remote FTP server.

The following example places the file indicated by the IDC_FTPEdit2 edit box on the FTP server, using the file name specified by the IDC_FTPEdit3 edit box. The HINTERNET handle, hSecondary, was created by InternetConnect after establishing an FTP session.

int WINAPI PutFile(HWND hX)
{
    char strInFile[80];
    char strOutFile[80];
    int intTransType;

    GetDlgItemText(hX,IDC_FTPEdit3,strOutFile,80);
    GetDlgItemText(hX,IDC_FTPEdit2,strInFile,80);

    if ((strlen(strOutFile)==0) | (strlen(strInFile)==0))
    {
        MessageBox(hX,"Target File or Destination File Missing","Put File", MB_OK);
        return 0;
    }
    else
    {
        intTransType = MessageBox(hX,
            "Do you want to upload in ASCII (Default:Binary)?",
            "Put File",MB_YESNO);

        if (intTransType==IDYES)
        {
            if(!FtpPutFile(hSecondary,strInFile,strOutFile,
                FTP_TRANSFER_TYPE_ASCII,0))
            {
                ErrorOut(hX,GetLastError(),"Get File");
                return 0;
            }
            else
            {
                MessageBox(hX,"ASCII Transfer Complete","Put File",MB_OK);
                return 1;
            }
        }
        else
        {
            if(!FtpPutFile(hSecondary,strInFile,strOutFile,
                FTP_TRANSFER_TYPE_BINARY,0))
            {
                ErrorOut(hX,GetLastError(),"Get File");
                return 0;
            }
            else
            {
                MessageBox(hX,"Binary Transfer Complete","Get File",MB_OK);
                DisplayDir(hX,INTERNET_FLAG_RELOAD);
                return 1;
            }
        }
    }
}

Deleting files from an FTP server

To delete a file from an FTP server, an application can use the FtpDeleteFile function. The calling application must have the necessary privileges specified to delete a file from the FTP server when InternetConnect creates the FTP session handle.

The following example deletes the file indicated by the IDC_FTPEdit2 edit box. The HINTERNET handle, hSecondary, was created by InternetConnect after establishing an FTP session. DisplayDir is another function that is designed to enumerate the directory.

int WINAPI DeleteFile(HWND hX)
{
    char strInFile[80];

    GetDlgItemText(hX,IDC_FTPEdit2,strInFile,80);

    if (strlen(strInFile)==0)
    {
        MessageBox(hX,"File Name Must Be Specified!","Remove Dir",MB_OK);
        return 0;
    }
    else
    {
        if(!FtpDeleteFile(hSecondary,strInFile))
        {
            ErrorOut(hX,GetLastError(),"Remove Dir");
            return 0;
        }
        else
        {
            MessageBox(hX,"File Deleted", "Remove Dir", MB_OK);
            return DisplayDir(hX,INTERNET_FLAG_RELOAD);
        }
    }
}

Renaming files and directories on an FTP server

Renaming files and directories on an FTP server can be performed by using the FtpRenameFile function. FtpRenameFile accepts two NULL-terminated strings that contain either partially or fully qualified names relative to the current directory and then renames the file designated by the first string to the name in the second string.

The following example renames the file or directory indicated by the IDC_FTPEdit2 edit box. The HINTERNET handle, hSecondary, was created by InternetConnect after establishing an FTP session. DisplayDir is another function that is designed to enumerate the directory.

int WINAPI RenameFile(HWND hX)
{
    char strInFile[80];
    char strOutFile[80];

    GetDlgItemText(hX,IDC_FTPEdit3,strOutFile,80);
    GetDlgItemText(hX,IDC_FTPEdit2,strInFile,80);

    if ((strlen(strOutFile)==0) | (strlen(strInFile)==0))
    {
        MessageBox(hX,"Target File or Destination File Missing","Put File",MB_OK);
        return 0;
    }
    else
    {
        if(!FtpRenameFile(hSecondary,strInFile,strOutFile))
        {
            ErrorOut(hX,GetLastError(),"Get File");
            DisplayDir(hX,INTERNET_FLAG_RELOAD);
            return 0;
        }
        else
        {
            return DisplayDir(hX,INTERNET_FLAG_RELOAD);
        }
    }
}


Gopher Sessions

The Win32 Internet Gopher functions create and use Internet Gopher utilities to access information on Gopher servers worldwide.

Gopher functions, like the FTP functions, cannot be used through a CERN type proxy because CERN proxies recognize only HTTP. Applications that need to access a Gopher server through a CERN proxy should use InternetOpenUrl to access the resource directly. For more information on direct resource access, see Accessing URLs directly.

The following diagram shows the relationship of Win32 Internet functions used for the Gopher protocol. The shaded boxes represent functions that return HINTERNET handles, while the plain boxes represent functions that use the HINTERNET handle created by the function on which they depend.

Win32 Internet functions used for Gopher protocol

For more information on HINTERNET handles and the handle hierarchy, see Appendix A: HINTERNET Handles.

Using the Win32 Internet Functions for Gopher Sessions

The following Win32 Internet functions are used during Gopher sessions. These functions are not recognized by CERN proxies. Applications that must function through CERN type proxies should use InternetOpenUrl and access the resources directly. For more information on direct resource access, see Accessing URLs directly.
Function | Description
GopherAttributeEnumerator | Defines a callback function that processes attribute information from a Gopher server.
GopherCreateLocator | Forms a Gopher locator for use in other Gopher function calls.
GopherFindFirstFile | Starts enumerating a Gopher directory listing. This function requires a handle created by InternetConnect.
GopherGetAttribute | Retrieves attribute information on the Gopher object. This function requires a handle created by InternetConnect.
GopherGetLocatorType | Parses a Gopher locator and determines its attributes.
GopherOpenFile | Starts retrieving a Gopher object. This function requires a handle created by InternetConnect.

Creating locators

The Win32 Internet function GopherCreateLocator allows applications to create Gopher locators.

This function accepts the host address, server port used by the host, display string, selector string, Gopher type, address of the buffer that stores the locator, and the buffer length. If the buffer address is set to NULL, the buffer length needed to store the locator is stored in the buffer length variable. If the buffer size is insufficient, the function fails. The GetLastError function returns ERROR_INSUFFICIENT_BUFFER and stores the necessary length in the buffer length variable.

The display string contains the Gopher document or directory to be displayed. If this parameter is NULL, the function returns the default directory for the Gopher server.

The selector string contains the information that the application is searching for in the Gopher server. This parameter can be set to NULL.

Gopher types define the resource type the selector string is looking for; they can also define whether this is a Gopher or Gopher+ request. The following values are valid Gopher types:
GOPHER_TYPE_ASK | Ask+ item.
GOPHER_TYPE_BINARY | Binary file.
GOPHER_TYPE_BITMAP | Bitmap file.
GOPHER_TYPE_CALENDAR | Calendar file.
GOPHER_TYPE_CSO | CSO telephone book server.
GOPHER_TYPE_DIRECTORY | Directory of additional Gopher items.
GOPHER_TYPE_DOS_ARCHIVE | MS-DOS® archive file.
GOPHER_TYPE_ERROR | Error condition indicator.
GOPHER_TYPE_GIF | GIF graphics file.
GOPHER_TYPE_GOPHER_PLUS | Gopher+ item.
GOPHER_TYPE_HTML | HTML document.
GOPHER_TYPE_IMAGE | Image file.
GOPHER_TYPE_INDEX_SERVER | Index server.
GOPHER_TYPE_INLINE | Inline file.
GOPHER_TYPE_MAC_BINHEX | Macintosh file in BINHEX format.
GOPHER_TYPE_MOVIE | Movie file.
GOPHER_TYPE_PDF | PDF file.
GOPHER_TYPE_REDUNDANT | Duplicated server indicator. The information contained within is a duplicate of the primary server. The primary server is defined as the last directory entry that did not have a GOPHER_TYPE_REDUNDANT type.
GOPHER_TYPE_SOUND | Sound file.
GOPHER_TYPE_TELNET | Telnet server.
GOPHER_TYPE_TEXT_FILE | ASCII text file.
GOPHER_TYPE_TN3270 | TN3270 server.
GOPHER_TYPE_UNIX_UUENCODED | UUENCODED file.
GOPHER_TYPE_UNKNOWN | Unknown item type.

Enumerating directories

Enumeration of a directory on a Gopher server requires the creation of an HINTERNET handle by GopherFindFirstFile. This handle is a branch of the Gopher session handle created by InternetConnect. GopherFindFirstFile locates the first file or directory on the server and returns it in a GOPHER_FIND_DATA structure. Use InternetFindNextFile until it fails, returning ERROR_NO_MORE_FILES. This method finds all subsequent files and directories on the server. For more information on InternetFindNextFile, see Finding the Next File.

To determine the resource type retrieved by GopherFindFirstFile or InternetFindNextFile, check the GopherType member of the GOPHER_FIND_DATA structure. The following values are valid Gopher types:
GOPHER_TYPE_ASK | Ask+ item.
GOPHER_TYPE_BINARY | Binary file.
GOPHER_TYPE_BITMAP | Bitmap file.
GOPHER_TYPE_CALENDAR | Calendar file.
GOPHER_TYPE_CSO | CSO telephone book server.
GOPHER_TYPE_DIRECTORY | Directory of additional Gopher items.
GOPHER_TYPE_DOS_ARCHIVE | MS-DOS® archive file.
GOPHER_TYPE_ERROR | Error condition indicator.
GOPHER_TYPE_GIF | GIF graphics file.
GOPHER_TYPE_GOPHER_PLUS | Gopher+ item.
GOPHER_TYPE_HTML | HTML document.
GOPHER_TYPE_IMAGE | Image file.
GOPHER_TYPE_INDEX_SERVER | Index server.
GOPHER_TYPE_INLINE | Inline file.
GOPHER_TYPE_MAC_BINHEX | Macintosh file in BINHEX format.
GOPHER_TYPE_MOVIE | Movie file.
GOPHER_TYPE_PDF | PDF file.
GOPHER_TYPE_REDUNDANT | Duplicated server indicator. The information contained within is a duplicate of the primary server. The primary server is defined as the last directory entry that did not have a GOPHER_TYPE_REDUNDANT type.
GOPHER_TYPE_SOUND | Sound file.
GOPHER_TYPE_TELNET | Telnet server.
GOPHER_TYPE_TEXT_FILE | ASCII text file.
GOPHER_TYPE_TN3270 | TN3270 server.
GOPHER_TYPE_UNIX_UUENCODED | UUENCODED file.
GOPHER_TYPE_UNKNOWN | Unknown item type.

Downloading Gopher resources

The Win32 Internet functions GopherOpenFile and InternetReadFile allow applications to download a Gopher resource.

To begin downloading a resource, GopherOpenFile must create an HINTERNET handle off the Gopher session handle returned by InternetConnect. After the handle is created, InternetReadFile can be used to download the resource. For more information on using InternetReadFile, see Reading files.


HTTP Sessions

The Win32 Internet functions allow you to access resources on the World Wide Web (WWW). These resources can be accessed directly by using InternetOpenUrl (for more information, see Accessing URLs directly) or the HTTP functions.

Resources on the WWW are accessed by using HTTP. The Win32 Internet functions include a set of stable HTTP functions that handle the underlying protocols, while allowing your application to access information on the WWW. As the HTTP protocol evolves, the underlying protocols will be updated to maintain HTTP function behavior.

The following diagram shows the relationships of the Win32 Internet functions that are used for the HTTP protocol. The shaded boxes represent functions that return HINTERNET handles, while the plain boxes represent functions that use the HINTERNET handle created by the function on which they depend.

Win32 Internet functions used for HTTP

For more information on HINTERNET handles and the handle hierarchy, see Appendix A: HINTERNET Handles.

Using the Win32 Internet Functions to Access the WWW

The following functions are used during HTTP sessions to access the WWW.
Function | Description
HttpAddRequestHeaders | Adds HTTP request headers to the HTTP request handle. This function requires a handle created by HttpOpenRequest.
HttpOpenRequest | Opens an HTTP request handle. This function requires a handle created by InternetConnect.
HttpQueryInfo | Queries information about an HTTP request. This function requires a handle created by the HttpOpenRequest or InternetOpenUrl function.
HttpSendRequest | Sends the specified HTTP request to the HTTP server. This function requires a handle created by HttpOpenRequest.
InternetErrorDlg | Displays predefined dialog boxes for common Internet error conditions. This function requires the handle used in the call to HttpSendRequest.

Initiating a connection to the WWW

To start a connection to the WWW, the application must call the InternetConnect function on the root HINTERNET returned by InternetOpen. InternetConnect must establish an HTTP session by declaring the INTERNET_SERVICE_HTTP service type. For more information on using InternetConnect, see Using InternetConnect.

Opening a request

The HttpOpenRequest function opens an HTTP request and returns an HINTERNET handle that can be used by the other HTTP functions. Unlike the other open functions (such as FtpOpenFile and InternetOpenUrl), HttpOpenRequest does not send the request to the Internet when called. The HttpSendRequest function sends the request and establishes a connection over the network.

HttpOpenRequest takes an HTTP session handle created by InternetConnect and a verb, object name, version string, referrer, accept types, flags, and context value.

The verb is a string to be used in the request. Common verbs used in requests include "GET", "PUT", and "POST". If this value is set to NULL, HttpOpenRequest uses the default value "GET".

The object name is a string that contains the name of the specified verb's target object. This is generally a file name, an executable module, or a search specifier. If the object name supplied is an empty string, HttpOpenRequest looks for the default page.

The version string should contain the HTTP version. If this parameter is set to NULL, the function uses "HTTP/1.0".

The referrer specifies the address of the document from which the object name was obtained. If this parameter is NULL, no referrer is specified.

The NULL-terminated string containing the accept types indicates the content types accepted by the application. Setting this parameter to NULL indicates that no content types are accepted by the application. If an empty string is supplied, the application is indicating it accepts only documents of type "text/*". The value "text/*" indicates text-only documents—not pictures or other binary files.

The flag values control caching, cookies, and security issues. For Microsoft Network (MSN), NTLM, and other types of authentication, set the INTERNET_FLAG_KEEP_CONNECTION flag.

If the INTERNET_FLAG_ASYNC flag was set in the call to InternetOpen, a nonzero context value should be set for proper asynchronous operation.

The following example is a sample call to HttpOpenRequest.

hHttpRequest = HttpOpenRequest(hHttpSession, "GET", "", NULL, "", NULL, 0,0);

Adding request headers

The Win32 Internet function HttpAddRequestHeaders allows applications to add one or more request headers to the initial request. This function allows an application to append additional free-format headers to the HTTP request handle; it is intended for use by sophisticated applications that need precise control over the request sent to the HTTP server.

HttpAddRequestHeaders needs an HTTP request handle created by HttpOpenRequest, a string containing the headers, the length of the headers, and modifiers.

The following modifiers can be used with HttpAddRequestHeaders:
HTTP_ADDREQ_FLAG_ADD | Adds the header if it does not exist. Used with HTTP_ADDREQ_FLAG_REPLACE.
HTTP_ADDREQ_FLAG_ADD_IF_NEW | Adds the header only if it does not already exist; otherwise, an error is returned.
HTTP_ADDREQ_FLAG_COALESCE | Coalesces headers of the same name.
HTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA | Coalesces headers of the same name. For example, adding "Accept: text/*" followed by "Accept: audio/*" with this flag forms the single header "Accept: text/*, audio/*", causing the first header found to be coalesced. It is up to the calling application to ensure a cohesive scheme with respect to coalesced/separate headers.
HTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON | Coalesces headers of the same name, using a semicolon.
HTTP_ADDREQ_FLAG_REPLACE | Replaces or removes a header. If the header value is empty and the header is found, it is removed. If the header value is not empty, the header value is replaced.

Sending a request

HttpSendRequest establishes a connection to the Internet and sends the request to the specified site. This function requires an HINTERNET handle created by HttpOpenRequest. HttpSendRequest can also send additional headers or optional information. The optional information is generally used for operations that write information to the server, such as PUT and POST.

After HttpSendRequest sends the request, the application can use the InternetReadFile, InternetQueryDataAvailable, and InternetSetFilePointer functions on the HINTERNET handle created by HttpOpenRequest to download the server's resources.

Posting data to the server

To post data to a server, the verb in the call to HttpOpenRequest must be either "POST" or "PUT". The address of the buffer containing the POST data should then be passed to the lpOptional parameter in HttpSendRequest. The dwOptionalLength parameter should be set to the size of the data.

Using the Microsoft Internet Explorer 4.0 version of WinInet, you can also use the InternetWriteFile function to post data on an HINTERNET handle sent using HttpSendRequestEx.

Getting information about a request

HttpQueryInfo allows an application to retrieve information about an HTTP request. The function requires an HINTERNET handle created by HttpOpenRequest or InternetOpenUrl, an information level value, and a buffer length. HttpQueryInfo also accepts a buffer that stores the information and a zero-based header index that enumerates multiple headers with the same name.

The following information level values can be used with a modifier to control the format in which the information is stored in lpvBuffer:
HTTP_QUERY_ALLOW | Receives the methods supported by the server.
HTTP_QUERY_CONTENT_DESCRIPTION | Receives the content description.
HTTP_QUERY_CONTENT_ID | Receives the content identification.
HTTP_QUERY_CONTENT_LENGTH | Receives the size of the resource in bytes.
HTTP_QUERY_CONTENT_TRANSFER_ENCODING | Receives the additional content coding that has been applied to the resource.
HTTP_QUERY_CONTENT_TYPE | Receives the content type of the resource (such as text/html).
HTTP_QUERY_DATE | Receives the date and time at which the message was originated.
HTTP_QUERY_EXPIRES | Receives the date and time after which the resource should be considered outdated.
HTTP_QUERY_LAST_MODIFIED | Receives the date and time at which the server believes the resource was last modified.
HTTP_QUERY_MIME_VERSION | Receives the version of the MIME protocol that was used to construct the message.
HTTP_QUERY_PRAGMA | Receives the implementation-specific directives that might apply to any recipient along the request/response chain.
HTTP_QUERY_PUBLIC | Receives the methods available from this server.
HTTP_QUERY_RAW_HEADERS | Receives all the headers returned by the server. Each header is terminated by "\0". An additional "\0" terminates the list of headers.
HTTP_QUERY_RAW_HEADERS_CRLF | Receives all the headers returned by the server. Each header is separated by a carriage return/line feed (CR/LF) sequence.
HTTP_QUERY_REQUEST_METHOD | Receives the verb that is being used in the request, typically GET or POST.
HTTP_QUERY_STATUS_CODE | Receives the status code returned by the server.
HTTP_QUERY_STATUS_TEXT | Receives any additional text returned by the server on the response line.
HTTP_QUERY_URL | Receives some or all of the URLs by which the Request-URL resource can be identified.
HTTP_QUERY_VERSION | Receives the last response code returned by the server.

The following modifiers can be used with the information values:
HTTP_QUERY_CUSTOM | Causes HttpQueryInfo to search for the ASCIIZ header name specified in lpvBuffer and store the header information in lpvBuffer.
HTTP_QUERY_FLAG_COALESCE | Combines the values from headers with the same name into the output buffer.
HTTP_QUERY_FLAG_NUMBER | Returns the data as a 32-bit number for headers whose value is a number, such as the status code.
HTTP_QUERY_FLAG_REQUEST_HEADERS | Queries request headers only.
HTTP_QUERY_FLAG_SYSTEMTIME | Returns the header value as a standard Win32 SYSTEMTIME structure, which does not require the application to parse the data. Use for headers whose value is a date/time string, such as "Last-Modified-Time".
HTTP_QUERY_INFO_NUMBER | Sets the data type returned by HttpQueryInfo to a DWORD.

Downloading resources from the WWW

After opening a request with HttpOpenRequest and sending it to the server with HttpSendRequest, the application can use the InternetReadFile, InternetQueryDataAvailable, and InternetSetFilePointer functions to download the resource from the HTTP server.

The following example downloads a resource. The function accepts the handle to the current window, the identification number of an edit box, and an HINTERNET handle created by HttpOpenRequest and sent by HttpSendRequest. It uses InternetQueryDataAvailable to determine the size of the resource and then downloads it using InternetReadFile. The contents are then displayed in the edit box.

int WINAPI Dumper(HWND hX, int intCtrlID, HINTERNET hResource)
{
     LPSTR     lpszData;          // buffer for the data
     DWORD     dwSize;               // size of the data available
     DWORD     dwDownloaded;     // size of the downloaded data
     DWORD     dwSizeSum=0;     // size of the data in the textbox
     LPSTR     lpszHolding;     // buffer to merge the textbox data and buffer

     // Set the cursor to an hourglass.
     SetCursor(LoadCursor(NULL,IDC_WAIT));

     // This loop handles reading the data.
     do
     {
          // The call to InternetQueryDataAvailable determines the amount of
          // data available to download.
          if (!InternetQueryDataAvailable(hResource,&dwSize,0,0))
          {
               ErrorOut(hX,GetLastError(),"InternetReadFile");
               SetCursor(LoadCursor(NULL,IDC_ARROW));
               return FALSE;
          }
          else
          {
               // Allocates a buffer of the size returned by InternetQueryDataAvailable
               lpszData = new char[dwSize+1];

               // Reads the data from the HINTERNET handle.
               if(!InternetReadFile(hResource,(LPVOID)lpszData,dwSize,&dwDownloaded))
               {
                    ErrorOut(hX,GetLastError(),"InternetReadFile");
                    delete[] lpszData;
                    break;
               }
               else
               {
                    // Adds a null terminator to the end of the data buffer
                    lpszData[dwDownloaded]='\0';

                    // Allocates the holding buffer
                    lpszHolding = new char[dwSizeSum + dwDownloaded + 1];

                    // Checks if there has been any data written to the textbox
                    if (dwSizeSum != 0)
                    {
                         // Retrieves the data stored in the textbox if any
                         GetDlgItemText(hX,intCtrlID,(LPSTR)lpszHolding,dwSizeSum);

                         // Adds a null terminator at the end of the textbox data
                         lpszHolding[dwSizeSum]='\0';
                    }
                    else
                    {
                         // Make the holding buffer an empty string.
                         lpszHolding[0]='\0';
                    }

                    // Adds the new data to the holding buffer
                    strcat(lpszHolding,lpszData);

                    // Writes the holding buffer to the textbox
                    SetDlgItemText(hX,intCtrlID,(LPSTR)lpszHolding);

                    // Delete the two buffers
                    delete[] lpszHolding;
                    delete[] lpszData;

                    // Add the size of the downloaded data to the textbox data size
                    dwSizeSum = dwSizeSum + dwDownloaded + 1;

                    // Check the size of the remaining data.  If it is zero, break.
                    if (dwDownloaded == 0)
                         break;
               }
          }
     }
     while(TRUE);

     // Close the HINTERNET handle
     InternetCloseHandle(hResource);

     // Set the cursor back to an arrow
     SetCursor(LoadCursor(NULL,IDC_ARROW));

     // Return
     return TRUE;
}


Microsoft Win32 Internet Functions Overview

The Microsoft® Win32® Internet (WinInet) API provides stand-alone applications with easy access to standard Internet protocols such as Gopher, FTP, and HTTP, abstracting the protocols into a high-level interface that is familiar to Win32 developers. This section covers how to use the Win32 Internet API in an application. See the Microsoft Win32 Internet Functions Reference for descriptions of the individual functions.

Introduction

Establishing a Dial-Up Connection to the Internet

Enabling Internet Functionality

Common Functions

Handling Uniform Resource Locators

Handling Authentication

FTP Sessions

Gopher Sessions

HTTP Sessions

Cookie Functions

Caching

Appendix A: HINTERNET Handles

Appendix B: Using Buffers

Appendix C: Handling Errors

Introduction

The following sections contain an overview of the Microsoft® Win32® Internet (WinInet) functions, which provide developers with a set of functions to interact with Gopher, FTP, and HTTP protocols. As the standards evolve, the Win32 Internet functions will handle the changes in underlying protocols, allowing the functions to maintain a consistent behavior. This overview describes how to use these functions to access the vast resources on the Internet.

The Win32 Internet functions do require an understanding of C/C++, a familiarity with Win32 programming, and a basic understanding of the FTP, Gopher, and HTTP protocols.

Internet Protocols

The three major protocols used on the Internet are the FTP, Gopher, and HTTP protocols.

For the more information on these protocols, see the Request For Comments (RFC) documents that cover FTP, Gopher, and HTTP specifications. The following documents on these protocols can be found on the Internet:

  • RFC 959, File Transfer Protocol (FTP), can be found at http://ds.internic.net/rfc/rfc959.txt. External link
  • RFC 1436, The Internet Gopher Protocol, can be found at http://ds.internic.net/rfc/rfc1436.txt. External link
  • RFC 1945, Hypertext Transfer Protocol - HTTP/1.0, can be found at http://ds.internic.net/rfc/rfc1945.txt. External link
  • RFC 2068, Hypertext Transfer Protocol - HTTP/1.1, can be found at http://ds.internic.net/rfc/rfc2068.txt. External link


Handling Uniform Resource Locators

A Uniform Resource Locator (URL) is a compact representation of the location and access method for a resource located on the Internet. Each URL consists of a scheme (HTTP, HTTPS, FTP, or Gopher) and a scheme-specific string. This string can also include a combination of a directory path, search string, or name of the resource. The Win32 Internet functions provide the ability to create, combine, break down, and canonicalize URLs. For more information on URLs, see RFC 1738, Uniform Resource Locators (URL). This document can be found at http://ds.internic.net/rfc/rfc1738.txt. External link

The URL functions operate in a task-oriented manner. The content and format of the URL that is given to the function is not verified. The calling application should track the use of these functions to ensure that the data is in the intended format. For example, the InternetCanonicalizeUrl function would convert the character "%" into the escape sequence "%25" when using no flags. If InternetCanonicalizeUrl is used on the canonicalized URL, the escape sequence "%25" would be converted into the escape sequence "%2525", which would not work properly.

The following table summarizes the URL functions in the Win32 Internet API.
Function | Description
InternetCanonicalizeUrl | Canonicalizes the URL that is passed to the function. By default, InternetCanonicalizeUrl always encodes.
InternetCombineUrl | Combines base and relative URLs into one complete URL.
InternetCrackUrl | Breaks the URL into its component parts. This information is returned in a URL_COMPONENTS structure.
InternetCreateUrl | Allows an application to create a complete URL from its component parts.
InternetOpenUrl | Locates the resource designated by a canonicalized URL and creates a handle, which can be used by InternetReadFile to retrieve that resource. InternetOpenUrl combines the tasks normally performed by InternetConnect with the operations handled by FtpOpenFile, GopherOpenFile, and HttpOpenRequest.

What Is a Canonicalized URL?

The format of all URLs must follow the accepted syntax and semantics in order to access resources via the Internet. Canonicalization is the process of formatting a URL to follow this accepted syntax and semantics.

Characters that must be encoded include any characters that have no corresponding graphic character in the US-ASCII coded character set (hexadecimal 80-FF, which are not used in the US-ASCII coded character set, and hexadecimal 00-1F and 7F, which are control characters), blank spaces, "%" (which is used to encode other characters), and unsafe characters (<, >, ", #, {, }, |, \, ^, ~, [, ], and ').

Using the Win32 Internet Functions to Handle URLs

The following table summarizes the URL functions included with the Win32 Internet functions.
Function | Description
InternetCanonicalizeUrl | Canonicalizes the URL.
InternetCombineUrl | Combines base and relative URLs.
InternetCrackUrl | Parses a URL string into components.
InternetCreateUrl | Creates a URL string from components.
InternetOpenUrl | Begins retrieving an FTP, Gopher, HTTP, or HTTPS resource.

Canonicalizing URLs

Canonicalizing a URL is the process that converts a URL (that might contain unsafe characters such as blank spaces, reserved characters, and so on) into an accepted format.

The InternetCanonicalizeUrl function can be used to canonicalize URLs. This function is very task-oriented, so the application should track its use carefully. InternetCanonicalizeUrl does not verify that the URL passed to it is already canonicalized and that the URL that it returns is valid.

The following five flags control how InternetCanonicalizeUrl handles a particular URL. The flags can be used in combination. If no flags are used, the function encodes the URL by default.
Value | Meaning
ICU_BROWSER_MODE | Do not encode or decode characters after "#" or "?", and do not remove trailing white space after "?". If this value is not specified, the entire URL is encoded, and trailing white space is removed.
ICU_DECODE | Convert all %XX sequences to characters, including escape sequences, before the URL is parsed.
ICU_ENCODE_SPACES_ONLY | Encode spaces only.
ICU_NO_ENCODE | Do not convert unsafe characters to escape sequences.
ICU_NO_META | Do not remove meta sequences (such as "." and "..") from the URL.

The ICU_DECODE flag should be used only on canonicalized URLs, because it assumes that all %XX sequences are escape codes and converts them into the characters indicated by the code. If the URL has a "%" symbol in it that is not part of an escape code, ICU_DECODE still treats it as one. This characteristic might cause InternetCanonicalizeUrl to create an invalid URL.

To use InternetCanonicalizeUrl to return a completely decoded URL, the ICU_DECODE and ICU_NO_ENCODE flags must be specified. This setup assumes that the URL being passed to InternetCanonicalizeUrl has been previously canonicalized.

Combining base and relative URLs

A relative URL is a compact representation of the location of a resource relative to an absolute base URL. The base URL must be known to the parser and usually includes the scheme, network location, and parts of the URL path. An application can call InternetCombineUrl to combine the relative URL with its base URL. InternetCombineUrl will also canonicalize the resultant URL.

Cracking URLs

The InternetCrackUrl function separates a URL into its component parts and returns the components indicated by the URL_COMPONENTS structure that is passed to the function.

The components that make up the URL_COMPONENTS structure are the scheme number, host name, port number, user name, password, URL path, and additional information (such as search parameters). Each component, except the scheme and port numbers, has a string member that holds the information and a member that holds the length of the string member. The scheme and port numbers have only a member that stores the corresponding value; they are both returned on all successful calls to InternetCrackUrl.

To get the value of a particular component in the URL_COMPONENTS structure, the member that stores the string length of that component must be set to a nonzero value. The string member can be either the address of a buffer or NULL.

If the pointer member contains the address of a buffer, the string length member must contain the size of that buffer. InternetCrackUrl returns the component information as a string in the buffer and stores the string length in the string length member.

If the pointer member is set to NULL, the string length member can be set to any nonzero value. InternetCrackUrl stores the address of the first character of the URL string that contains the component information and sets the string length to the number of characters in the remaining part of the URL string that pertains to the component.

All pointer members set to NULL with a nonzero length member point to the appropriate starting point in the URL string. The length stored in the length member must be used to determine the end of the individual component's information.

To finish initializing the URL_COMPONENTS structure properly, the dwStructSize member must be set to the size of the URL_COMPONENTS structure.

The following example returns the components of the URL in the edit box, IDC_PreOpen1, and returns the components to the list box, IDC_PreOpenList. To display only the information for an individual component, this function copies the character immediately after the component's information in the string and temporarily replaces it with a NULL.

int WINAPI Cracker(HWND hX)
{
    URL_COMPONENTS urlcmpTheUrl;
    int intTestSize = 80;
    LPSTR lpszUrlIn;
    LPURL_COMPONENTS lpUrlComp = &urlcmpTheUrl;
    char TempOut[256];
    char tempChar;

    lpszUrlIn = new char[intTestSize];
    GetDlgItemText(hX,IDC_PreOpen1,lpszUrlIn,intTestSize);
    SendDlgItemMessage(hX,IDC_PreOpenList,LB_RESETCONTENT,0,0);
    urlcmpTheUrl.dwStructSize = sizeof(urlcmpTheUrl);

    urlcmpTheUrl.lpszScheme = NULL;
    urlcmpTheUrl.lpszHostName = NULL;
    urlcmpTheUrl.lpszUserName = NULL;
    urlcmpTheUrl.lpszPassword = NULL;
    urlcmpTheUrl.lpszUrlPath = NULL;
    urlcmpTheUrl.lpszExtraInfo = NULL;

    /* the following lines set which components will be displayed */
    urlcmpTheUrl.dwSchemeLength = 1;
    urlcmpTheUrl.dwHostNameLength = 1;
    urlcmpTheUrl.dwUserNameLength = 1;
    urlcmpTheUrl.dwPasswordLength = 1;
    urlcmpTheUrl.dwUrlPathLength = 1;
    urlcmpTheUrl.dwExtraInfoLength = 1;

    if (!InternetCrackUrl(lpszUrlIn,strlen(lpszUrlIn),0, lpUrlComp))
    {
        ErrorOut(hX,GetLastError(),"Cracker");
        return FALSE;
    }
    else
    {
        if (urlcmpTheUrl.dwSchemeLength != 0)
        {
            tempChar = urlcmpTheUrl.lpszScheme[urlcmpTheUrl.dwSchemeLength];
            urlcmpTheUrl.lpszScheme[urlcmpTheUrl.dwSchemeLength]='\0';
            sprintf(TempOut, "Scheme: %s", urlcmpTheUrl.lpszScheme);
            SendDlgItemMessage(hX,IDC_PreOpenList,LB_ADDSTRING,0,
                (LPARAM)TempOut);
            urlcmpTheUrl.lpszScheme[urlcmpTheUrl.dwSchemeLength]= tempChar;
        }

        sprintf(TempOut, "Scheme number: %d", urlcmpTheUrl.nScheme);
        SendDlgItemMessage(hX,IDC_PreOpenList,LB_ADDSTRING,0,
            (LPARAM)TempOut);

        if (urlcmpTheUrl.dwHostNameLength != 0)
        {
            tempChar = urlcmpTheUrl.lpszHostName[urlcmpTheUrl.dwHostNameLength];
            urlcmpTheUrl.lpszHostName[urlcmpTheUrl.dwHostNameLength] = '\0';
            sprintf(TempOut, "Host Name: %s", urlcmpTheUrl.lpszHostName);
            SendDlgItemMessage(hX,IDC_PreOpenList,LB_ADDSTRING,0,
                (LPARAM)TempOut);
            urlcmpTheUrl.lpszHostName[urlcmpTheUrl.dwHostNameLength] = tempChar;
        }

        sprintf(TempOut, "Port Number: %d", urlcmpTheUrl.nPort);
        SendDlgItemMessage(hX,IDC_PreOpenList,LB_ADDSTRING,0,
            (LPARAM)TempOut);

        if (urlcmpTheUrl.dwUserNameLength != 0)
        {
            tempChar = urlcmpTheUrl.lpszUserName[urlcmpTheUrl.dwUserNameLength];
            urlcmpTheUrl.lpszUserName[urlcmpTheUrl.dwUserNameLength] = '\0';
            sprintf(TempOut, "User Name: %s", urlcmpTheUrl.lpszUserName);
            SendDlgItemMessage(hX,IDC_PreOpenList,LB_ADDSTRING,0,
                (LPARAM)TempOut);
            urlcmpTheUrl.lpszUserName[urlcmpTheUrl.dwUserNameLength] = tempChar;
        }

        if (urlcmpTheUrl.dwPasswordLength != 0)
        {
            tempChar= urlcmpTheUrl.lpszPassword[urlcmpTheUrl.dwPasswordLength];
            urlcmpTheUrl.lpszPassword[urlcmpTheUrl.dwPasswordLength] = '\0';
            sprintf(TempOut, "Password: %s", urlcmpTheUrl.lpszPassword);
            SendDlgItemMessage(hX,IDC_PreOpenList,LB_ADDSTRING,0,
                (LPARAM)TempOut);
            urlcmpTheUrl.lpszPassword[urlcmpTheUrl.dwPasswordLength] = tempChar;
        }

        if (urlcmpTheUrl.dwUrlPathLength != 0)
        {
            tempChar=urlcmpTheUrl.lpszUrlPath[urlcmpTheUrl.dwUrlPathLength];
            urlcmpTheUrl.lpszUrlPath[urlcmpTheUrl.dwUrlPathLength] = '\0';
            sprintf(TempOut, "Path: %s", urlcmpTheUrl.lpszUrlPath);
            SendDlgItemMessage(hX,IDC_PreOpenList,LB_ADDSTRING,0,
                (LPARAM)TempOut);
            urlcmpTheUrl.lpszUrlPath[urlcmpTheUrl.dwUrlPathLength] = tempChar;
        }

        if(urlcmpTheUrl.dwExtraInfoLength != 0)
        {
            tempChar = urlcmpTheUrl.lpszExtraInfo[urlcmpTheUrl.dwExtraInfoLength];
            urlcmpTheUrl.lpszExtraInfo[urlcmpTheUrl.dwExtraInfoLength] = '\0';
            sprintf(TempOut, "Extra: %s", urlcmpTheUrl.lpszExtraInfo);
            SendDlgItemMessage(hX,IDC_PreOpenList,LB_ADDSTRING,0,
                (LPARAM)TempOut);
            urlcmpTheUrl.lpszExtraInfo[urlcmpTheUrl.dwExtraInfoLength] = tempChar;
        }

        return TRUE;
    }
}

Creating URLs

The InternetCreateUrl function uses the information in the URL_COMPONENTS structure to create a Uniform Resource Locator.

The components that make up the URL_COMPONENTS structure are the scheme, host name, port number, user name, password, URL path, and additional information (such as search parameters). Each component, except the port number, has a string member that holds the information and a member that holds the length of the string member.

For each required component, the pointer member should contain the address of the buffer holding the information. The length member should be set to zero if the pointer member contains the address of a zero-terminated string; the length member should be set to the string length if the pointer member contains the address of a string that is not zero-terminated. The pointer member of any components that are not required must be set to NULL.

Accessing URLs directly

Gopher, FTP, and HTTP resources on the Internet can be accessed directly by using the InternetOpenUrl, InternetReadFile, and InternetFindNextFile functions. InternetOpenUrl opens a connection to the resource at the URL passed to the function. When this connection is made, there are two possible steps. First, if the resource is a file, InternetReadFile can download it; second, if the resource is a directory, InternetFindNextFile can enumerate the files within the directory (except when using CERN proxies). For more information on InternetReadFile, see Reading files. For more information on InternetFindNextFile, see Finding the next file.

For applications that need to operate through a CERN proxy, InternetOpenUrl can be used to access FTP directories and files. The FTP requests are packaged to appear like an HTTP request, which the CERN proxy would accept.

InternetOpenUrl uses the HINTERNET handle created by the InternetOpen function and the URL of the resource. The URL must include the scheme ("http:", "ftp:", "gopher:", "file:" [for a local file], or "https:" [for hypertext protocol secure]) and network location (such as "www.microsoft.com"). The URL can also include a path (for example, "/windows/feature/") and resource name (for example, "default.htm"). For HTTP or HTTPS requests, additional headers can be included.

InternetQueryDataAvailable, InternetFindNextFile, InternetReadFile, and InternetSetFilePointer (HTTP or HTTPS URLs only) can use the handle that is created by InternetOpenUrl to download the resource.

The following diagram illustrates what handles to use with each function.

Handles to use with functions

The root HINTERNET handle created by InternetOpen is used by InternetOpenUrl. The HINTERNET handle created by InternetOpenUrl can be used by InternetQueryDataAvailable, InternetReadFile, InternetFindNextFile (not shown here), and InternetSetFilePointer (HTTP or HTTPS URLs only).

For more information about HINTERNET handles and the handle hierarchy, see Appendix A: HINTERNET Handles.

The following example connects to the resource by using the InternetOpenUrl function. The sample function then uses the InternetReadFile function to download the resource. The function displays the downloaded resource in the edit box indicated by intCtrlID.

int WINAPI UrlDump(HWND hX, int intCtrlID)
{

     HINTERNET hUrlDump;
     DWORD dwSize=TRUE;
     LPSTR lpszData;
     LPSTR lpszOutPut;
     LPSTR lpszHolding;
     int nCounter=1;
     int nBufferSize;
     DWORD BigSize=8000;

     hUrlDump = InternetOpenUrl(hRootHandle, "server.name", NULL, NULL,
        INTERNET_FLAG_RAW_DATA, 0);

     do
     {
          // Allocate the buffer
          lpszData =new char[BigSize+1];

          // Read the data
          if(!InternetReadFile(hUrlDump,(LPVOID)lpszData,BigSize,&dwSize))
          {
               ErrorOut(hX,GetLastError(),"InternetReadFile");
               delete []lpszData;
               break;
          }
          else
          {
               // Add a null terminator to the end of the buffer
               lpszData[dwSize]='\0';

               // Check if all of the data has been read.  This should never
               // get called on the first time through the loop.
               if (dwSize == 0)
               {
                    // Write the final data to the textbox
                    SetDlgItemText(hX,intCtrlID,lpszHolding);

                    // Delete the existing buffers.
                    delete [] lpszData;
                    delete [] lpszHolding;
                    break;
               }

               // Determine the buffer size to hold the new data and the data
               // already written to the textbox (if any).
               nBufferSize = (nCounter*BigSize)+1;

               // Increment the number of buffers read
               nCounter++;

               // Allocate the output buffer
               lpszOutPut = new char[nBufferSize];

               // Make sure the buffer is not the initial buffer
               if(nBufferSize != int(BigSize+1))
               {
                    // Copy the data in the holding buffer
                    strcpy(lpszOutPut,lpszHolding);

                    // Concatenate the new buffer with the output buffer
                    strcat(lpszOutPut,lpszData);

                    // Delete the holding buffer
                    delete [] lpszHolding;
               }
               else
               {
                    // Copy the data buffer
                    strcpy(lpszOutPut, lpszData);
               }

               // Allocate a holding buffer
               lpszHolding = new char[nBufferSize];

               // Copy the output buffer into the holding buffer
               memcpy(lpszHolding,lpszOutPut,nBufferSize);

               // Delete the other buffers
               delete [] lpszData;
               delete [] lpszOutPut;

          }

     }
     while (TRUE);

     // Close the HINTERNET handle
     InternetCloseHandle(hUrlDump);

     // Set the cursor back to an arrow
     SetCursor(LoadCursor(NULL,IDC_ARROW));

     // Return
     return TRUE;
}


GOPHER_ATTRIBUTE_TYPE

typedef struct {
    DWORD CategoryId
    DWORD AttributeId
    union {
        GOPHER_ADMIN_ATTRIBUTE Admin;
        GOPHER_MOD_DATE_ATTRIBUTE ModDate;
        GOPHER_SCORE_ATTRIBUTE Score;
        GOPHER_SCORE_RANGE_ATTRIBUTE ScoreRange;
        GOPHER_SITE_ATTRIBUTE Site;
        GOPHER_ORGANIZATION_ATTRIBUTE Organization;
        GOPHER_LOCATION_ATTRIBUTE Location;
        GOPHER_GEOGRAPHICAL_LOCATION_ATTRIBUTE GeographicalLocation;
        GOPHER_TIMEZONE_ATTRIBUTE TimeZone;
        GOPHER_PROVIDER_ATTRIBUTE Provider;
        GOPHER_VERSION_ATTRIBUTE Version;
        GOPHER_ABSTRACT_ATTRIBUTE Abstract;
        GOPHER_VIEW_ATTRIBUTE View;
        GOPHER_VERONICA_ATTRIBUTE Veronica;
        GOPHER_ASK_ATTRIBUTE_TYPE Ask;
        GOPHER_UNKNOWN_ATTRIBUTE Unknown;
    } AttributeType;
} GOPHER_ATTRIBUTE_TYPE, *LPGOPHER_ATTRIBUTE_TYPE;

Contains the relevant information of a single Gopher attribute for an object.

CategoryId
Gopher name for the attribute. The possible values include:
GOPHER_CATEGORY_ID_ABSTRACT
GOPHER_CATEGORY_ID_ADMIN
GOPHER_CATEGORY_ID_ALL
GOPHER_CATEGORY_ID_INFO
GOPHER_CATEGORY_ID_UNKNOWN
GOPHER_CATEGORY_ID_VERONICA
GOPHER_CATEGORY_ID_VIEWS
AttributeId
Identifier of the structure contained in the AttributeType member. The possible values include:
GOPHER_ATTRIBUTE_ID_ABSTRACT
GOPHER_ATTRIBUTE_ID_ADMIN
GOPHER_ATTRIBUTE_ID_GEOG
GOPHER_ATTRIBUTE_ID_LOCATION
GOPHER_ATTRIBUTE_ID_MOD_DATE
GOPHER_ATTRIBUTE_ID_ORG
GOPHER_ATTRIBUTE_ID_PROVIDER
GOPHER_ATTRIBUTE_ID_RANGE
GOPHER_ATTRIBUTE_ID_SCORE
GOPHER_ATTRIBUTE_ID_SITE
GOPHER_ATTRIBUTE_ID_TIMEZONE
GOPHER_ATTRIBUTE_ID_TREEWALK
GOPHER_ATTRIBUTE_ID_TTL
GOPHER_ATTRIBUTE_ID_UNKNOWN
GOPHER_ATTRIBUTE_ID_VERSION
GOPHER_ATTRIBUTE_ID_VIEW
AttributeType
Actual setting for the Gopher attribute. The specific value of AttributeType depends on the AttributeId member. The definitions of the various attribute structures are available in Wininet.h.

See also GopherGetAttribute


GOPHER_FIND_DATA

typedef struct {
    TCHAR DisplayString[MAX_GOPHER_DISPLAY_TEXT + 1];
    DWORD GopherType;
    DWORD SizeLow;
    DWORD SizeHigh;
    FILETIME LastModificationTime;
    TCHAR Locator[MAX_GOPHER_LOCATOR_LENGTH + 1];
} GOPHER_FIND_DATA, FAR *LPGOPHER_FIND_DATA;

Contains information retrieved by the GopherFindFirstFile and InternetFindNextFile functions.

DisplayString
String that contains the friendly name of an object. An application can display this string to allow the user to select the object.
GopherType
Mask of flags that describe the item returned. Can be one of the following values:
GOPHER_TYPE_ASK | Ask+ item.
GOPHER_TYPE_BINARY | Binary file.
GOPHER_TYPE_BITMAP | Bitmap file.
GOPHER_TYPE_CALENDAR | Calendar file.
GOPHER_TYPE_CSO | CSO telephone book server.
GOPHER_TYPE_DIRECTORY | Directory of additional Gopher items.
GOPHER_TYPE_DOS_ARCHIVE | MS-DOS archive file.
GOPHER_TYPE_ERROR | Indicator of an error condition.
GOPHER_TYPE_GIF | GIF graphics file.
GOPHER_TYPE_GOPHER_PLUS | Gopher+ item.
GOPHER_TYPE_HTML | HTML document.
GOPHER_TYPE_IMAGE | Image file.
GOPHER_TYPE_INDEX_SERVER | Index server.
GOPHER_TYPE_INLINE | Inline file.
GOPHER_TYPE_MAC_BINHEX | Macintosh file in BINHEX format.
GOPHER_TYPE_MOVIE | Movie file.
GOPHER_TYPE_PDF | PDF file.
GOPHER_TYPE_REDUNDANT | Indicator of a duplicated server. The information contained within is a duplicate of the primary server. The primary server is defined as the last directory entry that did not have a GOPHER_TYPE_REDUNDANT type.
GOPHER_TYPE_SOUND | Sound file.
GOPHER_TYPE_TELNET | Telnet server.
GOPHER_TYPE_TEXT_FILE | ASCII text file.
GOPHER_TYPE_TN3270 | TN3270 server.
GOPHER_TYPE_UNIX_UUENCODED | UUENCODED file.
GOPHER_TYPE_UNKNOWN | Item type is unknown.
SizeLow
Low 32 bits of the file size.
SizeHigh
High 32 bits of the file size.
LastModificationTime
Time when the file was last modified.
Locator
String that identifies the file. An application can pass the locator string to GopherOpenFile or GopherFindFirstFile.


HTTP_VERSION_INFO

typedef  struct{
    DWORD dwMajorVersion;
    DWORD dwMinorVersion;

Contains the global HTTP version (either 1.0 or 1.1).

dwMajorVersion
Major version number. Must be 1.
dwMinorVersion
Minor version number. Can be either 1 or 0.


INTERNET_ASYNC_RESULT

typedef struct {
    DWORD dwResult;
    DWORD dwError;
} INTERNET_ASYNC_RESULT, * LPINTERNET_ASYNC_RESULT;

Contains the result of a call to an asynchronous function. This structure is used with INTERNET_STATUS_CALLBACK.

dwResult
HINTERNET, DWORD, or BOOL return code from an asynchronous function.
dwError
Error message if dwResult indicates that the function failed. If the operation succeeded, this member usually contains ERROR_SUCCESS.


INTERNET_AUTHNOTIFY_DATA

typedef struct {
    DWORD cbStruct;
    DWORD dwOptions;
    PFN_PUTHNOTIFY pfnNotify;
    DWORD dwConext;
} INTERNET_AUTHNOTIFY_DATA;
cbStruct
Size of the structure.
dwOptions
Reserved; must be set to zero.
pfnNotify
Notification callback to retry InternetErrorDlg.
dwContext
Context to pass to the notification function.


INTERNET_BUFFERS

typedef struct _INTERNET_BUFFERS {
    DWORD dwStructSize;
    struct _INTERNET_BUFFERS * Next;
    LPCTSTR lpcszHeader;
    DWORD dwHeadersLength;
    DWORD dwHeadersTotal;
    LPVOID lpvBuffer;
    DWORD dwBufferLength;
    DWORD dwBufferTotal;
    DWORD dwOffsetLow;
    DWORD dwOffsetHigh;
} INTERNET_BUFFERS, * LPINTERNET_BUFFERS;

Contains both the data and header information.

dwStructSize
Double-word value used for API versioning. Set to the size of the INTERNET_BUFFERS structure.
Next
Address of the next INTERNET_BUFFERS structure.
lpcszHeader
String value containing the headers. This value can be NULL.
dwHeadersLength
Double-word value containing the length of the headers if lpcszHeader is not NULL.
dwHeadersTotal
Double-word value that contains the size of the headers if there is not enough memory in the buffer.
lpvBuffer
Address of the data buffer.
dwBufferLength
Double-word value that contains the length of the buffer if lpvBuffer is not NULL.
dwBufferTotal
Double-word value that contains the total size of the chunk or the content length if it is not chunked.
dwOffsetLow
Double-word value that is used for read ranges.
dwOffsetHigh
Double-word value that is used for read ranges.


INTERNET_CACHE_ENTRY_INFO

typedef struct _CACHE_ENTRY_INFO {
    DWORD dwStructSize;
    LPSTR lpszSourceUrlName;
    LPSTR lpszLocalFileName;
    DWORD CacheEntryType;
    DWORD dwUseCount;
    DWORD dwHitRate;
    DWORD dwSizeLow;
    DWORD dwSizeHigh;
    FILETIME LastModifiedTime;
    FILETIME ExpireTime;
    FILETIME LastAccessTime;
    FILETIME LastSyncTime;
    LPBYTE lpHeaderInfo;
    DWORD dwHeaderInfoSize;
    LPSTR lpszFileExtension;
    union (DWORD dwReserved; DWORD dwExemptDelta;)
} INTERNET_CACHE_ENTRY_INFO, *LPINTERNET_CACHE_ENTRY_INFO;

Contains information about an entry in the cache.

dwStructSize
Size, in bytes, of this structure.
lpszSourceUrlName
Address of a string that contains the URL name. The string occupies memory area at the end of this structure.
lpszLocalFileName
Address of a string that contains the local file name. The string occupies memory area at the end of this structure.
CacheEntryType
Cache type bitmask. Currently, the cache entry type value of resources from the Internet is equal to zero. For History and Cookie entries, the cache entry type is a combination of two values. One value determines how the cache entry is handled; the second value indicates what is being cached.

The value that determines how the cache entry is handled can be one of the following:
NORMAL_CACHE_ENTRY | Normal cache entry; can be deleted to recover space for new entries.
SPARSE_CACHE_ENTRY | Not currently implemented.
STABLE_CACHE_ENTRY | Not currently implemented.
STICKY_CACHE_ENTRY | Sticky cache entry that is exempt from scavenging for amount of time specified by dwExemptDelta. The default value set by CommitUrlCacheEntry is one day.

The value that indicates what is being cached can be one of the following:
COOKIE_CACHE_ENTRY | Cookie cache entry.
OCX_CACHE_ENTRY | Not currently implemented.
URLHISTORY_CACHE_ENTRY | Visited link cache entry.

dwUseCount
Current user count of the cache entry.
dwHitRate
Number of times the cache entry was retrieved.
dwSizeLow
Low-order double word of the file size.
dwSizeHigh
High-order double word of the file size.
LastModifiedTime
Last modified time of this URL, in GMT format.
ExpireTime
Expiration time of this file, in GMT format.
LastAccessTime
Last accessed time, in GMT format.
LastSyncTime
Last time the cache was synchronized.
lpHeaderInfo
Address of a buffer that contains the header information. The buffer occupies memory at the end of this structure.
dwHeaderInfoSize
Size of the lpHeaderInfo buffer.
lpszFileExtension
Address of a string that contains the file extension used to retrieve the data as a file. The string occupies memory area at the end of this structure.
union (DWORD dwReserved; DWORD dwExemptDelta;)
Exemption time, in seconds, from the last accessed time.

There is no cache entry size limit, so applications that need to enumerate the cache must be prepared to allocate variable-sized buffers. For more information, see Appendix B: Using Buffers.


INTERNET_CERTIFICATE_INFO

typedef struct {
    FILETIME ftExpiry;
    FILETIME ftStart;
    LPSTR lpszSubjectInfo;
    LPSTR lpszIssuerInfo;
    LPSTR lpszProtocolName;
    LPSTR lpszSignatureAlgName;
    LPSTR lpszEncryptionAlgName;
    DWORD dwKeySize;
} INTERNET_CERTIFICATE_INFO, * LPINTERNET_CERTIFICATE_INFO;

Contains certificate information returned from the server. This structure is used by the InternetQueryOption function.

ftExpiry
FILETIME structure that contains the date the certificate expires.
ftStart
FILETIME structure that contains the date the certificate becomes valid.
lpszSubjectInfo
Address of a buffer that contains the name of the organization, site, and server for which the certificate was issued.
lpszIssuerInfo
Address of a buffer that contains the name of the organization, site, and server that issued the certificate.
lpszProtocolName
Address of a buffer that contains the name of the protocol used to provide the secure connection.
lpszSignatureAlgName
Address of a buffer that contains the name of the algorithm used for signing the certificate.
lpszEncryptionAlgName
Address of a buffer that contains the name of the algorithm used for doing encryption over the secure channel (SSL/PCT) connection.
dwKeySize
Size, in bytes, of the key.

Applications requesting this information must free pointers that are allocated and placed in the returned structure.


INTERNET_CONNECTED_INFO

typedef struct {
    DWORD dwConnectedState;
    DWORD dwFlags
} INTERNET_CONNECTED_INFO, * LPINTERNET_CONNECTED_INFO;

Contains the information to set the global online/offline state.

dwConnectedState
DWORD value that contains the state information. Can be one of the following values:
INTERNET_STATE_CONNECTED | Connected to network. Replaces INTERNET_STATE_ONLINE.
INTERNET_STATE_DISCONNECTED | Disconnected from network. Replaces INTERNET_STATE_OFFLINE.
INTERNET_STATE_DISCONNECTED_BY_USER | Disconnected by user request. Replaces INTERNET_STATE_OFFLINE_USER.
INTERNET_STATE_IDLE | No network requests are being made by Win32 Internet functions.
INTERNET_STATE_BUSY | Network requests are being made by WinInet.
dwFlags
DWORD value that controls the transition between states. Can be ISO_FORCE_DISCONNECTED, which puts Win32 Internet functions into offline mode. All outstanding requests will be aborted with a canceled error.


*
  * Previous Topic: INTERNET_CONNECTED_INFO
  * Next Topic: INTERNET_PREFETCH_STATUS

INTERNET_ONLINE_OFFLINE_INFO

Replaced by INTERNET_CONNECTED_INFO.


INTERNET_PREFETCH_STATUS

typedef struct {
    DWORD dwStatus;
    DWORD dwSize;
} INTERNET_PREFETCH_STATUS, * LPINTERNET_PREFETCH_STATUS;

Contains the status of a prefetch download operation.

dwStatus
Status of the download. Can be one of the following values:
INTERNET_PREFETCH_ABORTED | Operation was aborted.
INTERNET_PREFETCH_COMPLETE | Operation has completed.
INTERNET_PREFETCH_PROGRESS | Operation is in progress.
dwSize
Size, in bytes, of data downloaded so far.


INTERNET_PROXY_INFO

typedef struct {
    DWORD dwAccessType;
    LPCSTR lpszProxy;
    LPCSTR lpszProxyBypass;
} INTERNET_PROXY_INFO, * LPINTERNET_PROXY_INFO;

Contains information that is supplied with the INTERNET_OPTION_PROXY value to get or set proxy information on a handle obtained from a call to the InternetOpen function.

dwAccessType
Access type. Can be one of the following values:
INTERNET_OPEN_TYPE_DIRECT | Internet accessed through a direct connection.
INTERNET_OPEN_TYPE_PRECONFIG | Applies only when setting proxy information.
INTERNET_OPEN_TYPE_PROXY | Internet accessed using a proxy.
lpszProxy
Proxy server list.
lpszProxyBypass
Proxy bypass list.


INTERNET_SCHEME

typedef enum {
    INTERNET_SCHEME_PARTIAL = -2,
    INTERNET_SCHEME_UNKNOWN = -1,
    INTERNET_SCHEME_DEFAULT = 0,
    INTERNET_SCHEME_FTP,
    INTERNET_SCHEME_GOPHER,
    INTERNET_SCHEME_HTTP,
    INTERNET_SCHEME_HTTPS,
    INTERNET_SCHEME_FILE,
    INTERNET_SCHEME_NEWS,
    INTERNET_SCHEME_MAILTO,
    INTERNET_SCHEME_FIRST = INTERNET_SCHEME_FTP,
    INTERNET_SCHEME_LAST = INTERNET_SCHEME_MAILTO
} INTERNET_SCHEME, * LPINTERNET_SCHEME;

Defines the flags used with the nScheme member of the URL_COMPONENTS structure.

INTERNET_SCHEME_PARTIAL
Partial URL.
INTERNET_SCHEME_UNKNOWN
Unknown URL scheme.
INTERNET_SCHEME_DEFAULT
Default URL scheme.
INTERNET_SCHEME_FTP
FTP URL scheme (ftp:).
INTERNET_SCHEME_GOPHER
Gopher URL scheme (gopher:).
INTERNET_SCHEME_HTTP
HTTP URL scheme (http:).
INTERNET_SCHEME_HTTPS
HTTPS URL scheme (https:).
INTERNET_SCHEME_FILE
File URL scheme (file:).
INTERNET_SCHEME_NEWS
News URL scheme (news:).
INTERNET_SCHEME_MAILTO
Mail URL scheme (mailto:).
INTERNET_SCHEME_FIRST
Lowest known scheme value.
INTERNET_SCHEME_LAST
Highest known scheme value.


INTERNET_VERSION_INFO

typedef struct {
    DWORD dwMajorVersion;
    DWORD dwMinorVersion;
} INTERNET_VERSION_INFO, * LPINTERNET_VERSION_INFO;

Contains the HTTP version number of the server. This structure is used when passing the INTERNET_OPTION_VERSION flag to the InternetQueryOption function.

dwMajorVersion
Major version number.
dwMinorVersion
Minor version number.


Structures

The following section describes the Win32 Internet function data structures and their uses.
GOPHER_ATTRIBUTE_TYPE
GOPHER_FIND_DATA
HTTP_VERSION_INFO
INTERNET_ASYNC_RESULT
INTERNET_AUTHNOTIFY_DATA
INTERNET_BUFFERS
INTERNET_CACHE_ENTRY_INFO
INTERNET_CERTIFICATE_INFO
INTERNET_CONNECTED_INFO
INTERNET_ONLINE_OFFLINE_INFO
INTERNET_PREFETCH_STATUS
INTERNET_PROXY_INFO
INTERNET_SCHEME
INTERNET_VERSION_INFO
URL_COMPONENTS


URL_COMPONENTS

typedef struct {
    DWORD dwStructSize;
    LPSTR lpszScheme;
    DWORD dwSchemeLength;
    INTERNET_SCHEME nScheme;
    LPSTR lpszHostName;
    DWORD dwHostNameLength;
    INTERNET_PORT nPort;
    LPSTR lpszUserName;
    DWORD dwUserNameLength;
    LPSTR lpszPassword;
    DWORD dwPasswordLength;
    LPSTR lpszUrlPath;
    DWORD dwUrlPathLength;
    LPSTR lpszExtraInfo;
    DWORD dwExtraInfoLength;
} URL_COMPONENTS;

Contains the constituent parts of a URL. This structure is used with the InternetCrackUrl and InternetCreateUrl functions.

dwStructSize
Size, in bytes, of this structure. Used for version checking. The size of this structure must be set to initialize this structure properly.
lpszScheme
Address of a buffer that contains the scheme name.
dwSchemeLength
Length of the scheme name.
nScheme
Enumerated scheme type, if known. For a list of scheme types, see INTERNET_SCHEME.
lpszHostName
Address of a buffer that contains the host name.
dwHostNameLength
Length of the host name.
nPort
Converted port number.
lpszUserName
Address of a buffer that contains the user name.
dwUserNameLength
Length of the user name.
lpszPassword
Address of a buffer that contains the password.
dwPasswordLength
Length of the password.
lpszUrlPath
Address of a buffer that contains the URL path.
dwUrlPathLength
Length of the URL path.
lpszExtraInfo
Address of a buffer that contains the extra information (for example, ?foo or #foo).
dwExtraInfoLength
Length of the extra information.

For InternetCrackUrl, if a pointer member and its corresponding length member are both zero, that component is not returned. If the pointer member is NULL but the length member is not zero, both the pointer and length members are returned. If both pointer and corresponding length members are nonzero, the pointer member points to a buffer where the component is copied. The component may be un-escaped, depending on the dwFlags parameter of InternetCrackUrl.

For InternetCreateUrl, the pointer members should be NULL if the component is not required. If the corresponding length member is zero, the pointer member is the address of a zero-terminated string. If the length member is not zero, it is the string length of the corresponding pointer member.


Reference Reference *
  * Previous Topic: Sample 4: Parsing an XML file using JScript
  * Next Topic: Objects

Reference

Objects

Interfaces

Methods


XML Object Model

This document defines the Extensible Markup Language (XML) Object Model for Microsoft® Internet Explorer 4.0. XML is a simplified subset of SGML, designed specifically for Web applications. Unlike HTML, in which every tag or element needs to be known in advance, the XML elements or attributes do not. An XML parser can use a document type definition (DTD) for a specific XML document if one is available.

Overview

Reference


Interfaces

The following section contains the interfaces associated with the XML object model.

IXMLDocument

IXMLElement

IXMLElementCollection


Methods

IXMLDocument::get_root

IXMLDocument::get_fileSize

IXMLDocument::get_fileModifiedDate

IXMLDocument::get_fileUpdatedDate

IXMLDocument::get_URL

IXMLDocument::put_URL

IXMLDocument::get_mimeType

IXMLDocument::get_readyState

IXMLDocument::get_charset

IXMLDocument::put_charset

IXMLDocument::get_version

IXMLDocument::get_doctype

IXMLDocument::createElement

IXMLElement::get_tagName

IXMLElement::put_tagName

IXMLElement::get_parent

IXMLElement::setAttribute

IXMLElement::get_Attribute

IXMLElement::removeAttribute

IXMLElement::get_children

IXMLElement::get_type

IXMLElement::get_text

IXMLElement::put_text

IXMLElement::addChild

IXMLElement::removeChild

IXMLElementCollection::get_length

IXMLElementCollection::put_length

IXMLElementCollection::get_newEnum

IXMLElementCollection::item


IXMLDocument::createElement

HRESULT IXMLDocument::createElement(
    [in] VARIANT vType,
    [optional, in] VARIANT var1,
    [retval, out] IXMLElement **ppElem)

Creates a new element that can then be added to a portion of the tree.

  • Returns S_OK if successful. Possible error codes include E_OUTOFMEMORY and E_INVALIDARG.
vType
Variant of type VT_I4, which contains an integer from the xmlelemTYPE enumeration, and indicates the type of the element that is desired:
typedef enum xmlelemTYPE {
    XMLELEMTYPE_ELEMENT,
    XMLELEMTYPE_TEXT,
    XMLELEMTYPE_COMMENT,
    XMLELEMTYPE_DOCUMENT,
    XMLELEMTYPE_DTD,
    XMLELEMTYPE_OTHER
} XMLELEM_TYPE;
var1
Optional. String used by IXMLElement::put_tagName to bind the name to the newly formed element.
ppElem
Indirect pointer in which to return the desired element.


IXMLDocument::get_charset

HRESULT IXMLDocument::get_charset(
    BSTR *pOutString)

Returns a string that specifies the character set of the input document according to ISO standards.

  • Returns S_OK if successful. Possible error codes include E_OUTOFMEMORY and E_INVALIDARG.
pOutString
Address of a string containing the character set format.


IXMLDocument::get_doctype

HRESULT IXMLDocument::get_doctype(
    BSTR *p)

Returns the content specified in the !DOCTYPE element.

  • Returns S_OK if successful. Possible error codes include E_OUTOFMEMORY and E_INVALIDARG.
p
Address of a string that contains document-specific information.


IXMLDocument::get_fileModifiedDate

HRESULT IXMLDocument::get_fileModifiedDate(
    BSTR  * p)

Returns the date when the file was last modified.

  • Returns S_OK if successful. Possible error codes include E_OUTOFMEMORY and E_INVALIDARG.
p
Address of a string containing the modified date.

This method is not yet implemented.


IXMLDocument::get_fileSize

HRESULT IXMLDocument::get_fileSize(
    BSTR  * p)

Returns the file size of the document.

  • Returns S_OK if successful. Possible error codes include E_OUTOFMEMORY and E_INVALIDARG.
p
Address of a string containing the file size.


IXMLDocument::get_fileUpdatedDate

HRESULT IXMLDocument::get_fileUpdatedDate(
    BSTR  * p)

Returns the date when the file was last updated.

  • Returns S_OK if successful. Possible error codes include E_OUTOFMEMORY and E_INVALIDARG.
p
Address of a string containing the updated date.

This method is not yet implemented.


IXMLDocument::get_mimeType

HRESULT IXMLDocument::get_mimeType(
    BSTR   p)

Returns the MIME (Multipurpose Internet Mail Extension) type.

  • Returns S_OK if successful. Possible error codes include E_OUTOFMEMORY and E_INVALIDARG.
p
String containing a MIME type.

MIME is a set of enhancements to SMTP allowing an Internet message to include a mixture of audio, image, video, and text components, and to accommodate a variety of international character sets. MIME messages are identified by a MIME header in the top level of the SMTP header. The MIME mechanisms are specified in the RFC 1341 document.


IXMLDocument::get_readyState

HRESULT IXMLDocument::get_readyState(
    LONG *pl)

Determines if the document is done loading.

  • Returns S_OK if successful. Possible error codes include E_OUTOFMEMORY and E_INVALIDARG.
pl
Address of a storage area in which to return the readystate property.

The returned readystate property, such as READYSTATE_LOADED, READYSTATE_LOADING, or READYSTATE_COMPLETE, indicates whether the document has been loaded completely. If the document is still loading, the returned value is READYSTATE_LOADING; if it is successfully loaded, it is READYSTATE_COMPLETE.


IXMLDocument::get_root

HRESULT IXMLDocument::get_root(
    IXMLElement **ppElem)

Returns the root element of the document. The CHANNEL element is considered the root element. The caller must call IUnknown::Release on the document.

  • Returns S_OK if successful. Possible error codes include E_OUTOFMEMORY and E_INVALIDARG.
ppElem
Indirect pointer in which to return the address of the root element's IXMLElement interface.


IXMLDocument::get_URL

HRESULT IXMLDocument::get_URL(
     BSTR  * p)

Returns the URL associated with the document, if one exists.

  • Returns S_OK if successful. Possible error codes include E_OUTOFMEMORY and E_INVALIDARG.
p
Address of a string containing a URL value.


IXMLDocument::get_version

HRESULT IXMLDocument::get_version(
    BSTR *p)

Returns the version of the XML specification being used.

  • Returns S_OK if successful. Possible error codes include E_OUTOFMEMORY and E_INVALIDARG.
p
Address of a string containing the version of XML being used.

The caller needs to deallocate the string by using SysFreeString.


IXMLDocument

IXMLDocument Methods
get_root
get_fileSize
get_fileModifiedDate
get_fileUpdatedDate
get_URL
put_URL
get_mimeType
get_readyState
get_charset
put_charset
get_version
get_doctype
createElement


IXMLDocument::put_charset

HRESULT IXMLDocument::put_charset(
    BSTR *p)

Specifies the output character set of the document according to ISO standards.

  • Returns S_OK if successful. Possible error codes include E_OUTOFMEMORY and E_INVALIDARG.
p
Address of a string containing the character set format.


IXMLDocument::put_URL

HRESULT IXMLDocument::put_URL(
     BSTR  p)

Loads a new document based on the URL provided. The current document is destroyed and the new document is loaded in its place.

  • Returns S_OK if successful. Possible error codes include E_OUTOFMEMORY and E_INVALIDARG.
p
String containing a URL address.


IXMLElement::addChild

HRESULT IXMLElement::addChild(
    [in] IXMLElement *pChildElem,
    long lIndex,
    long lReserved)

Adds a child to this element.

  • Returns S_OK if successful. E_INVALIDARG is returned if the index is inappropriate.
pChildElem
Address of the new child element.
lIndex
Index of the child collection at which this child should be added. If this is zero, it is added at the first element of the collection. If this is less than zero, the element is simply added to the end of the child collection.
lReserved
Should always be -1.

All the children and descendants of this new child element remain attached as before. Any element can have only one parent element, so the previous parent will lose this child from its subtree. Any threads that have already traversed the tree and expect this element to have the old parent will fail unpredictably. Note that it is possible to use this method to break off a subtree from one XML document and attach it to another XML document. However, there are some stringent restrictions on when this can be done:

  • There can be no outstanding references on collections on the child element or any of its descendants.
  • There can be no reference on any of the descendant elements of this child.

If these are not adhered to, an error will be returned.

The results when using the IXMLElementCollection::get_newEnum method from a collection obtained from this element are undefined if the enumerator is not reset.

Finally, the implementation of breaking off a node that has many children and attaching it to a tree of another document is somewhat more expensive than breaking off a node and attaching it to another node of the same document.


IXMLElement::get_children

HRESULT IXMLElement::get_children(
    IXMLElementCollection * * ppChildren)

Retrieves the collection of an element's children.

  • Returns one of the following values:
    S_OK | Success.
    E_FAIL | No children are present.
    E_OUTOFMEMORY | Not enough memory to process this request.
    S_FALSE | If no children exist, ppChildren is set to NULL.
ppChildren
Indirect pointer in which to return an address of the element collection. The ppChildren parameter is NULL if no children are present.

The collection allows the application to make queries about the size of the collection as well as enumerate through the children or access any of them by index. If no children exist, ppChildren is set to NULL and the return code is S_FALSE. The caller must call (ppChildren)->Release when it is done using this collection. Further discussion of IXMLElementCollection is available later in this document.


IXMLElement::get_parent

HRESULT IXMLElement::get_parent(
    IXMLElement ** pParent)

Every element in the tree, except the root of a document, has a parent. This parent element is AddRef'ed before being returned, and it is up to the caller to call IUnknown::Release on the returned parent element.

  • Returns S_OK if successful. Error return values include E_OUTOFMEMORY and E_INVALIDARG.

    Can also return S_FALSE if no parent exists (for the root or for a newly created element). pParent is set to zero to prevent errors when scripting agents (such as JScript or VBScript) call this method on behalf of a script.

pParent
Indirect pointer in which to return an address of the parent element. The parent element is always nonnull except for the root.


IXMLElement::get_tagName

HRESULT IXMLElement::get_tagName(
    BSTR * pTagName)

Returns the name of the tag as a string.

  • Returns S_OK if successful. Error return values include E_OUTOFMEMORY and E_INVALIDARG.
pTagName
Indirect pointer in which to return the tag name.

The caller can use SysFreeString to free the string. The name is always all uppercase. The name of the comment element is returned as "!". The other META tags have names that correspond to the special character followed by the META tag name, such as the following:

The name of <?XML ...> is "?XML".


IXMLElement::get_text

HRESULT IXMLElement::get_text(
    BSTR *pContent)

Returns the content of text and comment elements.

  • Returns S_OK if successful. Error values include E_INVALIDARG, E_OUTOFMEMORY, and E_FAIL.
pContent
Indirect pointer in which to return the content. The caller must free any returned content by using SysFreeString.

The content of a text element is the text between the tags. Consider the following elements:

<CHANNEL>
<TITLE>Top Stories</TITLE>
    .
    .
    .
</CHANNEL>

The text element child of the TITLE element has the content "Top Stories". Here the TITLE element has one child, which is the text element, and this child has the content "Top Stories".

However, calling IXMLElement::get_text on the TITLE element strips markup from the content within the TITLE tag. Use this method to get all the text in a tag. For example:

<TITLE>
This is <H> bold </H> text
</TITLE>

A good downlevel client should use "This is bold text" after stripping away any markup by calling IXMLElement::get_text on the TITLE element.

Finally, the content of a comment element is the comment. For example, the following example has the name "!" and has the content " This is a comment ".

<! This is a comment />


IXMLElement::get_type

HRESULT IXMLElement::get_type(
    long *plType)

  • Returns S_OK if successful.
plType
Indirect pointer to return the type.

Each node of the tree is labeled as being one of the following types:

typedef  enum xmlelemTYPE {
    XMLELEMTYPE_ELEMENT,
    XMLELEMTYPE_TEXT,
    XMLELEMTYPE_COMMENT,
<!--    XMLELEMTYPE_DOCUMENT,
    XMLELEMTYPE_DTD, -->
    XMLELEMTYPE_OTHER
} XMLELEM_TYPE;

For Internet Explorer 4.0, the interesting element types are XMLELEMTYPE_ELEMENT, XMLELEMTYPE_TEXT, and XMLELEMTYPE_COMMENT.

In the following example, both the CHANNEL and the TITLE elements are marked as being of type XMLELEMTYPE_ELEMENT. Their names are returned as "CHANNEL" and "TITLE", respectively. (The names are always all uppercase.) The TITLE element has one child, which is a text element marked as being of type XMLELEMTYPE_TEXT.

<CHANNEL>
    <title> Breaking News </title>
    <!-- This is a comment element-->
</CHANNEL>


IXMLElement::get_Attribute

HRESULT IXMLElement::get_Attribute(
    BSTR strPropertyName,
    VARIANT* PropertyValue)

Allows for the retrieval of an attribute's value.

  • Returns S_OK if successful. Other returned error values include E_OUTOFMEMORY and S_FALSE if no such attribute exists to prevent scripting errors.
strPropertyName
Name of the attribute.
PropertyValue
Indirect pointer in which to return the value. Always returned as a BSTR.

An attribute's name is provided. The value of the attribute is returned as a variant, which is always of type VT_BSTR. The caller must release the value by calling VariantClear.


IXMLElement

IXMLElement Methods
get_tagName
put_tagName
get_parent
setAttribute
getAttribute
removeAttribute
get_children
get_type
get_text
put_text
addChild
removeChild


IXMLElement::put_tagName

HRESULT IXMLElement::put_tagName(
    BSTR  pTagName)

Sets the name of the tag and stores a copy of the string.

  • Returns S_OK if successful, or E_FAIL on failure.
pTagName
Address of a string containing the tag name.

The caller can use SysFreeString to free the string. The name is always all uppercase. The name of the comment element is returned as "!". The other META tags have names that correspond to the special character followed by the META tag name, such as the following:

The name of <?XML ...> is "?XML".


IXMLElement::put_text

HRESULT IXMLElement::put_text(
    BSTR pContent)

Adds or changes the content of text and comment elements.

  • Returns S_OK if successful. Error values include E_OUTOFMEMORY and E_INVALIDARG.
pContent
Content. A private copy of this string is made.


IXMLElement::removeAttribute

HRESULT IXMLElement::removeAttribute(
    BSTR strPropertyName)

Deletes an attribute from an element. The attribute is specified by using the attribute name.

  • Returns S_OK if successful. Other returned error values include E_OUTOFMEMORY and E_INVALIDARG if no such attribute exists.
strPropertyName
Name of the attribute.


IXMLElement::removeChild

HRESULT IXMLElement::removeChild(
    [in] IXMLElement *pChildElem)

Removes a child of this element.

  • Returns S_OK if successful.
pChildElem
Address of the child element that should be removed.

The element remains in memory and can be reattached to a tree by using IXMLElement::addChild. All the children and descendants of this child element remain attached as before. Any threads that have already traversed the tree and expect this element to have the old parent will fail unpredictably. It is possible to use this method to break off a subtree from one XML document and attach it to another XML document. However, there are restrictions as explained in IXMLElement::addChild.

The results when using the IXMLElementCollection::get_newEnum method from a collection obtained from this element (the parent) are undefined if the enumerator is not reset.


IXMLElement::setAttribute

HRESULT IXMLElement::setAttribute(
    BSTR strPropertyName,
    VARIANT PropertyValue)

Allows the setting of an attribute of this element.

  • Returns S_OK if successful. Error return values include E_OUTOFMEMORY and E_INVALIDARG.
strPropertyName
Name of the attribute
PropertyValue
Value of the attribute. The allowed input type is VT_BSTR.

The attribute's name and its new value are provided. The previous value of this attribute is lost. A private copy of the input value is made. The attribute value is always stored as a string, thus it should be sent in as a string.


IXMLElementCollection::get_length

HRESULT IXMLElementCollection::get_length(
    long *plLength)

Obtains the number of elements in the collection.

  • Returns S_OK if successful.
plLength
Indirect pointer in which to return the size of the collection.


IXMLElementCollection::get_newEnum

HRESULT IXMLElementCollection::get__newEnum(
    IUnknown ** ppUnk)

Returns a pointer to an IEnumVARIANT enumerator that is obtained by calling IUnknown::QueryInterface on the returned object.

  • Returns S_OK if successful. Error values include E_FAIL if there are no children, and E_OUTOFMEMORY and E_INVALIDARG.
ppUnk
Indirect pointer in which to return the enumerator.

IEnumvariant is documented in the Microsoft Developer Network (MSDN). It allows the enumeration of variants. Each variant that is returned is of type VT_DISPATCH. This returned object is merely an element object, and the IXMLElement interface on the returned object can be obtained by calling IUnknown::QueryInterface on it. It is up to the caller to call IUnknown::Release on the returned enumeration. It is also the responsibility of the caller to call VariantClear on every returned element.


IXMLElementCollection::item

HRESULT IXMLElementCollection::item(
    VARIANT Var1,
    VARIANT Var2,
    IDispatch **ppDisp)

  • Returns S_OK if successful. Error values include E_OUTOFMEMORY, E_INVALIDARG, and E_FAIL. ppDisp is set to NULL if the call fails.
Var1
Index or a name. The preferred variant type of an index is VT_I4; the preferred variant type of a name is VT_BSTR.
Var2
Empty (type VT_EMPTY) or an index.
ppDisp
Indirect pointer in which to return an address of the collection or element that is to be returned.

This method is fairly involved and can be used in different ways to retrieve members of a collection or another collection. If Var1 specifies an index and Var2 is empty, the item at that index is returned if such an element does exist. Var1 can also specify a name, in which case the returned object is a collection of all elements in this collection that have the specified name. However, if there is only one element with that name, the returned object is an XML element. It is also possible to specify Var1 as a name and Var2 as an index. In that case, the returned object is an XML element that is the Var2th object of the name specified by Var1. The caller must call IUnknown::Release on any returned objects.


IXMLElementCollection IXMLElementCollection *
  * Previous Topic: IXMLElement
  * Next Topic: Methods

IXMLElementCollection

IXMLElementCollection Methods
get_length
put_length
get_newEnum
item


IXMLElementCollection::put_length

HRESULT IXMLElementCollection::put_length(
    long length)

This method has no effect.


Objects

The following list contains the objects associated with the XML object model.

XML Document

XML Element

Element Collections

XML Document

The object model allows an application to load an XML document and manipulate it. The document can be loaded by specifying a URL moniker or by simply providing a stream. The application can then get several properties of the document, such as URL, mime type, and created/accessed/modified time. The entire XML document is navigated by starting at the root element. In addition, the object model provides for notifications on the addition of immediate children of any given node.

The XML object inherits from the following interfaces:
IUnknown
IDispatch
IXMLDocument
IXMLError
IPersistMoniker
IPersistStream
IPersistStreamInit

The application can use either IPersistMoniker::Load or IPersistStreamInit::Load to load an XML document. It can use IPersistStreamInit::Save to save the XML document to a stream. You can also use IXMLDocument::put_URL.

XML Element

Each XML tag is represented by an object. This object derives from the following interfaces:
IUnknown
IDispatch
IXMLElement

Element Collections

The children of an element are manipulated in this object model by using collections. It is possible to enumerate the members of a collection as well as to access them by index. It is also possible to create a specialized collection of all the elements that have a certain name. Such a specialized collection is then manipulated in an identical fashion.

The XML object derives from the following interfaces:
IDispatch
IXMLElementCollection

A collection of the children of an element's pElem is obtained by using the IXMLElement::get_children method as follows:

IXMLElement *pElem = NULL;
IXMLElementCollection *pChildren = NULL;
    .
    .
    .
hr = pElem->get_children(&pChildren);
if(SUCCEEDED(hr) && pChildren)
{

}

Between calls to IXMLElement::addChild, the client application must call IXMLElementCollection::get_length on the parent collection to ensure that the application has the correct length and can request the correct index to an element when needed.

When it is guaranteed that no further elements will be added as children to this parent node, this API is called with a NULL parameter. It is guaranteed that this sink will be called at least once with a NULL parameter. The sink should then disconnect itself from this connection point when it knows that no further children are being added.


Overview

The most generic object model for an XML document will be able to take in any XML document as input and provide to the application a means of manipulating this XML document. For more information on XML, see http://www.microsoft.com/sitebuilder/standards/xml/.

Note Applications should not use fibers on any thread on which the XML Object Model is created by calling IPersistMoniker::Load, since the Msxml.dll uses fibers for asynchronous downloads and they may interfere with each other.

XML-based documents are currently being used for at least two different applications for Microsoft Internet Explorer 4.0:

  • CDF files (Channel Definition Format), where a channel is a Web site that has been enabled for Webcasting to information-receiving programs such as Internet Explorer 4.0. The mechanism that makes this possible in Internet Explorer 4.0 is the CDF file. The CDF file provides an index of resources available in the channel, and a recommended schedule for when the channel should be updated on the local computer.
  • XML-based documents are also being used in Internet Explorer 4.0 for describing download modules for download of code in the form of cabinet files, Java packages, and so on. This new format is meant to supersede .inf files and is called the Open Software Description (OSD) format.

The interfaces in the following section describe a minimal set of objects that can be used to construct an object model for XML. In the future (post Internet Explorer 4.0), this object model will be extended to allow for a richer set of methods. The goals for the design of this set of interfaces as well as the justification for those goals are, in order of priority:

  • The object model should enable the ability to manipulate any generic XML document. However, the methods needed for manipulating a CDF were highest in priority.
  • The feel of the object model should mimic that of the IE4/MSHTML object model as closely as possible. This is to enable a programmer familiar with IE4/MSHTML to get started easily.

Object Model Overview

The object model is free-threaded, thus no marshaling is required.

An XML document can be thought of as a tree. A container tag is a nonleaf node in this tree. Tags that do not contain any other tags end up as leaf nodes of this tree. A root element whose children are all the top-level nodes is imposed.

Samples

This section contains some simple implementations of the XML object model. The samples are:

  • Sample 1: Parsing an XML file
  • Sample 2: Parsing a CDF file for specific tags
  • Sample 3: Using IPersistMoniker::Load to load a document
  • Sample 4: Parsing an XML file using JScript


Sample 1: Parsing an XML file

#define UNICODE

#include <windows.h>
#include <windowsx.h>
#include <stdlib.h>
#include <stdio.h>
#include <io.h>
#include <urlmon.h>
#include <hlink.h>
#include <dispex.h>
#include "mshtml.h"
#include "msxml.h"

#define ASSERT(x)  if(!(x)) DebugBreak()
#define CHECK_ERROR(cond, err) if (!(cond)) {pszErr=(err); goto done;}
#define SAFERELEASE(p) if (p) {(p)->Release(); p = NULL;} else ;

int _cdecl main (int argc, char **argv)
{
    PSTR pszErr = NULL;
    IXMLDocument           *pDoc = NULL;
    IStream                *pStm = NULL;
    IPersistStreamInit     *pPSI = NULL;
    CHAR                   buf[MAX_PATH];
    CHAR                   *pszURL;

    HRESULT hr;

    //
    // Check usage.
    //
    if (argc != 2)
    {
        fprintf (stderr, "Usage:   %s URL\n", argv[0]);
        fprintf (stderr, "Eg %s c:\\nt\\private\\inet\\xml\\test\\channel.cdf\n", argv[0]);
        fprintf (stderr, "or %s http://ohserv/users/julianj/msnbc.cdf\n", argv[0]);
        exit (1);
    }

    //
    // HACK if passed in a file name; expand if it doesn't look like a URL.
    //
    if (CompareStringA(LOCALE_USER_DEFAULT, NORM_IGNORECASE, argv[1], 7, "http://", 7) == CSTR_EQUAL)
    {
        pszURL = argv[1];
    }
    else
    {
        pszURL = buf;
        GetFullPathNameA(argv[1], MAX_PATH, pszURL, NULL);
    }

    hr = CoInitialize(NULL);
    ASSERT(SUCCEEDED(hr));

    //
    // Create an empty XML document.
    //
    hr = CoCreateInstance(CLSID_XMLDocument, NULL, CLSCTX_INPROC_SERVER,
                                IID_IXMLDocument, (void**)&pDoc);

    CHECK_ERROR (pDoc, "CoCreateInstance Failed");

    //
    // Synchronously create a stream on a URL.
    //
    hr = URLOpenBlockingStreamA(0, pszURL, &pStm, 0,0);
    CHECK_ERROR(SUCCEEDED(hr) && pStm, "Couldn't open stream on URL")
    //
    // Get the IPersistStreamInit interface to the XML doc.
    //
    hr = pDoc->QueryInterface(IID_IPersistStreamInit, (void **)&pPSI);
    CHECK_ERROR(SUCCEEDED(hr), "QI for IPersistStreamInit failed");

    //
    // Init the XML doc from the stream.
    //
    hr = pPSI->Load(pStm);
    //CHECK_ERROR(SUCCEEDED(hr), "Couldn't load XML doc from stream");

    if(SUCCEEDED(hr))
    {
        printf("%s : XML File is well formed \r\n",argv[0]);

    }
    else
    {
        // Print error information !
        IXMLError *pXMLError = NULL ;
        XML_ERROR xmle;

        hr = pPSI->QueryInterface(IID_IXMLError, (void **)&pXMLError);
        CHECK_ERROR(SUCCEEDED(hr), "Couldn't get IXMLError");

        ASSERT(pXMLError);

        hr = pXMLError->GetErrorInfo(&xmle);
        SAFERELEASE(pXMLError);
        CHECK_ERROR(SUCCEEDED(hr), "GetErrorInfo Failed");

        printf("%s :", argv[0]);
        wprintf(TEXT(" Error on line %d. Found %s while expecting %s\r\n"),
                            xmle._nLine,
                            xmle._pszFound,
                            xmle._pszExpected);

        SysFreeString(xmle._pszFound);
        SysFreeString(xmle._pszExpected);
        SysFreeString(xmle._pchBuf);
    }

done: // Clean up.
    //
    // Release any used interfaces.
    //
    SAFERELEASE(pPSI);
    SAFERELEASE(pStm);
    SAFERELEASE(pDoc);

    if (pszErr)
        fprintf (stderr, "%s, last error %d\n", pszErr, GetLastError());
    return 0;
}


Sample 2: Parsing a CDF file for specific tags

//*******************************
// XML OM test code
//
// *******************************

#include <windows.h>
#include <windowsx.h>
#include <stdlib.h>
#include <stdio.h>
#include <io.h>
#include <urlmon.h>
#include <hlink.h>
#include <dispex.h>
#include "mshtml.h"
#include "msxml.h"

#define ASSERT(x)  if(!(x)) DebugBreak()
#define CHECK_ERROR(cond, err) if (!(cond)) {pszErr=(err); goto done;}
#define SAFERELEASE(p) if (p) {(p)->Release(); p = NULL;} else ;

#define WALK_ELEMENT_COLLECTION(pCollection, pDispItem) \
    {\
        long length;\
        \
        if (SUCCEEDED(pChildren->get_length(&length)) && length > 0)\
        {\
            VARIANT vIndex, vEmpty;\
            vIndex.vt = VT_I4;\
            vEmpty.vt = VT_EMPTY;\
                                 \
            for (long i=0; i<length; i++)\
            {\
                vIndex.lVal = i;\
                IDispatch *pDispItem = NULL;\
                if (SUCCEEDED(pCollection->item(vIndex, vEmpty, &pDispItem)))\
                {

#define END_WALK_ELEMENT_COLLECTION(pDispItem) \
                    pDispItem->Release();\
                }\
            }\
        }\
    }

void Indent(int indent)
{
    while (indent-->0)
    {
        printf("   ");
    }
}

void Output(int indent, const char *format, ...)
{
    va_list argptr;

    va_start(argptr, format);

    Indent(indent);

     (void)vprintf(format, argptr);
}

void OutputLn(int indent, const char *format, ...)
{
    va_list argptr;

    va_start(argptr, format);

    printf("\n");

    Indent(indent);

    (void)vprintf(format, argptr);
}

//
// Dump an element attribute member if present.
//
void DumpAttrib(IXMLElement *pElem, BSTR bstrAttribName)
{
    VARIANT vProp;

    VariantInit(&vProp);

    if (SUCCEEDED(pElem->getAttribute(bstrAttribName, &vProp)))
    {
        if (vProp.vt == VT_BSTR)
        {
            printf(" %S=\"%S\"", bstrAttribName, vProp.bstrVal);
        }
        VariantClear(&vProp);
    }
}

//
// Helper routine to quickly find out if this is a named element
// currently only used to improve the format of the output.
//
BOOL IsNamedElement(IXMLElement *pElem)
{
    BSTR bstrName;

    if (SUCCEEDED(pElem->get_tagName(&bstrName)))
    {
        if (bstrName)
        {
            SysFreeString(bstrName);
            return TRUE;
        }
    }
    return FALSE;
}

//
// Returns TRUE if this element had children.
//
void DumpElement
(
    IXMLElement *pElem, // the XML element to dump
    int indent          // indentation level
)
{
    BSTR bstrTagName = NULL;
    BSTR bstrContent = NULL;
    IXMLElementCollection * pChildren;
    //
    // Note this nonsense with children and grandchildren is just so we get
    // nicely formatted output!
    //
    BOOL fHadNamedChild = FALSE;

    //
    // Dump the name of the NODE.
    //
    pElem->get_tagName(&bstrTagName);
    if (bstrTagName)
    {
        //
        // Special case the output of the special tags.
        //
        if (wcscmp(bstrTagName, L"XML") == 0)
        {
            Output(indent, "<\?XML version=\"1.0\"\?>\n");
            SysFreeString(bstrTagName);
            return;
        }
        else if (wcscmp(bstrTagName, L"DOCTYPE") == 0)
        {
            Output(indent,
              "<!DOCTYPE CHANNEL SYSTEM \"http://www.w3c.org/Channel.dtd\">\n");
            SysFreeString(bstrTagName);
            return;
        }
        else
        {
            OutputLn(indent, "<%S", bstrTagName);
        }
    }

    //
    // Dump the attributes if present.
    //
    DumpAttrib(pElem, L"VALUE");
    DumpAttrib(pElem, L"HREF");
    DumpAttrib(pElem, L"HOUR");
    DumpAttrib(pElem, L"DAY");
    DumpAttrib(pElem, L"IsClonable");
    DumpAttrib(pElem, L"Type");

    //
    // Dump the text contents if present.
    //
    XMLELEM_TYPE xmlElemType;
    if (SUCCEEDED(pElem->get_type((long *)&xmlElemType)))
    {
        if (xmlElemType == XMLELEMTYPE_TEXT)
        {
            if (SUCCEEDED(pElem->get_text(&bstrContent)))
            {
                if (bstrContent)
                {
                    printf("%S", bstrContent);
                    SysFreeString(bstrContent);
                }
            }
        }
    }

    //
    // Find the children if they exist.
    //
    if (SUCCEEDED(pElem->get_children(&pChildren)) && pChildren)
    {
        //
        // Close the tag if present but with "children present" closure
        // that is use > instead of />.
        //
        if (bstrTagName) printf(">");

        WALK_ELEMENT_COLLECTION(pChildren, pDisp)
        {
            //
            // pDisp will iterate over an IDispatch for each item in the collection.
            //
            IXMLElement * pChild;
            if (SUCCEEDED(pDisp->QueryInterface(
                                     IID_IXMLElement, (void **)&pChild)))
            {
                if (IsNamedElement(pChild))
                    fHadNamedChild = TRUE;

                //
                // Recursively dump children.
                //
                DumpElement(pChild, indent+1);

                pChild->Release();
            }
        }
        END_WALK_ELEMENT_COLLECTION(pDisp);
        pChildren->Release();

        //
        // Display closing tag.
        //
        if (bstrTagName)
        {
            if (fHadNamedChild)
            {
                OutputLn(indent, "</%S>", bstrTagName);
            }
            else
            {
                printf("</%S>", bstrTagName);
            }
        }
    }
    else
    {
        //
        // No children so terminate tag on same line.
        //
        if (bstrTagName) printf("/>");
    }

    if (bstrTagName)
        SysFreeString(bstrTagName);
}

int MyStrToOleStrN(LPOLESTR pwsz, int cchWideChar, LPCTSTR psz)
{
    int i;
    i=MultiByteToWideChar(CP_ACP, 0, psz, -1, pwsz, cchWideChar);
    if (!i)
    {
        //DBG_WARN("MyStrToOleStrN string too long; truncated");
        pwsz[cchWideChar-1]=0;
    }
    else
        ZeroMemory(pwsz+i, sizeof(OLECHAR)*(cchWideChar-i));

    return i;
}

int _cdecl main (int argc, char **argv)
{
    PSTR pszErr = NULL;
    IXMLDocument           *pDoc = NULL;
    IStream                *pStm = NULL;
    IPersistStreamInit     *pPSI = NULL;
    IXMLElement            *pElem = NULL;
    TCHAR                  buf[MAX_PATH];
    TCHAR                  *pszURL;
    WCHAR                  *pwszURL=NULL;
    BSTR                   pBURL=NULL;

    HRESULT hr;

    //
    // Check usage.
    //
    if (argc != 2)
    {
        fprintf (stderr, "Usage:   omtest2 URL\n");
        fprintf (stderr, "Eg omtest2 c:\\nt\\private\\inet\\xml\\test\\channel.uni\n");
        fprintf (stderr, "or omtest2 http://ohserv/users/julianj/channel.xml\n");
        exit (1);
    }

    //
    // HACK if passed in a file name, expand if it doesn't look like a URL.
    //
    if (CompareString(LOCALE_USER_DEFAULT, NORM_IGNORECASE, argv[1], 7, "http://", 7) == CSTR_EQUAL)
    {
        pszURL = argv[1];
    }
    else
    {
        pszURL = buf;
        GetFullPathName(argv[1], MAX_PATH, pszURL, NULL);
    }

    hr = CoInitialize(NULL);
    ASSERT(SUCCEEDED(hr));

    //
    // Create an empty XML document.
    //
    hr = CoCreateInstance(CLSID_XMLDocument, NULL, CLSCTX_INPROC_SERVER,
                                IID_IXMLDocument, (void**)&pDoc);

    CHECK_ERROR (pDoc, "CoCreateInstance Failed");

    //
    // Synchronously create a stream on a URL.
    //
    //hr = URLOpenBlockingStream(0, pszURL, &pStm, 0,0);
    //CHECK_ERROR(SUCCEEDED(hr) && pStm, "Couldn't open stream on URL")

    //
    // Get the IPersistStreamInit interface to the XML doc.
    //
    //hr = pDoc->QueryInterface(IID_IPersistStreamInit, (void **)&pPSI);
    //CHECK_ERROR(SUCCEEDED(hr), "QI for IPersistStreamInit failed");

    //
    // Init the XML doc from the stream.
    //
    //hr = pPSI->Load(pStm);

    pwszURL = (WCHAR *)LocalAlloc(LMEM_FIXED, ((sizeof(WCHAR))*(strlen(pszURL) + 2)));
    CHECK_ERROR(pwszURL, "Mem Alloc Failure");

    hr = MyStrToOleStrN(pwszURL, (strlen(pszURL) + 1), pszURL);
    CHECK_ERROR(SUCCEEDED(hr), "Failed to convert to UNICODE");
    pBURL = SysAllocString(pwszURL);
    CHECK_ERROR(pBURL, "Mem Alloc Failure");
    LocalFree(pwszURL);

    hr = pDoc->put_URL(pBURL);

    if (SUCCEEDED(hr))
    {
        //
        // Now walk the OM and look at interesting things.
        //
        hr = pDoc->get_root(&pElem);
        CHECK_ERROR(SUCCEEDED(hr), "Failed to get_root of XML object");

        //
        // Dump the top level meta nodes of the document.
        //
        BSTR bstrVal;
        hr = pDoc->get_version(&bstrVal);
        if(FAILED(hr) || !bstrVal)
        {
            bstrVal = SysAllocString(L"1.0");
        }
        //
        Output(0, "<\?XML version=\"%S\" ",bstrVal);
        SysFreeString(bstrVal);
        bstrVal = NULL;

        hr = pDoc->get_encoding(&bstrVal);
        if(SUCCEEDED(hr) && bstrVal)
        {
            Output(0, "encoding=\"%S\" ",bstrVal);
            SysFreeString(bstrVal);
        }
        Output(0, "\?>\n");

        //
        // Look for doctype information.
        //

        // Disabled till DavidSch makes a fix
        /*
        bstrVal = NULL;
        hr = pDoc->get_doctype(&bstrVal);
        if(SUCCEEDED(hr) && bstrVal)
        {
            Output(0, "<!DOCTYPE %S>",bstrVal);
            SysFreeString(bstrVal);

        }
        */
        //
        // Dump the root element and all children of the XML object.
        //

        DumpElement(pElem, 0); // -1 to counteract nameless outer container
    }
    else
    {
        //
        // Failed to parse stream, output error information.
        //
        IXMLError *pXMLError = NULL ;
        XML_ERROR xmle;

        hr = pDoc->QueryInterface(IID_IXMLError, (void **)&pXMLError);
        CHECK_ERROR(SUCCEEDED(hr), "Couldn't get IXMLError");

        ASSERT(pXMLError);

        hr = pXMLError->GetErrorInfo(&xmle);
        SAFERELEASE(pXMLError);
        CHECK_ERROR(SUCCEEDED(hr), "GetErrorInfo Failed");

        printf("%s: Error on line %d. Found %S while expecting %S\r\n",
                argv[0],
                xmle._nLine,
                xmle._pszFound,
                xmle._pszExpected);

        SysFreeString(xmle._pszFound);
        SysFreeString(xmle._pszExpected);
        SysFreeString(xmle._pchBuf);
    }

done: // Clean up.
    //
    // Release any used interfaces.
    //
    SAFERELEASE(pPSI);
    SAFERELEASE(pStm);
    SAFERELEASE(pElem);
    SAFERELEASE(pDoc);
    SysFreeString(pBURL);
    if (pszErr)
        fprintf (stderr, "%s, last error %d\n", pszErr, GetLastError());
    return 0;
}


Sample 3: Using IPersistMoniker::Load to load a document

//****************************************
// MSXML OM test code
//
// adapted for multithreaded urlmon testing
//****************************************

#include <windows.h>
#include <windowsx.h>
#include <stdlib.h>
#include <stdio.h>
#include <io.h>
#include <urlmon.h>
#include <hlink.h>
#include <dispex.h>
#include "mshtml.h"
#include "msxml.h"

int MyStrToOleStrN(LPOLESTR pwsz, int cchWideChar, LPCTSTR psz);
#define ASSERT(x)  if(!(x)) DebugBreak()
#define CHECK_ERROR(cond, err) if (!(cond)) {pszErr=(err); goto done;}
#define SAFERELEASE(p) if (p) {(p)->Release(); p = NULL;} else ;
//
// SAFECAST(obj, type)
//
// This macro is extremely useful for enforcing strong typechecking on other
// macros.  It generates no code.
//
// Simply insert this macro at the beginning of an expression list for
// each parameter that must be typechecked.  For example, for the
// definition of MYMAX(x, y), where x and y absolutely must be integers,
// use:
//
//   #define MYMAX(x, y)    (SAFECAST(x, int), SAFECAST(y, int), ((x) > (y) ? (x) : (y)))
//
//
#define SAFECAST(_obj, _type) (((_type)(_obj)==(_obj)?0:0), (_type)(_obj))

#define WALK_ELEMENT_COLLECTION(pCollection, pDispItem) \
    {\
        long length;\
        \
        if (SUCCEEDED(pCollection->get_length(&length)) && length > 0)\
        {\
            VARIANT vIndex, vEmpty;\
            vIndex.vt = VT_I4;\
            vEmpty.vt = VT_EMPTY;\
                                 \
            for (long i=0; i<length; i++)\
            {\
                vIndex.lVal = i;\
                IDispatch *pDispItem = NULL;\
                if (SUCCEEDED(pCollection->item(vIndex, vEmpty, &pDispItem)))\
                {

#define END_WALK_ELEMENT_COLLECTION(pDispItem) \
                    pDispItem->Release();\
                }\
            }\
        }\
    }

//==========================================================================

class CTestBindStatusCallback : public IBindStatusCallback
                              , public IAuthenticate
                              , public IHttpSecurity

    {
    public:
        // *** IUnknown methods ***
        STDMETHOD(QueryInterface)(REFIID riid, LPVOID * ppvObj);
        STDMETHOD_(ULONG, AddRef)(void) ;
        STDMETHOD_(ULONG, Release)(void);

        // *** IAuthenticate ***
        STDMETHOD(Authenticate)(
            HWND *phwnd,
            LPWSTR *pszUsername,
            LPWSTR *pszPassword);

        // *** IBindStatusCallback ***
        STDMETHOD(OnStartBinding)(
            /* [in] */ DWORD grfBSCOption,
            /* [in] */ IBinding *pib);

        STDMETHOD(GetPriority)(
            /* [out] */ LONG *pnPriority);

        STDMETHOD(OnLowResource)(
            /* [in] */ DWORD reserved);

        STDMETHOD(OnProgress)(
            /* [in] */ ULONG ulProgress,
            /* [in] */ ULONG ulProgressMax,
            /* [in] */ ULONG ulStatusCode,
            /* [in] */ LPCWSTR szStatusText);

        STDMETHOD(OnStopBinding)(
            /* [in] */ HRESULT hresult,
            /* [in] */ LPCWSTR szError);

        STDMETHOD(GetBindInfo)(
            /* [out] */ DWORD *grfBINDF,
            /* [unique][out][in] */ BINDINFO *pbindinfo);

        STDMETHOD(OnDataAvailable)(
            /* [in] */ DWORD grfBSCF,
            /* [in] */ DWORD dwSize,
            /* [in] */ FORMATETC *pformatetc,
            /* [in] */ STGMEDIUM *pstgmed);

        STDMETHOD(OnObjectAvailable)(
            /* [in] */ REFIID riid,
            /* [iid_is][in] */ IUnknown *punk);

        /* *** IHttpSecurity ***  */
        STDMETHOD(GetWindow)(REFGUID rguidReason, HWND* phwnd);

        STDMETHOD(OnSecurityProblem)(DWORD dwProblem);

        // Worker routines

        IBinding*       m_pib;
        IMoniker*        m_pmk;
        IBindCtx*       m_pbc;
        HANDLE          m_hEvent;

        ULONG m_cRef;

        VOID Abort(); // Aborts the binding
        ~CTestBindStatusCallback();
        CTestBindStatusCallback(IBindCtx *pbc, IMoniker *pmkIn, HANDLE hEvent);
    };

void Indent(int indent, FILE *fileID)
{
    while (indent-->0)
    {
        fprintf(fileID, "    ");
    }
}

//
// Dump an element attribute member if present.
//
void DumpAttrib(IXMLElement *pElem, BSTR bstrAttribName, FILE *fileID)
{
    VARIANT vProp;

    VariantInit(&vProp);

    if (SUCCEEDED(pElem->getAttribute(bstrAttribName, &vProp)))
    {
        if (vProp.vt == VT_BSTR)
        {
            fprintf(fileID, "%S=\"%S\" ", bstrAttribName, vProp.bstrVal);
        }
        VariantClear(&vProp);
    }
}

HRESULT DumpElement(IXMLElement *pElem, int indent, FILE *fileID)
{
    BSTR bstr = NULL;
    IXMLElementCollection * pChildren;

    Indent(indent, fileID);

    //
    // Dump the name of the NODE.
    //
    pElem->get_tagName(&bstr);
    fprintf(fileID, "<%S ", bstr?bstr:L"XML");

    //
    // Dump the attributes if present.
    //
    DumpAttrib(pElem, L"VALUE", fileID);
    DumpAttrib(pElem, L"HREF", fileID);
    DumpAttrib(pElem, L"HOUR", fileID);
    DumpAttrib(pElem, L"DAY", fileID);
    DumpAttrib(pElem, L"IsClonable", fileID);
    DumpAttrib(pElem, L"Type", fileID);

    //
    // Find the children if they exist.
    //
    if (SUCCEEDED(pElem->get_children(&pChildren)) && pChildren)
    {
        fprintf(fileID, ">\n");

        WALK_ELEMENT_COLLECTION(pChildren, pDisp)
        {
            //
            // pDisp will iterate over an IDispatch for each item in the collection.
            //
            IXMLElement * pChild;
            if (SUCCEEDED(pDisp->QueryInterface(IID_IXMLElement, (void **)&pChild)))
            {
                DumpElement(pChild, indent+1, fileID);
                pChild->Release();
            }
        }
        END_WALK_ELEMENT_COLLECTION(pDisp);
        pChildren->Release();
        //
        // Have output children display closing tag.
        //
        Indent(indent, fileID);
        fprintf(fileID, "</%S>\n", bstr?bstr:L"XML");
    }
    else
    {
        //
        // No children so terminate tag on same line.
        //
        fprintf(fileID, "/>\n");
    }

    if (bstr)
        SysFreeString(bstr);

    return S_OK;
}

HANDLE g_hMutex = NULL;
ULONG g_ulNextThreadId = 0;

DWORD WINAPI LoadFunc(CHAR *pszUrl)
{

FILE *fileID = stdout;
    HRESULT hr;
    IXMLElement *pElem = NULL;
    IUnknown *pUnk = NULL;
    IXMLDocument *pDoc = NULL;
    IMoniker *pmk = NULL;
    HANDLE hEvent = NULL;
    IBindStatusCallback *pPreviousCallback = NULL;
    IPersistMoniker *pPersistmk = NULL;
    PSTR pszErr = NULL;
    IBindCtx *pbc = NULL;
    IBindStatusCallback *pbsc = NULL;
    DWORD dwRet;
    LONG len;
    WCHAR *pwszUrl;

    ASSERT(SUCCEEDED(hr));
    len = lstrlenA(pszUrl);

    pwszUrl = (WCHAR *)LocalAlloc(LMEM_FIXED, (len + 1)*sizeof(WCHAR));
    ASSERT(pwszUrl);
    MyStrToOleStrN(pwszUrl, len + 1, pszUrl);

    //
    // Dump the root element and all children of the XML object.
    //

    ASSERT(SUCCEEDED(hr));
    if (!pDoc)
    {
        hr = CoCreateInstance(CLSID_XMLDocument, NULL, CLSCTX_INPROC_SERVER,
                                IID_IUnknown, (void**)&pUnk);
    }

    CHECK_ERROR (pUnk, "CoCreateInstance");

    hr = pUnk->QueryInterface(IID_IXMLDocument, (void **)&pDoc);

    ASSERT(SUCCEEDED(hr));
    pUnk->Release();
    pUnk = NULL;
    CHECK_ERROR (pDoc, "QI for IXMLDocument");

    hr = pDoc->QueryInterface(IID_IPersistMoniker, (void **)&pPersistmk);
    ASSERT(SUCCEEDED(hr));

    CHECK_ERROR(pPersistmk, "QI for IPersistMoniker");

    hr = CreateURLMoniker(NULL, pwszUrl, &pmk);
    ASSERT(SUCCEEDED(hr));
    CHECK_ERROR(pmk, "CreateURLMoniker");

    hr = CreateBindCtx(0, &pbc);
    if((!pbc) || FAILED(hr))
        goto done;

    pbc->AddRef();

    hEvent = CreateEventA(0, 0, 0, 0);
    pbsc = new CTestBindStatusCallback(pbc, pmk, hEvent);
    ASSERT(pbsc);
    if(!pbsc)
    {
        fprintf (stderr, "Out of memory ");
        goto done;
    }
    pbsc->AddRef();

    hr = RegisterBindStatusCallback(pbc, pbsc, &pPreviousCallback, 0);
    if(FAILED(hr))
    {
        fprintf (stderr, "RegisterBindStatusCallback : Failed");
        goto done;
    }

    hr = pPersistmk->Load(FALSE, pmk, pbc, 0);

    ASSERT(SUCCEEDED(hr));

    if(pPersistmk)
    {
        pPersistmk->Release();
        pPersistmk = NULL;
    }

    while(1)
    {
        MSG msg;
        dwRet =  MsgWaitForMultipleObjects(1, &hEvent, FALSE, INFINITE, QS_ALLINPUT);
        if(dwRet == WAIT_OBJECT_0)
        {
            // We're done
            break;
         }
         else
         {
            GetMessage(&msg, NULL, 0, 0);
            DispatchMessage(&msg);
         }
    }
    // Ready to start dumping the document.

    //
    // Now walk the OM and look at interesting things.
    //
    hr = pDoc->get_root(&pElem);
    CHECK_ERROR(pElem, "Thread Failed to get_root of XML object");

    DumpElement(pElem, 0, fileID);

done: // Clean up.
    fclose(fileID);
    pElem->Release();
    LocalFree(pwszUrl);
    pbsc->Release();
    return 0;
}

int MyStrToOleStrN(LPOLESTR pwsz, int cchWideChar, LPCTSTR psz)
{
    int i;
    i=MultiByteToWideChar(CP_ACP, 0, psz, -1, pwsz, cchWideChar);
    if (!i)
    {
        //DBG_WARN("MyStrToOleStrN string too long; truncated");
        pwsz[cchWideChar-1]=0;
    }
    else
        ZeroMemory(pwsz+i, sizeof(OLECHAR)*(cchWideChar-i));

    return i;
}

#define NUM_THREADS 1
const WCHAR *szUrls[NUM_THREADS] = {  L"http://ie_tools/bharats/msnbc0.cdf",
                                      //L"http://ie_tools/bharats/msnbc1.cdf",
                                     // L"http://ie_tools/bharats/msnbc2.cdf",
                                      //L"http://ie_tools/bharats/msnbc3.cdf",
                                      //L"http://ie_tools/bharats/msnbc4.cdf"
                                    };

int _cdecl main (int argc, char **argv)
{
    PSTR pszErr = NULL;
    IStream                *pStm = NULL;
    IPersistStreamInit     *pPSI = NULL;
    IXMLElement            *pElem = NULL;
    char                  buf[MAX_PATH];
    char                  *pszURL;
    UINT uNumThreads = NUM_THREADS; // Atleast three threads
    UINT ui;// iterator
    DWORD dwThreadId;
    HANDLE hThd;
    WCHAR *pwszStrUrlCopy = NULL;
    LONG len;

    HRESULT hr;

    //
    // Check usage.
    //
    if (argc < 2)
    {
        fprintf (stderr, "Usage:   %s URL\n",argv[0]);
        fprintf (stderr, "Eg %s c:\\nt\\private\\inet\\xml\\test\\channel.uni\n", argv[0]);
        fprintf (stderr, "or %s http://ohserv/users/julianj/channel.xml\n", argv[0]);
        exit (1);
    }

    // HACK if passed in a file name, expand if it doesn't look like a URL.
    //

    if (CompareString(LOCALE_USER_DEFAULT, NORM_IGNORECASE, argv[1], 7, "http://", 7) == CSTR_EQUAL)
    {
        pszURL = argv[1];
    }
    else
    {
        pszURL = buf;
        GetFullPathName(argv[1], MAX_PATH, pszURL, NULL);
    }

    hr = CoInitialize(NULL);
    ASSERT(SUCCEEDED(hr));

    //
    // Create an empty XML document.
    //
    LoadFunc(pszURL);

    len = lstrlen(pszURL) + 1;

    //
    // Dump the root element and all children of the XML object onto screen.

done: // Clean up.
    //
    // Release any used interfaces.
    //
    SAFERELEASE(pPSI);
    SAFERELEASE(pStm);
    SAFERELEASE(pElem);

    if (pszErr)
        fprintf (stderr, "%s, last error %d\n", pszErr, GetLastError());

    return 0;
}

STDMETHODIMP CTestBindStatusCallback::QueryInterface(
                                REFIID riid,
                                LPVOID * ppvObj)
{
    if (IsEqualIID(riid, IID_IBindStatusCallback) ||
        IsEqualIID(riid, IID_IUnknown))
    {
        *ppvObj = SAFECAST(this, IBindStatusCallback*);
    }
    else if (IsEqualIID(riid, IID_IAuthenticate))
    {
        *ppvObj = SAFECAST(this, IAuthenticate*);
    }
    else if (IsEqualIID(riid, IID_IHttpSecurity))
    {
        *ppvObj = SAFECAST(this, IHttpSecurity*);
    }
    else
    {
        *ppvObj = NULL;
        return E_NOINTERFACE;
    }

    ((LPUNKNOWN)*ppvObj)->AddRef();
    return NOERROR;
}

ULONG CTestBindStatusCallback::AddRef(void)
{
    return ++m_cRef;
}

ULONG CTestBindStatusCallback::Release(void)
{
    if( 0L != --m_cRef )
        return m_cRef;

    delete this;
    return 0L;
}

VOID CTestBindStatusCallback::Abort()
{
    if(m_pib)
    {
        m_pib->Abort();
    }
}

CTestBindStatusCallback::CTestBindStatusCallback(IBindCtx *pbc, IMoniker *pmkIn, HANDLE hEvent)
{

    // Initialize object.
    m_cRef=0L;

    m_pib = NULL;
    m_pbc = pbc;
    if(m_pbc)
        m_pbc->AddRef();

    m_pmk = pmkIn;
    if(m_pmk)
        m_pmk->AddRef();

    m_hEvent = hEvent;
}

CTestBindStatusCallback::~CTestBindStatusCallback()
{
    SAFERELEASE(m_pib);
    SAFERELEASE(m_pbc);

    SAFERELEASE(m_pmk);
    if(m_hEvent)
        CloseHandle(m_hEvent);
}

// IAuthenticate Methods
STDMETHODIMP CTestBindStatusCallback::Authenticate(
    HWND *phwnd,
    LPWSTR *pszUsername,
    LPWSTR *pszPassword)
{
    return E_NOTIMPL;
}

// IBindStatusCallback Methods
STDMETHODIMP CTestBindStatusCallback::OnStartBinding(DWORD grfBSCOption,
IBinding *pibIn)
{

    return S_OK;

}

STDMETHODIMP CTestBindStatusCallback::GetPriority(LONG *pnPriority)
{
    return S_OK;
}

STDMETHODIMP CTestBindStatusCallback::OnLowResource(DWORD reserved)
{
    return S_OK; //BUGBUG
}

STDMETHODIMP CTestBindStatusCallback::OnProgress(
    ULONG ulProgress,
    ULONG ulProgressMax,
    ULONG ulStatusCode,
    LPCWSTR szStatusText)
{
    return S_OK;
}

STDMETHODIMP CTestBindStatusCallback::OnStopBinding(
    HRESULT hresult,
    LPCWSTR szError)
{
    HRESULT hr = S_OK;
    if(SUCCEEDED(hresult))
    {
        OutputDebugString(TEXT("Done Loading succesfully"));
    }
    // Signal event to wake up thread to navigate children.
    SetEvent(m_hEvent);

    SAFERELEASE(m_pib);
    return hr;
}

STDMETHODIMP CTestBindStatusCallback::GetBindInfo(
    DWORD *grfBINDF, /* [out] */
    BINDINFO *pbindinfo /* [unique][out][in] */ )
{
    return E_NOTIMPL;

}

STDMETHODIMP CTestBindStatusCallback::OnDataAvailable(
    /* [in] */ DWORD grfBSCF,
    /* [in] */ DWORD dwSize,
    /* [in] */ FORMATETC *pformatetc,
    /* [in] */ STGMEDIUM *pstgmed)
{
    return S_OK;
}

STDMETHODIMP CTestBindStatusCallback::OnObjectAvailable(
    /* [in] */ REFIID riid,
    /* [iid_is][in] */ IUnknown *punk)
{
    return S_OK;
}

/* *** IHttpSecurity ***  */
        // BUGBUG - Do we need to implement this interface
STDMETHODIMP CTestBindStatusCallback::GetWindow(REFGUID rguidReason, HWND*
phwnd)
{
    if (!phwnd)
        return E_POINTER;

    *phwnd = NULL; // BUGBUG
    return S_OK;
}

STDMETHODIMP CTestBindStatusCallback::OnSecurityProblem(DWORD dwProblem)
{
    // Force UI - return S_FALSE for all problems.
    return S_FALSE;
}


Sample 4: Parsing an XML file using JScript

<HTML>
<HEAD>
<TITLE>JScript XML Sample</TITLE>
</HEAD>
<BR>
<H1><B><CENTER>JScript XML Sample</B></H1>
<P>This page demonstrates using XML in JScript. Enter a valid XML or CDF file in the
text box below and it will be parsed using MSXML and JScript. CDF is based on XML.
Information about each element in the file will be displayed in another window. For more
information on CDF, please see the <A HREF="http://www.microsoft.com/ie/authors/">Internet
Explorer 4.0 authors and developers </A> site.

<P>Enter an XML or CDF file name:<BR>
<INPUT TYPE=TEXT NAME="cdfURL" VALUE="" size=50><BR>

<OBJECT
    classid="clsid:CFC399AF-D876-11D0-9C10-00C04FC99C8E"
    id="MSXML"
    Name="xmlDoc">
</OBJECT>

<BR><BR>

<INPUT TYPE = "BUTTON"
    NAME = "ParseCDF"
    VALUE = "Parse The XML/CDF File"
    onClick = "WalkXMLMain(cdfURL.value)">

</CENTER>

<SCRIPT>
var win;                                // status goes here
var doc;                                // document to write on
var knownAttrs = new Object;            // element attribute variable

//
// Display the attribute.
//
function dumpAttrs(elem)
{
    var i, val, result = "";

    for (i in knownAttrs)
    {
    val = elem.getAttribute(knownAttrs[i]);
        if ((val != "") && (val != null))
            result = result + knownAttrs[i] + "=" + val + " ";
    }

    return result;
}

//
// Display the element information for each element in the file.
//
function dumpElement(elem)
{
    var children, cChildren, child
    var i, length;

    if (elem == null)
    {
        alert("elem == null");
        window = document;              //      Force a run-time error to bail
    }

    children = elem.children;
    if (children != null)
    length = children.length;
    else
    length = 0;

// Display the element information in the table.
    doc.write("<TR><TD>" + GetTagName(elem) + "</TD>");
    doc.write("<TD>" + GetType(elem.type) + "</TD>");
    if (elem.parent != null) // skip text for root node
    doc.write("<TD>" + elem.text + "</TD>");
    else
    doc.write("<TD>" + " " + "</TD>");
    doc.write("<TD>" + dumpAttrs(elem) + "</TD>");
    doc.write("<TD>" + GetParentTag(elem) + "</TD>");
    doc.write("<TD>" + length + "</TD></TR>");

// If the element has children, call dumpElement again
    if (children != null)
    {

        cChildren = children.length;

        for (i = 0; i < cChildren; i++)
        {
            child = children.item(i);
            dumpElement(child);
        }
    }
}

//
// Initialize the knownAttrs variable.
//
function loadKnownAttrs()
{
// Incomplete list, just for example.
    knownAttrs[0] = "HREF";
    knownAttrs[1] = "STYLE";
    knownAttrs[2] = "HOUR";
    knownAttrs[3] = "DAY";
    knownAttrs[4] = "MIN";
    knownAttrs[5] = "IsClonable";
    knownAttrs[6] = "Type";
    knownAttrs[7] = "BASE";
    knownAttrs[8] = "SELF";
}

//
// Write information to the browser status bar.
//
function setStatus(s)
{
    win.status = s;
}

//
// Main function, calls dumpElement.
//
function WalkXMLMain(cdfName)
{
    var startTime = new Date();
    var CDFFile, xmlDoc;

    win = window.open("", "XMLOutput");
    doc = win.document;

    doc.writeln("<HTML>");
    doc.writeln("<TITLE>XML Output</TITLE>");
    doc.writeln("<BODY>");
    doc.writeln("<PRE>");

    setStatus("Loading known attributes...");
    loadKnownAttrs();

    setStatus("Creating XML object...");
    xmlDoc = MSXML;

    setStatus("Loading XML document...");
    xmlDoc.URL = cdfName;
    setStatus("File has been assigned to xmlDoc.URL");

// Show the document information.
    ShowDocInfo(xmlDoc);

// Initialize the table for the element information.
    MakeNodeHeader(win);

// Traverse the XML tree showing the element information.
    dumpElement(xmlDoc.root);

    doc.writeln("</TABLE>");
    var stopTime = new Date();
    doc.writeln("<FONT SIZE=&quot+1&quot><P>Start: " + startTime + "   Stop: " + stopTime + "</FONT>");
    doc.writeln("</PRE>");
    doc.writeln("</BODY>");
    doc.writeln("</HTML>");

    xmlDoc = null;
    setStatus("Done!");
}

//
// Initialize the table for the element information.
//
function MakeNodeHeader(win)
{
    doc.writeln("<BR><BR><H2>Element Information</H2></CENTER>");
    doc.write("<FONT SIZE=&quot+1&quot><P>The properties of each node in the XML file is listed in the following table.<BR><BR></FONT>");

    doc.write("<TABLE BORDER CELLSPACING=2 CELLPADDING=2>");
    doc.write("<TR><TD ALIGN=LEFT><B>Tag Name</B></TD>");
    doc.write("<TD ALIGN=LEFT><B>Type</B></TD>");
    doc.write("<TD ALIGN=LEFT><B>Text (if any)</B></TD>");
    doc.write("<TD ALIGN=LEFT><B>Attribute</B></TD>");
    doc.write("<TD ALIGN=LEFT><B>Parent</B></TD>");
    doc.write("<TD ALIGN=LEFT><B># of Children</B></TD></TR>");
}

//
// Return the element type.
//
function GetType(type)
{

  if (type == 0)
    return "ELEMENT";

  if (type == 1)
    return "TEXT";

  if (type == 2)
    return "COMMENT";

  if (type == 3)
    return "DOCUMENT";

  if (type == 4)
    return "DTD";
  else
    return "OTHER";
}

//
// Return the tag name.
//
function GetTagName(elem)
{
  if (elem.type == 0)
    return elem.tagName;
  else
    return " ";
}

//
// Return the parent tag name.
//
function GetParentTag(elem)
{
  if (elem.parent != null)
    return GetTagName(elem.parent);
  else
    return " ";
}

//
// Display document information about the XML file.
//
function ShowDocInfo(xmlDoc)
{
  doc.writeln("<FONT FACE=&quottimes&quot SIZE=&quot+1&quot><CENTER><H2>Document Information</H2>");
  if (xmlDoc.URL != null)
    doc.writeln("<P>URL is: " + xmlDoc.URL);
  doc.writeln("<P>Version is: " + xmlDoc.version);
  if (xmlDoc.doctype != null)
    doc.writeln("<P>Doc Type is: " + xmlDoc.doctype);
  if (xmlDoc.readyState != null)
    doc.writeln("<P>Ready State is: " + GetReadyState(xmlDoc.readyState));
  if (xmlDoc.charset != null)
    doc.writeln("<P>Character Set is: " + xmlDoc.charset);
}

//
// Return the ready state of the document.
//
function GetReadyState(state)
{
  if (state == 0)
    return "READYSTATE_UNINTIALIZED";
  if (state == 1)
    return "READYSTATE_LOADING";
  if (state == 2)
    return "READYSTATE_LOADED";
  if (state == 3)
    return "READYSTATE_INTERACTIVE";
  if (state == 4)
    return "READYSTATE_COMPLETE";
  else
    return "undefined";
}

</SCRIPT>
</BODY>
</HTML>


Appendix A: Header File Additions Required for ActiveX Controls

The following definitions didn't make it into the Urlmon.idl and Urlmon.h files in time for the Microsoft® Internet Explorer 4.0 release, so they need to be added to those files for any ActiveX™ Controls that access the new URL security zone manager implemented in Internet Explorer 4.0.

#define CONFIRMSAFETYACTION_LOADOBJECT    0x00000001

struct CONFIRMSAFETY
{
    CLSID clsid;
    IUnknown *punk;
    DWORD dwFlags;
};

static const GUID GUID_CUSTOM_CONFIRMOBJECTSAFETY =
    { 0x10200490, 0xfa38, 0x11d0, { 0xac, 0xe, 0x0, 0xa0, 0xc9, 0xf, 0xff, 0xc0 } };


URL Security Zones Overview

Monikers, URLs, security zones, and pluggable protocols provide capabilities that allow you to asynchronously bind objects, bind Uniform Resource Locators (URLs), manage URL security zones, and create custom URL protocols. This section covers the functionality exported by the Urlmon.dll dynamic-link library (DLL).

Introduction

About URLs and Name Spaces

About URL Security Zones

Handling URL Security Zones

Creating a Customized URL Security Manager

Accessing the Default Managers

Appendix A: Header File Additions Required for ActiveX Controls

Introduction

If you want to compile programs that use the functionality provided in Urlmon.dll, you must make sure the Urlmon.h header file is in the include directory, and the Urlmon.lib library file is in the library directory, of the C/C++ compiler you use.

This documentation assumes that you have an understanding of Microsoft® Win32® programming. Also, for asynchronous monikers, asynchronous pluggable protocols, and URL monikers you should have an understanding of OLE and COM programming. For the Internet-related interfaces, methods, and functions, an understanding of the format and syntax of URLs is also required. For more information, see RFC 1738, Uniform Resource Locators (URL). You can find this document at http://ds.internic.net/rfc/rfc1738.txt. External Link

About URLs and Name Spaces

A Uniform Resource Locator (URL) follows the syntax described in RFC 1738, which specifies a protocol scheme followed by a scheme-specific portion (<scheme>:<scheme-specific portion>). For example, in the URL http://www.microsoft.com/, "http" is the scheme and "//www.microsoft.com/" is the scheme-specific portion.

The beginning portion of the scheme-specific portion of the URL contains the server name. This portion of the URL is often referred to as the URL name space.

About URL Security Zones

To fully understand URL security zones, you need to understand a few terms:

  • URL action is an action that a browser can take that might pose a security risk to the local computer. These include actions such as running a Java applet (URLACTION_JAVA_PERMISSIONS in this case) or an ActiveX™ control (URLACTION_ACTIVEX_RUN in this case).
  • URL policy is a policy that determines what permission or trust level is set for a particular URL action. These include setting the safety level for Java to high (URLPOLICY_JAVA_HIGH in this case).
  • URL security zone is a group of URL name spaces that are assigned an equal level of permission (or trust). Each URL action for the zone has an appropriate URL policy assigned to it that reflects the level of trust given to the URL name spaces in that zone.

Previously, Microsoft Internet Explorer utilized the same security policy for all URL name spaces. Each URL action in a particular security level was handled by a predetermined URL policy, which could not be changed. In Internet Explorer 4.0, URL name spaces are divided into URL security zones, which have different levels of trust assigned to them. Users can easily customize the default URL security zones by changing the URL policy settings for each URL action with the user interface provided by Internet Explorer.

Default URL Security Zones

The default URL security zones used by Internet Explorer 4.0 are:

  • The Intranet
  • Trusted Web sites
  • Internet
  • Untrusted sites

The Intranet zone is used for content located on a company's intranet. Since the servers and information would be within a company's firewall, a user or company could assign a higher trust level to the content on their intranet.

The following table contains the default settings for the intranet zone.
URL action | URL policy | Aggregates
URLACTION_ACTIVEX_RUN | URLPOLICY_ALLOW | none
URLACTION_DOWNLOAD_SIGNED_ACTIVEX | URLPOLICY_QUERY | none
URLACTION_DOWNLOAD_UNSIGNED_ACTIVEX | URLPOLICY_DISALLOW | none
URLACTION_ACTIVEX_OVERRIDE_OBJECT_SAFETY | URLPOLICY_QUERY | URLACTION_ACTIVEX_OVERRIDE_DATA_SAFETY and URLACTION_ACTIVEX_OVERRIDE_SCRIPT_SAFETY
URLACTION_SCRIPT_RUN | URLPOLICY_ALLOW | none
URLACTION_SCRIPT_JAVA_USE | URLPOLICY_ALLOW | none
URLACTION_JAVA_PERMISSIONS | URLPOLICY_JAVA_HIGH | none
URLACTION_HTML_FONT_DOWNLOAD | URLPOLICY_ALLOW | none
URLACTION_SHELL_FILE_DOWNLOAD | URLPOLICY_QUERY | none
URLACTION_HTML_SUBMIT_FORMS | URLPOLICY_QUERY | URLACTION_HTML_SUBMIT_FORMS_FROM and URLACTION_HTML_SUBMIT_FORMS_TO
URLACTION_SHELL_INSTALL_DTITEMS | URLPOLICY_QUERY | none
URLACTION_SHELL_MOVE_OR_COPY | URLPOLICY_QUERY | none
URLACTION_SHELL_VERB | URLPOLICY_ALLOW | none
URLACTION_CREDENTIALS_USE | URLPOLICY_CREDENTIALS_MUST_PROMPT_USER | none
URLACTION_CHANNEL_SOFTDIST_PERMISSIONS | URLPOLICY_CHANNEL_SOFTDIST_PRECACHE | none
URLACTION_SHELL_WEBVIEW_VERB | URLPOLICY_ALLOW | none

The Trusted Web sites zone is used for content located on Web sites that are considered more reputable and/or trustworthy than other sites on the Internet. Users can use this zone to assign a higher trust level to these sites to minimize the number of authentication requests. The URLs of these trusted Web sites would need to be mapped into this zone.

The following table contains the default settings for the Trusted Web sites zone.
URL action | URL policy | Aggregates
URLACTION_ACTIVEX_RUN | URLPOLICY_ALLOW | none
URLACTION_DOWNLOAD_SIGNED_ACTIVEX | URLPOLICY_ALLOW | none
URLACTION_DOWNLOAD_UNSIGNED_ACTIVEX | URLPOLICY_QUERY | none
URLACTION_ACTIVEX_OVERRIDE_OBJECT_SAFETY | URLPOLICY_QUERY | URLACTION_ACTIVEX_OVERRIDE_DATA_SAFETY and URLACTION_ACTIVEX_OVERRIDE_SCRIPT_SAFETY
URLACTION_SCRIPT_RUN | URLPOLICY_ALLOW | none
URLACTION_SCRIPT_JAVA_USE | URLPOLICY_ALLOW | none
URLACTION_JAVA_PERMISSIONS | URLPOLICY_JAVA_LOW | none
URLACTION_HTML_FONT_DOWNLOAD | URLPOLICY_ALLOW | none
URLACTION_SHELL_FILE_DOWNLOAD | URLPOLICY_QUERY | none
URLACTION_HTML_SUBMIT_FORMS | URLPOLICY_ALLOW | URLACTION_HTML_SUBMIT_FORMS_FROM and URLACTION_HTML_SUBMIT_FORMS_TO
URLACTION_SHELL_INSTALL_DTITEMS | URLPOLICY_ALLOW | none
URLACTION_SHELL_MOVE_OR_COPY | URLPOLICY_ALLOW | none
URLACTION_SHELL_VERB | URLPOLICY_QUERY | none
URLACTION_CREDENTIALS_USE | URLPOLICY_CREDENTIALS_SILENT_LOGON_OK | none
URLACTION_CHANNEL_SOFTDIST_PERMISSIONS | URLPOLICY_CHANNEL_SOFTDIST_AUTOINSTALL | none
URLACTION_SHELL_WEBVIEW_VERB | URLPOLICY_ALLOW | none

The Internet zone is used for the Web sites on the Internet that do not belong to another zone. The default settings would cause the user to be prompted whenever potentially unsafe content was about to be downloaded. Web sites that are not mapped into other zones automatically fall into this zone.

The following table contains the default settings for the Internet zone.
URL action | URL policy | Aggregates
URLACTION_ACTIVEX_RUN | URLPOLICY_ALLOW | none
URLACTION_DOWNLOAD_SIGNED_ACTIVEX | URLPOLICY_QUERY | none
URLACTION_DOWNLOAD_UNSIGNED_ACTIVEX | URLPOLICY_DISALLOW | none
URLACTION_ACTIVEX_OVERRIDE_OBJECT_SAFETY | URLPOLICY_QUERY | URLACTION_ACTIVEX_OVERRIDE_DATA_SAFETY and URLACTION_ACTIVEX_OVERRIDE_SCRIPT_SAFETY
URLACTION_SCRIPT_RUN | URLPOLICY_ALLOW | none
URLACTION_SCRIPT_JAVA_USE | URLPOLICY_ALLOW | none
URLACTION_JAVA_PERMISSIONS | URLPOLICY_JAVA_HIGH | none
URLACTION_HTML_FONT_DOWNLOAD | URLPOLICY_ALLOW | none
URLACTION_SHELL_FILE_DOWNLOAD | URLPOLICY_QUERY | none
URLACTION_HTML_SUBMIT_FORMS | URLPOLICY_QUERY | URLACTION_HTML_SUBMIT_FORMS_FROM and URLACTION_HTML_SUBMIT_FORMS_TO
URLACTION_SHELL_INSTALL_DTITEMS | URLPOLICY_QUERY | none
URLACTION_SHELL_MOVE_OR_COPY | URLPOLICY_QUERY | none
URLACTION_SHELL_VERB | URLPOLICY_QUERY | none
URLACTION_CREDENTIALS_USE | URLPOLICY_CREDENTIALS_MUST_PROMPT_USER | none
URLACTION_CHANNEL_SOFTDIST_PERMISSIONS | URLPOLICY_CHANNEL_SOFTDIST_PRECACHE | none
URLACTION_SHELL_WEBVIEW_VERB | URLPOLICY_QUERY | none

The Untrusted sites zone is used for Web sites that contain content that could cause, or have caused, problems when downloaded. This zone could be used to cause the user to be prompted every time potentially unsafe content was about to be downloaded or prevent that content from being downloaded. The URLs of these untrusted Web sites would need to be mapped into this zone.

The following table contains the default settings for the Untrusted sites zone.
URL action | URL policy | Aggregates
URLACTION_ACTIVEX_RUN | URLPOLICY_DISALLOW | none
URLACTION_DOWNLOAD_SIGNED_ACTIVEX | URLPOLICY_DISALLOW | none
URLACTION_DOWNLOAD_UNSIGNED_ACTIVEX | URLPOLICY_DISALLOW | none
URLACTION_ACTIVEX_OVERRIDE_OBJECT_SAFETY | URLPOLICY_DISALLOW | URLACTION_ACTIVEX_OVERRIDE_DATA_SAFETY and URLACTION_ACTIVEX_OVERRIDE_SCRIPT_SAFETY
URLACTION_SCRIPT_RUN | URLPOLICY_ALLOW | none
URLACTION_SCRIPT_JAVA_USE | URLPOLICY_DISALLOW | none
URLACTION_JAVA_PERMISSIONS | URLPOLICY_JAVA_HIGH | none
URLACTION_HTML_FONT_DOWNLOAD | URLPOLICY_QUERY | none
URLACTION_SHELL_FILE_DOWNLOAD | URLPOLICY_DISALLOW | none
URLACTION_HTML_SUBMIT_FORMS | URLPOLICY_DISALLOW | URLACTION_HTML_SUBMIT_FORMS_FROM and URLACTION_HTML_SUBMIT_FORMS_TO
URLACTION_SHELL_INSTALL_DTITEMS | URLPOLICY_DISALLOW | none
URLACTION_SHELL_MOVE_OR_COPY | URLPOLICY_DISALLOW | none
URLACTION_SHELL_VERB | URLPOLICY_DISALLOW | none
URLACTION_CREDENTIALS_USE | URLPOLICY_CREDENTIALS_MUST_PROMPT_USER | none
URLACTION_CHANNEL_SOFTDIST_PERMISSIONS | URLPOLICY_CHANNEL_SOFTDIST_PROHIBIT | none
URLACTION_SHELL_WEBVIEW_VERB | URLPOLICY_QUERY | none

There is also an implicit zone used for content that exists on the local computer. The content found on the local computer, except for content cached by Microsoft Internet Explorer on the local system, is treated with a high level of trust. Content that has been cached by Internet Explorer is accessed through the URL of origin and is assigned to the appropriate zone.

The following table contains the default settings for the local computer zone.
URL action | URL policy | Aggregates
URLACTION_ACTIVEX_RUN | URLPOLICY_ALLOW | none
URLACTION_DOWNLOAD_SIGNED_ACTIVEX | URLPOLICY_ALLOW | none
URLACTION_DOWNLOAD_UNSIGNED_ACTIVEX | URLPOLICY_ALLOW | none
URLACTION_ACTIVEX_OVERRIDE_OBJECT_SAFETY | URLPOLICY_QUERY | URLACTION_ACTIVEX_OVERRIDE_DATA_SAFETY and URLACTION_ACTIVEX_OVERRIDE_SCRIPT_SAFETY
URLACTION_SCRIPT_RUN | URLPOLICY_ALLOW | none
URLACTION_SCRIPT_JAVA_USE | URLPOLICY_ALLOW | none
URLACTION_JAVA_PERMISSIONS | URLPOLICY_JAVA_MEDIUM | none
URLACTION_HTML_FONT_DOWNLOAD | URLPOLICY_ALLOW | none
URLACTION_SHELL_FILE_DOWNLOAD | URLPOLICY_ALLOW | none
URLACTION_HTML_SUBMIT_FORMS | URLPOLICY_ALLOW | URLACTION_HTML_SUBMIT_FORMS_FROM and URLACTION_HTML_SUBMIT_FORMS_TO
URLACTION_SHELL_INSTALL_DTITEMS | URLPOLICY_ALLOW | none
URLACTION_SHELL_MOVE_OR_COPY | URLPOLICY_ALLOW | none
URLACTION_SHELL_VERB | URLPOLICY_ALLOW | none
URLACTION_CREDENTIALS_USE | URLPOLICY_CREDENTIALS_SILENT_LOGON_OK | none
URLACTION_CHANNEL_SOFTDIST_PERMISSIONS | URLPOLICY_CHANNEL_SOFTDIST_PRECACHE | none
URLACTION_SHELL_WEBVIEW_VERB | URLPOLICY_ALLOW | none

Asynchronous pluggable protocols can specify how their URLs should be assigned to a security zone. The IInternetProtocolInfo::ParseUrl method using the PARSE_SECURITY_URL value should return a URL that the security manager can use to make decisions.

URL Actions and Policies

Each URL security zone has a set of URL actions with a URL policy assigned to it. The URL actions cover all operations that have security implications. A URL policy is assigned to each URL action to determine how that URL action will be handled. For example, URLACTION_JAVA_PERMISSIONS would be checked for operations related to Java applets. To force all Java applets to run out of a sandbox (that is, prevent it from doing anything that would be a security risk to the local computer), the URL policy would be set to URLPOLICY_JAVA_HIGH.

Some URL actions are an aggregate of two or more URL actions. The user interface for the default URL security zone manager would allow the user to set the aggregate value only (such as URLACTION_HTML_SUBMIT_FORMS). The browser would call the specific value (such as URLACTION_HTML_SUBMIT_FORMS_FROM) because it is reacting to that particular action. If the aggregate URL action has a URL policy set, that policy is used for the aggregate URL action and the specific URL actions it aggregated. All security zone managers must be designed to handle calls to the specific URL actions and know where to find the appropriate URL policy.

Handling URL Security Zones

There are two scenarios where you would use the URL security zone interfaces:

  • Applications that are hosting either the WebBrowser control or IE4/MSHTML and want to implement their own security manager to handle security zones.
  • Controls that are hosted by IE4/MSHTML and want to get information about a security setting.

In a few cases, an application might want to manage the default URL security zone settings by using the IInternetZoneManager interface. The changes would not be static, because the user could override any changes by setting the URL security zone options in Internet Explorer 4.0. In most cases, applications that need to control the URL security zone settings should create an application that hosts the WebBrowser control or IE4/MSHTML and implement their own security manager.

Interfaces related to URL security zones

  • IInternetHostSecurityManager
  • IInternetSecurityManager
  • IInternetSecurityMgrSite
  • IInternetZoneManager

Applications Hosting the WebBrowser Control or IE4/MSHTML

The WebBrowser control or IE4/MSHTML hosts could create a security manager (by implementing the IInternetSecurityManager interface) that handles the URL actions and policies that are important to the host. Other URL actions and policies would be passed to the default security manager so it can handle them appropriately. The IInternetSecurityMgrSite interface would be used to handle Windows®-related information from the component so that the customized security manager can handle any user interface it needed.

To create a customized security manager, the component must implement the IInternetSecurityManager interface. Any methods or URL actions that the customized security manager wants the default security manager to act on should return INET_E_DEFAULT_ACTION.

The component must also implement a ClientSite object when embedding either the WebBrowser control or IE4/MSHTML.

The following steps occur for a URL action:

  1. IE4/MSHTML uses CoCreateInstance to create an instance of the Internet Security Manager.

    Creating an instance of the security manager

  2. The Internet Security Manager calls the QueryInterface method on IE4/MSHTML to get its IServiceProvider interface. IE4/MSHTML then calls the QueryInterface method on the IOleClientSite interface to get the IServiceProvider interface.

    Finding the IServiceProvider interface

  3. IServiceProvider::QueryService is called to get an IInternetSecurityManager interface. The component then passes a pointer to its implementation of IInternetSecurityManager to the Internet Security Manager.

    Getting a reference to the custom security manager

  4. Calls from IE4/MSHTML to the IInternetSecurityManager methods are passed to the custom security manager from the default Internet Security Manager.

    Passing a call to the custom security manager

  5. If the method called returns INET_E_DEFAULT_ACTION, the default implementation of IInternetSecurityManager is used to resolve the call. Otherwise the result from the custom security manager is returned.

    Returning back to the default security manager

  6. The Internet Security Manager returns the result back to IE4/MSHTML.

    Returning back to IE4/MSHTML

Note The URL security zone API offers support only for a single, customized security manager to delegate URL actions back to the default security manager. If more than one customized security manager is implemented, the additional security managers must explicitly find and invoke the security manager above it to allow multiple delegations to operate correctly.

Components Hosted by IE4/MSHTML

Components hosted by the WebBrowser control or IE4/MSHTML might need to query the security manager for the URL policies being implemented in the URL security zone they are in. These components include script engines (JScript and VBScript), controls, Java applets, code download, and so on. For example, the code download component of Internet Explorer 4.0 needs to ask the security manager if it can download unsigned ActiveX Controls. The component calls the IInternetHostSecurityManager::ProcessUrlAction method to check what the policy is on Java applets to help make its decision.

To query for URL policies, these components use the IInternetHostSecurityManager interface. The component must also have the address of a site interface implemented by the WebBrowser control or IE4/MSHTML. The exact site interface would depend on the type of component being hosted. For example, a script engine should have the IActiveScriptSite interface implemented, while controls would implement an IOleClientSite interface. To get the address of this interface:

  1. The component calls the QueryInterface method on the site interface to get the IServiceProvider interface. The component then calls IServiceProvider::QueryService to get the IInternetHostSecurityManager interface.

    Accessing the host security manager

  2. The component calls the IInternetHostSecurityManager methods. The host security manager creates an instance of the Internet Security Manager. The host security manager then adds the URL and calls the associated method on the IInternetSecurityManager interface.

    Getting security zone information

    If a custom security manager was implemented by a host application, the default Internet Security Manager would pass the call up to the custom security manager's IInternetSecurityManager interface.

  3. The IInternetSecurityManager method would return its results to IInternetHostSecurityManager, which would then pass the results to the component.

    Returning results back from the security manager

Creating a Customized URL Security Manager

A customized URL security manager can be created for applications that host either the WebBrowser control or IE4/MSHTML by implementing the IInternetSecurityManager interface. Most of the IInternetSecurityManager methods, except IInternetSecurityManager::ProcessUrlAction, would only need to return INET_E_DEFAULT_ACTION to defer the call to the default security manager.

The following example shows an implementation of the IInternetSecurityManager::ProcessUrlAction method for a customized security manager that wants to require that data be encrypted.

HRESULT MySecurityManager::ProcessUrlAction(
    LPWSTR pwszUrl,
    DWORD dwAction,
    BYTE *pPolicy,
    DWORD cbPolicy,
    DWORD dwReserved
)
{
    DWORD dwPolicy = URLPOLICY_ENCRYPT_REQUIRED;

    if (dwAction == URLACTION_ENCRYPT_DATA)
    {
        if (cbPolicy >= sizeof (DWORD))
         {
                *(DWORD *)pPolicy = dwPolicy;
                return S_OK;
        }
        else
            return S_FALSE;
    }
    else
        return INET_E_DEFAULT_ACTION;
}

Note The Internet Explorer 4.0 default security manager cannot be replaced by a customized security manager.

Accessing the Default Managers

To access the default Internet Security Manager and Internet Zone Manager objects, the client application should use the CoCreateInstance function to create an instance of these objects.

The following sample creates an instance of both the Internet Security Manager and the Internet Zone Manager.

HRESULT hr;
IInternetSecurityManager *pSecurityMgr;
IInternetZoneManager *pZoneMgr;

hr = CoCreateInstance(CLSID_InternetSecurityManager, NULL, CLSCTX_INPROC_SERVER,
            IID_IInternetSecurityManager, (void**)&pSecurityMgr);

hr = CoCreateInstance(CLSID_InternetZoneManager, NULL, CLSCTX_INPROC_SERVER,
            IID_IInternetZoneManager, (void**)&pZoneMgr);


URL Security Zones Reference

This reference covers the APIs that are exported from the Urlmon.dll dynamic-link library. These APIs allow a developer to:

  • Create monikers that can instantiate a named object and return a pointer to one of the object's interfaces asynchronously.
  • Create an asynchronous moniker whose data is referenced by a URL (Uniform Resource Locator).
  • Implement customized URL protocols, name space handlers, and MIME filters.
  • Use functions that combine the functionality of asynchronous monikers and URL monikers.
  • Manage URL security zones.

The reference contains the interfaces, methods, functions, structures, enumerated types, security zone flags, and error codes used by these APIs.

Objects

Interfaces

Methods

Functions

Structures

Enumerated Types

URL Security Zone Flags


URL Security Zones

Monikers, URLs, security zones, and pluggable protocols provide capabilities that allow you to asynchronously bind objects, bind Uniform Resource Locators (URLs), manage URL security zones, and create custom URL protocols. This section covers the functionality exported by the Urlmon.dll dynamic-link library (DLL).

URL Security Zones Overview

URL Security Zones Reference


URL Security Zone Flags

The URL security zones use two sets of values: URL actions and URL policies. The URL actions determine what actions can be taken in a given security zone. URL policies define how a URL action will be handled.

URL Action Flags

URL Policy Flags


URL Action Flags

The following list contains the values associated with the actions that can be taken in a URL security zone.

URLACTION_ACTIVEX_CONFIRM_NOOBJECTSAFETY
User can decide whether to load and script an ActiveX control that is not safe.
URLACTION_ACTIVEX_CURR_MAX
Current maximum value of the URL action ActiveX flags.
URLACTION_ACTIVEX_MAX
Maximum value of the URL action ActiveX flags.
URLACTION_ACTIVEX_MIN
Minimum value of the URL action ActiveX flags.
URLACTION_ACTIVEX_OVERRIDE_DATA_SAFETY
Determines if ActiveX safety for untrusted data can be overridden.
URLACTION_ACTIVEX_OVERRIDE_OBJECT_SAFETY
Determines if the ActiveX control object safety is overridden or enforced for pages in the URL security zone. Object safety should be overridden only if all ActiveX Controls and scripts that might interact with them on pages in the zone can be reliably trusted not to breach security. Aggregate of URLACTION_ACTIVEX_OVERRIDE_DATA_SAFETY and URLACTION_ACTIVEX_OVERRIDE_SCRIPT_SAFETY.
URLACTION_ACTIVEX_OVERRIDE_SCRIPT_SAFETY
Determines whether ActiveX safety for scripting is overridden.
URLACTION_ACTIVEX_RUN
Manages the execution of ActiveX Controls and plug-ins from HTML pages in the zone.
URLACTION_ACTIVEX_TREATSUNTRUSTED
Not currently implemented.
URLACTION_AUTHENTICATE_CLIENT
Determines the strength of client authentication when the user's credentials are used over the network. This URL action does not have any effect if the URL action URLACTION_CREDENTIALS_USE is assigned the URL policy URLPOLICY_CREDENTIALS_ANONYMOUS_ONLY.
URLACTION_CHANNEL_SOFTDIST_MAX
Maximum value for a URL action Software Update Channel flag.
URLACTION_CHANNEL_SOFTDIST_MIN
Minimum value for a URL action Software Update Channel flag.
URLACTION_CHANNEL_SOFTDIST_PERMISSIONS
Determines the level of trust placed on Software Update Channels.
URLACTION_CREDENTIALS_USE
Determines how the user's credentials are used over the network.
URLACTION_DOWNLOAD_CURR_MAX
Maximum value for the URL action download flags.
URLACTION_DOWNLOAD_MAX
Maximum value of a URL action download flag.
URLACTION_DOWNLOAD_MIN
Mimimum value of a URL action download flag.
URLACTION_DOWNLOAD_SIGNED_ACTIVEX
Manages the download of signed ActiveX Controls from the URL zone of the HTML page that contains the control.
URLACTION_DOWNLOAD_UNSIGNED_ACTIVEX
Manages the download of unsigned ActiveX Controls from the URL zone of the HTML page that contains the control.
URLACTION_HTML_CURR_MAX
Current maximum value of the URL action HTML flags.
URLACTION_HTML_FONT_DOWNLOAD
Determines if HTML font downloads are allowed.
URLACTION_HTML_JAVA_RUN
Determines if Java applets are allowed to run.
URLACTION_HTML_MAX
Maximum value of the URL action HTML flags.
URLACTION_HTML_MIN
Minimum value of the URL action HTML flags.
URLACTION_HTML_SUBMIT_FORMS
Determines if HTML forms on pages in the URL security zone, or submitted to servers in the zone, are allowed. Aggregate of the URLACTION_HTML_SUBMIT_FORMS_FROM and URLACTION_HTML_SUBMIT_FORMS_TO flags.
URLACTION_HTML_SUBMIT_FORMS_FROM
Determines if form submissions from pages in the security zone are allowed. This flag is part of the URLACTION_HTML_SUBMIT_FORMS aggregate flag.
URLACTION_HTML_SUBMIT_FORMS_TO
Determines if form submissions to a server in the security zone are allowed. This flag is part of the URLACTION_HTML_SUBMIT_FORMS aggregate flag.
URLACTION_INFODELIVERY_CURR_MAX
Reserved for future use.
URLACTION_INFODELIVERY_MAX
Reserved for future use.
URLACTION_INFODELIVERY_MIN
Reserved for future use.
URLACTION_INFODELIVERY_NO_ADDING_CHANNELS
Reserved for future use.
URLACTION_INFODELIVERY_NO_ADDING_SUBSCRIPTIONS
Reserved for future use.
URLACTION_INFODELIVERY_NO_CHANNEL_LOGGING
Reserved for future use.
URLACTION_INFODELIVERY_NO_EDITING_CHANNELS
Reserved for future use.
URLACTION_INFODELIVERY_NO_EDITING_SUBSCRIPTIONS
Reserved for future use.
URLACTION_INFODELIVERY_NO_REMOVING_CHANNELS
Reserved for future use.
URLACTION_INFODELIVERY_NO_REMOVING_SUBSCRIPTIONS
Reserved for future use.
URLACTION_JAVA_CURR_MAX
Current maximum value of the URL action Java flags.
URLACTION_JAVA_MAX
Maximum value for URL action Java flags.
URLACTION_JAVA_MIN
Minimum value for URL action Java flags.
URLACTION_JAVA_PERMISSIONS
Determines the Java permissions for the zone.
URLACTION_NETWORK_CURR_MAX
Current maximum value for URL action network flags.
URLACTION_NETWORK_MAX
Maximum value for URL action network flags.
URLACTION_NETWORK_MIN
Minimum value for URL action network flags.
URLACTION_SCRIPT_SAFE_ACTIVEX
Determines if scripting of safe ActiveX controls is allowed or not.
URLACTION_SCRIPT_CURR_MAX
Current maximum value for a URL action script flag.
URLACTION_SCRIPT_JAVA_USE
Determines if script code on HTML pages in the URL security zone can use Java applets if the properties, methods, and events of the applet are exposed to scripts or not.
URLACTION_SCRIPT_MAX
Maximum value for a URL action script flag.
URLACTION_SCRIPT_MIN
Minimum value for a URL action script flag.
URLACTION_SCRIPT_OVERRIDE_SAFETY
Do not use ActiveX safety for objects created by scripts.
URLACTION_SCRIPT_RUN
Determines if script code on the pages in the URL security zone are run or not.
URLACTION_SHELL_CURR_MAX
Current maximum value for a URL action shell flag.
URLACTION_SHELL_FILE_DOWNLOAD
Determines if file downloads are permitted from the URL security zone of the HTML page with the link that is causing the download.
URLACTION_SHELL_INSTALL_DTITEMS
Determines if desktop items can be installed.
URLACTION_SHELL_MAX
Maximum value for a URL action shell flag.
URLACTION_SHELL_MIN
Minimum value for a URL action shell flag.
URLACTION_SHELL_MOVE_OR_COPY
Determines if move or copy operations are allowed.
URLACTION_SHELL_VERB
Determines if launching of applications and files is permitted from the URL security zone.
URLACTION_SHELL_WEBVIEW_VERB
Determines if executable files and HTML pages can be launched from WebView. There is no user interface that affects this URL action.


URL Policy Flags

The following list contains the values associated with the policies used with the URL action flags.

URLPOLICY_ALLOW
Allow the action to take place silently.
URLPOLICY_AUTHENTICATE_CHALLENGE_RESPONSE
Use challenge-response authentication schemes (such as NTLM).
URLPOLICY_AUTHENTICATE_CLEARTEXT_OK
Use basic HTTP authentication.
URLPOLICY_AUTHENTICATE_MUTUAL_ONLY
Require mutual authentication with the server.
URLPOLICY_CHANNEL_SOFTDIST_AUTOINSTALL
Allow automatic installation of software updates.
URLPOLICY_CHANNEL_SOFTDIST_PRECACHE
Cache content downloaded from Software Update Channels.
URLPOLICY_CHANNEL_SOFTDIST_PROHIBIT
Prohibit downloads from Software Update Channels.
URLPOLICY_CREDENTIALS_ANONYMOUS_ONLY
Only allow anonymous logons, so the user's credentials are not exposed.
URLPOLICY_CREDENTIALS_MUST_PROMPT_USER
Prompt user to enter a username and password.
URLPOLICY_CREDENTIALS_SILENT_LOGON_OK
Automatically log on with the user's credentials.
URLPOLICY_DISALLOW
Do not allow the action.
URLPOLICY_JAVA_CUSTOM
Not currently implemented.
URLPOLICY_JAVA_HIGH
Set high Java security. Java applets will run in a sandbox.
URLPOLICY_JAVA_LOW
Set low Java security. Java applets will be allowed to do high-capability operations, such as file I/O.
URLPOLICY_JAVA_MEDIUM
Set medium Java security. Java applets run in a sandbox with additional capabilities, such as scratch space.
URLPOLICY_JAVA_PROHIBIT
Prevent Java applets from running.
URLPOLICY_MASK_PERMISSIONS
Mask that can be used for comparisons to get the bits that have to do with permissions.
URLPOLICY_QUERY
Prompt the user to determine if an action is allowed.


Enumerated Types

This section contains the enumerated types that are exposed by Urlmon.dll.
PSUACTION
PUAF
SZM_FLAGS
URLTEMPLATE
URLZONE
URLZONEREG
ZAFLAGS


PSUACTION

typedef enum _tagPSUACTION{
    PSU_DEFAULT = 1,
    PSU_SECURITY_URL_ONLY
} PSUACTION;

This enumerated type contains the flags passed into the CoInternetGetSecurityURL function.

PSU_DEFAULT
Retrieve the security URL and return its domain.
PSU_SECURITY_URL_ONLY
Retrieve just the security URL.


PUAF

typdef enum {
    PUAF_DEFAULT = 0x0000000,
    PUAF_NOUI = 0x00000001,
    PUAF_ISFILE = 0x00000002,
    PUAF_WARN_IF_DENIED = 0x00000004,
    PUAF_FORCEUI_FOREGROUND = 0x00000008,
    PUAF_CHECK_TIFS = 0x00000010,
} PUAF;

This enumerated type contains the flags passed into IInternetSecurityManager::ProcessUrlAction.

PUAF_DEFAULT
Use the defaults associated with the action.
PUAF_NOUI
Do not display any user interfaces.
PUAF_ISFILE
Assume the URL is a file. The protocol scheme, "file://", is not required.
PUAF_WARN_IF_DENIED
Warn user that a URL action was denied.
PUAF_FORCEUI_FOREGROUND
Force the user interface to be displayed in the foreground.
PUAF_CHECK_TIFS
Obsolete. Do not use.


SZM_FLAGS

typedef enum {
    SZM_CREATE = 0x00000000,
    SZM_DELETE = 0x00000001,
} SZM_FLAGS;

This enumerated type contains the flag values used for creating and enumerating security zone mappings.

SZM_CREATE
Create a new mapping.
SZM_DELETE
Delete the mapping.


URLTEMPLATE

typdef enum tagURLTEMPLATE{
    URLTEMPLATE_CUSTOM = 0x00000,
    URLTEMPLATE_PREDEFINED_MIN = 0x10000,
    URLTEMPLATE_LOW = 0x10000,
    URLTEMPLATE_MEDIUM = 0x11000,
    URLTEMPLATE_HIGH = 0x12000,
    URLTEMPLATE_PREDEFINED_MAX = 0x20000
} URLTEMPLATE;

This enumerated type contains the security level templates.

URLTEMPLATE_CUSTOM
Current set of policies are not based on any template.
URLTEMPLATE_PREDEFINED_MIN
Minimum value of the predefined values for this enumerated type.
URLTEMPLATE_LOW
Use low security settings (all downloads okay).
URLTEMPLATE_MEDIUM
Use medium security settings (user queried before downloading potentially dangerous content).
URLTEMPLATE_HIGH
Use high security settings (no potentially dangerous content is downloaded).
URLTEMPLATE_PREDEFINED_MAX
Maximum value of the predefined values for this enumerated type.


URLZONE

typedef enum tagURLZONE {
    URLZONE_PREDEFINED_MIN = 0,
    URLZONE_LOCAL_MACHINE = 0,
    URLZONE_INTRANET,
    URLZONE_TRUSTED,
    URLZONE_INTERNET,
    URLZONE_UNTRUSTED,
    URLZONE_PREDEFINED_MAX = 999,
    URLZONE_USER_MIN = 1000,
    URLZONE_USER_MAX = 10000
} URLZONE;

This enumerated type contains all the predefined zones used by Internet Explorer.

URLZONE_PREDEFINED_MIN
Minimum value allowed for a zone value.
URLZONE_LOCAL_MACHINE
Zone used for content already on the user's local computer. This zone is not exposed by the user interface.
URLZONE_INTRANET
Zone used for content found on an intranet.
URLZONE_TRUSTED
Zone used for trusted Web sites on the Internet.
URLZONE_INTERNET
Zone used for most of the content on the Internet.
URLZONE_UNTRUSTED
Zone used for Web sites that are not trusted.
URLZONE_PREDEFINED_MAX
Maximum value allowed for a zone value.
URLZONE_USER_MIN
Minimum value allowed for a user-defined zone.
URLZONE_USER_MAX
Maximum value allowed for a user-defined zone.


URLZONEREG

typedef enum _URLZONEREG {
    URLZONEREG_DEFAULT = 0,
    URLZONEREG_HKLM,
    URLZONEREG_HKCU
} URLZONEREG;

This enumerated type contains the registry location values.

URLZONEREG_DEFAULT
Use the default registry location.
URLZONEREG_HKLM
Use HKEY_LOCAL_MACHINE.
URLZONEREG_HKCU
Use HKEY_CURRENT_USER.


ZAFLAGS

typdef enum {
    ZAFLAGS_CUSTOM_EDIT = 0x00000001,
    ZAFLAGS_ADD_SITES = 0x00000002,
    ZAFLAGS_REQUIRE_VERIFICATION = 0x00000004,
    ZAFLAGS_INCLUDE_PROXY_OVERRIDE = 0x00000008,
    ZAFLAGS_INCLUDE_INTRANET_SITES = 0x00000010,
    ZAFLAGS_NO_UI = 0x00000020,
    ZAFLAGS_SUPPORTS_VERIFICATION = 0x00000040,
    ZAFLAGS_UNC_AS_INTRANET = 0x00000080,
} ZAFLAGS;

This enumerated type contains the zone attribute flags.

ZAFLAGS_CUSTOM_EDIT
Edit a custom URL security zone.
ZAFLAGS_ADD_SITES
Add sites to a URL security zone.
ZAFLAGS_REQUIRE_VERIFICATION
Require user verification.
ZAFLAGS_INCLUDE_PROXY_OVERRIDE
Override the proxy settings.
ZAFLAGS_INCLUDE_INTRANET_SITES
URL security zone includes intranet sites.
ZAFLAGS_NO_UI
Do not display any user interfaces.
ZAFLAGS_SUPPORTS_VERIFICATION
Supports server verification.
ZAFLAGS_UNC_AS_INTRANET


CoInternetCreateSecurityManager CoInternetCreateSecurityManager *
  * Previous Topic: Functions
  * Next Topic: CoInternetCreateZoneManager

CoInternetCreateSecurityManager

Obsolete. Do not use.


CoInternetCreateZoneManager CoInternetCreateZoneManager *
  * Previous Topic: CoInternetCreateSecurityManager
  * Next Topic: CoInternetGetSecurityURL

CoInternetCreateZoneManager

Obsolete. Do not use.


CoInternetGetSecurityURL

HRESULT CoInternetGetSecurityURL(
    LPCWSTR pwzUrl,
    LPWSTR *ppwzSecUrl,
    PSUACTION psuAction,
    DWORD dwReserved
);

Retrieves the security URL for the specified URL.

pwzUrl
String value that contains the URL.
ppwzSecUrl
Address of the string value that contains the security URL.
psuAction
PSUACTION value that determines what information is returned.
dwReserved
Reserved. Must be set to zero.


Functions

This section describes the functions included in monikers, URLs, security zones, and pluggable protocols.
CoInternetCreateSecurityManager
CoInternetCreateZoneManager
CoInternetGetSecurityURL


Interfaces

This section contains the interfaces exposed by monikers, URLs, security zones, and pluggable protocols.
IInternetHostSecurityManager
IInternetSecurityManager
IInternetSecurityMgrSite
IInternetZoneManager


Methods

This section contains the methods exposed by monikers, URLs, security zones, and pluggable protocols.
IInternetHostSecurityManager::GetSecurityId
IInternetHostSecurityManager::ProcessUrlAction
IInternetHostSecurityManager::QueryCustomPolicy
IInternetSecurityManager::GetSecurityId
IInternetSecurityManager::GetSecuritySite
IInternetSecurityManager::GetZoneMappings
IInternetSecurityManager::MapUrlToZone
IInternetSecurityManager::ProcessUrlAction
IInternetSecurityManager::QueryCustomPolicy
IInternetSecurityManager::SetSecuritySite
IInternetSecurityManager::SetZoneMapping
IInternetSecurityMgrSite::EnableModeless
IInternetSecurityMgrSite::GetWindow
IInternetZoneManager::CreateZoneEnumerator
IInternetZoneManager::DestroyZoneEnumerator
IInternetZoneManager::GetZoneActionPolicy
IInternetZoneManager::GetZoneAt
IInternetZoneManager::GetZoneAttributes
IInternetZoneManager::GetZoneCustomPolicy
IInternetZoneManager::LogAction
IInternetZoneManager::PromptAction
IInternetZoneManager::SetZoneActionPolicy
IInternetZoneManager::SetZoneAttributes
IInternetZoneManager::SetZoneCustomPolicy


IInternetHostSecurityManager::GetSecurityId

HRESULT GetSecurityId(
    [out] BYTE *pbSecurityId,
    [in, out] DWORD *pcbSecurityId,
    [in] DWORD dwReserved
);

Retrieves the security identification of the host.

  • Returns S_OK if successful, or E_INVALIDARG if the buffer is set to NULL or the string passed in to pwszUrl is not a valid URL.
pbSecurityId
Address of a buffer containing the scheme, domain name, and zone of the host.
pcbSecurityId
Address of a double word value containing the size of the buffer being passed in.
dwReserved
Reserved. Must be set to zero.

If successful, pbSecurityId contains the scheme, domain, and zone information in the following format:

<scheme>:<domain>+<zone>

The pcbSecurityID parameter will contain the actual size of the data stored in the buffer.


IInternetHostSecurityManager

This interface is provided by the HTML host for components to use to manage security.
IInternetHostSecurityManager methods | Description
GetSecurityId | Retrieves the security identification of the host.
ProcessUrlAction | Retrieves the policy associated with the URL action in the given context.
QueryCustomPolicy | Retrieves the custom policy associated with the specified key in the given context.

Use SID_SInternetHostSecurityManager to request this interface when using IServiceProvider::QueryService.


IInternetHostSecurityManager::ProcessUrlAction

HRESULT ProcessUrlAction(
    [in] DWORD dwAction,
    [out] BYTE *pPolicy,
    [in] DWORD cbPolicy,
    [in] BYTE *pContext,
    [in] DWORD cbContext,
    [in] DWORD dwFlags,
    [in] DWORD dwReserved
);

Retrieves the policy associated with the URL action in the given context.

  • Returns one of the following values:
    S_OK | Successful, and the URL policy is URLPOLICY_ALLOW.
    S_FALSE | Found a valid URL policy that is not URLPOLICY_ALLOW.
    E_OUTOFMEMORY | Not enough memory to complete the operation.

    The method can also return an HRESULT derived from the Win32 error code ERROR_NOT_FOUND if the URL action could not be read from the registry.

dwAction
Double-word value that contains the action to process. Can be one of the URL Action Flags values.
pPolicy
Address of the output buffer to store the policy. Since all the URLPOLICY_* values are double-word values, the buffer should be greater than or equal to the size of a DWORD. Can contain one of the URL Policy Flags values.
cbPolicy
Double-word value that contains the size of the output buffer.
pContext
Address of a buffer that contains the context information used by the delegation routines.
cbContext
Double-word value that contains the size of the context information buffer.
dwFlags
Double-word value that contains the flags controlling this method. Can be one of the PUAF values.
dwReserved
Reserved. Must be set to zero.


IInternetHostSecurityManager::QueryCustomPolicy

HRESULT QueryCustomPolicy(
    [in] REFGUID guidKey,
    [out] BYTE **ppPolicy,
    [out] DWORD *pcbPolicy,
    [in] BYTE *pContext,
    [in] DWORD cbContext,
    [in] DWORD dwReserved
);

Retrieves the custom policy associated with the specified key in the given context.

  • Returns S_OK if successful, or E_OUTOFMEMORY if not enough memory to complete the operation.

    This method can also return the HRESULT derived from the Win32 error code ERROR_NOT_FOUND if the action could not be read from the registry.

guidKey
Globally unique identifier associated with the custom policy.
ppPolicy
Address of a pointer to the buffer to store the policy information.
pcbPolicy
Address of a double-word value that contains the policy buffer size.
pContext
Address of a buffer that contains the context information.
cbContext
Unsigned long integer value that contains the size of the context buffer.
dwReserved
Reserved. Must be set to zero.


IInternetSecurityManager::GetSecurityId

HRESULT GetSecurityId(
    [in] LPCWSTR pwszUrl,
    [out] BYTE *pbSecurityId,
    [in, out] DWORD *pcbSecurityId,
    [in] DWORD dwReserved
);

Retrieves the security identification of the given URL.

  • Returns S_OK if successful, or E_INVALIDARG if the buffer is set to NULL or the string passed in to pwszUrl is not a valid URL.
pwszUrl
String value that contains the URL.
pbSecurityId
Address of a buffer that contains the scheme, domain name, and zone associated with the URL.
pcbSecurityId
Address of a double-word value containing the size of the buffer being passed in.
dwReserved
Unsigned long integer that indicates the domain to use. If set to zero, the full domain name is used. Otherwise, a string value containing a suffix to the domain name can be specified. This larger domain name, the full domain name combined with the suffix, will be used as the security ID.

If successful, pbSecurityId contains the scheme, domain, and zone information in the following format:

<scheme>:<domain>+<zone>

And pcbSecurityID will contain the actual size of the data stored in the buffer.


IInternetSecurityManager::GetSecuritySite

HRESULT GetSecuritySite(
    [out] IInternetSecurityMgrSite **ppSite

Retrieves the security site manager.

  • Returns S_OK if successful.
ppSite
Address of a pointer to the current IInternetSecurityMgrSite interface.


IInternetSecurityManager::GetZoneMappings

HRESULT GetZoneMappings(
    [in] DWORD dwZone,
    [out] IEnumString **ppenumString,
    [in] DWORD dwFlags
);

Retrieves the complete set of patterns mapped to a zone.

  • Returns S_OK if successful or E_OUTOFMEMORY if there is not enough memory to complete the operation.
dwZone
DWORD value that contains the zone index.
ppenumString
Address of a pointer to the IEnumString interface that will enumerate the strings for the security zone mappings.
dwFlags
Reserved. Must be set to zero.


IInternetSecurityManager

This interface allows client applications to influence the security of the browser components.
IInternetSecurityManager methods | Description
GetSecurityId | Retrieves the domain of the given URL.
GetSecuritySite | Retrieves the security site manager.
GetZoneMappings | Retrieves the zone mappings.
MapUrlToZone | Retrieves the zone index for the given URL.
ProcessUrlAction | Determines the policy for the specified action and displays a user interface if the policy indicates that the user should be queried.
QueryCustomPolicy | Retrieves the custom policy associated with the URL and specified key in the given context.
SetSecuritySite | Sets the security site manager.
SetZoneMapping | Maps a pattern into the specified zone.

Use SID_SInternetSecurityManager to request this interface when using IServiceProvider::QueryService.


IInternetSecurityManager::MapUrlToZone

HRESULT MapUrlToZone(
    [in] LPCWSTR pwszUrl,
    [out] DWORD *pdwZone,
    [in] DWORD dwFlags
);

Retrieves the zone index for the given URL.

  • Returns E_INVALIDARG if pdwZone is set to NULL, or S_OK otherwise.
pwszUrl
String value that contains the URL.
pdwZone
Address of a double-word variable that contains the zone index.
dwFlags
Double-word value that contains flags that control this method. If the value is set to ISECMGR_PREPEND_FILE, IInternetSecurityManager::MapUrlToZone adds the "file:" to the beginning of the URL stored in pwszUrl.


IInternetSecurityManager::ProcessUrlAction

HRESULT ProcessUrlAction(
    [in] LPCWSTR pwszUrl,
    [in] DWORD dwAction,
    [out] BYTE *pPolicy
    [in] DWORD cbPolicy,
    [in] DWORD dwReserved
);

Determines the policy for the specified action, and displays a user interface if the policy indicates that the user should be queried.

  • Returns one of the following values:
    S_OK | Successful, and the URL policy is URLPOLICY_ALLOW.
    S_FALSE | Found a valid URL policy that is not URLPOLICY_ALLOW.
    E_OUTOFMEMORY | Not enough memory to complete the operation.

    The method might also return an HRESULT derived from the Win32 error code ERROR_NOT_FOUND if the URL action could not be read from the registry.

pwszUrl
String value that contains the URL.
dwAction
Double-word value that contains the action to be performed. Can be one of the URL Action Flags values.
pPolicy
Address of the buffer where the policy for the given URL and action will be stored. Can contain one of the URL Policy Flags values.
cbPolicy
Double-word value that contains the size of the buffer.
dwReserved
Reserved. Must be set to zero.


IInternetSecurityManager::QueryCustomPolicy

HRESULT QueryCustomPolicy(
    [in] LPCWSTR pwszUrl,
    [in] REFGUID guidKey,
    [out] BYTE **ppPolicy,
    [out] DWORD *pcbPolicy,
    [in] BYTE *pContext
    [in] DWORD cbContext,
    [in] DWORD dwReserved
);

Retrieves the custom policy associated with the URL and specified key in the given context.

  • Returns S_OK if successful, or E_OUTOFMEMORY if there is not enough memory to complete the operation.

    This method can also return the HRESULT derived from the Win32 error code ERROR_NOT_FOUND if the action could not be read from the registry.

pwszUrl
String value containing the URL.
guidKey
Globally unique identifier associated with the custom policy.
ppPolicy
Address of a pointer to the buffer to store the policy information.
pcbPolicy
Address of a double-word value that contains the policy buffer size.
pContext
Address of a buffer that contains the context information.
cbContext
Unsigned long integer value that contains the size of the context buffer.
dwReserved
Reserved. Must be set to zero.


IInternetSecurityManager::SetSecuritySite

HRESULT SetSecuritySite (
    [in, unique] IInternetSecurityMgrSite *pSite

Sets the security site manager.

  • Returns S_OK if successful.
pSite
Address of the IInternetSecurityMgrSite interface to set.


IInternetSecurityManager::SetZoneMapping

HRESULT SetZoneMapping(
    [in] DWORD dwZone,
    [in] LPCWSTR lpszPattern,
    [in] DWORD dwFlags
);

Maps a pattern into the specified zone.

  • Returns one of the following values:
    S_OK | Success.
    E_ACCESSDENIED | Attempting to enter a non-SSL site into a zone that requires server verification.
    URL_E_INVALID_SCHEME | Either an improper scheme or no scheme is specified in the URL.
    E_FAIL | Mapping already exists.

    The method can also return the HRESULT derived from the Win32 error code ERROR_FILE_EXISTS if the URL already exists in another zone.

dwZone
Double-word value that contains the zone index.
lpszPattern
String value that contains the URL pattern with a limited number of wildcards.
dwFlags
Double-word value that indicates whether the mappings should be added or deleted. Can be one of the SZM_FLAGS values.


IInternetSecurityMgrSite::EnableModeless

HRESULT EnableModeless(
    [in] BOOL fEnable
);

Enables the use of modeless pop-up windows.

  • Returns S_OK if successful, or E_FAIL otherwise.
fEnable
Boolean value that sets whether modeless pop-up windows are used. TRUE enables modeless pop-up windows; FALSE disables them.


IInternetSecurityMgrSite::GetWindow

HRESULT GetWindow(
    [out] HWND *phwnd
);

Retrieves the parent window handle.

  • Returns S_OK if successful, or E_FAIL otherwise.
phwnd
Address of the parent window handle.


IInternetSecurityMgrSite

This interface is provided by an HTML host to be used by components to manage the user interface of the security manager.
IInternetSecurityMgrSite methods | Description
EnableModeless | Enables or disables the use of modeless pop-up windows.
GetWindow | Retrieves the handle to the parent window.


IInternetZoneManager::CreateZoneEnumerator

HRESULT CreateZoneEnumerator(
    [out] DWORD *pdwEnum,
    [out] DWORD *pdwCount,
    [in] DWORD dwFlags
);

Creates a zone enumerator.

pdwEnum
Address of the double-word value that serves as the zone enumerator.
pdwCount
Address of a double-word value that contains the number of zones enumerated.
dwFlags
Reserved. Must be set to zero.


IInternetZoneManager::DestroyZoneEnumerator

HRESULT DestroyZoneEnumerator(
    [in] DWORD dwEnum
);

Destroys a zone enumerator.

dwEnum
Double-word enumerator that was created by IInternetZoneManager::CreateZoneEnumerator.


IInternetZoneManager::GetZoneActionPolicy

HRESULT GetZoneActionPolicy(
    [in] DWORD dwZone,
    [in] DWORD dwAction,
    [out] BYTE *pPolicy,
    [in] DWORD cbPolicy,
    [in] URLZONEREG urlZoneReg
);

Retrieves the policy associated with the given URL action.

dwZone
Double-word value of the zone.
dwAction
Double-word value of the action.
pPolicy
Address of the buffer to store the policy information.
cbPolicy
Double-word value containing the size of the buffer.
urlZoneReg
URLZONEREG value that indicates the section in the registry to search.


IInternetZoneManager::GetZoneAt

HRESULT GetZoneAt(
    [in] DWORD dwEnum,
    [in] DWORD dwIndex,
    [out] DWORD *pdwZone
);

Retrieves the zone associated with the specified index on the given enumerator.

dwEnum
Double-word value that contains the enumerator created by IInternetZoneManager::CreateZoneEnumerator.
dwIndex
Double-word value that contains the index of the zone in the enumerator.
pdwZone
Address of a double-word value that contains the zone.

The index set in dwIndex must be greater than or equal to zero and less than or equal to the value pointed to by pdwCount in the call to IInternetZoneManager::CreateZoneEnumerator.


IInternetZoneManager::GetZoneAttributes

HRESULT GetZoneAttributes(
    [in] DWORD dwZone,
    [in, out, unique] ZONEATTRIBUTES *pZoneAttributes
);

Retrieves the zone attributes.

dwZone
Double-word value that contains the zone index.
pZoneAttributes
Address of a ZONEATTRIBUTES variable to store the zone's attributes.


IInternetZoneManager::GetZoneCustomPolicy

HRESULT GetZoneCustomPolicy(
    [in] DWORD dwZone,
    [in] REFGUID guidKey,
    [out] BYTE **ppPolicy,
    [out] DWORD *pcbPolicy,
    [in] URLZONEREG urlZoneReg
);

Retrieves the named custom policy associated with the zone.

  • Returns S_OK if the key is found and the buffer is allocated.
dwZone
Double-word value that contains the zone.
guidKey
Globally unique identifier that indicates the key to look up.
ppPolicy
Address of a buffer to contain the policy information.
pcbPolicy
Address of a double-word value that contains the size of the buffer.
urlZoneReg
URLZONEREG value that determines how the registry is accessed.


IInternetZoneManager

This interface is used by a host to control the security zone infrastructure.
IInternetZoneManager methods | Description
CreateZoneEnumerator | Creates a zone enumerator.
DestroyZoneEnumerator | Destroys the zone enumerator.
GetZoneActionPolicy | Retrieves the policy associated with the given URL action.
GetZoneAt | Retrieves the zone associated with the specified index and enumerator.
GetZoneAttributes | Retrieves the attributes of the specified zone.
GetZoneCustomPolicy | Retrieves the custom policies associated with the zone.
LogAction | Not currently implemented.
PromptAction | Not currently implemented.
SetZoneActionPolicy | Sets the policy associated with the given action on the specified zone.
SetZoneAttributes | Sets the attributes of the specified zone.
SetZoneCustomPolicy | Sets the custom policy on the specified zone.


IInternetZoneManager::LogAction IInternetZoneManager::LogAction *
  * Previous Topic: IInternetZoneManager::GetZoneCustomPolicy
  * Next Topic: IInternetZoneManager::PromptAction

IInternetZoneManager::LogAction

Not currently implemented.


IInternetZoneManager::PromptAction

HRESULT PromptAction(
    [in] DWORD dwAction,
    [in] HWND hwndParent,
    [in] LPCWSTR pwszUrl,
    [in] LPCWSTR pwszText,
    [in] DWORD dwPromptFlags
);
);

Not currently implemented.


IInternetZoneManager::SetZoneActionPolicy

HRESULT SetZoneActionPolicy(
    [in] DWORD dwZone,
    [in] DWORD dwAction,
    [in] BYTE *pPolicy,
    [in] DWORD cbPolicy,
    [in] URLZONEREG urlZoneReg
);

Sets the action policy associated with a zone.

  • Returns S_OK if the action is valid.
dwZone
Double-word value that contains the zone index.
dwAction
Double-word value that contains the index number of the action.
pPolicy
Address of the buffer that contains the policy information.
cbPolicy
Double-word value that contains the size of the buffer.
urlZoneReg
URLZONEREG value that indicates how the registry is accessed.


IInternetZoneManager::SetZoneAttributes

HRESULT SetZoneAttributes(
    [in] DWORD dwZone,
    [in] ZONEATTRIBUTES *pZoneAttributes
);

Sets the zone attributes.

  • Returns S_OK if successful.
dwZone
Double-word value that contains the zone index.
pZoneAttributes
Address of a ZONEATTRIBUTES value that contains the zone attributes to be set.


IInternetZoneManager::SetZoneCustomPolicy

HRESULT SetZoneCustomPolicy(
    [in] DWORD dwZone,
    [in] REFGUID guidKey,
    [out] BYTE *pPolicy,
    [in] DWORD cbPolicy,
    [in] URLZONEREG urlZoneReg
);

Sets a named custom policy associated with a zone.

  • Returns S_OK if successful.
dwZone
Double-word value that contains the zone index.
guidKey
Globally unique identifier that contains the key.
pPolicy
Address of the buffer that contains the policy to be set.
cbPolicy
Double-word value that contains the size of the buffer.
urlZoneReg
URLZONEREG value that indicates where the information will be set in the registry.


Internet Security Manager

CLSID_InternetSecurityManager

The Internet Security Manager is an object that manages security.

Interfaces
IInternetSecurityManager


Internet Zone Manager

CLSID_InternetZoneManager

The Internet Zone Manager is an object that manages zones.

Interfaces
IInternetZoneManager


Objects

This section contains the objects exposed by monikers, URLs, security zones, and pluggable protocols.
Internet Security Manager
Internet Zone Manager


Structures Structures *
  * Previous Topic: CoInternetGetSecurityURL
  * Next Topic: ZONEATTRIBUTES

Structures

This section contains the structures that are exposed by Urlmon.dll.
ZONEATTRIBUTES


ZONEATTRIBUTES

typedef struct _ZONEATTRIBUTES {
    ULONG cbSize;
    WCHAR szDisplayName[MAX_PATH];
    WCHAR szDescription[MAX_ZONE_DESCRIPTION];
    WCHAR szIconPath[MAX_PATH];
    DWORD dwTemplateMinLevel;
    DWORD dwTemplateRecommended;
    DWORD dwTemplateCurrentLevel;
    DWORD dwFlags;
} ZONEATTRIBUTES, *LPZONEATTRIBUTES;

Contains the attributes of a particular zone.

cbSize
Unsigned long integer value that contains the size of the structure.
szDisplayName
Array of wide characters that contains the display name of the zone.
szDescription
Array of wide characters that contains the description of the zone.
szIconPath
Array of wide characters that contains the path to the icon associated with this zone.
dwTemplateMinLevel
Double-word value that contains the minimum template level.
dwTemplateRecommended
Double-word value that contains the recommended template level.
dwTemplateCurrentLevel
Double-word value that contains the current template level.
dwFlags
Double-word value that contains the flags associated with the specified zone. Can be one of the ZAFLAGS values.


Using the Microsoft Agent Character Editor

ActiveX™ Technology for Interactive Software Agents

August 1997
Microsoft Corporation

Note: This document is provided for informational purposes only and Microsoft makes no warranties, either expressed or implied, in this document. The entire risk of the use or the results of this document remains with the user.

Information in this document is subject to change without notice. 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.

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. Microsoft, MS, MS-DOS, Windows, Windows NT, and the Windows logo are either registered trademarks or trademarks of Microsoft Corporation in the U.S. and/or other countries. Other product and company names mentioned herein may be the trademarks of their respective owners.

Contents

Introduction

Installing the Agent Character Editor

Starting the Agent Character Editor

Defining a New Character

Command Reference

Toolbar buttons

Introduction

The Microsoft® Agent Character Editor enables you to compile character animations for use with Microsoft Agent. You can define animations by importing Windows bitmap images, setting their duration, and optionally including branching, sound effects, and speaking overlays. For information about designing a character's animation, see Designing Characters for Microsoft Agent.

With the Agent Character Editor you can define the character's name and description as well as output options, including text-to-speech (TTS), synthesized voice output, pop-up menu support, and the character's word balloon design.

Back to contents

Installing the Agent Character Editor

To install the Microsoft Agent Character Editor, open its self-extracting cabinet file. This will automatically install the appropriate files on your system. If you are downloading the Agent Character Editor from the Microsoft Web site, the downloading software gives you the option to save the file and open it or open it automatically as soon as the download completes.

If you plan to use a TTS engine for your character's output, you need to install that engine before you begin creating your character. A special version of the Lernout & Hauspie® TruVoice Text-To-Speech Engine (American English language) can be downloaded from the Microsoft Agent Web site. You can use and distribute this engine as part of a Microsoft Agent application, subject to the conditions described in the End User Licensing Agreement that displays when you install the engine. If you plan to use another TTS engine, contact that vendor to confirm their support for Microsoft Agent and for information on their licensing provisions for use and redistribution.

Back to contents

Starting the Agent Character Editor

To run the Agent Character Editor, choose the Agent Character Editor option from the Windows Taskbar's Start menu, or double-click the Microsoft Agent Character Editor icon on your desktop. The Editor's window will open, displaying its menus, a toolbar with frequently used commands, a tree listing the components that make up a character's definition, and a set of tabbed pages that change based on your selection in the component tree.

Figure 1. Microsoft Agent Character Editor window

To access fields in the window from the keyboard, you can use the tab key and shift+tab to navigate between controls, or use the access key (altunderlined letter) to move to a specific control. Once the Editor completes starting up, you can begin creating a new character definition or load an existing character definition.

The status bar displays information about commands or toolbar buttons when you move the pointer over them. It also displays summary information about your character animation data and status information when you build a character.

Back to contents

Defining a New Character

To define a new character, run the Agent Character Editor. If you have an existing character file loaded, choose the New command from the File menu or the New button on the toolbar. This action selects the Character icon in the tree and displays its property pages on the right side of the window. The following sections describe how to set your character's properties and how to create animations for the character.

Setting Your Character's Properties

To begin defining a character, provide the character's name by entering it in the Name text box (32 characters maximum). Because Microsoft Agent uses the name to allow users to access the character, specify a user-friendly name. Supply a name that can be pronounced using conventional spelling, or you may disable speech input for the character. You can also specify a short optional description (256 characters) for your character in the Description text box. The server exposes what you enter in the Description text box to client applications.

For your character's spoken output, Microsoft Agent provides the choice of a synthesized, text-to-speech (TTS) voice or a voice that uses recorded sound files. If you want to use a synthesized voice, check the Use Synthesized Speech For Voice Output option. This will add a Voice page for selecting the characteristics of the voice. Choose the Voice page and use the controls on it page to select a voice, speed, and pitch of any compatible TTS engines you have installed. The range of the voice parameters you can select depends on TTS engines. If you have not yet installed a TTS engine, the Voice ID list will be empty. You must have a TTS engine installed before you define your character's voice settings in the Agent Character Editor.

If you plan to use a TTS engine for your character's output, you must also install that engine on the user's system. For more information on how to install the Lernout & Hauspie® TruVoice engine on a user's system from a Web script, see Programming the Microsoft Agent Control. If you are using another TTS engine, check with the vendor for appropriate installation information. If you select a voice based on a particular TTS engine, but the user has a different TTS engine installed, the server attempts to fit the voice based on the characteristics you defined in the Agent Character Editor.

If you plan to use recorded sound files (.WAV files) for your character's spoken output, do not check the Use Synthesized Speech For Voice Output option. Instead, you will need to record the spoken output audio files separately and load them from your application code.

The Use Word Balloon on the character's Properties page enables you to determine whether you want to support this feature for your character. Once defined, it cannot be changed through the Microsoft Agent programming interface.

When the Use Word Balloon option is checked, you can access the Word Balloon page. The options on the Word Balloon page enable you to change the default characteristics of your word balloon. The Characters Per Line setting enables you to define the width of the balloon based on the average number of characters per line. You can set the default height based on either a fixed number of lines you want to display at once or automatically sized to the text you supply in the Speak method. You can also set whether the balloon automatically hides after a Speak method is completed and whether the balloon automatically displays or "paces" words to the character's speech output speed setting.

The Word Balloon page also enables you to set the default font for the character's word balloon and the balloon's display colors. However, be aware that users can override your word balloon font settings using the Microsoft Agent Property Sheet.

Each character requires a unique identifier (GUID). The server uses the identifier to differentiate characters. When you create a new character, the Editor automatically creates a new identifier for your character. You need to change a character's identifier only if you copied the character definition file of another character or if you intentionally want to differentiate a character from a former version. To change a character's identifier, click the New GUID button and the Editor will generate a new identifier.

Creating Animations

To begin creating animations for your character, select the Animations icon in the tree. This displays the Properties page with the default settings for all animations. You can alter the frame size, the default frame duration, and color palette settings on the Properties page. The animation frame height and width must remain constant throughout the entire character definition (that is, for all of that character's animations). Although you can change the frame size from its default setting (128 x 128 pixels), images displayed in the Editor will be scaled to fit default display size. If you change the default frame setting, you can display the frame's full, non-scaled size by choosing Open Frame Window from the Edit menu.

By default, the Editor uses the first bitmap image you load to set your character's default color palette, and sets the color in the 11th palette position as your transparency color. However, you can change these settings using the buttons in the Palette Information group. Your character's color palette must not remap the standard system colors. The Editor will automatically reserve the system's color palette when displaying images. In addition, make sure all your animation images use the same color palette and transparency color. If they do not, you may see color remapping of your images when you load them into the Editor.

Once you have determined your global animation settings, you can begin creating animations. To create a new animation, choose New Animation from the Edit menu or the New Animation button on the toolbar. This adds a new animation icon in the tree under the Animations icon and assigns the new icon a default name. You can rename your animation by typing in the Animation Name field. Note that animation names within a character definition must be unique. Also, avoid using characters in the name that are not valid characters for filenames.

Every animation is composed of frames. To create a new frame for your animation, choose New Frame from either the Edit menu or the toolbar. This adds a new frame icon to the tree under your animation icon, and displays three tabbed pages. The General page includes controls that enable you to load and adjust an image for your frame. It also includes a display area for the frame's appearance.

Figure 2: The Frame Image display and controls

A frame can contain one or more images. To define an image for a frame, click the Add Image File button just above the Images list box. The Select Image Files dialog box displays, which allows you to select a bitmap image file.

Figure 3. The Select Image Files dialog box

Select the file you want to load, choose Open, and the image appears in the frame display on the General page. The Editor accepts only images that are stored as 1-bit (monochrome), 4-bit, or 8-bit Windows bitmap format, or as .GIF format.

You can use the four arrow buttons beneath the image in the Position box to adjust the image's appearance within the frame. If the image is larger than your frame's size, only the portion of the image that appears within the frame will display. If you increase the frame size, the image may be scaled to fit within the display area of the Editor.

You can also display a frame by choosing Open Frame Window from the Edit menu. This displays the current frame in a separate window without scaling the images loaded into the frame. This window's initial size is based on your frame's height and width settings. You can resize it smaller, but not larger. The Frame Window reflects the changes you make using the controls in the Editor and also allows you view the frame while viewing its other property pages.

Figure 4. Image Position controls

You can compose a frame from multiple images. Each time you select the Add Image button and choose another image, the image gets added to the list and to the image display area. You can also add multiple images by selecting more than one file. Press shift or ctrl while you click in the Select Image Files dialog box, and then choose Open. The Move Up and Move Down buttons above the Images list box move a selected image in the display order (z-order) for the frame. You can also move images by dragging them within the list. Selecting an image in the list and clicking the Delete button removes an image. To change an image you have loaded to another image file, you can click the filename to edit it directly or use the Ellipsis (…) button to bring up the Select Image Files dialog box and select a different file.

Figure 5. The Ellipsis button

You can use the Duration text box to set the duration for the frame; that is, how long the frame will be displayed. If a frame has no image and zero duration, the frame will not be displayed when the animation plays.

You can also specify a sound effect file to play when the frame is displayed. If you plan to load the character from a Web server, you may want to compress the sound effect file to minimize load time. You can then specify the compressed sound file in the Agent Character Editor. In addition, avoid using a sound effect with a duration longer than the duration of your animation and especially avoid a sound effect that loops, because the Microsoft Agent animation services do not send an animation complete event until the sound completes. Also avoid specifying a sound effect for any animation you assign to the Listening or Hearing states, because this interferes with speech input. Finally, while you can include more than one sound effect in an animation, avoid placing them so they overlap, because this may affect the timing of the animation. Also, keep in mind that sound effects may play at different rates based on the user's hardware.

To add frames to your animation, choose the New Frame command again and follow the same procedure. As an option, you can also load multiple images and automatically generate new frames for them. To use this feature, choose New Frames From Images from the Edit menu. The frames will be created in alphabetic order based on the image filenames. When you are finished defining all frames for your animation, you can choose the New Animation command again to begin a new animation.

There are other ways to add frames to animations and move frames within or between animations. You can select another frame (from the same or another animation) and choose Cut or Copy, then select the animation or a frame in that animation and choose Paste. You can also drag a frame from one animation to another. If you drag within an animation, the action moves the frame. If you drag to another animation, it copies the frame. Dragging to a preceding frame in the same animation inserts the frame before the frame to which you drag. Dragging to a following frame places it after the frame to which you drag. If you drag a frame using the right mouse button, releasing the button displays a pop-up menu with your transfer choices.

You can also create an animation by copying an existing animation (select the animation and choose Copy), and selecting the Animations icon or another animation icon and choosing Paste. The Editor automatically creates a new name for the animation, although you can change the name.

Branching

When you create a frame, you can also define which frame plays next. By default, the next frame played in the animation sequence is always the next frame in the z-order. However, by choosing the Branching page, you can set the probability for up to three other frames that the server may play. Enter the probability percentage and the target frame number in the appropriate fields. You can specify branching even for frames that don't have images and have their duration set to zero. This enables you to branch without first displaying a particular image.

Figure 6. The Branching page

You can use the branching feature to create animations that will loop indefinitely. However, note that when a looping animation plays, other animations in the character's queue will not play until an event--such as a user pressing the push-to-talk key or the client application calling the Stop method--halts the looping animation. Therefore, carefully consider the context in which the animation will be used before creating a looping animation.

Previewing an Animation

You can preview your animation in the Agent Character Editor by choosing the Preview command on the Edit menu or the Preview button on the toolbar. This plays your animation, including any branches and sound effects, starting from the current selected frame. It resets to the current selected frame when the animation completes. To play your entire animation, go to the tree view, select the animation's icon or first frame of the animation, and choose the Preview command. The Editor animates your frames on the General page. To stop the preview before it ends, choose the Stop Preview command. The Preview command automatically changes to Stop Preview while the preview plays.

Assigning Speaking Overlays

You can define a character so that it speaks during the last frame of its animation. On this frame, choose the Overlay page. This page enables you to load and assign mouth image files to the standard mouth positions supported by Microsoft Agent. Click the Add Image button and select the image from the dialog box. You can also select multiple images, and the Editor will load and assign the images starting with the mouth position you selected. Click the Move Up and Move Down buttons or drag an entry to change an image assignment in the list. Click the Delete button to remove an image. You can also edit the pathname of an assigned file by clicking its entry in the list and retyping its filename, or by choosing the Ellipsis (…) button to display the Select Image Files dialog box.

Figure 7. The Overlay page image controls

Assigning a Return Animation

To create a smooth transition from one animation to the next, design your animation sequences to begin and end with a neutral image. For more information, see Designing Characters for Microsoft Agent. However, this does not mean that every animation must end at the neutral position. You can animate a character through a sequence of frames, have it speak during the last frame, and create a separate, complementary animation that returns the character to the neutral position. This complementary animation is called a Return animation. Define a Return animation like any other animation. To assign the Return animation, select an animation in the tree, and select the Return animation you created from the Return Animation drop-down list on the Properties page.

Creating and assigning a Return animation has an added benefit: When the server gets a request to play another animation, it will attempt to play the Return animation for the last animation it played, if a Return animation is assigned. This ensures a smooth transition. If an animation begins and ends at the neutral position, you don't need to define a Return animation. Similarly, if you intend to handle transitions from one animation to another yourself, you may not need to assign a Return animation.

Assigning Animations to States

The Microsoft Agent animation services automatically play animations when the hosting client application uses certain methods. For example, when an application calls the MoveTo and GestureAt methods, the server automatically determines where the character is displayed and plays an appropriate animation. Similarly, Microsoft Agent automatically plays Idle animations when the user has not interacted with the character for several seconds. These conditions when the server automatically plays animations on an application's behalf are called states. However, for the server to know which animation to play, you must assign animations to these states.

To define a state, create the appropriate animation, expand the States entry in the tree view of the Editor window, and select the State icon. The list of animations you have created appear in a list box on the right side of the window. Check the animation you want to assign to this state. Note that you can assign more than one animation to the same state. This allows the server to randomly select different animations for the state. Assigning an animation to a state does not prevent an animation from playing that animation directly.

You can also assign an animation to a state by selecting the animation's entry in the tree. The Assign To State list box on the Properties page lists the states. Select the check box of the state to which you're assigning the animation.

Saving Your Character Definition

You can save your character's definition file by choosing the Save command on the File menu or the Save Character Definition button on the toolbar. If you want to save the character definition file with a new name, choose the Save As command on the File menu. The Editor saves a character's editable definition as an Agent Character Definition (.ACD) file. You can also edit this self-documenting text file format with most text editors and word processing applications.

Printing Your Character Definition

To print your character's definition, choose the Print command on the File menu or the Print button on the toolbar. To set the properties for your printed output, choose the Page Setup command and choose your settings before selecting the Print command.

Building A Character

When you are done creating your animations, the character and images must be compiled into a special format that Microsoft Agent uses to load this data. To build a character, select the Build Character command on the File menu or from the toolbar. If you have unsaved edits in your character definition file, the Editor saves the definition file before displaying the Build Character dialog box.

Figure 7. The Build Character dialog box

The Agent Character Editor will automatically propose a filename based on your character definition filename. The Build Character dialog box also includes a drop-down list so you can choose between building the character as a single storage file (.ACS) or as multiple files. If you choose the latter, the Editor builds an .ACF file that includes character's data and an .AAF file for each animation you created. If you plan to install and access a character stored on the same machine as your client application, you would typically choose the single structured file format. This format provides easy and efficient installation of and access to the character. However, if the character will be accessed from a Web server using the HTTP protocol, build your character using the .ACF (individual) file format. This latter file structure allows a Web page script to load individual animation files, storing the data in the user's browser file cache. It provides more efficient access over the Web because animation data can be downloaded as needed rather than requiring the user to wait for the entire set of animations to download at one time. In addition, because the character's data is stored in the browser cache, the file space can be automatically reclaimed.

Although you can also download character data (either as a single structured file or multiple files) from a Web server and install elsewhere on a user's machine, such a method requires security provisions for downloading and installation. As a result, Microsoft Agent does not include support for downloadable installation of a character except to the browser's cache. However, you can still support this scenario by creating your own installation control and distribute it following appropriate security conventions. For more information, see the Microsoft Internet Client Software Development Kit.

The Compress option enables you to set whether the character data is compressed. Typically, you will want to set this option to compact your character data, although building a character with the compacted data takes longer.

Once you build a character, subsequent builds will be faster if you build the character to the same directory location. The character editor automatically verifies and copies those files that have not changed, and recompiles any data that has been edited.

Editing an Existing Character

To edit an existing character, choose Open on the File menu, select the character's definition file (.ACD) in the resulting dialog box, and choose Open. The file will load into the Editor. Note that you cannot load compiled character files (.ACS, .ACF, or .AAF) with the Editor.

Because the character's definition file (.ACD) is a text file, you can also edit a character's definition by opening the file with a text editor or word processing program. However, when completing your changes, make sureto save the file in its original format before loading it into the character editor for compilation.

Storing Additional Data in Your Character Definition

You can also store your own data as part of your character. You can use this capability to include special information about your character or other data. Once compiled with the character editor, this information can be accessed at run time when the character is loaded by using the ExtraData property.

To define your own data as part of the character's definition, you must load the character's definition file (.ACD) into a text editor. Then in the DefineCharacter section of the file (between the DefineCharacter and EndCharacter tags), add an entry using the following syntax:

ExtraData = "string"

The string you supply should appear between two double-quotes and can include any characters other than double quotes, provided that the programming language you use to read the data at run time supports them. You can only include a single ExtraData entry, but the string you supply with it can be of any length.

To compile this data with your character, save the file in the original text format and load the character definition file into the character editor. Then build the character following the normal conventions. You can access the data at run time using the ExtraData property.

Back to contents

Command Reference

The File Menu

New

Resets the Agent Character Editor for creating a new character definition. If an existing character is loaded and has unsaved edits, the Editor displays a message to determine whether to save or discard unsaved changes.

Open

Displays the Open File dialog box, enabling you to open an existing character definition file for editing. If an existing character is loaded and has unsaved edits to a file, the Editor displays a message to determine whether to save or discard unsaved changes.

Save

Saves the character definition. If the character definition does not exist (has not been named), the Editor displays the Save As dialog box for input of the filename.

Save As

Displays the Save As dialog box, enabling you to enter a new name for the character definition file.

Print

Displays the Print dialog box, enabling you to choose a printing option and to print the character definition file.

Build Character

Displays the Build Character dialog box, which includes options for defining how to build a character's data and animation files for use with Microsoft Agent.

Page Setup

Displays the Page Setup dialog box that enables you to set the printing options for the character definition file.

Most Recently Open Files

Keeps track of the recent character definition files you opened. Choosing a file automatically opens that file for editing. If an existing character is loaded and has unsaved edits to a file, the Editor displays a message to determine whether to save or discard unsaved changes.

Exit

Quits the Agent Character Editor. If an existing character is loaded and has unsaved edits to a file, the Editor displays a message to determine whether to save or discard unsaved changes.

The Edit Menu

Undo

Removes a change made in the Editor.

Redo

Reverses an undo action in the Editor.

Cut

Removes the selected item from the Editor and places it on the Windows Clipboard.

Copy

Copies the selected item in the Editor to the Windows Clipboard.

Paste

Copies data from the current Windows Clipboard to the selected location.

Delete

Removes the selected item from the Editor.

New Animation

Creates a new animation object in the Editor.

New Frame

Creates a new frame for an animation.

New Frames from Files

Displays the Select Image Files dialog box and creates frames using the selected files.

Preview | Stop Preview

Plays an animation, starting from its selected frame.

Open Frame Window

Displays the current frame and its images in a separate window without scaling the images loaded into the frame.

The Help Menu

Help Topics

Displays the Help Topics dialog box, enabling you to select a Editor help topic.

About Microsoft Editor

Displays a dialog box with copyright and version information for the Editor.

Back to contents

Toolbar buttons

[CHA3154K 951 bytes ]

New

Resets the Editor for creating a new character definition. If an existing character is loaded and has unsaved edits to a file(s), the Editor displays a message to determine whether to save or discard unsaved changes.

Open

Displays the Open File dialog box, enabling you to open an existing character definition file for editing. If an existing character is loaded and has unsaved edits to a file(s), the Editor displays a message to determine whether to save or discard unsaved changes.

Save

Saves the character definition. If the character definition does not exist (has not been named), the Editor displays the Save As dialog box for input of the filename.

Print

Prints the current character definition file open in the Editor.

Cut

Removes the selected item in the Editor and places it on the Windows Clipboard.

Copy

Copies the selected item in the Editor to the Windows Clipboard.

Paste

Copies data from the current Windows Clipboard to the selected location.

Delete

Removes the selected item from the Editor.

Undo

Removes a change made in the Editor.

Redo

Reverses an undo action in the Editor.

New Animation

Creates a new animation object in the Editor.

New Frame

Creates a new frame for an animation.

Preview

Plays an animation, starting from its selected frame.

Stop Preview

Stops playing the preview of an animation.

Add Image File

Displays the Select Image File dialog box. Selected images are added to the list.

Move Up

Moves an image up in the ordered (z-ordered) list. In a frame's images list, this moves the image up in the visual z-order.

Move Down

Moves an image down in the ordered (z-ordered) list. In a frame's images list, this moves the image down in the visual z-order.

Back to contents


Microsoft Agent

Microsoft Agent Microsoft Agent *

ActiveX™ Technology for Interactive Software Agents

Microsoft® Agent supports the presentation of software agents as interactive personalities within the Microsoft Windows® interface. Microsoft® Agent comes with a cast of three characters: Merlin, Genie, and Robby; shown above. Developers can use these characters as interactive assistants to introduce, guide, entertain, or otherwise enhance their Web pages or applications. Microsoft® Agent also includes tools for defining custom characters.

  • Component Installation
  • Documentation
  • Frequently Asked Questions
  • Character Data
  • Samples
  • Support
  • Licensing and Redistribution


Microsoft Agent Component Installation

Microsoft Agent Microsoft Agent *

Component Installation

Instructions

If you are reading this documentation from the Internet Client SDK Web site, the links below will not work. You need to download Microsoft Agent before you can install Microsoft Agent components. Go to the Component Library section of the Internet Client SDK download page to download Microsoft Agent.

If you have already installed Microsoft Agent from the Internet Client SDK CD or download site, and are reading this page from your local disk, simply click on any link below to install the corresponding component. When prompted, choose Run this program or Open it.

System requirements

  1. Windows 95 or Windows NT® 4.00(x86)
  2. Internet Explorer version 3.0 or later
  3. A Pentium 100 MHz PC (or faster)
  4. At least 16MB of RAM
  5. At least 661K free disk space for the core components, plus at least 1.26 MB if you plan to use speech output, and an additional 6.68 MB if you plan to use speech input
  6. A Windows-compatible sound card
  7. A compatible set of speakers and microphone (recommended)
Agent Essentials

• Microsoft Agent Core Components (version 1.5)
Includes the control, data provider, server, and other essential files for Microsoft Agent.

Speech Engines

• Lernout & Hauspie® TruVoice Text-To-Speech Engine (version 1.5)
The TruVoice Engine provides speech output capabilities for Microsoft Agent and the Agent Character Editor.

• Microsoft Command and Control Speech Engine (version 3.0)
The Command and Control Engine provides speech input capabilities for Microsoft Agent. Visit the Microsoft Speech Research Group Web site for more information on this speech recognition engine.

Character and Sound Editors

• Microsoft Agent Character Editor (version 1.5)
The Agent Character Editor lets you compose your own characters for use with Microsoft Agent.

• Microsoft Agent Linguistic Information Sound Editing Tool (version 1.5)
The Linguistic Information Sound Editing Tool enables you to generate phoneme and word-break information for enhancing sound (.WAV) files to support high-quality lip-synching character animation.


Microsoft Agent Programming Interface Overview

Microsoft Agent Microsoft Agent *

Programming Interface Overview

ActiveX™ Technology for Interactive Software Agents

August 1997
Microsoft Corporation

Note: This document is provided for informational purposes only and Microsoft makes no warranties, either expressed or implied, in this document. The entire risk of the use or the results of this document remains with the user.

Information in this document is subject to change without notice. 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.

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. Microsoft, MS, MS-DOS, Windows, Windows NT, and the Windows logo are either registered trademarks or trademarks of Microsoft Corporation in the U.S. and/or other countries. Other product and company names mentioned herein may be the trademarks of their respective owners.

Contents

Introduction

Licensing and Distribution

Animation Services

Input Services

Output Services

Introduction

The Microsoft Agent API provides services that support the display and animation of animated characters. Implemented as an OLE Automation (Component Object Model [COM]) server, Microsoft Agent enables multiple applications, called clients or client applications, to host and access its animation, input, and output services at the same time. A client can be any application that supports the Microsoft Agent's COM interfaces.

Although you can call Microsoft Agent's COM interfaces directly, Microsoft Agent also includes an ActiveX™ control. This control makes it easy to access Microsoft Agent's services from programming languages that support the ActiveX control interface. For information, see Programming the Microsoft Agent Server Interface and Programming the Microsoft Agent Control.

As a COM server, Microsoft Agent starts up only when a client application requests to connect to it. It remains running until all clients close their connection. When no connected clients remain, Microsoft Agent automatically exits. Microsoft Agent also exits when a user explicitly chooses the Exit command on the pop-up menu of Microsoft Agent's taskbar icon and confirms exiting in the warning message box. This action causes the server to send a Shutdown event to all connected clients advising them that the server is exiting.

Back to contents

Licensing and Distribution

The Microsoft Agent self-extracting executable installs a number of system files and registry entries. Web developers can include the CLSID in the <OBJECT> tag of their HTML page, subject to the provisions of the license agreement displayed when the control is downloaded and installed. Application developers who want to add Microsoft Agent services and any of its components (including Microsoft Agent character files) to their application must obtain a redistribution license for Microsoft Agent. For more information on redistribution of Microsoft Agent, see Microsoft Agent Licensing and Redistribution.

Back to contents

Animation Services

Microsoft Agent's animation services manage the animation and movement of a character's image in its own window on the screen. An animation is defined as a sequence of timed and optionally branched frames, composed of one or more images. Specifying the Play statement with the name of an animation plays that animation. Animation names are specific to a character definition. As an animation plays, the shape of its window changes to the match the image in the frame. This results in a movable graphic image, or sprite, displayed on top of the desktop and all windows.

Each client application can display and animate its own character. You can also share a character between multiple client applications. Microsoft Agent also supports clients using multiple characters displayed at the same time. The animation services enable you to animate characters independently or synchronize their animation.

To access a character, use the Load method to load the character's data. Microsoft Agent's services include a data provider that supports two formats for loading character and animation data: a single structured file and separate files. Typically, you would use the single file format (.ACS) when the data can be stored locally. The multiple file format (.ACF, .AAF) works best when you want to download animations individually, such as when accessing animations from a Web page script.

Microsoft Agent provides a set of characters you can download and use, subject to the provisions of the license agreement. For information on accessing the characters, see the Microsoft Agent Character Data page.

You can define your own character and its animations using any rendering tool you prefer. To compile a character's animations for use with Microsoft Agent, use the Microsoft Agent Character Editor. This tool enables you to define a character's default properties as well as define animations for the character. The Microsoft Agent Character Editor also enables you to select the appropriate file format when you create a character. For alternative formats or rendering, you can supply your own animation data provider.

The animation services also play certain animations automatically. For example, when you call the MoveTo and GestureAt methods, the server determines what animation to play based on the character's current position. Similarly, the services play Idling animations when the user has not interacted with the character. These server-managed animations are called "states," and are defined when a character is created. For more information, see Using The Microsoft Agent Character Editor.

Client applications can directly hide or show a character by using the Hide or Show methods that play the animations assigned to the Hiding and Showing states and set the character's Visible property. This functionality enables you to display or hide a character using your own interface.

Although the server produces no output when a character is hidden, the server still queues and processes the animation request (plays the animation), but passes a request status back to the client. In the hidden state, the character cannot become input-active. However, if the user speaks the name of a hidden character (when speech input is enabled), the server automatically shows the character.

Microsoft Agent queues animation requests and processes them asynchronously. This enables your application's code to continue while character animations play. However, you can still monitor and manage your character's animation queue by creating an object reference to the request.

Back to contents

Input Services

A client application provides the primary user interface for interaction with a character. You can program a character to respond to any form of input, from button-clicks to typed-in text. In addition, Microsoft Agent provides events so you can program what happens when the user clicks, double-clicks, or drags the character. The server passes the coordinates of the pointer and any modifier key state for these events.

Speech Input Support

In addition to supporting mouse and keyboard interaction, Microsoft Agent includes support for speech input. You can use The Microsoft Command and Control Engine for supporting speech recognition. This speech recognition engine enables users to speak naturally without pausing between words. Speech recognition is speaker-independent, but it can be trained for improved performance. Because Microsoft Agent's support for speech input is based on Microsoft SAPI (Speech Application Programming Interface), you can use Microsoft Agent with other engines that are SAPI-compliant.

The user can initiate speech input by pressing and holding the push-to-talk hot key. In this mode, if the speech engine receives the beginning of spoken input, it holds the audio channel open until it detects the end of the utterance. However, when not receiving input, it does not block audio output. This enables the user to issue multiple voice commands while holding down the key, and the character can respond when the user isn't speaking. If a character attempts to speak while the user is speaking, the character's audible output fails though text may still be displayed in its word balloon. If the character has the audio channel while listening key is pressed, the server automatically transfers control back to the user after processing the text in the Speak method. An optional MIDI tone is played to cue the user to begin speaking. This enables the user to provide input even if the application driving the character failed to provide logical pauses in its output.

Because multiple client applications can share the same character and because multiple clients can use different characters at the same time, the server designates one client as the input-active client and sends mouse and voice input only to that client application. This maintains the orderly management of user input, so that an appropriate client responds to the input. Typically, user interaction determines which client application becomes input-active. For example, if the user clicks a character, that character's client application becomes input-active. Similarly, if a user speaks the name of a character, it becomes input-active. Also, when the server processes a character's Show method, the client of that character becomes input-active. In addition, you can call the Activate method to make your client input-active, but you should do so only when your client application is active. For example, if the user clicks your application's window, activating your application, you can call the Activate method to receive and process mouse and speech input.

If multiple clients use the same character, the server defines the last one shown or the last one input-active as the current input-active character. However, you can also use the Activate method to set your client to become input-active or remain non-input-active when the user selects that character.

The Commands Window

When a speech engine is installed and enabled, Microsoft Agent also includes a special interface called the Commands Window. This window displays the voice-enabled commands defined by the client applications for a character.

Figure 1. Commands Window

The Commands Window appears when the Open Commands Window command is chosen. Client commands appear in the Commands Window based on the Caption and Voice property settings of their Commands collection object.

The server creates a set of voice commands for general interaction and displays these under the Global Commands entry.

Caption | Voice Grammar
Open | Close Commands Window | ((open | show) [the] commands [window] | what can I say [now]) toggles with: close [the] commands [window]
Repeat Last Statement | (repeat [last statement] | what did you say)
CharacterName | [show] CharacterName*
Hide All Characters | hide all [characters]
Hide CharacterName | hide CharacterName**
Microsoft Agent Properties | Close Microsoft Agent Property Sheet | [(open | show)] [microsoft] agent (properties | property sheet) toggles with: close [microsoft] agent (properties | property sheet)
* All loaded characters are listed.

** A character is listed here only if it is currently visible.

The server automatically displays the commands of the current input-active client and, if necessary, scrolls the window to display as many of the client's commands as possible, based on the size of the window. If the character has no client entries, the Global Commands entry is expanded. Non-input-active clients appear in the tree as single entries.

Speaking the voice command for a client's Commands collection switches to that client and the Commands Window displays the commands of that client. No other entries are expanded. Similarly, if the user switches characters, the Commands Window changes to display the commands of its input-active client. If the client is already input-active, speaking its voice command has no effect. (However, if the user collapses the active client's subtree with the mouse, speaking the client name redisplays the client's subtree.) If a client has voice commands, but no Voice setting for its Commands object (or no Caption), the tree displays "(command undefined)" as the parent entry, but only when that client is input-active and the client has commands in its collection that have Caption and Voice settings. The server includes voice commands in the Global Commands entry ([show] [me] global commands). If the user speaks "Global Commands," the Commands Window always displays its associated subtree entries. If they are already displayed, the command has no effect.

Although you can also display or hide the Commands Window from your application's code using the Visible property, you cannot change the Commands Window size or location. The server maintains the Commands Window's properties based on the user's interaction with the window. Its initial location is immediately adjacent to the Microsoft Agent taskbar icon.

The Commands Window is included in the ALT+TAB window order. This enables a user to switch to the window to scroll, resize, or reposition the window with the keyboard.

The Listening Tip

When speech input is installed, Microsoft Agent includes a special tooltip window that displays when the user presses the push-to-talk hot key. The following table summarizes the display of the Listening Tip when speech recognition is enabled.

Action Result
User presses the listening mode hot key The Listening Tip appears below the active client's character and displays:

-- CharacterName is listening --
for "InputActiveClientCaption" commands.

The first line identifying the character is centered. The second line is left justified and breaks to a third line when it exceeds the Listening Tip's maximum width.

If an input-active client of the character does not have a caption or defined voice parameters for its Commands object, the Listening Tip displays:

-- CharacterName is listening --
for commands.

If there are no visible characters, the Listening Tip appears adjacent to the Microsoft Agent taskbar icon and displays:

-- All characters are hidden --
Say the name of a character to display it.

If the speech recognition is still initializing, the Listening Tip displays:

Say the name of a character to display it.

If the audio channel is busy, as when the character is audibly speaking or some other application is using the audio channel, the Listening Tip displays:

-- CharacterName is preparing to listen --
Please wait to speak.
User presses the listening mode hot key and speaks a voice command The Listening Tip appears below the active client's character and displays:

-- CharacterName heard --
"CommandText"

The first line is centered. The second line is left justified and breaks to a third line when it exceeds the Listening Tip's maximum width.

The Listening Tip automatically times out after being presented. If the "heard" text time-out completes when the user presses the hot key, the tip reverts to the "listening" text unless the server receives another matching utterance. In this case, the tip displays the new "heard" text and begins the time-out for that tip text. If the user releases the hot key and the server is displaying the "heard" text, the time-out continues. However, although the server displays the "listening" text, it immediately removes the Listening Tip when the user releases the hot key.

The Listening Tip does not appear when the pointer is over the Microsoft Agent taskbar icon. Instead, the standard notification tip window appears and displays "Press the name of hot key key to talk to InputActiveCharacterName" when the server is enabled. If all characters are hidden, the tip displays, "Press the name of hot key key and say the name of a character." However, if the user presses the speaking hot key, the tip reflects the same text as the listening tip. For example, it displays, "CharacterName is listening for InputActiveClientCaption commands," or, "CharacterName is listening for commands," if the input-active client has not defined its Caption property; and "CharacterName heard CommandText," when the speech engine processes a recognition. When the user disables speech input (or speech recognition is not installed), the icon's tooltip displays, "Microsoft Agent is running." When the server is in its suspended state, the tip displays, "Microsoft Agent is suspended."

Clients cannot write directly to the Listening Tip, but you can specify alternative "heard" text that the server displays on recognition of a matching voice command. To do this, set the Confidence property and the new ConfidenceText property for the command. If spoken input matches the command, but the best match does not exceed the confidence setting, the server uses the text set in the ConfidenceText property in the tip window. If the client does not supply this value, the server displays the text (grammar) it matched.

Pop-up Menu Support

Microsoft Agent includes a pop-up menu (also known as a contextual menu) for each character that the server displays automatically when a user right-clicks the character. This menu displays some standard commands managed by the server, but it also enables you to add and remove commands that your client application defines. The current input-active client's commands appear, provided that their Caption and Visible properties have been set. If the Enabled property has been set to True, the command appears enabled; if False, the command appears disabled (unavailable appearance). You define the access key for the entry by including an ampersand (&) before the text character of the Caption text setting. A separator appears before these commands. To create entries on a character's pop-up menu, define a Commands collection object and set the Caption and Visible properties of the commands. Note that menu entries do not change while the menu displays. If you add or remove commands or change their properties, the menu displays the changes when the user redisplays the menu.

The captions of any other clients (non-input-active) appear after another separator. To appear in the list, the Caption and Visible properties of their associated Commands object must be set. An ampersand in the text setting of the Caption property defines the access key for the entry. It is possible that access keys for menu items may be non-unique; however, this cannot be avoided. Separators appear only when there are items in the menu to separate. If no entries exist, the separator for that group does not appear.

Because the server provides the right-click pop-up menu as a standard service, avoid defining your own pop-up menu on the right-click event. However, if you define your own character, you can disable the server's pop-up menu by using the Microsoft Agent Character Editor. This enables you to support your own interface for the right-click action for your character. However, the pop-up menu cannot be disabled by a client application.

When the user selects a command from a character's pop-up menu or the Commands Window, the server triggers the Command event of the associated client and passes back the parameters of the input using the UserInput object.

The server also provides a pop-up menu for the Microsoft Agent taskbar icon. This menu provides the user access to all connected characters, and automatically assigns access keys for the characters based on the first letter of the character name. The menu also includes an entry that provides user access to the Microsoft Agent property sheet. You cannot modify the contents of the Microsoft Agent taskbar pop-up menu.

When the user chooses Exit from the Microsoft Agent taskbar icon pop-up menu, the server notifies the user that applications (clients with existing connections to the server) may not operate correctly and requests confirmation. If the user confirms shutting down the server, the server sends all client applications a Shutdown event. Your application becomes responsible for how it handles this state. Client applications cannot stop or cancel server shutdown.

If the server gets a request to restart after being shut down, for example, because a new client connects, the server partially reloads in suspended state, displaying the "suspended" Microsoft Agent icon in the taskbar notification area. Microsoft Agent also displays a message box indicating that the current application has requested to restart its services and offers to restart the server. (It also includes an option for the user not to be prompted again.) If the user chooses to restart, the server restores in its full operation and sends clients the Restart event. If the user chooses not to restart, the server remains its suspended state until all its clients close their connections or the user explicitly chooses to exit it again.

The Microsoft Agent Property Sheet

The Microsoft Agent property sheet provides options for users to adjust their interaction with all characters. For example, users can disable speech input or change input parameters. Users can also change the output settings for the word balloon. These settings override any that are set by a client application or set as part of the character definition. Your application cannot change or disable these options, because they apply to the general user preferences for operation of all characters. However, your application can display or close the property sheet and access the location of its window.

Back to contents

Output Services

Microsoft Agent also supports audio output for the character. This includes spoken output and sound effects. For spoken output, the server lip-syncs the character's defined mouth images to the output. You can choose text-to-speech (TTS) synthesis, recorded audio, or only word balloon text output.

Synthesized Speech Support

If you use synthesized speech, your character has the ability to say almost anything, which provides the greatest flexibility. With recorded audio, you can give the character a specific or unique voice. To specify output, provide the spoken text as a parameter of the Speak method.

Because Microsoft Agent's architecture uses Microsoft SAPI for synthesized speech output, you should be able to use any engine that conforms to this specification, and support International Phonetic Alphabet (IPA) output using the Visual method of the ITTSNotifySinkW interface. For further information on the SAPI interfaces, see the Microsoft Speech SDK.

Audio Output Support

Microsoft Agent enables you to use audio files for a character's spoken output. You can record audio files and use the Speak method to play that data. Microsoft Agent animation services automatically support lip-syncing the character mouth by using the audio characteristics of the audio file. Microsoft Agent also supports a special format for audio files, which includes additional phoneme and word-break information for more enhanced lip-sync support. You can generate this special format using the Microsoft Linguistic Information Sound Editing Tool (coming soon).

Word Balloon Support

Spoken output can also appear as textual output in the form of a cartoon word balloon. This can be used to supplement the spoken output of a character or as an alternative to audio output.

Figure 2. The Word Balloon

Word balloons support only captioned communication from the character, not user input. Therefore, the word balloon does not support input controls. If you want to provide user input for a character, supply those interfaces from your application or the other input services provided by Microsoft Agent, such as the pop-up menu.

When you define a character, you can specify whether to include word balloon support. However, if you use a character that includes word balloon support, you cannot disable the support.

Animation Sound Effects

Microsoft Agent also enables you to include sound effects as a part of a character's animation. Using the Microsoft Agent Character Editor, you can specify the filename of standard Windows® sound (.WAV) files to trigger on a given frame. Note that Microsoft Agent does not mix sound effects and spoken output, so spoken output does not begin until a sound effect completes. Therefore, avoid any long or looping sound effect as a part of a character's animation.

Back to contents


Microsoft Agent Character Data

Microsoft Agent Microsoft Agent *

Character Data

Microsoft Agent provides three standard characters: Genie, Merlin, and Robby. For each character, three types of character data are available:

• HTTP Access to Animations
All the animations for each standard character are available from a World Wide Web server maintained by Microsoft. Individual animations can be downloaded from this server after a character is loaded using an HTTP URL.

• File Access to Animations
As an alternative to using HTTP access, the complete set of animations for each standard character is available in a single, downloadable file. This file can be accessed using a local or UNC path, but cannot be accessed via HTTP URL.

• Images Only
Static and dynamic images, in GIF format, for each standard character. Can be used to visually represent a character in an application or web page.

HTTP Access to Animations

A complete set of animations for each of the three characters is maintained on a World Wide Web server at http://agent.microsoft.com/characters/. Each character is found is a separate directory with the same name as the character. For example, the Genie character is found at http://agent.microsoft.com/characters/genie/genie.acf.

To access character animations via HTTP from a web page, you specify the correct URL for the character you want to use in the Load request. Once the Load has succeeded, all subsequent Get requests for that character's animations will automatically go to the specified URL and download the animation into the user's cache of temporary internet files.

File Access to Animations

These files contain the animation data for the three standard Microsoft Agent characters. If you are developing an intranet application for Microsoft Agent, these files provide the animations you will need. You can install these files on a user's machine along with your application, and load the character data into your application using a local path. Alternately, you can publish these files on a network share and load the character data into your application using a UNC path. Note that both if these uses are subject to the terms of the Microsoft Agent License and Redistribution agreement. These files cannot be accessed using an HTTP URL.

If you are reading this documentation from the Internet Client SDK Web site, you need to download Microsoft Agent before these files will be available. Go to the Component Library section of the Internet Client SDK download page to download Microsoft Agent.

If you have already installed Microsoft Agent from the Internet Client SDK CD or download site, and are reading this page from your local disk, simply click on any link below to install these files into a new location. When prompted, choose Save it to disk. The standard location for character animation files is \Program Files\Microsoft Agent\Characters\.

• Character animation file for Genie (genie.acs)
• Character animation file for Merlin (merlin.acs)
• Character animation file for Robby (robby.acs)

Images Only

These are static and animated images for the three standard Microsoft Agent characters. The images are supplied in GIF format. They can be hosted directly on HTML pages or within the WebBrowser control in Visual Basic® or C++ applications. They can be used in any situation where a visual representation of one or more standard characters is needed.

To copy an image file, right-click on an image below and select Save Picture As... from the shortcut menu.

Animated Images
Static Images


Programming the Microsoft Agent Control

ActiveX™ Technology for Interactive Software Agents

August 1997
Microsoft Corporation

Note: This document is provided for informational purposes only and Microsoft makes no warranties, either expressed or implied, in this document. The entire risk of the use or the results of this document remains with the user.

Information in this document is subject to change without notice. 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.

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. Microsoft, MS, MS-DOS, Windows, Windows NT, and the Windows logo are either registered trademarks or trademarks of Microsoft Corporation in the U.S. and/or other countries. Other product and company names mentioned herein may be the trademarks of their respective owners.

Contents

Document Conventions

Accessing the Control in Web Pages

Accessing the Control from Visual Basic and Other Programming Languages

Accessing Microsoft Agent Services Directly

The Request Object

The Agent Control

The Characters Object

The AudioOutput Object

The SpeechInput Object

The CommandsWindow Object

The PropertySheet Object

Although applications can write directly to the Microsoft Agent services using its automation server interfaces, Microsoft Agent also includes an ActiveX™ (OLE) control. The control supports easy programming using a scripting language such as Microsoft® Visual Basic® Scripting Edition (VBScript) or other languages that support the ActiveX control interface.

Document Conventions

This documentation uses the following typographical conventions:

Convention | Description
Sub, Visible, Caption | Words in bold with initial letter capitalized indicate keywords.
agent, String, Now | Italic words indicate placeholders for information you supply.
ENTER, F1 | Words in all capital letters indicate filenames, key names, and key sequences.
Agent1.Commands.Enabled = True

Words in this font indicate code samples.

' This is a comment

An apostrophe (') indicates a code comment.

Agent1.Commands.Add "Test1", _
"Test 1", "test one"

A space and an underscore (_) continues a line of code.

[words or expression]

Items inside square brackets are optional.

This | That

A vertical bar indicates a choice between two or more items.

agent | The word "agent" in italics represents the name of the agent control you use.

The descriptions of programming interfaces in this document follow the conventions for Microsoft VBScript. However, they should be generally applicable to other languages as well.

Back to contents

Accessing the Control in Web Pages

To access the Microsoft Agent services from a Web page, use the HTML <OBJECT> tag within the <HEAD> or <BODY> element of the page, specifying the Microsoft CLSID (class identifier) for the control. In addition, use a CODEBASE parameter to specify the location of the Microsoft Agent installation file and its version number. The following example illustrates how to use the CODEBASE parameter to autodownload the English language version 1.5 of Microsoft Agent. For information about the current location of the Microsoft Agent installation file for specific language versions and the current release number available, see the Microsoft Agent download page.
<OBJECT
classid="clsid:F5BE8BD2-7DE6-11D0-91FE-00C04FD701A5"
CODEBASE = "http://activex.microsoft.com/controls/agent/MSagent.exe#VERSION=1,5,0,0"
id=Agent
>
</OBJECT>

Before any script on the page can access its services, Microsoft Agent must be installed on the system loading the page. If Microsoft Agent is not installed on the target system, Microsoft Internet Explorer will automatically download the Microsoft Agent server, data provider, and ActiveX control and ask the user whether to proceed with installation. Once installed, these three items do not have to be reinstalled unless the user uninstalls them. To begin using a character, you must also download its data using the Load and Get methods. For more information about the syntax for loading a character, see the Load method.

Note that you can also use the methods, properties, and events exposed by the browser to program the character; for example, to program its reaction to a button click. Consult the documentation for your browser to determine what features it exposes in its scripting model. For the Microsoft Internet Explorer, see the Document Object Model References in the Internet Client SDK.

Supporting Microsoft Agent from a Web page requires Microsoft Internet Explorer version 3.0 or later. For other browsers, contact the supplier for information regarding their support for ActiveX.

Using VBScript

To program Microsoft Agent from VBScript, use the HTML <SCRIPT> tags. To access the programming interface, use the name of control you assign in the <OBJECT> tag, followed by the subobject (if any), the name of the method or property, and any parameters or values supported by the method or property:

agent[.object].Method parameter,[parameter]
agent[.object].Property = value

For events, include the name of the control followed by the name of the event and any parameters:

Sub agent_event (ByVal parameter[,ByVal parameter])
statements...
End Sub

You can also specify an event handler using the <SCRIPT> tag's For…Event syntax:

<SCRIPT LANGUAGE=VBScript For=agent Event=event[(parameter[,parameter])]>
statements...
</SCRIPT>

Although Microsoft Internet Explorer supports this latter syntax, not all browsers do. For compatibility, use only the former syntax for events.

With VBScript 2.0, you can verify whether Microsoft Agent is installed by trying to create the object and checking to see if it exists. The following sample demonstrates how to check for the Agent control without triggering an auto-download of the control (as would happen if you included an <OBJECT> tag for the control on the page):

<!-- WARNING - This code requires VBScript 2.0.
It will always fail to detect the Agent control
in VbScript 1.x, because CreateObject doesn't work.
-->

<SCRIPT LANGUAGE=VBSCRIPT>
If HaveAgent() Then
  'Microsoft Agent control was found.
document.write "<H2 align=center>Found</H2>"
Else
  'Microsoft Agent control was not found.
document.write "<H2 align=center>Not Found</H2>"
End If

Function HaveAgent()
' This procedure attempts to create an Agent Control object.
' If it succeeds, it returns True.
'  This means the control is available on the client.
' If it fails, it returns False.
'  This means the control hasn't been installed on the client.

 Dim agent
 HaveAgent = False
 On Error Resume Next
 Set agent = CreateObject("Agent.Control.1")
 HaveAgent = IsObject(agent)

End Function

</SCRIPT>

You can download VBScript 2.0 and obtain further information on VBScript at the Microsoft VBScript site.

Using JavaScript and JScript

If you use JavaScript™ or Microsoft JScript™ to access Microsoft Agent's programming interface, follow the conventions for this language for specifying methods or properties:
agent.object.Method (parameter)
agent.object.Property = value

JavaScript does not currently have event syntax for non-HTML objects. However, with Internet Explorer you can use the <SCRIPT> tag's For...Event syntax:

<SCRIPT LANGUAGE="JScript" FOR="object" EVENT="event()">
statements...
</SCRIPT>

Because not all browsers currently support this event syntax, you may want to use JavaScript only for pages that support Microsoft Internet Explorer or for code that does not require event handling.

The current release of JScript does not support collections. To access methods and properties of the Character object, use the Character method. Similarly, to access the properties of a Command object, use the Command method.

Accessing Speech Support for Microsoft Agent

Although Microsoft Agent's services include support for speech recognition, a compatible speech engine must be installed to access Agent's speech recognition support. Your license for Microsoft Agent includes a license for the Microsoft Command and Control Speech Engine when used as part of a Microsoft Agent client application. For information, see Microsoft Speech Research Group web site.

To support automatic downloading and installation of Microsoft Command and Control from an HTML page, include a separate <OBJECT> tag specifying the CLSID of the engine. In addition, include a CODEBASE parameter to specify the location of the installation file as well as the version number, as shown in the following example. For the current location and version number to use for autodownloading the Microsoft Command and Control speech engine, consult the information posted on the Microsoft Agent download site at http://www.microsoft.com/workshop/prog/agent/agentdl.htm.

<OBJECT
classid="clsid:161FA781-A52C-11d0-8D7C-00A0C9034A7E"
CODEBASE = http://www.research.microsoft.com/research/srg/actcnc.exe#VERSION=3,0,0,1831
>
</OBJECT>

The license for Microsoft Command and Control does not permit redistribution of the speech engine independently. For information on licensing the engine separately from Microsoft Agent, contact the Microsoft Speech Research group. The Microsoft Command and Control engine is currently available only for English language input; however, other speech recognition vendors supporting the Microsoft Speech API may provide support for other languages. If you use another speech engine, contact its vendor for compatibility, installation, and licensing information.

Similarly, if you want to use Microsoft Agent's synthesized speech services, you must install a compatible text-to-speech (TTS) speech engine for your character's output. Your license for Microsoft Agent includes a license to use a special version of the Lernout & Hauspie® TruVoice engine, but only when used with Microsoft Agent.

To support automatic downloading and installation of this engine from an HTML page, include the engine's CLSID in the <OBJECT> tag. In addition, include a CODEBASE parameter to specify the location of the installation file as well as the version number, such as shown in the following example. For the current location and version number to use for autodownloading the Lernout & Hauspie Text to Speech Engine for Microsoft Agent, consult the information posted on the Microsoft Agent download site at http://www.microsoft.com/workshop/prog/agent/agentdl.htm.

<OBJECT
classid="clsid:B8F2846E-CE36-11D0-AC83-00C04FD97575"
CODEBASE = "http://activex.microsoft.com/controls/agent/cgram.exe#VERSION=1,5,0,0"
>
</OBJECT>

This speech output engine supports only English language output. However, because Microsoft Agent uses the Microsoft Speech API, other languages may be available. If you want to use another compatible speech engine, contact its vendor for further information about their installation and licensing. Note that if you want to downloaded sound (.WAV) files for your character's voice output, you do not have to install a TTS engine.

Back to contents

Accessing the Control from Visual Basic and Other Programming Languages

You can also use Microsoft Agent's control from Visual Basic® and other programming languages. Make sure that the language fully supports the ActiveX control interface, and follow its conventions for adding and accessing ActiveX controls.

Accessing Microsoft Agent's control from Visual Basic requires that you first create the control. The easiest way to do this is to place an instance of the control on a form. (You may have to add the control to your toolbox before adding it to your form.) Follow Visual Basic syntax for specifying methods, properties, or events. Using Microsoft Agent's control with Visual Basic is very similar to using the control with VBScript, except that events in Visual Basic must include the data type of passed parameters. However, adding the Microsoft Agent control to a form will automatically include Microsoft Agent's events with their appropriate parameters. For more advanced scenarios, such as creating an Agent control at run time, see the Connected property.

Most programming languages that support ActiveX controls follow conventions similar to Visual Basic. For programming languages that do not support object collections, you can use the Character method and Command method to access methods and properties of items in the collection.

Back to contents

Accessing Microsoft Agent Services Directly

If you are using C, C++, or Java™, you can access the Microsoft Agent server directly using its ActiveX (OLE) interfaces. For more information on these interfaces, see Programming the Microsoft Agent Server Interface.

The Agent Object Model

The Microsoft Agent Object Model consists of the following objects:
  • Request
  • Agent (control)
  • Characters (collection)
  • Character
  • Commands (collection)
  • Command
  • Balloon
  • SpeechInput
  • AudioOutput
  • CommandsWindow
  • PropertySheet

These objects are organized in the following hierarchy. (The dotted line following an object indicates that multiple objects can exist.)

Figure 3. The Agent Object

Back to contents

The Request Object

The server processes some methods, such as Load, Get, Play, and Speak, asynchronously. This enables your application code to continue while the method is completing. When a client application calls one of these methods, the control creates and returns a Request object for the request. You can use the Request object to track the status of the method by assigning an object variable to the method. In VBScript and Visual Basic, first declare an object variable:
   Dim MyRequest as Object

In VBScript, you don't include the variable type in your declaration:

   Dim MyRequest

And use Visual Basic's Set statement to assign the variable to the method call:

    Set Request = agent.Characters("CharacterID").method (parameter[s])

This adds a reference to the Request object. The Request object will be destroyed when there are no more references to it. Where you declare the Request object and how you use it determines its lifetime. If the object is declared local to a subroutine or function, it will be destroyed when it goes out of scope; that is, when the subroutine or function is complete. If the object is declared globally, it will not be destroyed until either the program terminates or a new value (or a value set to "empty") is assigned to the object.

The Request object provides several properties you can query. For example, the Status property returns the current status of the request. You can use this property to check the status of your request:

 Dim MyRequest

 Set MyRequest = Agent.Characters.Load ("Genie", _
  "http://agent.microsoft.com/characters/genie/genie.acf")

 If (MyRequest.Status = Pending) then
  'do something

 Else If (MyRequest.Status = Complete) then
  'do something right away

 End If

The Status property returns the status of a Request object as a Long integer value.

Status | Definition
0 | Request successfully completed.
1 | Request failed.
2 | Request pending (in the queue, but not complete).
3 | Request interrupted.
4 | Request in progress.

The Request object also includes a Long integer value in the Number property that returns the error or cause of the Status code. If none, this value is zero (0). The Description property contains a string value that corresponds to the error number. If the string doesn't exist, Description contains "Application-defined or object-defined error".

For the values and meaning returned by the Number property, see Error Codes.

The server places animation requests in the specified character's queue. This enables the server to play the animation on a separate thread, and your application's code can continue while animations play. If you create a Request object reference, the server automatically notifies you when an animation request has started or completed through the RequestStart and RequestComplete events. Because methods that return Request objects are asynchronous and may not complete during the scope of the calling function, declare your reference to the Request object globally.

The following methods can be used to return a Request object: GestureAt, Get, Hide, Interrupt, Load, MoveTo, Play, Show, Speak, Wait.

Back to contents

The Agent Control

Referencing the Agent control provides access to events and most other objects supported by Microsoft Agent. The Agent control also directly exposes its own set of properties.

Agent Control Properties

The following properties are directly accessed from the Agent control:

Connected, Name, Suspended

In addition, some programming environments may assign additional design-time or run-time properties. For example, Visual Basic adds Left, Index, Tag, and Top properties that define the location of the control on a form even though the control does not appear on the form's page at run time.

Connected Property

Description
Returns or sets whether the current control is connected to the Microsoft Agent server.
Syntax
agent.Connected [= boolean]
Part | Description
boolean | A Boolean expression specifying whether the control is connected. True The control is connected. False The control is not connected.

Remarks

In many situations, specifying the control automatically creates a connection with the Microsoft Agent server. For example, specifying the Microsoft Agent control's CLSID in the <OBJECT> tag in a Web page automatically opens a server connection and exiting the page closes the connection. Similarly, for Visual Basic or other languages that enable you to drop a control on a form, running the program automatically opens a connection and exiting the program closes the connection. If the server isn't currently running, it automatically starts.
However, if you want to create an Agent control at run time, you may also need to explicitly open a new connection to the server using the Connected property. For example, in Visual Basic you can create an ActiveX object at run time using the Set statement with the New keyword (or CreateObject function). While this creates the object, it will not create the connection to the server, so you must use the Connected property before any code that calls into Microsoft Agent's programming interface, as shown in the following example:
 ' Declare a global variable for the control
 Dim MyAgent as Agent

 ' Create an instance of the control using New
 Set MyAgent = New Agent

 ' Open a connection to the server
 MyAgent.Connected = True

 ' Load a character
 MyAgent.Characters.Load "Genie", "C:\Some Directory\Genie.acs"

 ' Display the character
 MyAgent.Characters("Genie").Show

Note that creating a control using this technique does not expose the Agent control's events. In Visual Basic 5.0, you can access the control's events by including the control in your project's references, and use the WithEvents keyword in your variable declaration:
 Dim WithEvents agent as Agent

 ' Create an instance of the control using New
 Set MyAgent = New Agent

Using WithEvents to create an instance of the Agent control at run time automatically opens the connection with the Microsoft Agent server. Therefore, you don't need to include a Connected statement.

You can close your control's connection to the server at run time by setting the Connected property to False. However, you must first release all references you defined to objects created by the server. In particular, you must release any references you created to character and command objects. In Visual Basic, you can disassociate a reference to an object by setting the reference to Nothing:

 Dim Genie as IAgentCtlCharacter

 Sub LoadCharacter

 ' Load the character into the Characters collection
 Agent1.Characters.Load "Genie", _
 "C:\Program Files\Microsoft Agent\Genie.acs"

 ' Create a reference to the character
 Set Genie = Agent1.Characters("Genie")

 End Sub

 Sub CloseConnection

 ' Release the reference to the character object
 Set Genie = Nothing

 ' Close the connection with the server
 Agent1.Connected = False

 End Sub

Although you can reopen your connection by resetting the Connected property to True, not all information established with the server in the original connection will be preserved. For example, if you loaded a character, you will have to reload it again before you can play any of its animations. Setting the Connected property to False does not destroy your instance of the control. You must use the syntax supported by your programming language for releasing the object. For example, in Visual Basic, you set the control to Nothing:
 Set Agent1 = Nothing

Attempting to query or set the Connected property before creating the control will raise an error.

Name Property

Description
Returns the name used in code to identify the control. This property is read-only at run time.
Syntax
agent.Name
Remarks
In some programming environments such as Visual Basic, adding the control automatically generates a default name for the control that can be changed at design time. For HTML scripts, you can define the name in the <OBJECT> tag. If you define the name, follow the conventions of the programming language for defining object names.

Suspended Property

Description
Returns a Boolean indicating the Microsoft Agent server operational state.
Syntax
agent.Suspended
Remarks
The Suspended property returns False when the server is in its normal running state. When the property returns True, the server is in its "suspended" state, which indicates that the user shut down the server and implies that no character interaction is desired. Client applications can only read this property, but you can display your own message box suggesting how to restart the server.
See Also
Restart event, Shutdown event

Agent Control Events

The Microsoft Agent control provides several events that enable your client application to track the state of the server:

ActivateInput, BalloonHide, BalloonShow, Bookmark, Click, Command, DblClick, DeactivateInput, DragComplete, DragStart, Hide, IdleComplete, IdleStart, Move, RequestComplete, RequestStart, Restart, Show, Shutdown, Size

ActivateInput Event

Description
Occurs when a client becomes input-active.
Syntax
Sub agent_ActivateInput (ByVal CharacterID)
Value | Description
CharacterID | Returns the ID of the character through which the client becomes input-active.

Remarks

The input-active client receives mouse and speech input events supplied by the server. The server sends this event only to the client that becomes input-active.
This event can occur when the user switches to your Commands object, for example, by choosing your Commands object entry in the Commands Window or in the pop-up menu for a character. It can also occur when the user selects a character (by clicking or speaking its name), when a character becomes visible, and when the character of another client application becomes hidden. You can also call the Activate method (with State set to 2) to explicitly make the character topmost, which results in your client application becoming input-active and triggers this event. However, this event does not occur if you use the Activate method only to specify whether your client is the active client of the character.
See Also
DeactivateInput event, Activate method

BalloonHide Event

Description
Occurs when a character's word balloon is hidden.
Syntax
Sub agent_BalloonHide (ByVal CharacterID)
Value | Description
CharacterID | Returns the ID of the character associated with the word balloon.

Remarks

The server sends this event only to the clients of the character (applications that have loaded the character) that uses the word balloon.
See Also
BalloonShow event

BalloonShow Event

Description
Occurs when a character's word balloon is shown.
Syntax
Sub agent_BalloonShow (ByVal CharacterID)
Value | Description
CharacterID | Returns the ID of the character associated with the word balloon.

Remarks

The server sends this event only to the clients of the character (applications that have loaded the character) that uses the word balloon.
See Also
BalloonHide event

Bookmark Event

Description
Occurs when a bookmark in a speech text string that your application defined is activated.
Syntax
Sub agent_Bookmark(ByVal BookmarkID)
Value | Description
BookmarkID | A Long integer identifying the bookmark number.

Remarks

To specify a bookmark event, use the Speak method with a Mrk tag in your supplied text. For more information about tags, see Speech Output Tags.

Click Event

Description
Occurs when the user clicks a character.
Syntax
Sub agent_Click (ByVal CharacterID, ByVal Button, ByVal Shift, ByVal X, ByVal Y)
Value | Description
CharacterID | Returns the ID of the clicked character as a string.
Button | Returns an integer that identifies the button that was pressed and released to cause the event. The button argument is a bit field with bits corresponding to the left button (bit 0), right button (bit 1), and middle button (bit 2). These bits correspond to the values 1, 2, and 4, respectively. Only one of the bits is set, indicating the button that caused the event.
Shift | Returns an integer that corresponds to the state of the SHIFT, CTRL, and ALT keys when the button specified in the button argument is pressed or released. A bit is set if the key is down. The shift argument is a bit field with the least-significant bits corresponding to the SHIFT key (bit 0), the CTRL key (bit 1), and the ALT key (bit 2). These bits correspond to the values 1, 2, and 4, respectively. The shift argument indicates the state of these keys. Some, all, or none of the bits can be set, indicating that some, all, or none of the keys are pressed. For example, if both CTRL and ALT were pressed, the value of shift would be 6.
X,Y | Returns an integer that specifies the current location of the mouse pointer. The X and Y values are always expressed in pixels, relative to the upper left corner of the screen.

Remarks

This event is sent only to the input-active client of a character. When the user clicks a character with no input-active client, the server sets its last input-active client as the current input-active client, sending the ActivateInput event to that client, and then sending the Click event.

Note Clicking a character does not disable all other character output (all characters). However, pressing the listening hot key does flush the input-active character's output and triggers the RequestComplete event, passing a Request.Status that indicates that the client's queue was interrupted.

Command Event

Description
Occurs when a (client's) command is chosen by the user.
Syntax
Sub agent_Command(ByVal UserInput)
Value Description
UserInput Identifies the Command object returned by the server.

The following properties can be accessed from the Command object:

CharacterID A string value identifying the name (ID) of the character that received the command.
Name A string value identifying the name (ID) of the command.
Confidence A Long integer value indicating the confidence scoring for the command.
Voice A string value identifying the voice text for the command.
Alt1Name A string value identifying the name of the next (second) best command.
Alt1Confidence A Long integer value indicating the confidence scoring for the next (second) best command.
Alt1Voice A string value identifying the voice text for the next best alternative command match.
Alt2Name A string value identifying the name of third best command match.
Alt2Confidence A Long integer identifying the confidence scoring for the third best command match.
Alt2Voice A string value identifying the voice text for the third best command match.
Count Long integer value indicating the number of alternatives returned.

Remarks

The server notifies you with this event when your application is input-active and the user chooses a command you defined to appear in the Commands Window or character's pop-up menu. The event passes back the number of possible matching commands in Count as well as the name, confidence scoring, and voice text for those matches.
If voice input triggers this event, the server returns a string that identifies the best match in the Name parameter, and the second- and third-best match in Alt1Name and Alt2Name. An empty string indicates that the input did not match any command your application defined; for example, it could be one of the server's defined commands. It is also possible that you may get the same command name returned in more than one entry. Confidence, Alt1Confidence, and Alt2Confidence parameters return the relative scores, in the range of -100 to 100, that are returned by the speech recognition engine for each respective match. Voice, Alt1Voice, and Alt2Voice parameters return the voice text that the speech recognition engine matched for each alternative. If Count returns zero (0), the server detected spoken input, but determined that there was no matching command.

If voice input was not the source for the command, for example, if the user selected the command from the character's pop-up menu, the server returns the name (ID) of the command selected in the Name property. It also returns the value of the Confidence parameter as 100, and the value of the Voice parameters as the empty string (""). Alt1Name and Alt2Name also return empty strings. Alt1Confidence and Alt2Confidence return zero (0), and Alt1Voice and Alt2Voice return empty strings. Count returns 1.

Note The Microsoft Command and Control engine supports returning values in the parameters of this event. If you use Microsoft Agent with another speech engine, check with the supplier to determine whether their engine supports the Microsoft Speech API interface for returning alternatives and confidence scores.

DblClick Event

Description
Occurs when the user double-clicks a character.
Syntax
Sub agent_DblClick (ByVal CharacterID, ByVal Button, ByVal Shift, ByVal X, ByVal Y)
Value | Description
CharacterID | Returns the ID of the double-clicked character as a string.
Button | Returns an integer that identifies the button that was pressed and released to cause the event. The button argument is a bit field with bits corresponding to the left button (bit 0), right button (bit 1), and middle button (bit 2). These bits correspond to the values 1, 2, and 4, respectively. Only one of the bits is set, indicating the button that caused the event.
Shift | Returns an integer that corresponds to the state of the SHIFT, CTRL, and ALT keys when the button specified in the button argument is pressed or released. A bit is set if the key is down. The shift argument is a bit field with the least-significant bits corresponding to the SHIFT key (bit 0), the CTRL key (bit 1), and the ALT key (bit 2). These bits correspond to the values 1, 2, and 4, respectively. The shift argument indicates the state of these keys. Some, all, or none of the bits can be set, indicating that some, all, or none of the keys are pressed. For example, if both CTRL and ALT were pressed, the value of shift would be 6.
X,Y | Returns an integer that specifies the current location of the mouse pointer. The X and Y values are always expressed in pixels, relative to the upper left corner of the screen.

Remarks

This event is sent only to the input-active client of a character. When the user double-clicks a character with no input-active client, the server sets its last input-active client as the current input-active client, sending the ActivateInput event to that client, and then sending the DblClick event.

DeactivateInput Event

Description
Occurs when a client becomes non-input-active.
Syntax
Sub agent_DeactivateInput (ByVal CharacterID)
Value | Description
CharacterID | Returns the ID of the character that makes the client become non-input-active.

Remarks

A non-input-active client no longer receives mouse or speech events from the server (unless it becomes input-active again). The server sends this event only to the client that becomes non-input-active. It does not occur when you use the Activate method and set the State parameter to 0.
This event occurs when your client application is input-active and the user chooses the caption of another client in a character's pop-up menu or the Commands Window. It may also occur when the user selects the name of another character by clicking or speaking. You also get this event when your character is hidden or another character becomes visible.
See Also
ActivateInput event

DragComplete Event

Description
Occurs when the user completes dragging a character.
Syntax
Sub agent_DragComplete (ByVal CharacterID, ByVal Button, ByVal Shift, ByVal X, ByVal Y)
Value | Description
CharacterID | Returns the ID of the dragged character as a string.
Button | Returns an integer that identifies the button that was pressed and released to cause the event. The button argument is a bit field with bits corresponding to the left button (bit 0), right button (bit 1), and middle button (bit 2). These bits correspond to the values 1, 2, and 4, respectively. Only one of the bits is set, indicating the button that caused the event.
Shift | Returns an integer that corresponds to the state of the SHIFT, CTRL, and ALT keys when the button specified in the button argument is pressed or released. A bit is set if the key is down. The shift argument is a bit field with the least-significant bits corresponding to the SHIFT key (bit 0), the CTRL key (bit 1), and the ALT key (bit 2). These bits correspond to the values 1, 2, and 4, respectively. The shift argument indicates the state of these keys. Some, all, or none of the bits can be set, indicating that some, all, or none of the keys are pressed. For example, if both CTRL and ALT were pressed, the value of shift would be 6.
X,Y | Returns an integer that specifies the current location of the mouse pointer. The X and Y values are always expressed in pixels, relative to the upper left corner of the screen.

Remarks

This event is sent only to the input-active client of a character. When the user drags a character with no input-active client, the server sets its last input-active client as the current input-active client, sending the ActivateInput event to that client, and then sending the DragStart and DragComplete events.
See Also
DragStart event

DragStart Event

Description
Occurs when the user begins dragging a character.
Syntax
Sub agent_DragStart (ByVal CharacterID, ByVal Button, ByVal Shift, ByVal X, ByVal Y)
Value | Description
CharacterID | Returns the ID of the clicked character as a string.
Button | Returns an integer that identifies the button that was pressed and released to cause the event. The button argument is a bit field with bits corresponding to the left button (bit 0), right button (bit 1), and middle button (bit 2). These bits correspond to the values 1, 2, and 4, respectively. Only one of the bits is set, indicating the button that caused the event.
Shift | Returns an integer that corresponds to the state of the SHIFT, CTRL, and ALT keys when the button specified in the button argument is pressed or released. A bit is set if the key is down. The shift argument is a bit field with the least-significant bits corresponding to the SHIFT key (bit 0), the CTRL key (bit 1), and the ALT key (bit 2). These bits correspond to the values 1, 2, and 4, respectively. The shift argument indicates the state of these keys. Some, all, or none of the bits can be set, indicating that some, all, or none of the keys are pressed. For example, if both CTRL and ALT were pressed, the value of shift would be 6.
X,Y | Returns an integer that specifies the current location of the mouse pointer. The X and Y values are always expressed in pixels, relative to the upper left corner of the screen.

Remarks

This event is sent only to the input-active client of a character. When the user drags a character with no input-active client, the server sets its last input-active client as the current input-active client, sending the ActivateInput event to that client, and then sending the DragStart event.
See Also
DragComplete event

Hide Event

Description
Occurs when a character is hidden.
Syntax
Sub agent_Hide (ByVal CharacterID, ByVal Cause)
Value | Description
CharacterID | Returns the ID of the hidden character as a string.
Cause Returns a value that indicates what caused the characer to be hidden.

1 The user hid the character (using the menu or voice command).
2 Your client application hid the character.
3 Another client application hid the character.

Remarks

The server sends this event to all clients of the character. To query the current state of the character, use the Visible property.
See Also
Show event, VisibilityCause property

IdleComplete Event

Description
Occurs when the server ends the Idling state of a character.
Syntax
Sub agent_IdleComplete (ByVal CharacterID)
Value | Description
CharacterID | Returns the ID of the idling character as a string.

Remarks

The server sends this event to all clients of the character.
See Also
IdleStart event

IdleStart Event

Description
Occurs when the server sets a character to the Idling state.
Syntax
Sub agent_IdleStart (ByVal CharacterID)
Value | Description
CharacterID | Returns the ID of the idling character as a string.

Remarks

The server sends this event to all clients of the character.
See Also
IdleComplete event

Move Event

Description
Occurs when a character is moved.
Syntax
Sub agent_Move (ByVal CharacterID, ByVal X, ByVal Y, ByVal Cause)
Value | Description
CharacterID | Returns the ID of the character that moved.
X | Returns the x-coordinate (in pixels) of the top edge of character frame's new location as an integer.
Y | Returns the y-coordinate (in pixels) of the left edge of character frame's new location as an integer.
Cause Returns a value that indicates what caused the character to move.

1 The user dragged the character.
2 Your client application moved the character.
3 Another client application moved the character.

Remarks

This event occurs when the user or an application changes the character's position. Coordinates are relevant to the upper left corner of the screen. This event is sent only to the clients of the character (applications that have loaded the character).
See Also
MoveCause property, Size event

RequestComplete Event

Description
Occurs when the server completes a queued request.
Syntax
Sub agent_RequestComplete (ByVal Request)
Value | Description
Request | Returns the Request object.

Remarks

This event returns a Request object. Because requests are processed asynchronously, you can use this event to determine when the server completes processing a request (such as a Get, Play, or Speak method) to synchronize this event with other actions generated by your application. The server sends the event only to the client that created the reference to the Request object and only if you defined a global variable for the request reference:
 Dim MyRequest
 Dim Genie

 Sub window_Onload

 Agent1.Characters.Load "Genie", _
  "http://agent.microsoft.com/characters/genie/genie.acf"

 Set Genie = Agent.Characters("Genie")

 ' This syntax will generate RequestStart and RequestComplete events.
 Set MyRequest = Genie.Get("state", "Showing")
 ' This syntax will not generate RequestStart and RequestComplete events.
 Genie.Get "state", "Hiding"

 End Sub

 Sub Agent1_RequestComplete(ByVal Request)

 If Request = MyRequest Then
  Status = "Showing animation is now loaded"

 End Sub

Note In VBScript 1.0, this event fires even if you don't define references to a Request object. This has been fixed in VBScript 2.0, which can be downloaded from http://www.microsoft.com/msdownload/scripting.htm.

See Also

RequestStart event

RequestStart Event

Description
Occurs when the server begins a queued request.
Syntax
Sub agent_RequestStart (ByVal Request)
Value | Description
Request | Returns the Request object.

Remarks

The event returns a Request object. Because requests are processed asynchronously, you can use this event to determine when the server begins processing a request (such as a Get, Play, or Speak method) and thereby synchronize this with other actions generated by your application. The event is sent only to the client that created the reference to the Request object and only if you defined a global variable for the request reference:
 Dim MyRequest
 Dim Genie

 Sub window_Onload

 Agent1.Characters.Load "Genie", _
   "http://agent.microsoft.com/characters/genie/genie.acf"
 Set Genie = Agent1.Characters("Genie")

 ' This syntax will generate RequestStart and RequestComplete events.
 Set MyRequest = Genie.Get("state", "Showing")

 ' This syntax will not generate RequestStart and RequestComplete events.
 Genie.Get ("state", "Hiding")
 End Sub

 Sub Agent1_RequestStart(ByVal Request)

 If Request = MyRequest Then
  Status = "Loading the Showing animation"

 End Sub

The Status returns 4 (request in progress) for the Request object returned.

Note In VBScript 1.0, this event fires even if you don't define references to a Request object. This has been fixed in VBScript 2.0, which can be downloaded from http://www.microsoft.com/msdownload/scripting.htm.

See Also

RequestComplete event

Restart Event

Description
Occurs when the server restarts from its suspended state.
Syntax
Sub agent_Restart ()
Remarks
The server sends this event to all client applications when the user chooses to restart the server from its suspended state. However, you will not get this event if you close your connection to the server when the server shuts down.

Show Event

Description
Occurs when a character is displayed.
Syntax
Sub agent_Show (ByVal CharacterID, ByVal Cause)
Value | Description
CharacterID | Returns the ID of the character shown as a string.
Cause Returns a value that indicates what caused the character to display.

2 The user showed the character (using the menu or voice command).
4 Your client application showed the character.
6 Another client application showed the character.

Remarks

The server sends this event to all clients of the character. To query the current state of the character, use the Visible property.

See Also

Hide event, VisibilityCause property

Shutdown Event

Description
Occurs when the user explicitly shuts down (exits) Microsoft Agent.
Syntax
Sub agent_Shutdown()
Remarks
When the user explicitly chooses Exit on the pop-up menu on the Microsoft Agent taskbar icon and confirms the choice in the warning message box, the server sends this event to all connected clients and then exits. The server also sets the control's Connected property to False. Any subsequent calls you make to the server will fail. You may want to handle this error condition.

Size Event

Description
Occurs when a character's size changes.
Syntax
Sub agent_Size (ByVal CharacterID, ByVal Width, ByVal Height)
Value | Description
CharacterID | Returns the ID of the character that was resized.
Width | Returns the character frame's new width (in pixels) as an integer.
Height | Returns the character frame's new height (in pixels) as an integer.

Remarks

This event occurs when an application changes the size of a character. This event is sent only to the clients of the character (applications that have loaded the character).

See Also

Move event

Back to contents

The Characters Object

Your client application can support one or more characters. In addition, you can share a character among several applications. Microsoft Agent defines the Characters object as a collection of characters. To access a character, load the character's data into the Characters collection and specify that that item in the collection uses the methods and properties supported for that character.

Characters Object Methods

The Characters object supports methods for accessing, loading, and unloading characters into its collection:

Character, Load, Unload

Character Method

Description
Returns a Character object in a Characters collection.
Syntax
agent.Characters.Character "CharacterID"
Remarks
You can use this method to access a Character object's methods and properties.

Note This method may be required for some programming languages that do not support collections. It is not required for VBScript or Visual Basic. For further information on specifying Character methods, see Character Object Methods.

Load Method

Description
Loads a character into the Characters collection.
Syntax
agent.Characters.Load "CharacterID", Provider
Part | Description
CharacterID | Required. A string value that you will use to refer to the character data to be loaded.
Provider Required. A variant data type that must be one of the following:

Filespec The local file location of the specified character's definition file.
URL The HTTP address for the character's definition file.
provider An alternate character definition provider (object).

Remarks

The Microsoft Agent Data Provider supports loading character data stored either as a single structured file (.ACS) with character data and animation data together or as separate character data (.ACF) and animation (.AAF) files. Use the single structured .ACS file to load a character that is stored on a local disk or network and accessed using a conventional file protocol (such as UNC pathnames). Use the separate .ACF and .AAF files when you want to load the animation files individually from a remote site where they are accessed using the HTTP protocol.
For .ACS files, using the Load method provides access a character's animations. For .ACF files, you also use the Get method to load animation data. The Load method does not support downloading .ACS files from an HTTP site.

Loading a character does not automatically display the character. Use the Show method first to make the character visible.

If you create an object reference and assign it to this method, it returns a Request object. If you use HTTP protocol, assigning a Request object to the Load method and checking its status in the RequestComplete event enables you to prevent your code from failing when the character data fails to load.

The Provider parameter also enables you to specify your own data provider (that would be loaded using a separate control) that can have its own methods for loading animation data. You only need to create a data provider object if you supply character data in special formats.

To load a character from the Microsoft Agent site, consult the character data page for the latest information on the location of the character files.

Unload Method

Description
Unloads the character data for the specified character.
Syntax
agent.Characters.Unload "CharacterID"
Remarks
Use this method when you no longer need a character, to free up memory used to store information about the character. If you access the character again, use the Load method.
This method does not return a Request object.

Character Object Methods

The server also exposes methods for each character in a Characters collection. The following methods are supported:

Activate, GestureAt, Get, Hide, Interrupt, MoveTo, Play, Show, Speak, Stop, StopAll, Wait

To use a method, reference the character in the collection. In VBScript and Visual Basic, you do this by specifying the ID for a character:

 Sub FormLoad

 'Load the genie character into the Characters collection
 Agent1.Characters.Load "Genie",
        "C:\Program Files\Microsoft Agent\Characters\Genie.acs"

 'Display the character
 Agent1.Characters("Genie").Show
 Agent1.Characters("Genie").Play "Greet"
 Agent1.Characters("Genie").Speak "Hello. "

 End Sub

To simplify the syntax of your code, you can define an object variable and set it to reference a character object in the Characters collection; then you can use your variable to reference methods or properties of the character. The following example demonstrates how you can do this using the Visual Basic Set statement:

 'Define a global object variable
 Dim Genie as Object

 Sub FormLoad

 'Load the genie character into the Characters collection
 Agent1.Characters.Load "Genie",
     "C:\Program Files\Microsoft Agent\Characters\Genie.acs"

 'Create a reference to the character
 Set Genie = Agent1.Characters("Genie")

 'Display the character
 Genie.Show

 'Get the Restpose animation
 Genie.Get "animation", "RestPose"

 'Make the character say Hello
 Genie.Speak "Hello."

 End Sub

In Visual Basic 5.0, you can also create your reference by declaring your variable as a Character object:

 Dim Genie as IAgentCtlCharacter

 Sub FormLoad

 'Load the genie character into the Characters collection
 Agent1.Characters.Load "Genie",
     "C:\Program Files\Microsoft Agent\Characters\Genie.acs"

 'Create a reference to the character
 Set Genie = Agent1.Characters("Genie")

 'Display the character
 Genie.Show

 End Sub

Declaring your object of type IAgentCtlCharacter enables early binding on the object, which results in better performance.

In VBScript, you cannot declare a reference as a particular type. However, you can simply declare the variable reference:

 <OBJECT
  classid="clsid:F5BE8BD2-7DE6-11D0-91FE-00C04FD701A5"
  CODEBASE = "http://activex.microsoft.com/controls/agent/MSagent.exe#VERSION=1,5,0,0"
  id=AgentCtl>

 </OBJECT>

 <SCRIPT LANGUAGE = VBScript>

 <!---

 Dim Genie

 SUB window_OnLoad

 \'Load the character
 AgentCtl.Characters.Load "Genie", _
  "http://agent.microsoft.com/characters/genie/genie.acf"

 'Create an object reference to the character in the collection
 set Genie= AgentCtl.Characters ("Genie")

 'Get the Showing state animation
 Genie.Get "state", "Showing"

 'Display the character
 Genie.Show

 'Get the RestPose animation
 Genie.Get "animation", "RestPose"

 'Make the character say Hello
 Genie.Speak "Hello."

 End Sub

 -->

 </SCRIPT>

Some programming languages do not support collections. However, you can access a Character object's methods with the Character method:

 agent.Characters.Character("CharacterID").method

In addition, you can also create a reference to the Character object to make your script code easier to follow:

 <OBJECT
  classid = "clsid:F5BE8BD2-7DE6-11D0-91FE-00C04FD701A5"
  CODEBASE = "http://activex.microsoft.com/controls/agent/MSagent.exe#VERSION=1,5,0,0"
  id=AgentCtl>

 </OBJECT>

 <SCRIPT LANGUAGE="JScript" FOR="window" EVENT="onLoad()">
 <!--

 //Load the character's data
 AgentCtl.Characters.Load ("Genie", _
      "http://agent.microsoft.com/characters/genie/genie.acf");

 //Create a reference to this object
 Genie = AgentCtl.Characters.Character("Genie");

 //Get the Showing state animation
 Genie.Get("state", "Showing");

 //Display the character
 Genie.Show();

 -->
 </SCRIPT>

Activate Method

Description
Sets the active client or character.
Syntax
agent.Characters ("CharacterID").Activate [State]
Part Description
State Optional. You can specify the following values for this parameter:

0 Not the active client.
1 The active client.
2 (Default) The topmost character.

Remarks

When multiple characters are visible, only one of the characters receives speech input at a time. Similarly, when multiple client applications share the same character, only one of the clients receives mouse input (for example, Microsoft Agent control click or drag events). The character set to receive mouse and speech input is the topmost character and the client that receives the input is the active client of that character. (The topmost character's window also appears at the top of the character windows z-order.) Typically, the user determines the topmost character by explicitly selecting the character. However, topmost activation also changes when a character is shown or hidden (the character becomes or is no longer topmost, respectively.)

You can also use this method to explicitly manage when your client receives input directed to the character such as when your application itself becomes active. For example, setting State to 2 makes the character topmost and your client receives all mouse and speech input events generated from user interaction with the character. Therefore, it also makes your client the input-active client of the character.

However, you can also set yourself to be the active client for a character without making the character topmost, by setting State to 1. This enables your client to receive input directed to that character when the character becomes topmost. Similarly, you can set your client to not be the active client (not to receive input) when the character becomes topmost, by setting State to 0.

Avoid calling this method directly after a Show method. Show automatically sets the input-active client. When the character is hidden, the Activate call may fail if it gets processed before the Show method completes.

If you call this method to a function, it returns a Boolean value that indicates whether the method succeeded. Attempting to call this method with the State parameter set to 2 when the specified character is hidden will fail. Similarly, if you set State to 0 and your application is the only client, this call fails because a character must always have a topmost client.

    Dim Genie as Object

    Sub FormLoad()

    Agent1.Characters.Load "Genie", _
        "C:\Program Files\Microsoft Agent\Characters\Genie.acs"

    Set Genie = Agent1.Characters ("Genie")

    If (Genie. Activate = True) Then
        'I'm active

    Else
        'I must be hidden or something

    End If

    End Sub
See Also
ActivateInput event, DeactivateInput event

GestureAt Method

Description
Plays the gesturing animation for the specified character at the specified location.
Syntax
agent.Characters ("CharacterID").GestureAt X,Y
Part | Description
X,Y | Required. An integer value that indicates the horizontal (X) screen coordinate and vertical (Y) screen coordinate to which the character will gesture. These coordinates must be specified in pixels.

Remarks

The server automatically plays the appropriate animation to gesture toward the specified location. The coordinates are always relative to the screen origin (upper left).
If you declare an object reference and set it to this method, it returns a Request object. In addition, if the associated animation has not been loaded on the local machine, the server sets the Request object's Status property to "failed" with an appropriate error number. Therefore, if you are using the HTTP protocol to access character animation data, use the Get method to load the Gesturing state animations before calling the GestureAt method.

Get Method

Description
Retrieves specified animation data for the specified character.
Syntax
agent.Characters ("CharacterID").Get Type, Name, [Queue]
Part Description
Type Required. A string value that indicates the animation data type to load.

"Animation" A character's animation data.

"State" A character's state data.

"WaveFile" A character's audio (for spoken output) file.

Name Required. A string that indicates the name of the animation type.

"name" The name of the animation or state.

For animations, the name is based on that defined for the character when saved using the Microsoft Agent Character Editor.

For states, the following values can be used:

"Gesturing" To get all Gesturing state animations.

"GesturingDown" To get the GesturingDown animation.

"GesturingLeft" To get the GesturingLeft animation.

"GesturingRight" To get the GesturingRight animation.

"GesturingUp" To get the GesturingUp animation.

"Hiding" To get the Hiding state animation.

"Hearing" To get the Hearing state animation.

"Idling" To get all Idling state animations.

"IdlingLevel1" To get all IdlingLevel1 animations.

"IdlingLevel2" To get all IdlingLevel2 animations.

"IdlingLevel3" To get all IdlingLevel3 animations.

"Listening" To get the Listening state animation.

"Moving" To get all Moving state animations.

"MovingDown" To get the MovingDown animation.

"MovingLeft" To get the MovingLeft animation.

"MovingRight" To get the MovingRight animation.

"MovingUp" To get the MovingUp animation.

"Showing" To get the Showing state animation.

"Speaking" To get the Speaking state animation.

You can specify multiple animations and states by separating them with commas. However, you cannot mix types in the same Get statement.

"URL or filespec" The specification for the sound (.WAV or .LWV) file. If the specification is not complete, it is interpreted as being relative to the specification used in the Load method.

Queue Optional. A Boolean expression specifying whether the server queues the Get request.

True (Default) Queues the Get request. Any animation request that follows the Get request (for the same character) waits until the animation data is loaded.

False Does not queue the Get request.

Remarks

You need to use the Get method only to retrieve animation data using the HTTP protocol.
If you declare an object reference and set it to this method, it returns a Request object. If the associated animation fails to load, the server sets the Request object's Status property to "failed" with an appropriate error number. You can use the RequestComplete event to check the status and determine what action to take.

Animation or sound data retrieved with the Get method is stored in the browser's cache. Subsequent calls will check the cache, and if the animation data is already there, the control loads the data directly from the cache. Once loaded, the animation or sound data can be played with the Play or Speak methods.

See Also
Load method

Hide Method

Description
Hides the specified character.
Syntax
agent.Characters ("CharacterID").Hide [Fast]
Part Description
Fast Optional. A Boolean value that indicates whether to skip the animation associated with the character's Hiding state True Does not play the Hiding animation.
False (Default) Plays the Hiding animation.

Remarks

The server queues the actions of the Hide method in the character's queue, so you can use it to hide the character after a sequence of other animations. You can play the action immediately by using the Stop method before calling this method.
If you declare an object reference and set it to this method, it returns a Request object. In addition, if the associated Hiding animation has not been loaded and you have not specified the Fast parameter as True, the server sets the Request object Status property to "failed" with an appropriate error number. Therefore, if you are using the HTTP protocol to access character or animation data, use the Get method and specify the Hiding state to load the animation before calling the Hide method. Hiding a character can also result in triggering the ActivateInput event of another client.

Note Hidden characters cannot access the audio channel. The server will pass back a failure status in the RequestComplete event if you generate an animation request and the character is hidden.

See Also

Show method

Interrupt Method

Description
Interrupts the animation for the specified character.
Syntax
agent.Characters ("CharacterID").Interrupt Request
Remarks
You can use this to sync up animation between characters. For example, if another character is in a looping animation, this method will stop the loop and move to the next animation in the character's queue. You cannot interrupt a character animation that you are not using (that you have not loaded).
To specify the request parameter, you must create a variable and assign the animation request you want to interrupt:
 Dim GenieRequest as Object
 Dim RobbyRequest as Object
 Dim Genie as Object
 Dim Robby as Object

 Sub FormLoad()

   MyAgent1.Characters.Load "Genie", _
       "C:\Program Files\Microsoft Agent\Characters\Genie.acs"

   MyAgent1.Characters.Load "Robby", _
       "C:\Program Files\Microsoft Agent\Characters\Robby.acs"

   Set Genie = MyAgent1.Characters ("Genie")
   Set Robby = MyAgent1.Characters ("Robby")

   Genie.Show

   Genie.Speak "Just a moment"

   Set GenieRequest = Genie.Play ("Processing")

   Robby.Show
   Robby.Play "confused"
   Robby.Speak "Hey, Genie. What are you doing?"
   Robby.Interrupt GenieRequest

   Genie.Speak "I was just checking on something."

 End Sub

You cannot interrupt the animation of the same character you specify in this method because the server queues the Interrupt method in that character's animation queue. Therefore, you can only use Interrupt to halt the animation of another character you have loaded.

If you declare an object reference and set it to this method, it returns a Request object.

Note Interrupt does not flush the character's queue; it halts the existing animation and moves on to the next animation in the character's queue. To halt and flush a character's queue, use the Stop method.

See Also

Stop method

MoveTo Method

Description
Moves the specified character to the specified location.
Syntax
agent.Characters ("CharacterID").MoveTo X,Y, [Speed]
Part | Description
X,Y | Required. An integer value that indicates the left edge (X) and top edge (Y) of the animation frame. Express these coordinates in pixels.
Speed | Optional. A Long integer value specifying in milliseconds how quickly the character's frame moves. The default value is 1000. Specifying zero (0) moves the frame without playing an animation.

Remarks

The server automatically plays the appropriate animation assigned to the Moving states. The location of a character is based on the upper left corner of its frame.
If you declare an object variable and set it to this method, it returns a Request object. In addition, if the associated animation has not been loaded on the local machine, the server sets the Request object's Status property to "failed" with an appropriate error number. Therefore, if you are using the HTTP protocol to access character or animation data, use the Get method to load the Moving state animations before calling the MoveTo method.

Even if the animation is not loaded, the server still moves the frame.

Note If you call MoveTo with a non-zero value before the character is shown, it will return a failure status if you assigned it a Request object, because the non-zero value indicates that you are attempting to play an animation when the character is not visible.

Play Method

Description
Plays the specified animation for the specified character.
Syntax
agent.Characters ("CharacterID").Play "AnimationName"
Part | Description
AnimationName | Required. A string that specifies the name of an animation sequence.

Remarks

An animation's name is defined when the character is compiled with the Microsoft Agent Character Editor. Before playing the specified animation, the server attempts to play the Return animation for the previous animation, if one has been assigned.
When accessing a character's animations using a conventional file protocol, you can simply use the Play method specifying the name of the animation. However, if you are using the HTTP protocol to access character animation data, use the Get method to load the animation before calling the Play method.

For more information, see the Get method.

To simplify your syntax, you can declare an object reference and set it to reference the Character object in the Characters collection and use the reference as part of your Play statements:

 Dim Genie
 Agent1.Characters.Load "Genie", _
  "http://agent.microsoft.com/characters/genie/genie.acf"

 Set Genie = Agent1.Characters ("Genie")

 Genie.Get "state", "Showing"
 Genie.Show

 Genie.Get "animation", "Greet, GreetReturn"
 Genie.Play "Greet"
 Genie.Speak "Hello."

If you declare an object reference and set it to this method, it returns a Request object. In addition, if you specify an animation that is not loaded or if the character has not been successfully loaded, the server sets the Status property of Request object to "failed" with an appropriate error number. However, if the animation does not exist and the character's data has already been successfully loaded, the server raises an error.

The Play method does not make the character visible. If the character is not visible, the server plays the animation invisibly, and sets the Status property of the Request object.

Show Method

Description
Makes the specified character visible and plays its associated Showing animation.
Syntax
agent.Characters ("CharacterID").Show [Fast]
Part | Description
Fast | Optional. A Boolean expression specifying whether the server plays the Showing animation. True Skips the Showing state animation. False (Default) Does not skip the Showing state animation.

Remarks

If you declare an object reference and set it to this method, it returns a Request object. In addition, if the associated Showing animation has not been loaded and you have not specified the Fast parameter as True, the server sets the Request object's Status property to "failed" with an appropriate error number. Therefore, if you are using the HTTP protocol to access character animation data, use the Get method to load the Showing state animation before calling the Show method.
Avoid setting the Fast parameter to True without first playing an animation beforehand; otherwise, the character frame may display with no image. In particular, note that if you call MoveTo when the character is not visible, it does not play any animation. Therefore, if you call the Show method with Fast set to True, no image will display. Similarly, if you call Hide then Show with Fast set to True, there will be no visible image.
See Also
Hide method

Speak Method

Description
Speaks the specified text for the specified character.
Syntax
agent.Characters ("CharacterID").Speak [Text], [ Url]
Part | Description
Text | Optional. A string that specifies what the character says.
Url | Optional. A string expression specifying the specification for an audio file. The specification can be a file specification or URL.

Remarks

Although the Text and Url parameters are optional, one of them must be supplied. To use this method with a character configured to speak only in its word balloon or using a text-to-speech (TTS) engine, simply provide the Text parameter. Include a space between words to define appropriate word breaks in the word balloon, even for languages that do not traditionally include spaces.

You can also include vertical bar characters (|) in the Text parameter to designate alternative strings, so that the server randomly chooses a different string each time it processes the method.

Character support of TTS output is defined when the character is compiled using the Microsoft Agent Character Editor. To generate TTS output, a compatible TTS engine must already be installed before calling this method. For further information, see Accessing Speech Support for Microsoft Agent.

If you use recorded sound-file output for the character, specify the file's location in the Url parameter. However, if you are using the HTTP protocol to access character or animation data, use the Get method to load the animation before calling the Speak method. When doing so, you still use the Text parameter to specify the words that appear in the character's word balloon. However, if you specify a linguistically enhanced sound file (.LWV) for the Url parameter and do not specify text for the word balloon, the Text parameter uses the text stored in the file.

You can also vary parameters of the speech output with special tags that you include in the Text parameter. For more information, see Speech Output Tags. If you declare an object reference and set it to this method, it returns a Request object. In addition, if the file has not been loaded, the server sets the Request object's Status property to "failed" with an appropriate error code number.

The Speak method uses the last action played to determine which speaking animation to play. For example, if you preceded the Speak command with a Play "GestureRight", the server will play GestureRight and then the GestureRight speaking animation.

If you call Speak and the audio channel is busy, the character's audio output will not be heard, but the text will display in the word balloon.

Note The word balloon's Enabled property must also be True for text to display.

Note If you are using a character that you did not compile, check the balloon FontName and CharSet properties for the character to determine whether they are appropriate for your locale. You may need to set these values before using the Speak method to ensure appropriate text display within the word balloon.

Stop Method

Description
Stops the animation for the specified character.
Syntax
agent.Characters ("CharacterID").Stop [Request]
Part | Description
Request | Optional. To use this parameter, set the Request object in your code.

Remarks

If you don't set the Request parameter, the server stops all animations for the character, including queued Get calls, and clears its animation queue unless the character is currently playing its Hiding or Showing animation. This method does not stop non-queued Get calls.

To stop a specific animation or Get call, declare an object variable and assign your animation request to that variable:

 Dim MyRequest
 Dim Genie

 Agent1.Characters.Load "Genie", _
  "http://agent.microsoft.com/characters/genie/genie.acf"

 Set Genie = Agent1.Characters ("Genie")

 Genie.Get "state", "Showing"
 Genie.Get "animation", "Greet, GreetReturn"

 Genie.Show

 'This animation will never play
 Set MyRequest = Genie.Play ("Greet")

 Genie.Stop MyRequest

This method will not generate a Request object.

See Also
StopAll method

StopAll Method

Description
Stops all animation requests or specified types of requests for the specified character.
Syntax
agent.Characters ("CharacterID").StopAll [Type]
Part Description
Type Optional. To use this parameter you can use any of the following values. You can also specify multiple types by separating them with commas.

"Get" To stop all queued Get requests.
"NonQueuedGet" To stop all non-queued Get requests (Get method with Queue parameter set to False).
"Move" To stop all queued MoveTo requests.
"Play" To stop all queued Play requests.
"Speak" To stop all queued Speak requests.

Remarks

If you don't set the Type parameter, the server stops all animations for the character, including queued and non-queued Get requests, and clears its animation queue. It also stops playing a character's Hiding or Showing animation. This method will not generate a Request object.
See Also
Stop method

Wait Method

Description
Causes the animation queue for the specified character to wait until the specified animation request completes.
Syntax
agent.Characters ("CharacterID").Wait Request
Part | Description
Request | A Request object specifying a particular animation. To set this parameter you must assign the Request object variable in your code.

Remarks

Use this method only when you support multiple (simultaneous) characters and are trying to sequence the interaction of characters (as a single client). (For a single character, each animation request is played sequentially--after the previous request completes.) If you have two characters and you want a character's animation request to wait until the other character's animation completes, set the Wait method to the other character's animation Request object, as shown in the following example:
 Dim GenieRequest
 Dim RobbyRequest
 Dim Genie
 Dim Robby

 Sub window_Onload

 Agent1.Characters.Load "Genie", _
  "http://agent.microsoft.com/characters/genie/genie.acf"
 Agent1.Characters.Load "Robby", _
  "http://agent.microsoft.com/characters/robby/robby.acf"

 Set Genie = Agent1.Characters("Genie")
 Set Robby = Agent1.Characters("Robby")

 Genie.Get "State", "Showing"
 Robby.Get "State", "Showing"

 Genie.Get "Animation", "Announce, AnnounceReturn, Pleased, _
  PleasedReturn"

 Robby.Get "Animation", "Confused, ConfusedReturn, Sad, SadReturn"

 Set Genie = Agent1.Characters ("Genie")
 Set Robby = Agent1.Characters ("Robby")

   Genie.MoveTo 100,100
 Genie.Show

 Robby.MoveTo 250,100
 Robby.Show

 Genie.Play "Announce"
 Set GenieRequest = Genie.Speak ("Why did the chicken cross the road?")

 Robby.Wait GenieRequest
 Robby.Play "Confused"
 Set RobbyRequest = Robby.Speak ("I don't know. Why did the chicken _
  cross the road?")

 Genie.Wait RobbyRequest
 Genie.Play "Pleased"
 Set GenieRequest = Genie.Speak ("To get to the other side.")

 Robby.Wait GenieRequest
 Robby.Play "Sad"
 Robby.Speak "I never should have asked."

 End Sub

Character Object Properties

The Character object exposes the following read-only properties:

Description, ExtraData, HasOtherClients, Height, IdleOn, Left, MoveCause, Name, Pitch, SoundEffectsOn, Speed, Top, VisibilityCause, Visible, Width

Note that the Height, Left, Top, and Width properties of a character differ from those that may be supported by the programming environment for the placement of the control. The Character properties apply to the visible presentation of a character, not the location of the Microsoft Agent control.

As with Character object methods, you can access a character's properties using the Characters collection, or simplify your syntax by declaring an object variable and setting it to a character in the collection. In the following example, Test1 and Test2 will be set to the same value:

 Dim Genie
 Dim MyRequest

 Sub window_Onload

 Agent.Characters.Load "Genie", _
  "http://agent.microsoft.com/characters/genie/genie.acf"

 Set Genie = Agent.Characters("Genie")

 Genie.MoveTo 15,15
 MyRequest = Genie.Show()

 End Sub

 Sub Agent_RequestComplete(ByVal Request)

 If Request = MyRequest Then
  Test1 = Agent.Characters("Genie").Top
  Test2 = Genie.Top
  MsgBox "Test 1 is " + cstr(Test1) + "and Test 2 is " + cstr(Test2)
 End If

 End Sub

Because the server loads a character asynchronously, ensure that the character has been loaded before querying its properties, for example, using the RequestComplete event. Otherwise, the properties may return incorrect values.

Description Property

Description
Returns or sets a string that specifies the description for the specified character.
Syntax
agent. Characters("CharacterID").Description
Remarks
The default value for the Description property for a character is defined when the character is compiled with the Microsoft Agent Character Editor.

Note The Description property setting is optional and may not be supplied for all characters.

ExtraData Property

Description
Returns a string that specifies additional data stored as part of the character.
Syntax
agent.Characters ("CharacterID").ExtraData

Remarks

The default value for the ExtraData property for a character is defined when the character is compiled with the Microsoft Agent Character Editor. It cannot be changed or specified at run time.

Note The ExtraData property setting is optional and may not be supplied for all characters.

HasOtherClients Property

Description
Returns whether the specified character is in use by other applications.
Syntax
agent.Characters ("CharacterID").HasOtherClients [= value]
Return | Description
True | The character has other clients.
False | The character does not have other clients.

Remarks

You can use this property to determine whether your application is the only or last client of the character, when more than one application is sharing (has loaded) the same character.

Height Property

Description
Returns or sets the height of the specified character's frame.
Syntax
agent.Characters ("CharacterID").Height [= value]
Part | Description
value | A Long integer that specifies the character's frame height.

Remarks

The Height property is always expressed in pixels, relative to screen coordinates (upper left).
Even though the character appears in an irregularly shaped region window, the height of the character is based on the external dimensions of the rectangular animation frame used when the character was compiled with the Microsoft Agent Character Editor.

IdleOn Property

Description
Returns or sets a Boolean value that determines whether the server manages the specified character's Idling state animations.
Syntax
agent.Characters ("CharacterID").IdleOn [=boolean]
Part | Description
True | Server idle processing is enabled. The character's Idling animations are automatically played.
False | Server idle processing is disabled. The character's Idling animations are not automatically played.

Remarks

The server automatically sets a time-out after the last animation played for a character. When this timer's interval is complete, the server begins the Idling state for a character, playing its associated Idling animations at regular intervals. The default value for the IdleOn property is True, meaning that the server manages the character's Idling state. If you want to manage the Idling state animations yourself, set the property to False.

Left Property

Description
Returns or sets the left edge of the specified character's frame.
Syntax
agent.Characters ("CharacterID").Left [= value]
Part | Description
value | A Long integer that specifies the left edge of the character's frame.

Remarks

The Left property is always expressed in pixels, relative to screen origin (upper left).
Even though the character appears in an irregularly shaped region window, the location of the character is based on the external dimensions of the rectangular animation frame used when the character was compiled with the Microsoft Agent Character Editor.

MoveCause Property

Description
Returns an integer value that specifies what caused the character's last move.
Syntax
agent.Characters ("CharacterID").MoveCause

Return | Description
0 | The character has not been moved.
1 | The user moved the character.
2 | Your application moved the character.
3 | Another client application moved the character.

Remarks

You can use this property to determine what caused the character to move, when more than one application is sharing (has loaded) the same character. These values are the same as those returned by the Move event.
See Also
Move event, MoveTo method

Name Property

Description
Returns or sets a string that specifies the default name of the specified character.
Syntax
agent.Characters ("CharacterID").Name
Remarks
The default value for the Name property for a character is defined when the character is compiled with the Microsoft Agent Character Editor. The server uses the Name property to automatically create commands for hiding and showing a character.

Pitch Property

Description
Returns a Long integer for the specified character's current speech output (TTS) pitch setting.
Syntax
agent.Characters ("CharacterID").Pitch
Remarks
This property applies only to characters configured for TTS output. If the speech synthesis (TTS) engine is not enabled or installed, or the character does not support TTS output, this property returns zero (0).
Although your application cannot write this value, you can include Pit (pitch) tags in your output text that will temporarily increase the pitch for a particular utterance. For further information, see Speech Output Tags.

SoundEffectsOn Property

Description
Returns or sets whether sound effects are enabled for your character.
Syntax
agent.Characters ("CharacterID").SoundEffectsOn [=boolean]
Part | Description
boolean | A Boolean expression specifying whether sound effects are enabled. True Sound effects are enabled. False Sound effects are disabled.

Remarks

This property determines whether sound effects included as a part of a character's animations will play when an animation plays.
See Also
SoundEffects property

Speed Property

Description
Returns a Long integer that specifies the speed of the character's speech output.
Syntax
agent.Characters ("CharacterID").Speed
Remarks
This property returns the current speaking output speed setting for the character. For characters using TTS output, the property returns the actual TTS output for the character. If TTS is not enabled or the character does not support TTS output, the setting reflects the user setting for output speed.

Although your application cannot write this value, you can include Spd (speed) tags in your output text that will temporarily speed up the output for a particular utterance. For further information, see Speech Output Tags.

Top Property

Description
Returns or sets the top edge of the specified character's frame.
Syntax
agent.Characters ("CharacterID").Top [= value]
Part | Description
value | A Long integer that specifies the character's top edge.

Remarks

The Top property is always expressed in pixels, relative to screen origin (upper left).
Even though the character appears in an irregularly shaped region window, the location of the character is based on the external dimensions of the rectangular animation frame used when the character was compiled with the Microsoft Agent Character Editor.

Use the MoveTo method to change the character's location.

VisibilityCause Property

Description
Returns an integer value that specifies what caused the character's visible state.
Syntax
agent.Characters ("CharacterID").VisibilityCause
Return | Description
0 | The character has not been shown.
1 | The user hid the character.
2 | The user showed the character.
3 | Your application hid the character.
4 | Your application showed the character.
5 | Another client application hid the character.
6 | Another client application showed the character.

Remarks

To You can use this property to determine what caused the character to move when more than one application is sharing (has loaded) the same character. These values are the same as those returned by the Show and Hide events.
See Also
Hide event, Show event, Hide method, Show method

Visible Property

Description
Returns a Boolean indicating whether the character is visible.
Syntax
agent.Characters ("CharacterID").Visible
Return | Description
True | The character is displayed.
False | The character is hidden (not visible).

Remarks

To make a character visible or hidden, use the Show or Hide methods.

Width Property

Description
Returns or sets the width of the frame for the specified character.
Syntax
agent.Characters ("CharacterID").Width [= value]
Part | Description
value | A Long integer that specifies the character's frame width.

Remarks

The Width property is always expressed in pixels.
Even though the character appears in an irregularly shaped region window, the location of the character is based on the external dimensions of the rectangular animation frame used when the character was compiled with the Microsoft Agent Character Editor.

The Commands Collection Object

The Microsoft Agent server maintains a list of commands that are currently available to the user. This list includes commands that the server defines for general interaction (such as Hide and Microsoft Agent Properties), the list of available (but non-input-active) clients, and the commands defined by the current active client. The first two sets of commands are global commands; that is, they are available at any time, regardless of the input-active client. Client-defined commands are available only when that client is input-active.

Each client application can define a collection of commands called the Commands collection. To add a command to the collection, use the Add or Insert method. Although you can specify a command's properties with separate statements, for optimum code performance, specify all of a command's properties in the Add or Insert method statement. For each command in the collection, you can determine whether user access to the command appears in the character's pop-up menu, in the Commands Window, in both, or in neither. For example, if you want a command to appear on the pop-up menu for the character, set the command's Caption and Visible properties. To display the command in the Commands Window, set the command's Caption and Voice properties.

A user can access the individual commands in your Commands collection only when your client application is input-active. Therefore, you'll typically want to set the Caption and Voice properties for the Commands collection object as well as for the commands in the collection, which places an entry for your Commands collection in a character's pop-up menu and in the Commands Window. When the user switches to your client by choosing its entry, the server automatically makes your client input-active and makes the commands in its collection available. This enables the server to present and accept only the commands that apply to the current input-active client's context. It also serves to avoid command-name collisions between clients.

When a character's pop-up menu displays, changes to the properties of a Commands collection or the commands in its collection do not appear until the user redisplays the menu. However, the Commands Window does display changes as they happen.

Commands Object Methods

The server supports the following methods for the Commands collection object:

Add, Command, Insert, Remove, RemoveAll

Add Method

Description
Adds a Command object to the Commands collection.
Syntax
agent.Characters ("CharacterID").Commands.Add Name, Caption, Voice, _
Enabled, Visible
Part | Description
Name | Required. A string value corresponding to the ID you assign for the command.
Caption | Optional. A string value corresponding to the name that will appear in the character's pop-up menu and in the Commands Window when the client application is input-active. For more information, see the Command object's Caption property.
Voice | Optional. A string value corresponding to the words or phrase to be used by the speech engine for recognizing this command. For more information on formatting alternatives for the string, see the Command object's Voice property.
Enabled | Optional. A Boolean value indicating whether the command is enabled. The default value is True. For more information, see the Command object's Enabled property.
Visible | Optional. A Boolean value indicating whether the command is visible in the character's pop-up menu for the character when the client application is input-active. The default value is True. For more information, see the Command object's Visible property.

Remarks

The value of a Command object's Name property must be unique within its Commands collection. You must remove a Command before you can create a new Command with the same Name property setting. Attempting to create a Command with a Name property that already exists raises an error.
See Also
Insert method, Remove method, RemoveAll method

Command Method

Description
Returns a Command object in a Commands collection.
Syntax
agent.Characters ("CharacterID").Commands.Command "Name"
Remarks
You can use this method to access a Command object's properties.

Note This method may be required for some programming languages. It is not required for VBScript or Visual Basic. For further information on specifying Command methods, see Command Object Properties.

Insert Method

Description
Inserts a Command object in the Commands collection.
Syntax
agent.Characters ("CharacterID").Commands.Insert Name, RefName, Before, _
Caption, Voice, Enabled, Visible
Part | Description
Name | Required. A string value corresponding to the ID you assign to the Command.
RefName | Required. A string value corresponding to the name (ID) of the command just above or below where you want to insert the new command.
Before | Optional. A Boolean value indicating whether to insert the new command before the command specified by RefName. True (Default). The new command will be inserted before the referenced command. False The new command will be inserted after the referenced command.
Caption | Optional. A string value corresponding to the name that will appear in the character's pop-up menu and in the Commands Window when the client application is input-active. For more information, see the Command object's Caption property.
Voice | Optional. A string value corresponding to the words or phrase to be used by the speech engine for recognizing this command. For more information on formatting alternatives for the string, see the Command object's Voice property.
Enabled | Optional. A Boolean value indicating whether the command is enabled. The default value is True. For more information, see the Command object's Enabled property.
Visible | Optional. A Boolean value indicating whether the command is visible in the Commands Window when the client application is input-active. The default value is True. For more information, see the Command object's Visible property.

Remarks

The value of a Command object's Name property must be unique within its Commands collection. You must remove a Command before you can create a new Command with the same Name property setting. Attempting to create a Command with a Name property that already exists raises an error.
See Also
Add method, Remove method, RemoveAll method

Remove Method

Description
Removes a Command object from the Commands collection.
Syntax
agent.Characters ("CharacterID").Commands.Remove Name
Part | Description
Name | Required. A string value corresponding to the ID for the command.

Remarks

When a Command object is removed from the collection, it no longer appears when the character's pop-up menu is displayed or in the Commands Window when your client application is input-active.
See Also
RemoveAll method

RemoveAll Method

Description
Removes all Command objects from the Commands collection.
Syntax
agent.Characters ("CharacterID").Commands.RemoveAll
Remarks
When a Command object is removed from the collection, it no longer appears when the character's pop-up menu is displayed or in the Commands Window when your client application is input-active.
See Also
Remove method

Commands Object Properties

The server supports the following properties for the Commands collection:

Caption, Count, Visible, Voice

An entry for the Commands collection can appear in both the pop-up menu and the Commands Window for a character. To make this entry appear, set its Caption property. The following table summarizes how the properties of a Commands object affect the entry's presentation:

Caption Property | Voice Property | Visible Property | Appears in Character's Pop-up Menu | Appears in Commands Window
Yes | Yes | True | Yes | Yes
Yes | No | True | Yes | No
Yes | Yes | False | No | Yes
Yes | No | False | No | No
No | Yes | True | No | No*
No | Yes | False | No | No*
No | No | True | No | No
No | No | False | No | No
*The command is still voice-accessible. If the client is input-active and has commands in its collection, "(command undefined)" appears in the Commands Window.

Caption Property

Description
Determines the text displayed for the Commands object in the character's pop-up menu and in the Commands Window.
Syntax
agent.Characters ("CharacterID").Commands.Caption [=string]
Part | Description
string | A string expression that evaluates to the text displayed as the caption.

Remarks

If you define commands for a Commands collection that have their Caption, Enabled, and Voice properties set, you would typically also define Caption and Voice settings for the associated Commands collection. If the Commands collection has no Voice or no Caption setting and is currently input-active, but the commands in its collection have Caption and Voice settings, the commands appear in the Commands Window tree view under "(undefined command)" when your client application becomes input-active.

Count Property

Description
Returns a Long integer (read-only property) that specifies the count of Command objects in the Commands collection.
Syntax
agent.Characters ("CharacterID").Commands.Count
Remarks
Count includes only the number of Command objects you define in your Commands collection. Server or other client entries are not included.

Visible Property

Description
Returns or sets a value that determines whether your Commands collection's caption appears in the character's pop-up menu.
Syntax
agent.Characters ("CharacterID").Commands.Visible [= boolean]
Part | Description
boolean | A Boolean expression specifying whether your Commands object appears in the character's pop-up menu. True The Caption for your Commands collection appears. False The Caption for your Commands collection does not appear.
Remarks
This property must be set to True for commands in your collection to appear in the pop-up menu when your application is input-active.

Voice Property

Description
Returns or sets the text that is passed to the speech engine (for recognition).
Syntax
agent.Characters ("CharacterID").Commands.Voice [= string]
Part | Description
string | A string value corresponding to the words or phrase to be used by the speech engine for recognizing this command.

Remarks

If you do not supply this parameter, the caption for your Commands object will not appear in the Commands Window.

The string expression you supply can include square bracket characters ([ ]) to indicate optional words and vertical bar characters, (|) to indicate alternative strings. Alternates must be enclosed in parentheses. For example, "(hello [there] | hi)" tells the speech engine to accept "hello," "hello there," or "hi" for the command. Remember to include appropriate spaces between the text that's in brackets or parentheses and the text that's not in brackets or parentheses.

You can also use an ellipsis (…) to support word spotting, that is, telling the speech recognition engine to ignore words spoken in this position in the phrase (sometimes called garbage words). When you use ellipses, the speech engine recognizes only specific words in the string regardless of when spoken with adjacent words or phrases. For example, if you set this property to "…check mail…", the speech recognition engine will match phrases like "please check mail" or "check mail please" to this command. Ellipses can be used anywhere within a string. However, be careful using this technique as voice settings with ellipses may increase the potential of unwanted matches.

When defining the word grammar for your command, always make sure that you include at least one word that is required; that is, avoid supplying only optional words. In addition, make sure that the word includes only pronounceable words and letters. For numbers, it is better to spell out the word than use the numeric representation. Also, omit any punctuation or symbols. For example, instead of "the #1 $10 pizza!", use "the number one ten dollar pizza". Including non-pronounceable characters or symbols for one command may cause the speech engine to fail to compile the grammar for all your commands. Finally, make your voice parameter as distinct as reasonably possible from other voice commands you define. The greater the similarity between the voice grammar for commands, the more likely the speech engine will make a recognition error. You can also use the confidence scores to better distinguish between two commands that may have similar or similar-sounding voice grammar.

Note The operation of this property depends on the state of the server's speech recognition property. For example, if speech recognition is disabled or not installed, this parameter has no effect. If speech recognition is enabled during a session, however, the command will become accessible when its client application is input-active.

The Command Object

A Command object is an item in a Commands collection. The server provides the user access to your Command objects when your client application becomes input-active.

To access the property of a Command object, you reference it in its collection using its Name property. In VBScript and Visual Basic you can use the Name property directly:

 agent.Characters("CharacterID").Commands("Name").property [= value]

For programming languages that don't support collections, use the Command method:

 agent.Characters("CharacterID").Commands.Command("Name").property [= value]

You can also reference a Command object by creating a reference to it. In Visual Basic, declare an object variable and use the Set statement to create the reference:

 Dim Cmd1 as Object
 ...
 Set Cmd1 = Agent.Characters("MyCharacterID").Commands("SampleCommand")
 ...
 Cmd1.Enabled = True

In Visual Basic 5.0, you can also declare the object as type IAgentCtlCommand and create the reference. This convention enables early binding, which results in better performance:

 Dim Cmd1 as IAgentCtlCommand
 ...
 Set Cmd1 = Agent.Characters("MyCharacterID").Commands("SampleCommand")
 ...
 Cmd1.Enabled = True

In VBScript, you can declare a reference as a particular type, but you can still declare the variable and set it to the Command in the collection:

 Dim Cmd1
 ...
 Set Cmd1 = Agent.Characters("MyCharacterID").Commands("SampleCommand")
 ...
 Cmd1.Enabled = True

A command may appear in either the character's pop-up menu and the Commands Window, or in both. To appear in the pop-up menu it must have a caption and have the Visible property set to True. In addition, its Commands collection object's Visible property must also be set to True. To appear in the Commands Window, a Command must have its Caption and Voice properties set. Note that a character's pop-up menu entries do not change while the menu displays. If you add or remove commands or change their properties while the character's pop-up menu is displayed, the menu displays those changes whenever the user next displays it. However, the Commands Window dynamically reflects any changes you make.

The following table summarizes how the properties of a Command affect its presentation:

Caption Property | Voice Property | Visible Property | Enabled Property | Appears in Character's Pop-up Menu | Appears in Commands Window
Yes | Yes | True | True | Normal | Yes
Yes | Yes | True | False | Disabled | No
Yes | Yes | False | True | Does not appear | Yes
Yes | Yes | False | False | Does not appear | No
Yes | No | True | True | Normal | No
Yes | No | True | False | Disabled | No
Yes | No | False | True | Does not appear | No
Yes | No | False | False | Does not appear | No
No | Yes | True | True | Does not appear | No*
No | Yes | True | False | Does not appear | No
No | Yes | False | True | Does not appear | No*
No | Yes | False | False | Does not appear | No
No | No | True | True | Does not appear | No
No | No | True | False | Does not appear | No
No | No | False | True | Does not appear | No
No | No | False | False | Does not appear | No
*The command is still voice-accessible.

Generally, if you define commands with Voice settings, you also define Caption and Voice settings for its associated Commands collection. If a Commands collection has no Voice or no Caption setting and is currently input-active, but its Command objects do have Caption and Voice settings and their Enabled properties are True, the Command objects appear in the Commands Window tree view under "(undefined command)" when your client application becomes input-active.

When the server receives input for one of your commands, it sends a Command event, and passes back the name of the Command as an attribute of the UserInput object. You can then use conditional statements to match and process the Command.

Command Object Properties

The following Command properties are supported:

Caption, Confidence, ConfidenceText, Enabled, Visible, Voice

Caption Property

Description
Determines the text displayed for a Command in the specified character's pop-up menu and the Commands Window.
Syntax
agent.Characters ("CharacterID").Commands("name").Caption [= string]
Part | Description
string | A string expression that evaluates to the text displayed as the caption for the Command.

Confidence Property

Description
Returns or sets whether the client's ConfidenceText appears in the Listening Tip.
Syntax
agent.Characters ("CharacterID").Commands("name"). Confidence [= number]
Part | Description
number | A numeric expression that evaluates to a Long integer that identifies confidence value for the Command.

Remarks

If the returned confidence value of the best match (UserInput.Confidence) does not exceed value you set for the Confidence property, the text supplied in ConfidenceText is displayed in the Listening Tip.

ConfidenceText Property

Description
Returns or sets the client's ConfidenceText that appears in the Listening Tip.
Syntax
agent.Characters ("CharacterID").Commands("name"). ConfidenceText [= string]
Part | Description
string | A string expression that evaluates to the text for the ConfidenceText for the Command.

Remarks

When the returned confidence value of the best match (UserInput.Confidence) does not exceed the Confidence setting, the server displays the text supplied in ConfidenceText in the Listening Tip.

Enabled Property

Description
Returns or sets whether the Command is enabled in the specified character's pop-up menu.
Syntax
agent.Characters ("CharacterID").Commands("name").Enabled [= boolean]
Part | Description
boolean | A Boolean expression specifying whether the Command is enabled. True The Command is enabled. False The Command is disabled.

Remarks

If the Enabled property is set to True, the Command object's caption appears as normal text in the character's pop-up menu when the client application is input-active. If the Enabled property is False, the caption appears as unavailable (disabled) text. A disabled Command is also not accessible for voice input.

Visible Property

Description
Returns or sets whether the Command is visible in the character's pop-up menu.
Syntax
agent.Characters ("CharacterID").Commands("name").Visible [= boolean]
Part | Description
boolean | A Boolean expression specifying whether the Command's caption appears in the character's pop-up menu. True (Default) The caption appears. False The caption does not appear.

Remarks

Set this property to False when you want to include voice input for your own interfaces without having them appear in the pop-up menu for the character. If you set a Command object's Caption property to the empty string (""), the caption text will not appear in the pop-up menu (for example, as a blank line), regardless of its Visible property setting.
The Visible property setting of a Command object's parent Commands collection does not affect the Visible property setting of the Command.

Voice Property

Description
Returns or sets the text that is passed to the speech engine grammar (for recognition) for matching this Command for the character.
Syntax
agent.Characters ("CharacterID").Commands ("name").Voice [= string]
Part | Description
string | A string value corresponding to the words or phrase to be used by the speech engine for recognizing this Command.

Remarks

If you do not supply this parameter, the caption for your Commands object will not appear in the Commands Window. If you specify a Voice parameter but not a Caption, the command will not appear in the Commands Window, but it will be voice-accessible when the client application becomes input-active.
Your string expression can include square bracket characters ([ ]) to indicate optional words and vertical bar characters (|) to indicate alternative strings. Alternates must be enclosed in parentheses. For example, "(hello [there] | hi)" tells the speech engine to accept "hello," "hello there," or "hi" for the command. Remember to include appropriate spaces between the text that's in brackets or parentheses and the text that's not in brackets or parentheses.

You can also use an ellipsis (…) to support word spotting, that is, telling the speech recognition engine to ignore words spoken in this position in the phrase (sometimes called garbage words). Therefore, the speech engine recognizes only specific words in the string regardless of when spoken with adjacent words or phrases. For example, if you set this property to "…check mail…", the speech recognition engine will match phrases like "please check mail" or "check mail please" to this command. Ellipses can be used anywhere within a string. However, be careful using this technique as it may increase the potential of unwanted matches.

When defining the word grammar for your command, always make sure that you include at least one word that is required; that is, avoid supplying only optional words. In addition, make sure that the word includes only pronounceable words and letters. For numbers, it is better to spell out the word rather than using the numeric representation. Also, omit any punctuation or symbols. For example, instead of "the #1 $10 pizza!", use "the number one ten dollar pizza". Including non-pronounceable characters or symbols for one command may cause the speech engine to fail to compile the grammar for all your commands. Finally, make your voice parameter as distinct as reasonably possible from other voice commands you define. The greater the similarity between the voice grammar for commands, the more likely the speech engine will make a recognition error. You can also use the confidence scores to better distinguish between two commands that may have similar or similar-sounding voice grammar.

Note The operation of this property depends on the state of the server's speech recognition property. For example, if speech recognition is disabled or not installed, this property has no effect.

The Balloon Object

Microsoft Agent supports textual captioning of spoken output using a cartoon word balloon. A character's initial word balloon window defaults are defined and compiled in the Microsoft Agent Character Editor. Once running, the word balloon's Enabled and Font properties may be overridden by the user. If a user changes the word balloon's properties, they affect all characters. You can access the properties for a character's word balloon through the Balloon object, which is a child of the Characters collection.

The Balloon object supports the following properties:

BackColor, BorderColor, CharSet, CharsPerLine, Enabled, FontName, FontBold, FontItalic, FontSize, FontStrikeThru, FontUnderline, ForeColor, NumberOfLines, Visible

BackColor Property

Description
Returns the background color currently displayed in the word balloon window for the specified character.
Syntax
agent.Characters ("CharacterID").Balloon.BackColor
Remarks
The valid range for a normal RGB color is 0 to 16,777,215 (&HFFFFFF). The high byte of a number in this range equals 0; the lower 3 bytes, from least to most significant byte, determine the amount of red, green, and blue, respectively. The red, green, and blue components are each represented by a number between 0 and 255 (&HFF).

BorderColor Property

Description
Returns the border color currently displayed for the word balloon window for the specified character.
Syntax
agent.Characters ("CharacterID").Balloon.BorderColor
Remarks
The valid range for a normal RGB color is 0 to 16,777,215 (&HFFFFFF). The high byte of a number in this range equals 0; the lower 3 bytes, from least to most significant byte, determine the amount of red, green, and blue, respectively. The red, green, and blue components are each represented by a number between 0 and 255 (&HFF).

CharSet Property

Description
Returns or sets the character set used for the font displayed in the specified character's word balloon.
Syntax
agent.Characters ("CharacterID").Balloon.CharSet = [ value]
Part Description
value A integer value that specifies the character set used by the font. The following are some common settings for value:

0 Standard Windows® characters (ANSI).
1 Default character set.
2 The symbol character set.
128 Double-byte character set (DBCS) unique to the Japanese version of Windows.
129 Double-byte character set (DBCS) unique to the Korean version of Windows.
134 Double-byte character set (DBCS) unique to the Simplified Chinese version of Windows.
136 Double-byte character set (DBCS) unique to the Traditional Chinese version of Windows.
255 Extended characters normally displayed by DOS applications.

For other character set values, consult the Microsoft Win32® documentation.

Remarks

The default value for the character set of a character's word balloon is set in the Microsoft Agent Character Editor. In addition, the user can override the character-set settings for all characters in the Microsoft Agent Property Sheet.

Note If you are using a character that you did not compile, check the FontName and CharSet properties for the character to determine whether they are appropriate for your locale. You may need to set these values before using the Speak method to ensure appropriate text display within the word balloon.

See Also
FontName property

CharsPerLine Property

Description
Returns the characters per line supported for the word balloon for the specified character.
Syntax
agent.Characters ("CharacterID").Balloon.CharsPerLine
Remarks
The CharsPerLine property returns the average number of characters (letters) being displayed in the word balloon as a Long integer value.

Enabled Property

Description
Returns whether the word balloon is enabled for the specified character.
Syntax
agent.Characters ("CharacterID").Balloon.Enabled
Remarks
The Enabled property returns a Boolean value specifying whether the balloon is enabled by the user. True indicates the Balloon is enabled. False indicates it is not enabled (displayed).
The word balloon can also be disabled as part of a character's definition when the character is compiled in the Microsoft Agent Character Editor. If a character is defined to not support the word balloon, this property will always be False for the character.

FontName Property

Description
Returns or sets the font used in the word balloon for the specified character.
Syntax
agent.Characters ("CharacterID").Balloon.FontName [= font]
Part | Description
font | A string value corresponding to the font's name.

Remarks

The FontName property defines the font used to display text in the word balloon window as a string. The default value for the font settings of a character's word balloon are set in the Microsoft Agent Character Editor. In addition, the user can override font settings for all characters in the Microsoft Agent Property Sheet.

Note If you are using a character that you did not compile, check the FontName and CharSet properties for the character to determine whether they are appropriate for your locale. You may need to set these values before using the Speak method to ensure appropriate text display within the word balloon.

See Also
CharSet property

FontBold Property

Description
Returns the font style currently displayed in the word balloon window for the specified character.
Syntax
agent.Characters ("CharacterID").Balloon.FontBold
Remarks
The FontBold property returns a Boolean value specifying whether the font is bold. True indicates the font is bold. False indicates the font is not bold.

The default value for the font settings of a character's word balloon are set in the Microsoft Agent Character Editor. In addition, the user can override font settings for all characters in the Microsoft Agent Property Sheet.

FontItalic Property

Description
Returns the font style currently displayed in the word balloon window for the specified character.
Syntax
agent.Characters ("CharacterID").Balloon.FontItalic
Remarks
The FontItalic property returns a Boolean value specifying whether the font is italic. True indicates the font is italic. False indicates the font is not italic.

The default value for the font settings of a character's word balloon are set in the Microsoft Agent Character Editor. In addition, the user can override font settings for all characters in the Microsoft Agent Property Sheet.

FontSize Property

Description
Returns or sets the font size supported for the word balloon for the specified character.
Syntax
agent.Characters ("CharacterID").Balloon.FontSize [= points]
Part | Description
points | A Long integer value specifying the font size in points.

Remarks

The FontSize property returns a Long integer value specifying the current font size in points. The maximum value for FontSize is 2160 points.

The default value for the font settings of a character's word balloon are set in the Microsoft Agent Character Editor. In addition, the user can override font settings for all characters in the Microsoft Agent Property Sheet.

FontStrikeThru Property

Description
Returns the font style currently displayed in the word balloon window for the specified character.
Syntax
agent.Characters ("CharacterID").Balloon.FontStrikeThru
Remarks
The FontStrikeThru property returns a Boolean value specifying whether the font uses the strikethrough effect. True indicates the font uses the strikethrough effect. False indicates the font does not use the strikethrough effect.

The default value for the font settings of a character's word balloon are set in the Microsoft Agent Character Editor. In addition, the user can override font settings for all characters in the Microsoft Agent Property Sheet.

FontUnderline Property

Description
Returns the font style currently displayed in the word balloon window for the specified character.
Syntax
agent.Characters ("CharacterID").Balloon.FontUnderline
Remarks
The FontUnderline property returns a Boolean value specifying whether the font is underlined. True indicates the font is underlined. False indicates the font is not underlined.

The default value for the font settings of a character's word balloon are set in the Microsoft Agent Character Editor. In addition, the user can override font settings for all characters in the Microsoft Agent Property Sheet.

ForeColor Property

Description
Returns the foreground color currently displayed in the word balloon window for the specified character.
Syntax
agent.Characters ("CharacterID").Balloon.ForeColor
Remarks
The ForeColor property returns a value that specifies the color of text in the word balloon. The valid range for a normal RGB color is 0 to 16,777,215 (&HFFFFFF). The high byte of a number in this range equals 0; the lower 3 bytes, from least to most significant byte, determine the amount of red, green, and blue, respectively. The red, green, and blue components are each represented by a number between 0 and 255 (&HFF).

NumberOfLines Property

Description
Returns the number of lines supported for the word balloon for the specified character.
Syntax
agent.Characters ("CharacterID").Balloon.NumberOfLines
Remarks
The NumberOfLines property returns the number of lines of text as a Long integer value.

Visible Property

Description
Returns or sets the visible setting for the word balloon for the specified character.
Syntax
agent.Characters ("CharacterID").Balloon.Visible [=boolean]
Part Description
boolean A Boolean expression specifying whether the word balloon is visible.

True The balloon is visible.
False The balloon is hidden.

Remarks

If you attempt to set this property while the character is speaking, moving, or being dragged, the property setting does not take effect until the preceding operation is completed. Calling the Speak method automatically makes the balloon visible, setting the Visible property to True. If the character's balloon AutoHide property is enabled, the balloon is automatically hidden after the output text is spoken. Clicking or dragging a character that is not currently speaking also automatically hides the balloon even if its AutoHide property is disabled. (A character's word-balloon AutoHide property can only be set in the Microsoft Agent Character Editor. The property is not exposed in the API.)

Back to contents

The AudioOutput Object

The AudioOutput object provides access to audio output properties maintained by the server. The properties are read-only, but the user can change them in the Microsoft Agent Property Sheet.

Enabled, SoundEffects

Enabled Property

Description
Returns a Boolean indicating whether audio (spoken) output is enabled.
Syntax
agent.AudioOutput.Enabled
Remarks
When the Enabled property returns True, the Speak method produces audio output. When it returns False, it means that speech output is not installed or has been disabled by the user. Only the user can set this property value.

SoundEffects Property

Description
Returns a Boolean indicating whether sound effects (.WAV) files configured as part of a character's actions will play.
Syntax
agent.AudioOutput.SoundEffects
Remarks
When the SoundEffects property returns True, sound effects included in a character's definition will be played. When False, the sound effects will not be played. Only the user can set this property value.

Back to contents

The SpeechInput Object

The SpeechInput object provides access to the speech input properties maintained by the server. The properties are read-only for client applications, but the user can change them in the Microsoft Agent Property Sheet. The server returns values only if a compatible speech engine has been installed and is enabled.

SpeechInput Properties

If a speech recognition engine is installed and enabled, accessing these properties will start the speech engine:

Enabled, Engine, HotKey, Installed, Language, ListeningTip

Enabled Property

Description
Returns a Boolean value indicating whether speech input is enabled.
Syntax
agent.SpeechInput.Enabled
Remarks
The Enabled property reflects the state of the speech recognition engine set in the Engine property. Values for other SpeechInput properties do not change when Enabled is set to False. Querying this property raises an error if no speech engine has been installed.

Note The user can override this property.

Engine Property

Description
Returns or sets the speech recognition engine that is currently selected for input.
Syntax
agent.SpeechInput.Engine [=modeID]
Part | Description
modeID | A string expression specifying the mode ID of the speech engine.

Remarks

The Engine property takes a string value specifying the mode ID of the speech engine. Querying this property raises an error if Installed or Enabled is False.

Note The user can override this property.

HotKey Property

Description
Returns a string that specifies the user's current setting for the push-to-talk hot key.
Syntax
agent.SpeechInput.HotKey
Remarks
Querying this property raises an error if Installed or Enabled is False.

Installed Property

Description
Returns a Boolean that indicates whether a compatible speech engine is installed.
Syntax
agent.SpeechInput.Installed
Remarks
If no compatible speech engine has been installed, this property returns False. However, querying any other SpeechInput properties raises an error. Therefore, check this property before checking the values of the SpeechInput or CommandsWindow objects.

Language Property

Description
Returns a string that specifies what language is configured for speech input.
Syntax
agent.SpeechInput.Language
Remarks
This property value is set based on the selected speech recognition engine set in the Engine property. Querying this property raises an error if Installed or Enabled is False.

ListeningTip Property

Description
Returns a Boolean indicating whether the server displays the Listening Tip.
Syntax
agent.SpeechInput.ListeningTip
Remarks
When ListeningTip returns True, the server displays the tip window when the user presses the push-to-talk hot key. Querying this property raises an error if Installed or Enabled is False.

Back to contents

The CommandsWindow Object

The CommandsWindow object provides access to properties of the Commands Window. The Commands Window is a shared resource primarily designed to enable users to view voice-enabled commands. If speech recognition is disabled, the Commands Window is also disabled, but you can still read its property settings. If no speech engine is installed or if speech is disabled, querying for the CommandsWindow properties raises an error.

CommandsWindow Properties

Height, Left, Top, Visible, Width

Height Property

Description
Returns an integer value specifying the current height, in pixels, of the Commands Window.
Syntax
agent.CommandsWindow.Height
Remarks
The server displays the Commands Window based on the position and size set by the user. Querying this property raises an error if no speech engine has been installed.

Left Property

Description
Returns an integer value specifying the left edge, in pixels, of the Commands Window.
Syntax
agent.CommandsWindow.Left
Remarks
The server displays the Commands Window based on the position and size set by the user. Querying this property raises an error if no speech engine has been installed.

Top Property

Description
Returns an integer value specifying the top edge, in pixels, of the Commands Window.
Syntax
agent.CommandsWindow.Top
Remarks
The server displays the Commands Window based on the position and size set by the user. Querying this property raises an error if no speech engine has been installed.

Visible Property

Description
Returns or sets whether the Commands Window is visible (open).
Syntax
agent.CommandsWindow.Visible [=boolean]
Part | Description
boolean | A Boolean expression specifying whether the Commands Window is visible. True The window is visible. False The window is hidden (closed).

Remarks

The server displays the window based on the position and size set by the user. Querying this property raises an error if no speech engine has been installed.

Note The user can override this property.

Width Property

Description
Returns an integer value specifying the width, in pixels, of the Commands Window.
Syntax
agent.CommandsWindow.Width
Remarks
The server displays the Commands Window based on the position and size set by the user. Querying this property raises an error if no speech engine has been installed.

Back to contents

The PropertySheet Object

The PropertySheet object provides several properties you can use if you want to manipulate the character relative to the Microsoft Agent Property Sheet:

Height, Left, Page, Top, Visible, Width

If you query Height, Left, Top, and Width properties before the property sheet has ever been shown, their values return as zero (0). Once shown, these properties return the last position and size of the window (relative to your current screen resolution).

Height Property

Description
Returns an integer value specifying the current height, in pixels, of the Microsoft Agent Property Sheet window.
Syntax
agent.PropertySheet.Height
Remarks
The server displays the window based on the location set by the user.

Left Property

Description
Returns an integer value specifying the current left edge, in pixels, of the Microsoft Agent Property Sheet window.
Syntax
agent.PropertySheet.Left
Remarks
The server displays the window based on the location set by the user.

Page Property

Description
Returns or sets the page displayed in the Microsoft Agent Property Sheet window.
Syntax
agent.PropertySheet.Page [= string]
Part | Description
string | A string expression with one of the following values. "Speech" Displays the Speech Recognition page. "Output" Displays the Output page. "Copyright" Displays the Copyright page.

Remarks

If no speech engine is installed, setting Page to "Speech" has no effect. Also, the window's Visible property must be set to True for the user to see the page.

Note The user can override this property.

Top Property

Description
Returns an integer value specifying the current top edge, in pixels, of the Microsoft Agent Property Sheet window.
Syntax
agent.PropertySheet.Top
Remarks
The server displays the window based on the location set by the user.

Visible Property

Description
Returns or sets whether the Microsoft Agent property sheet window is visible (open).
Syntax
agent.PropertySheet.Visible [=boolean]
Part | Description
boolean | A Boolean expression specifying whether the window is visible. True The window is visible. False The window is hidden (closed).

Remarks

The server displays the window based on the location and size set by the user.

Note The user can override this property.

Width Property

Description
Returns an integer value specifying the current width, in pixels, of the Microsoft Agent Property Sheet window.
Syntax
agent.PropertySheet.Width
Remarks
The server displays the window based on the location set by the user.

Back to contents


Designing Characters for Microsoft Agent

ActiveX™ Technology for Interactive Software Agents

August 1997
Microsoft Corporation

Contents

Abstract

Characters

Animations

Agent States

Appendix

Note: This document is provided for informational purposes only and Microsoft makes no warranties, either expressed or implied, in this document. The entire risk of the use or the results of this document remains with the user.

Information in this document is subject to change without notice. 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.

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. Microsoft, MS, MS-DOS, Windows, Windows NT, and the Windows logo are either registered trademarks or trademarks of Microsoft Corporation in the U.S. and/or other countries. Other product and company names mentioned herein may be the trademarks of their respective owners.

Abstract

This document provides information that can help you design and develop a character for use with Microsoft Agent. It includes conceptual and technical information on character, image, and animation design; the size, use of color, and types of images you need to create; suggested animations; speaking animations; and agent states. The Appendix describes effective animation principles you can use to create visually convincing animated characters.

This is advanced-level information intended for experienced developers. More information on the Agent Character Editor and designing and developing characters is provided in Using the Microsoft Agent Character Editor.

Back to contents

Characters

Human communication is fundamentally social. Microsoft Agent allows you to leverage this aspect of interaction using animated characters. How you design a character can have a dramatic effect on its success.

When designing a character, first consider the profile of your target audience and what appeals to them as well as what tasks they do. Similarly, consider how well your character's design matches its purpose in addition to the application it supports. A "dog" character might work well for a retrieval or security application, but not for a financial management application.

Also think about your character's basic personality type: dominant or submissive, emotional or reserved, sophisticated or down-to-earth; or perhaps you want to adapt its personality based on user interaction. For example, you can provide a control that enables a user to adjust whether the character volunteers more information or waits to be asked. The name you supply for your character can infer a particular type of personality. For example, "Max" and "Milton" may convey very different personalities. The Microsoft Agent Character Editor enables you to set your character's name and include a short description. These attributes can be queried at run time.

In addition, decide whether you plan to use a synthetic voice (using a text-to-speech engine) or recorded voice (.WAV file). This decision may depend on the type of character you use, the languages you plan to support, and what you want the character to be able to say. For example, a synthesized voice enables your character to speak almost anything. Programming what your character will say is easy and quick: You just supply the text the character will speak. However, using a computer-generated speech engine requires some extra overhead for initial installation and will be language-specific. Further, most synthesized voices sound computer-generated. It may be difficult to simulate a voice that matches your character, particularly if you use a character that already has an established identity or one that has a very distinctive voice. In such a case, you may want to use recorded audio files for your output. Microsoft Agent also supports lip-syncing for recorded audio output. Although audio files provide a natural voice and are easier to implement in other languages, they must be copied or downloaded to local machines. Recorded audio files also limit your character to the vocabulary contained in them.

You can also decide to use the word balloon for output and the default settings for the balloon's font and color. Note, however, that the user can change the font and color attributes. In addition, you cannot assume that the word balloon's state remains constant because the user can turn balloon off.

Back to contents

Animations

A character's animations reflect its personality and behavior. The number and types of animations you create for a character depend on what your character does and how it responds to different situations.

Like traditional animations, digital animations involve creating a series of slightly differing images that, when displayed sequentially, provide the illusion of action. Creating high-quality animation images may require a skilled animator, but the style and presentation of the character you create also affect quality. Two-dimensional characters with simple shapes and features can sometimes be as effective as (or more effective than) highly rendered characters. It is not necessary to create a realistic image to portray an effective character. Many popular cartoon characters are not realistic in their presentation, yet they are effective because the animator understands how to convey action and emotion. The Appendix provides general information about fundamental animation design principles.

Frames

Each animation you create for a Microsoft Agent character is composed of a timed sequence of frames. Each frame in the animation is composed of one or more bitmap images. Images can be as small as you need them or as large as the frame itself.

Animation details such as eye blinking or finger movement can be included as additional images for the frame. You can overlay several images to create a composite, and vary their position in the layers. This technique enables you to reuse images in multiple frames and vary the details that change. For example, if you want to have a character wave its hand, for each frame you could use a base image with everything but the hand and overlay the base image with a different hand image. Similarly, if you want to make the character blink, you can overlay a different set of eyes over a base image for each frame. Images can also be offset from the base image. However, only the part of the image that exists within the frame's size will be displayed.

You can have as many frames in an animation as you wish; however, a typical animation averages about 14 frames so that it plays for no more than 6 seconds. This modest length of time ensures that your character appears responsive to user input. In addition, the greater the number of frames, the larger your animation file. For downloaded Web-based characters, keep the size of your animation file as small as possible while still providing a reasonably-sized set of frames, so that the character's animation does not appear jerky.

Image Design

You can use any graphics or animation tool to create images for animation frames, provided that you store the final images in the Windows® bitmap (.BMP) format. When the images are created, use the Microsoft Agent Character Editor to assemble, sequence, and time the images, supply other character information, and compile all the information into a final character file.

Character images must be designed to a 256-color palette, preserving the 20 standard Windows system colors in their standard position in the palette (the first ten and last ten positions). That means your character's color palette can use the standard system colors and up to 236 other colors. When defining your palette, include any props your character uses in the animation. If your character's palette places colors in the system color positions, those character colors will be overwritten with the system colors when Microsoft Agent creates the palette.

The larger the number of colors you use in a character's color palette, the greater the possibility that part of your character's colors may get remapped for systems configured to an 8-bit (256) color setting. Consider also the palette usage of the application in which the character will be used. It's best to avoid having the character remap the colors of its host application and vice-versa. Similarly, if you plan to support multiple characters displayed at the same time, you'll probably want to maintain a consistent palette for those characters. You might consider using only the standard system colors in your character if you target users with an 8-bit color configuration. However, this still may not prevent remapping of your character's color if another application extensively redefines the color palette. On systems set to higher color resolutions, color palette remapping should not be a problem because the system manages the color palettes automatically.

Using a larger number of colors in an image can also increase the overall size of your animation file. The number of colors and frequency of variation may determine how well your character file compresses. For example, a two-dimensional character that uses only a few colors will compress better than a three-dimensional, shaded character.

You must use the same color palette for your entire character file. You cannot change the palette for different animations. If you attempt to support 8-bit color configurations, consider using the same palette for your application and any other characters you plan to support.

The 11th position in the palette is defined by default as the transparency (or alpha) color, although you can also set the color using the Microsoft Agent Character Editor. The Microsoft Agent animation services render transparent any pixels in this color, so use the color in your images only where you want transparency.

Carefully consider the shape of your character, because it can affect animation performance. To display the character, the animation services create a region window based on the overall image. Small irregular areas often require more region data and may reduce the animation performance of your character. Therefore, when possible, avoid gaps or single-pixel elements and details.

Avoid anti-aliasing the outside edge of your character. Although anti-aliasing is a good technique to reduce jagged edges, it is based on adjacent colors. Because your character may appear on top of a variety of colors, anti-aliasing the outside edge may make your character appear poorly against other backgrounds. However, you can use anti-aliasing on the inside details of your character without encountering this problem.

Frame Size

Frame size should typically be no larger than 128 x 128 pixels. Although characters can be larger or smaller in either dimension, the Microsoft Agent Character Editor uses this as its display size, and scales character images if you define a larger frame size. The 128 x 128 frame size makes reasonable tradeoffs with the space the character will occupy on the screen. Your application can scale a character at run time.

Frame Duration

You can use the Microsoft Agent Character Editor to set how long each frame of animation will display before moving to the next frame. Set the duration of each frame to at least 10 hundredths of a second (10 frames per second); anything less might not be perceptible on some systems. You can also set the duration longer, but avoid unnatural pauses in the action.

The Microsoft Agent Character Editor also supports branching from one frame in an animation to another, based on probability percentages that you supply. For any given frame, you can define up to three different branches. Branching enables you to create animations that vary when they are played and animations that loop. However, be careful when using branching as it may create problems when trying to play one animation after another. For example, if you play a looping or branching animation, it could continue indefinitely unless you use a Stop method. If you are uncertain, avoid branching.

Frames that don't have images and are set to zero duration do not appear when included in an animation. You can use this feature to create frames that support branching without being visible. However, a frame that does not have images yet has a duration greater than zero will be displayed. Therefore, avoid including empty frames in your animation, because the user may not be able to distinguish an empty frame from when the character is hidden.

Frame Transition

When designing an animation, consider how to smoothly transition from and to the animation. For example, if you create an animation in which the character gestures right, and another in which the character gestures left, you want the character to animate smoothly from one position to the other. Although you could build this into either animation, a better solution is to define a neutral or transitional position from which the character starts and returns. Animating to the neutral position can be incorporated as part of each animation or as a separate animation. In the Microsoft Agent Character Editor, you can specify a complementary Return animation for each animation for your character. The Return animation should typically be no more than 2-4 frames so the character can quickly transition to the neutral position.

For example, using the "gesturing right, then gesturing left" scenario, you can create a GestureRight animation, starting with a frame where the character appears in a neutral position, and add frames with images that extend the character's hand to the right. Then create its Return animation: a complementary animation with images that return the character to its neutral position. You can assign this as the Return animation for the GestureRight animation. Next, create the GestureLeft animation that starts from the neutral position and extends the character's arm to the left. Finally, create a complementary Return animation for this animation as well. A Return animation typically begins with an image that follows the last image of the preceding animation.

Starting and returning to the same neutral position, either within an animation or by using a Return animation, enables you to play any animation in any order. The Microsoft Agent animation services automatically play your designated Return animation in many situations. For example, the services play the designated Return animation before playing your character's Idling state animations. It is a good idea to define and assign Return animations if your animations do not already end in the neutral position.

If you want to provide your own transitions between specific animations; for example, because you always play them in a well-defined order, you can avoid defining Return animations. However, it is still a good idea to begin and end the sequence of animations from the neutral position.

Suggested Animations

The following table lists the animations defined for the Microsoft Agent sample characters and can be used as a guide for designing your own characters. How you plan to use a character determines the names and number of animations you support for a character.

An asterisk after an animation indicates a speaking animation that includes mouth overlay images for the last frame of the animation.

Animation | Example of Use | Example Animation
Acknowledge | When the character acknowledges the user's request. | Character nods or flashes "OK" hand gesture. Note that this animation should return the character to its neutral position.
Alert* | When the character is waiting for instructions, typically played after the user turns on listening mode. | Character faces front, breathing, blinking occasionally, but clearly awaiting instruction.
AlertReturn | When the character completes coming to the alert position. | Character returns to its neutral position.
Announce* | When the character has found information for the user. | Character gestures by raising eyebrows and hand or opens an envelope.
AnnounceReturn | When the character completes telling the user about the information it has found. | Character returns to its neutral position.
Appearing | When the character starts up or returns after being summoned. | Character pops up in a puff of smoke, beams in, or walks on-screen.
Confused* | When the character doesn't understand what to do. | Character scratches head.
ConfusedReturn | When the character returns from the Confused animation. | Character returns to neutral position.
Congratulate* | When the character or user completes a task (a stronger form of the Acknowledge animation.) | Character performs congratulatory gesture, conveys "YES!"
CongratulateReturn | When the character completes a Congratulate animation. | Character returns to neutral position.
Decline* | When the character cannot do or declines the user's request. | Character shakes head, conveys "no can do."
DeclineReturn | When the character completes the Decline animation. | Character returns to neutral position.
DontRecognize* | When the character didn't recognize the user's request. | Character holds hand to ear.
DontRecognizeReturn | When the character completes the DontRecognize animation. | Character returns to neutral position.
Explain* | When the character explains something to the user. | Character gestures as if explaining something.
ExplainReturn | When the character completes the Explain animation. | Character returns to neutral position.
GestureDown* | When the character needs to point to something below it. | Character points down.
GestureDownReturn | When the character completes gesturing down. | Character returns to neutral position.
GestureLeft* | When the character needs to point to something at its left. | Character points with left hand.
GestureLeftReturn | When the character is finished gesturing left. | Character returns to neutral position.
GestureRight* | When the character needs to point to something at its right. | Character points with right hand or morphs into an arrow pointing right.
GestureRightReturn | When the character is finished gesturing right. | Character returns to neutral position.
GestureUp* | When the character needs to point to something above it. | Character points up.
GestureUpReturn | When the character is finished gesturing up. | Character returns to neutral position.
GetAttention | When the character needs to notify the user about something important. | Character waves hands or jumps up and down.
GetAttentionReturn | When the character completes the GetAttention animation. | Character returns to neutral position.
GlanceDown | When character wants to subtly direct attention below. | Character looks briefly downward and returns to neutral position.
GlanceLeft | When character wants to subtly direct attention to the left. | Character looks briefly to the left and returns to neutral position.
GlanceRight | When character wants to subtly direct attention to the right. | Character looks briefly to the right and returns to neutral position.
GlanceUp | When character wants to subtly direct attention upward. | Character looks briefly upward and returns to neutral position.
Greet* | When the user starts up the system. | Character smiles and waves.
GreetReturn | When the character completes the greeting. | Character returns to neutral position.
Hear | When the character hears the start of an spoken utterance (actively listening). | Character leans forward and nods, or turns head showing response to speech input.
Hide | When the user dismisses the character. | Character removes self from screen.
Idle1 | When the character has no task and the user is not interacting with the character. | Character blinks or looks around, remaining in or returning to the neutral position.
Idle2 | When the character has been idle for some time. | Character yawns or reads magazine remaining in or returning to the neutral position.
Idle3 | When the character has been idle for a long time. | Character sleeps or puts on headphones to listen to music.
Idle3Return | When the character transitions out of the Idling Level 3 state. | Character returns to its neutral position.
LookDown | When the character needs to look down. | Character looks down.
LookDownReturn | When the character completes looking down. | Character returns to its neutral position.
LookLeft | When the character needs to look left. | Character looks to the left.
LookLeftReturn | When the character completes looking left. | Character returns to its neutral position.
LookRight | When the character needs to look right. | Character looks to the right.
LookRightReturn | When the character completes looking right. | Character returns to its neutral position.
LookUp | When the character needs to look up. | Character looks up.
LookUpReturn | When the character completes looking up. | Character returns to its neutral position.
Leaving* | When the user dismisses the character. | Character removes self from screen.
MoveDown | When the character prepares to move down. | Character transitions to a walking/flying down position.
MoveDownReturn | When the character completes moving down. | Character returns to its neutral position.
MoveLeft | When the character prepares to move left. | Character transitions to a walking/flying left position.
MoveLeftReturn | When the character completes moving left. | Character returns to its neutral position.
MoveRight | When the character prepares to move right. | Character transitions to a walking/flying right position.
MoveRightReturn | When the character completes moving right. | Character returns to its neutral position.
MoveUp | When the character prepares to move up. | Character transitions to a walking/flying up position.
MoveUpReturn | When the character completes moving up. | Character returns to its neutral position.
Pleased* | When the character is pleased with the user's request or choice. | Character smiles.
PleasedReturn | When the character completes the Pleased animation. | Character returns to neutral position.
Processing | When the character is busy processing a task. | Character scribbles on pad of paper. Note: This animation loops to some intermediate frame that occurs after the character moves to an appropriate position.
ProcessingReturn | When the character completes the Processing animation. | Character returns to its neutral position.
Read* | When the character reads something to the user. | Character displays book or paper, reads, and looks back at user.
ReadContinued* | When the character reads further to the user. | Character reads again, then looks back at user.
ReadReturn | When the character completes the Read animation. | Character returns to its neutral position.
Reading | When the character reads something but cannot accept input. | Character reads from a piece of paper. (Note: This animation loops.)
ReadingReturn | When the character completes the Reading animation. | Character returns to its neutral position.
RestPose* | When the character speaks from its neutral position. | Character stands with relaxed but attentive posture.
Sad* | When the character is disappointed with the user's choice. | Character frowns or looks disappointed.
SadReturn | When the character completes the Sad animation. | Character returns to neutral position.
Searching | When character is searching for user-specified information. | Character shuffles through file drawer or other container looking for something. Note: This animation loops to some intermediate frame(s) that occurs after the character moves to an appropriate position.
SearchingReturn | When the character completes the Search animation. | Character returns to its neutral position.
Show | When the character starts up or returns after being summoned. | Character pops up in a puff of smoke, beams in, or walks on-screen.
StartListening* | When the character is listening. | Character puts hand to ear.
StartListeningReturn | When the character completes the StartListening animation. | Character returns to neutral position.
StopListening* | When the character stops listening. | Character puts hands over ears.
StopListeningReturn | When the character completes the animation. | Character returns to neutral position.
Suggest* | When the character has a tip or suggestion for the user. | Light bulb appears next to character.
SuggestReturn | When the character completes the Suggest animation. | Character returns to its neutral position.
Surprised* | When the character is surprised by the user's action or choice. | Character widens eyes, opens mouth.
SurprisedReturn | When the character completes the Surprised animation. | Character returns to its neutral position.
Think* | When the character is thinking about something. | Character looks up and holds hand on head.
ThinkReturn | When the character completes the Think animation. | Character returns to its neutral position.
Uncertain* | When the character needs the user to confirm a request. | Character looks quizzical, conveys ("are you sure?")
UncertainReturn | When the character completes the Uncertain animation. | Character returns to its neutral position.
Wave* | When the user chooses to shut down the server or system. | Character waves goodbye or hello.
WaveReturn | When the character completes the Wave animation. | Character returns to its neutral position.
Write* | When the character is listening for instructions from the user. | Character displays paper, writes, and looks back at user.
WriteContinued* | When the character continues listening for instructions from the user. | Character writes on a piece of paper and looks back at user.
WriteReturn | When the character completes the Write animation. | Character returns to its neutral position.
Writing | When the character writes out information for the user. | Character writes on piece of paper. Note: This animation loops.
WritingReturn | When the character completes the Writing animation. | Character returns to its neutral position.

Speaking Animation

Supply mouth images for each animation during which you want the character to be able to speak, unless your character's design has no animated mouth or indication of spoken output. Mouth images allow your character to lip-sync to spoken output. You define mouth images separately and as Windows bitmap files. They must match the same color palette as the other images in your animation.

The Microsoft Agent animation services display mouth animation frames on top of the last frame of an animation, also called the speaking frame of the animation. For example, when the character speaks in the GestureRight animation, the animation services overlay the mouth animation frames on the last frame of GestureRight. A character cannot speak while animating, so you only supply mouth images for the last frame of an animation. In addition, the speaking frame must be the end frame of an animation, so a character cannot speak in a looping animation.

Typically, you would supply the mouth images in the same size as the frame (and base image), but include only the area that animates as part of the mouth movement, and render the rest of the image in the transparent color. Design the image so that it matches the image in the speaking frame when overlaid on top of it. To have it match correctly, it is likely you'll need to create a separate set of mouth images for every animation in which the character speaks.

A mouth image can include more than the mouth itself, such as the chin or other parts of the character's body while it speaks. However, if you move a hand or leg, note that it may appear to move randomly because the mouth overlay displayed will be based on the current phoneme of a spoken phrase. In addition, the server clips the mouth image to the speaking frame image's outline. Design your mouth overlay image to remain within the outline of its base speaking frame image, because the server uses the base image to create the window boundary for the character.

The Microsoft Agent Character Editor enables you to define seven basic mouth positions that correspond to common phoneme mouth shapes shown in the following table:

Mouth Animation Images

Mouth Position | Sample Image | Representation
Closed | [DES3112C 884 bytes ] | Normal mouth closed shape. Also used for phonemes such as "m" as in "mom," "b" as in "bob," "f" as in "fife."
Open-wide 1 | [DES3112D 899 bytes ] | Mouth is slightly open, at full width. Used for phonemes such as "g" as in "gag," "l" as in "lull," "ear" as in "hear."
Open-wide 2 | [DES3112E 912 bytes ] | Mouth is partially open, at full width. Used for phonemes such as "n" as in "nun," "d" as in "dad," "t" as in "tot."
Open-wide 3 | [DES3112F 920 bytes ] | Mouth is open, at full width. Used for phonemes such as "u" as in "hut," "ea" as in "head," "ur" as in "hurt."
Open-wide 4 | [DES3112G 926 bytes ] | Mouth is completely open, at full width. Used for phonemes such as "a" as in "hat," "ow" as in "how."
Open-medium | [DES3112H 903 bytes ] | Mouth is open at half width. Used for phonemes such as "oy" as in "ahoy," "o" as in "hot."
Open-narrow | [DES3112I 897 bytes ] | Mouth is open at narrow width. Used for phonemes such as "o" as in "hoop", "o" as in "hope," "w" as in "wet."

Back to contents

Agent States

The Microsoft Agent animation services automatically play certain animations for you. For example, when you use MoveTo or GestureAt commands, the animation services play an appropriate animation. Similarly, after the idle time out, the services automatically play animations. To support these states, you can define appropriate animations and then assign them to the states. You can still play any animation you define directly using the Play method, even if you assign it to a state.

You can assign multiple animations to the same state, and the animation services will randomly choose one of your animations. This enables your character to exhibit far more natural variety in its behavior.

Although animations that you assign to states can include branching frames, avoid looping animations (animations that branch forever). Otherwise, you will have to use the Stop method before you can play another animation.

It's important to define and assign at least one animation for each state that occurs for the character. If you do not supply these animations and state assignments, your character may not appear to behave appropriately to the user. However, if a state does not occur for a particular character, you need not assign an animation to that state. For example, if your host application never calls the MoveTo method, you can skip creating and assigning Moving state animations.

State | Example of Use
GesturingDown | When the GestureAt animation method is processed.
GesturingLeft | When the GestureAt animation method is processed.
GesturingRight | When the GestureAt animation method is processed.
GesturingUp | When the GestureAt animation method is processed.
Hearing | When the beginning of spoken input is detected.
Hiding | When the user or the application hides the character.
IdlingLevel1 | When the character begins the Idling state.
IdlingLevel2 | When the character begins the second Idling level state.
IdlingLevel3 | When the character begins the final Idling level state.
Listening | When the character starts listening (the user first presses the speech input hot key).
MovingDown | When the MoveTo animation method is processed.
MovingLeft | When the MoveTo animation method is processed.
MovingRight | When the MoveTo animation method is processed.
MovingUp | When the MoveTo animation method is processed.
Showing | When the user or the application shows the character.
Speaking | When the Speak animation method is processed.

The Hearing and Listening States

The animation you assign to the Listening state plays when the user presses the push-to-talk hot key for speech input. Create and assign a short animation that makes the character look attentive. Similarly, define its Return animation to have a short duration so that the character plays its Hearing state animation when the user speaks. A Hearing state animation should also be brief, and designed to let the user know that the character is actively listening to what the user says. Head tilts or other slight gestures are appropriate. To provide natural variability, provide several Hearing state animations.

The Gesturing States

You need to create and assign Gesturing state animations only if you plan to use the GestureAt method. Gesturing state animations play when Microsoft Agent processes a call to the GestureAt method. If you define mouth overlays for your Gesturing state animations, the character can speak as it gestures.

The animation services determine the character's location and its relation to the location of the coordinates specified in the method, and play an appropriate animation. Gesturing direction is always with respect to the character; for example, GestureRight should be a gesture to the character's right.

The Showing and Hiding States

The Showing and Hiding states play the assigned animations when the user or the host application requests to show or hide the character. These states also appropriately set the character frame's Visible state. When defining animations for these states, keep in mind that a character can appear or depart at any screen location. Because the user can show or hide any character, always support at least one animation for these states.

Animations that you assign to the Showing state typically end with a frame containing the character's neutral position image. Conversely, Hiding state animations typically begin with the neutral position. Showing and Hiding state animations can include an empty frame at the beginning or end, respectively, to provide a transition from the character's current state.

The Idling States

The Idling states are progressive. The animation services begin using the Level 1 assignments for the first idle period, and use the Level 2 animations for the second. After this, the idle cycle progresses to the Level 3 assigned animations and remains in this state until canceled, such as when a new animation request begins.

Design animations for the Idling states to communicate the state of the character, but not to distract the user. The animations should appropriately reflect the responsiveness of the character in subtle but clear ways. For example, glancing around or blinking are good animations to assign to the IdlingLevel1 state. Yawning and reading animations work well for the IdlingLevel2 state. Sleeping or listening to music with headphones are good examples of animations to assign to the IdlingLevel3 state. Animations that include many or large movements are not well suited for idle animations because they draw the user's attention. Because Idling state animations are played frequently, provide several Idling state animations, especially for the IdlingLevel1 and IdlingLevel2 states.

Note that an application can turn off the automatic idle processing for a character and manage the character's Idling state itself. The Agent Idling states are designed to help you avoid any situation where the character has no animation to play. A character image that does not change after a brief period of time is like an application displaying a wait pointer for a long time, which detracts from the sense of believability and interactivity. Maintaining the illusion does not take much: sometimes just an animated blink, visible breath, or body shift.

The Speaking State

The animation services use the Speaking state when a speaking animation cannot be found for the current animation. Assign a simple speaking animation to this state. For example, you can use a single frame consisting of the character's neutral positon with mouth overlays.

The Moving States

The Moving states play when an application calls the MoveTo method. The animation services determine which animation to play based on the character's current location and the specified coordinates. Movement direction is based on the character's position. Therefore, the animation you assign to the MovingLeft animation should be based on the character's left. If you don't use the MoveTo method, you can skip creating and assigning an animation.

Moving state animations should animate the character into its moving position. The last frame of this animation is displayed as the character's frame is moved on the screen. There is no support for animating the character while its frame moves.

Back to contents

Appendix

Animation Principles

Effective animation design requires more than simply rendering a character. Successful animators follow a variety of principles and techniques to create "believable" characters.

Squash and Stretch

There should be a degree of distortion as an animated object moves. The amount of deformation that occurs reflects the rigidity of that object. Flattening or elongating a part of character's body as it moves helps you convey the nature and composition of the character.

Anticipation

Anticipation sets the stage for an upcoming action. Without anticipatory actions, body movements look abrupt, rigid, and unnatural. This principle is based on how a body moves in the real world. Movement in one direction often begins with movement in the opposite direction. Legs contract before a jump. To exhale, you first inhale. Anticipatory action also has an important role in communicating the nature of both the character and the action and helps your audience prepare for the action. A key aspect of creating a believable character involves demonstrating that the character's actions stem from a purposeful intent. Anticipation helps communicate the character's motivation to the audience.

Timing

Timing defines the nature of an action. The speed that a head moves from left to right conveys whether a character is casually looking around or giving a negative response. Timing also helps convey the weight and size of an object. Larger objects tend to take longer to accelerate and decelerate than smaller ones. In addition, the pacing of a character's movements affects how it draws attention. In a normal scenario, rapid motion draws the eye, while in a frenetic environment, stationary or slow movements may have the same effect.

Staging

The background and props a character uses can also convey its mood or purpose. Staging also includes what the character wears, lighting effects, viewing angle, and the presence of other characters. These elements all contribute to reinforcing a character's personality, objectives, and actions. Effective staging involves understanding how to direct the eye to where you want to communicate.

Follow-Through and Overlapping Action

Just as a golfer's follow-through communicates the result of the swing, the transition from one action to the next is important in communicating the relationship between the actions. Actions rarely come to a sudden and complete stop. So, too, follow-through and overlapping actions allow you to establish the flow of the character's motion. You can typically implement this by varying the speed at which different parts of a body move, allowing movement beyond the primary aspect of the motion. For example, the fingers of a hand typically follow the movement of the wrist in a hand gesture. This principle also emphasizes that actions should not come to a complete stop, but smoothly blend into other actions.

Slow In-and-Out

Slow In-and-Out refers to moving a character smoothly from one pose to another. The character begins and ends actions slowly. You accomplish this by the number, timing, and location of "inbetween" frames. The more inbetween frames you include, the slower and smoother the transition.

Arcs

Living objects in nature rarely move in a perfectly straight line. As a result, arcs or curved paths for movement provide more natural effects. Arcs also convey speed of motion. The slower the motion, the higher the arc, and the faster the motion, the flatter the arc.

Exaggeration

Good animators often exaggerate the shape, color, emotion, or actions of a character. Making aspects of the motion "larger than life" more clearly communicates the idea of the action to the audience. For example, a character's arms may stretch to the point that they appear elastic. However, exaggeration must be balanced. If used in some situations and not others, the exaggerated action may appear unrealistic. Similarly, if you exaggerate one aspect of an image, consider what other aspects should be exaggerated to match.

Secondary Action

Animation requires more than the mechanistic creation of inbetween images from one pose to the next. A primary action is typically supported by secondary actions. Secondary actions can enhance the presentation, but should not detract from or dominate the main action. Facial expressions can often be used as secondary actions to body movement. Richness comes from adding elements that support the main idea.

Solid Drawing

Creating an animated character involves more than creating a series of images. Effective animation design considers how the character looks in different positions and from different angles. Even characters rendered as two-dimensional images become more realistic and believable if considered conceptually in three dimensions. Avoid twins: mirroring the position the face, arms, and legs on both sides of the body. This results in a wooden, unnatural presentation. Body movement is rarely symmetrical, but involves overall balancing of posture or reactions.

Appeal

Successful implementation depends on how well you understand your audience. Your character's overall image and personality should appeal to your target audience; appeal does not require photo-realism. A character's personality can be conveyed--no matter how simple its shape--by using gestures, posture, and other mannerisms. A common assignment of beginning animators is to create a variety of expressions for a flour sack or small rug. Characters with simple shapes are often more effective than complex ones. Consider, for example, that many popular characters have only three fingers and a thumb.

Back to contents


Microsoft Agent Documentation

Microsoft Agent Microsoft Agent *

Documentation

• Introduction
A brief overview of Microsoft Agent.

• User Interface
A concise description of the user interface elements.

• Programming Interface Overview
Information on animation services, input services, and output services.

• Programming the Control
The control's objects, methods, events, and properties.

• Programming the Server Interface
Information on the server interface, with a plethora of code examples.

• Error Codes
A list of the error numbers along with their hex values and descriptions.

• Speech Output Tags
How to modify speech output through tags inserted in the speech text string.

• Designing Characters
Design and develop a character for use with Microsoft Agent.

• Using the Character Editor
Use the Microsoft Agent Character Editor to compile character animations.

• Using the Linguistic Information Sound Editing Tool
Use linguistically enhanced sound files to support lip-syncing character output.

• Animations for Genie Character
A list of animations supported for the Microsoft Agent Genie character.

• Animations for Merlin Character
A list of animations supported for the Microsoft Agent Merlin character.

• Animations for Robby Character
A list of animations supported for the Microsoft Agent Robby character.


Microsoft Agent Error Codes

Microsoft Agent Microsoft Agent *

Error Codes

ActiveX™ Technology for Interactive Software Agents

August 1997
Microsoft Corporation

Note: This is a preliminary document and may be changed substantially prior to final commercial release. This document is provided for informational purposes only and Microsoft makes no warranties, either expressed or implied, in this document. The entire risk of the use or the results of this document remains with the user.

Information in this document is subject to change without notice. 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.

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. Microsoft, MS, MS-DOS, Windows, Windows NT, and the Windows logo are either registered trademarks or trademarks of Microsoft Corporation in the U.S. and/or other countries. Other product and company names mentioned herein may be the trademarks of their respective owners.

Microsoft Agent returns the following error information:

Error Number | Hex Value | Description
-2147213310 | 0x80042002 | Invalid character ID. The specified ID may be misspelled or not yet defined.
-2147213309 | 0x80042003 | Animation not supported. Please verify that the animation name is correct.
-2147213308 | 0x80042004 | No animation for this state. Please verify that an animation has been assigned to this state.
-2147213307 | 0x80042005 | Sound file not found. Please verify that the path and filename are correct.
-2147213306 | 0x80042006 | Command name not found. Please verify that the command name you specified is correct.
-2147213305 | 0x80042007 | Command name already in use. The specified command name has already been defined.
-2147213302 | 0x8004200A | Character is hidden. The method failed because the character is hidden.
-2147213301 | 0x8004200B | Character already loaded. Please check for previous Load method calls.
-2147213300 | 0x8004200C | Invalid balloon access. There was an attempt to access the word balloon, but the character does not support a word balloon.
-2147213299 | 0x8004200D | Invalid Commands Window access. Display of the Commands Window requires speech recognition support and the speech recognition engine has been disabled or is not installed.
-2147213298 | 0x8004200E | Invalid Get method Type parameter. Please verify that the type you specified is supported and spelled correctly.
-2147213296 | 0x80042010 | MoveTo method failed. A character cannot be moved while it is being dragged.
-2147213054 | 0x80042102 | Request object not found. The Request object no longer exists in the character's animation queue.
-2147213053 | 0x80042103 | Invalid use of the Stop method. A character cannot stop another character. Try the Interrupt method.
-2147213052 | 0x80042104 | Invalid use of the Interrupt method. A character cannot interrupt itself.
-2147213051 | 0x80042105 | Invalid use of the Wait method. A character cannot wait for its own requests to complete.
-2147213050 | 0x80042106 | Invalid bookmark. Please make sure that the bookmark specified is not reserved by Microsoft Agent.
-2147213049 | 0x80042107 | Microsoft Agent suspended. Right-click the Microsoft Agent taskbar icon and choose Restart Microsoft Agent.
-2147213048 | 0x80042108 | Request object removed. The specified Request object was removed from the character queue.
-2147213047 | 0x80042109 | Interrupted by Repeat Last Statement. The method request was interrupted because Repeat Last Statement was chosen.
-2147213046 | 0x8004210A | Interrupted by Listening key. The method request was interrupted because the Listening key was pressed.
-2147213045 | 0x8004210B | Interrupted by spoken input. The method request was interrupted because of spoken input.
-2147213044 | 0x8004210C | Interrupted by application. The application interrupted the character's animation queue.
-2147213043 | 0x8004210D | Interrupted by hiding. The method request was interrupted because the character was hidden.
-2147212799 | 0x80042201 | Unable to initialize data provider. The Microsoft Agent Data Provider was not properly initialized.
-2147212798 | 0x80042202 | Character data out of date. The specified character file version is not supported by the installed version of Microsoft Agent. You need to update the character.
-2147212797 | 0x80042203 | Invalid version. The version of Microsoft Agent installed is older than the specified character file. Please verify that you have the correct version of Microsoft Agent installed.
-2147212796 | 0x80042204 | Invalid character file. The specified file is not a Microsoft Agent character file. Please verify that the filename is correct.
-2147212795 | 0x80042205 | Invalid character ID. The specified ID may be misspelled or not yet defined.
-2147212794 | 0x80042206 | Invalid sound file. The specified file is not a valid sound (.WAV) file.
-2147212793 | 0x80042207 | Corrupt sound file. The specified sound file does not have correct data.
-2147212792 | 0x80042208 | Multimedia access failure. There was a problem accessing the system's multimedia component.
-2147212791 | 0x80042209 | Protocol failure. The URL protocol you specified is not supported by Microsoft Agent.
-2147212543 | 0x80042301 | Audio device failure. There was a problem accessing the audio device. Please verify that your sound card and drivers are correctly installed.
-2147212542 | 0x80042302 | No installed speech engine. Microsoft Agent could not find a compatible speech recognition engine.
-2147212541 | 0x80042303 | Speech input failure. The speech recognition engine failed to initialize. Please verify that the speech recognition engine is correctly installed.
-2147212540 | 0x80042304 | Invalid Commands object. There is a problem in the specified Commands object definition.
-2147212539 | 0x80042305 | Missing right parenthesis. The text for the Voice property of a command is missing a right parenthesis to specify an alternative.
-2147212538 | 0x80042306 | Missing right square bracket. The text for the Voice property of a command is missing a right square bracket to specify an option.
-2147212537 | 0x80042307 | Missing left parenthesis. The text for the Voice property of a command is missing a left parenthesis for specifying an alternative.
-2147212536 | 0x80042308 | Missing left square bracket. The text for the Voice property of a command is missing a left square bracket to specify an option.
-2147212535 | 0x80042309 | Missing parentheses. The text for the Voice property of a command is missing surrounding parentheses to specify alternatives.
-2147212534 | 0x8004230A | Speech input mode access failure. There was a problem accessing the speech recognition mode. Please verify that the speech engine is correctly installed.
-2147212533 | 0x8004230B | Invalid speech input mode. The specified speech recognition input mode could not be found. Please verify that the mode ID is correct.
-2147212532 | 0x8004230C | Speech disabled. The user has disabled speech recognition. The speech input object's properties are not available.
-2147212287 | 0x80042401 | Audio device failure. There was a problem accessing the audio device. Please verify that your sound card and drivers are correctly installed.
-2147212286 | 0x80042402 | Text-to-speech (TTS) failure. There was a problem initializing the text-to-speech engine.
-2147212285 | 0x80042403 | TTS failure. There was a problem initializing the text-to-speech engine.
-2147212284 | 0x80042404 | TTS failure. There was a problem initializing the text-to-speech engine.
-2147212283 | 0x80042405 | TTS failure. There was a problem initializing the text-to-speech engine.
-2147212282 | 0x80042406 | Lip-sync failure. There was a problem in the Microsoft Agent lip-sync component.
-2147212281 | 0x80042407 | Lip-sync failure. There was a problem in the Microsoft Agent lip-sync component.
-2147212280 | 0x80042408 | Lip sync failure. There was a problem in the Microsoft Agent lip-sync component.
-2147212030 | 0x80042502 | Unable to initialize Microsoft Agent. Make sure that Microsoft Agent is properly installed.
-2147212029 | 0x80042503 | Speech-input language access failure. There was a problem accessing the language of the speech recognition engine.
-2147024894 | 0x80070001 | The system cannot find the specified file.
-2147024883 | 0x8007000C | The data is invalid.
-2146697214 | 0x800C0002 | Invalid URL. Please verify that the specified URL exists and is correct.
-2146697212 | 0x800C0004 | Server access failure. The attempt to connect with the server failed. Please verify that the server is running and available.
-2146697210 | 0x800C0006 | File not found. The file could not be found at the specified URL. Please make sure the URL is correct.
-2146697205 | 0x800C000B | Server connection time-out. The connection to the server timed out. Please verify that the server is running and available.
-2146697202 | 0x800C000E | Server security access failure. There was a security problem when accessing the server.
-2147213297 | 0x8004200F | Invalid animation. The specified animation may be damaged or has no frames.


Microsoft Agent End-User License Agreement

Microsoft Agent Microsoft Agent *

Microsoft Agent

END-USER LICENSE AGREEMENT FOR MICROSOFT SOFTWARE

Microsoft Corporation

IMPORTANT-READ CAREFULLY: This Microsoft End-User License Agreement ("EULA") is a legal agreement between you (either an individual or a single entity) and Microsoft Corporation for the Microsoft software product identified above, which includes computer software and may include associated media, printed materials, and "online" or electronic documentation ("SOFTWARE PRODUCT"). By installing, copying, or otherwise using the SOFTWARE PRODUCT, you agree to be bound by the terms of this EULA. If you do not agree to the terms of this EULA, you may not use the SOFTWARE PRODUCT.

SOFTWARE PRODUCT LICENSE

The SOFTWARE PRODUCT is protected by copyright laws and international copyright treaties, as well as other intellectual property laws and treaties. The SOFTWARE PRODUCT is licensed, not sold.

INTRODUCTION. The SOFTWARE PRODUCT is comprised of the following components: Microsoft Agent Server; Microsoft Agent Control; Microsoft Character Animation Data and Image Files; and Microsoft Agent Data Provider. This EULA describes your rights with respect to such components.

This EULA also grants you rights to install and use one copy of the "Microsoft Command and Control" speech engine and/or one copy of the "Lernout & Hauspie TruVoice Text-To-Speech Engine for Microsoft Agent" for use solely with the SOFTWARE PRODUCT.

1. GRANT OF LICENSE. This EULA grants you the following rights:

Software Product as a Whole. You may install and use one (1) copy of the SOFTWARE PRODUCT on a single computer.

Components/Engines Additional Rights/Restrictions. Certain components of the SOFTWARE PRODUCT and the engines are subject to the following additional provisions:

Microsoft Character Animation Data and Image Files. You may download and use the Character Animation Data and Image Files designated by Microsoft as "Redistributable Character Animation Data and Image Files" solely in conjunction with Microsoft Agent. You may create scripts or programs that use the Microsoft Agent API to animate the character and static or animated images that are provided by Microsoft to enable the end-user selection of an animated image, provided, however, that you do not: (a) use the Character Animation Data and Image Files to disparage Microsoft, its products or services or for promotional goods or for products which, in Microsoft's reasonable judgment, may diminish or otherwise damage Microsoft's goodwill in the SOFTWARE PRODUCT, including but not limited to uses which could be deemed under applicable law to be obscene or pornographic, uses which are excessively violent, unlawful, or which purpose is to encourage unlawful activities; (b) use the Character Animation Data and Image files to imply Microsoft's sponsorship, endorsement or approval of your software application, service or content provided on your Internet site; (c) alter the Character Animation Data and Image Files in any way; and (d) combine the Animated Character(s) or Animation data files with any other object, including, but not limited to, other logos, words, graphics, photos, slogans, numbers, design features or symbols.

"Microsoft Command and Control" Speech Engine. The "Microsoft Command and Control" speech engine is available on a separate download site apart from the Microsoft Agent site at http://www.microsoft.com; or via a web page script using the "Microsoft Command and Control" speech engine CLSID in an object tag. This EULA grants you the right, at no cost, to install and use one copy per computer of the "Microsoft Command and Control" speech engine subject to the Use Restrictions described below.

Lernout & Hauspie TruVoice Text-to-Speech Engine for Microsoft Agent. The "Lernout & Hauspie TruVoice Text-to-Speech Engine for Microsoft Agent" is available from the Microsoft Agent site at http://www.microsoft.com; or via a web page script using the "Lernout & Hauspie TruVoice Text-to-Speech Engine for Microsoft Agent" CLSID in an object tag. This EULA grants you the right to install, and use one (1) copy per computer of the "Lernout & Hauspie TruVoice Text-to-Speech Engine for Microsoft Agent" solely in conjunction with the SOFTWARE PRODUCT subject to the Use Restrictions below.

Use Restrictions. The "Microsoft Command and Control" speech engine and the "Lernout & Hauspie TruVoice Text-to-Speech Engine for Microsoft Agent" are designated collectively as "ENGINE(S)". You may (a) place a notice on your web site or application that states the ENGINE(S) are available for installation only from the Microsoft Agent site at http://www.microsoft.com; (b) include the respective ENGINES' CLSID in an object tag on your web site that will automatically download the ENGINE(S) for the end-users from the Microsoft web site; provided, however the ENGINE(S) only operate in conjunction with Microsoft Agent; (c) you do not permit further redistribution of the ENGINE(S) by your end-user customers; (d) you do not use Microsoft's name, logo, or trademarks to market your web site; (e) you include a valid copyright notice on your web site; and (f) you agree to indemnify, hold harmless, and defend Microsoft from and against any claims or lawsuits, including attorneys' fees, that arise or result from the use or distribution of your web site. Contact Microsoft for the applicable royalties due and other licensing terms for all other uses and/or distribution of the ENGINE(S).

2. DESCRIPTION OF OTHER RIGHTS AND LIMITATIONS.

Support Services. Microsoft may provide you with support services related to the SOFTWARE PRODUCT ("Support Services"). Use of Support Services is governed by the Microsoft polices and programs described in the user manual, in "on line" documentation and/or other Microsoft-provided materials. Any supplemental software code provided to you as part of the Support Services shall be considered part of the SOFTWARE PRODUCT and subject to the terms and conditions of this EULA. With respect to technical information you provide to Microsoft as part of the Support Services, Microsoft may use such information for its business purposes, including for product support and development. Microsoft will not utilize such technical information in a form that personally identifies you.

Limitations on Certain Testing Methods. You may not use the SOFTWARE PRODUCT for benchmarking or performance testing.

Limitations on Reverse Engineering, Decompilation, and Disassembly. You may not reverse engineer, decompile, or disassemble the SOFTWARE PRODUCT, except and only to the extent that such activity is expressly permitted by applicable law notwithstanding this limitation.

Rental. You may not rent, lease or lend the SOFTWARE PRODUCT.

Software Transfer. You may permanently transfer all of your rights under this EULA, provided you retain no copies, you transfer all of the SOFTWARE PRODUCT (including all component parts, the media and printed materials, any upgrades, this EULA, and, if applicable, the Certificate of Authenticity), and the recipient agrees to the terms of this EULA.

3. ALL RIGHTS NOT EXPRESSLY GRANTED HEREIN ARE RESERVED BY MICROSOFT.

4. TERMINATION. Without prejudice to any other rights, Microsoft may terminate this EULA if you fail to comply with the terms and conditions of this EULA. In such event, you must destroy all copies of the SOFTWARE PRODUCT and all of its component parts.

5. COPYRIGHT. All title and copyrights in and to the SOFTWARE PRODUCT (including but not limited to any images, photographs, animations, video, audio, music, text, and "applets" incorporated into the SOFTWARE PRODUCT), the accompanying printed materials, and any copies of the SOFTWARE PRODUCT are owned by Microsoft or its suppliers. The SOFTWARE PRODUCT is protected by copyright laws and international treaty provisions. Therefore, you must treat the SOFTWARE PRODUCT like any other copyrighted material. You may not copy the printed materials accompanying the SOFTWARE PRODUCT.

6. U.S. GOVERNMENT RESTRICTED RIGHTS. The SOFTWARE PRODUCT and documentation are provided with RESTRICTED RIGHTS. Use, duplication, or disclosure by the Government is subject to restrictions as set forth in subparagraph (c)(1)(ii) of the Rights in Technical Data and Computer Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and (2) of the Commercial Computer Software-Restricted Rights at 48 CFR 52.227-19, as applicable. Manufacturer is Microsoft Corporation/One Microsoft Way/Redmond, WA 98052-6399.

7. EXPORT RESTRICTIONS. You acknowledge that the SOFTWARE PRODUCT licensed hereunder is subject to the export control laws and regulations of the U.S.A., and any amendments thereof. You confirm that with respect to the SOFTWARE PRODUCT, you will not export or re-export it, directly or indirectly, to any countries that are subject to U.S.A. export restrictions. You further acknowledge that the SOFTWARE PRODUCT may include technical data subject to export and re-export restrictions imposed by U.S.A. law.

MISCELLANEOUS

If you acquired this product in the United States, this EULA is governed by the laws of the State of Washington. If you acquired this product in Canada, this EULA is governed by the laws of the Province of Ontario, Canada. Each of the parties hereto irrevocably attorns to the jurisdiction of the courts of the Province of Ontario and further agrees to commence any litigation which may arise hereunder in the courts located in the Judicial District of York, Province of Ontario. If this product was acquired outside the United States, then local law may apply. Should you have any questions concerning this EULA, or if you desire to contact Microsoft for any reason, please contact the Microsoft subsidiary serving your country, or write: Microsoft Sales Information Center/One Microsoft Way/Redmond, WA 98052-6399.

LIMITED WARRANTY

NO WARRANTIES. To the maximum extent permitted by applicable law, Microsoft and its suppliers disclaim all warranties and conditions, either express or implied, including, but not limited to, implied warranties of merchantability, fitness for a particular purpose, title and non-infringement, with regard to the SOFTWARE PRODUCT, and the provision of or failure to provide Support Services. This limited warranty gives you specific legal rights. You may have others, which vary from state/jurisdiction to state/jurisdiction.

LIMITATION OF LIABILITY. To the maximum extent permitted by applicable law, in no event shall Microsoft or its suppliers be liable for any special, incidental, indirect, or consequential damages whatsoever (including, without limitation, damages for loss of business profits, business interruption, loss of business information, or any other pecuniary loss) arising out of the use of or inability to use the SOFTWARE PRODUCT or the provision of or failure to provide Support Services, even if Microsoft has been advised of the possibility of such damages. In any case, Microsoft's entire liability under any provision of this EULA shall be limited to the greater of the amount actually paid by you for the SOFTWARE PRODUCT or US$5.00; provided however, if you have entered into a Microsoft Support Services Agreement, Microsoft's entire liability regarding Support Services shall be governed by the terms of that agreement. Because some states and jurisdictions do not allow the exclusion or limitation of liability, the above limitation may not apply to you.

Si vous avez acquis votre produit Microsoft au CANADA, la garantie limitée suivante vous concerne :

GARANTIE LIMITÉE

AUCUNE AUTRE GARANTIE - DANS LA MESURE PRÉVUE PAR LA LOI, MICROSOFT ET SES FOURNISSEURS EXCLUENT TOUTE AUTRE GARANTIE OU CONDITION, EXPRESSE OU IMPLICITE, Y COMPRIS MAIS NE SE LIMITANT PAS AUX GARANTIES OU CONDITIONS IMPLICITES DU CARACTÈRE ADÉQUAT POUR LA COMMERCIALISATION OU UN USAGE PARTICULIER EN CE QUI CONCERNE LE LOGICIEL OU CONCERNANT LE TITRE , L'ABSENCE DE CONTREFAÇON DUDIT LOGICIEL, ET TOUTE DOCUMENTATION ÉCRITE QUI L'ACCOMPAGNE, AINSI QUE POUR TOUTE DISPOSITION CONCERNANT LE SUPORT TECHNIQUE OU LA FAÇON DONT CELUI-CI A ÉTÉ RENDU. CETTE GARANTIE LIMITÉE VOUS ACCORDE DES DROITS JURIDIQUES SPÉCIFIQUES.

PAS DE RESPONSABILITÉ POUR LES DOMMAGES INDIRECTS - MICROSOFT OU SES FOURNISSEURS NE SERONT PAS RESPONSABLES EN AUCUNE CIRCONSTANCE POUR TOUT DOMMAGE SPÉCIAL, INCIDENT, INDIRECT, OU CONSÉQUENT QUEL QU'IL SOIT (Y COMPRIS, SANS LIMITATION, LES DOMMAGES ENTRAINÉS PAR LA PERTE DE BÉNÉFICES, L'INTERRUPTION DES ACTIVITÉS, LA PERTE D'INFORMATION OU TOUTE AUTRE PERTE PÉCUNIAIRE) DÉCOULANT DE L'UTILISATION OU DE L'IMPOSSIBILITÉ D'UTILISATION DE CE LOGICIEL AINSI QUE POUR TOUTE DISPOSITION CONCERNANT LE SUPORT TECHNIQUE OU LA FAÇON DONT CELUI-CI A ÉTÉ RENDU ET CE, MÊME SI MICROSOFT A ÉTÉ AVISÉE DE LA POSSIBILITÉ DE TELS DOMMAGES. LA RESPONSABILITÉ DE MICROSOFT EN VERTU DE TOUTE DISPOSITION DE CETTE CONVENTION NE POURRA EN AUCUN TEMPS EXCÉDER LE PLUS ÉLEVÉ ENTRE i) LE MONTANT EFFECTIVEMENT PAYÉ PAR VOUS POUR LE LOGICIEL OU ii) US$5.00. ADVENANT QUE VOUS AYEZ CONTRACTÉ PAR ENTENTE DISTINCTE AVEC MICROSOFT POUR UN SUPPORT TECHNIQUE ÉTENDU, VOUS SEREZ LIÉ PAR LES TERMES D' UNE TELLE ENTENTE.

La présente Convention est régie par les lois de la province d'Ontario, Canada. Chacune des parties à la présente reconnaît irrévocablement la compétence des tribunaux de la province d'Ontario et consent à instituer tout litige qui pourrait découler de la présente auprès des tribunaux situés dans le district judiciaire de York, province d'Ontario. Au cas où vous auriez des questions concernant cette licence ou que vous désiriez vous mettre en rapport avec Microsoft pour quelque raison que ce soit, veuillez contacter la succursale Microsoft desservant votre pays, dont l'adresse est fournie dans ce produit, ou écrivez à : Microsoft Sales Information Center, One Microsoft Way, Redmond, Washington 98052-6399.


Microsoft Agent Frequently Asked Questions

Microsoft Agent Microsoft Agent *

Frequently Asked Questions

• Technical FAQ
Answers to the most frequently asked technical questions.

• Troubleshooting Microsoft Agent
A list of symptoms and steps to help isolate and solve problems.


Microsoft Agent Genie Animation List

Microsoft Agent Microsoft Agent *

Microsoft Agent Animations for Genie Character

ActiveX™ Technology for Interactive Software Agents

August 1997
Microsoft Corporation

Note: This document is provided for informational purposes only and Microsoft makes no warranties, either expressed or implied, in this document. The entire risk of the use or the results of this document remains with the user.

Information in this document is subject to change without notice. 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.

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. Microsoft, MS, MS-DOS, Windows, Windows NT, and the Windows logo are either registered trademarks or trademarks of Microsoft Corporation in the U.S. and/or other countries. Other product and company names mentioned herein may be the trademarks of their respective owners.

The Microsoft Agent Genie Character is a copyrighted work of Microsoft Corporation. You may use the character subject to the terms of the End User License Agreement for Microsoft Agent.

Genie supports the animations listed in the table below. Refer to Programming the Microsoft Agent Server Interface and Programming the Microsoft Agent Control for information on how to call the character's animations.

If accessing these character animations using the HTTP protocol and the control's Get or server's Prepare method, consider how you will download them. Instead of downloading all the animations at once, you may want to retrieve the Showing and Speaking state animations first. This will allow you to display the character quickly and have it speak while bringing down other animations asynchronously. In addition, to ensure that character and animation data load successfully, use the RequestComplete event. If a load request fails, you can retry loading the data or display an appropriate message.

Animation | Return Animation | Supports Speaking | Assigned to State | Description
Acknowledge | None | No | None | Nods head
Alert | AlertReturn | Yes | Listening | Straightens and raises eyebrows
AlertReturn | None | No | None | Returns to neutral position
Announce | AnnounceReturn | Yes | None | Raises hand
AnnounceReturn | None | No | None | Returns to neutral position
Blink | None | No | IdlingLevel1 | Blinks eyes
Confused | ConfusedReturn | Yes | None | Scratches head
ConfusedReturn | None | No | None | Returns to neutral position
Congratulate | CongratulateReturn | Yes | None | Thumbs-up gesture
CongratulateReturn | None | No | None | Returns to neutral position
Decline | DeclineReturn | Yes | None | Raises hands and shakes head
DeclineReturn | None | No | None | Returns to neutral position
DontRecognize | DontRecognizeReturn | Yes | None | Holds hand to ear
DontRecognizeReturn | None | No | None | Returns to neutral position
Explain | ExplainReturn | Yes | None | Extends arms to side
ExplainReturn | None | No | None | Returns to neutral position
GestureDown | GestureDownReturn | Yes | GesturingDown | Gestures down
GestureDownReturn | None | No | None | Returns to neutral position
GestureLeft | GestureLeftReturn | Yes | GesturingLeft | Gestures left
GestureLeftReturn | None | No | None | Returns to neutral position
GestureRight | GestureRightReturn | Yes | GesturingRight | Gestures right
GestureRightReturn | None | No | None | Returns to neutral position
GestureUp | GestureUpReturn | Yes | GesturingUp | Gestures up
GestureUpReturn | None | No | None | Returns to neutral position
GetAttention | GetAttentionReturn | Yes | None | Waves arms
GetAttentionReturn | None | No | None | Returns to neutral position
GlanceDown | None | No | None | Looks down briefly
GlanceLeft | None | No | None | Looks left briefly
GlanceRight | None | No | None | Looks right briefly
GlanceUp | None | No | None | Looks up briefly
Greet | GreetReturn | Yes | None | Bows
GreetReturn | None | No | None | Returns to neutral position
Hear_1 | None | No | Hearing | Ears extend
Hear_2 | None | No | Hearing | Tilts head left
Hear_3 | None | No | Hearing | Turns head left
Hear_4 | None | No | Hearing | Turns head right
Hide | None | No | Hiding | Disappears
Idle1_1 | None | No | IdlingLevel1 | Takes breath
Idle1_2 | None | No | IdlingLevel1 | Glances left and blinks
Idle1_3 | None | No | IdlingLevel1 | Glance right and blinks
Idle1_4 | None | No | IdlingLevel1 | Glances up to the right and blinks
Idle1_5 | None | No | IdlingLevel1 | Glances down and blinks
Idle1_6 | None | No | IdlingLevel1 | Glances up and blinks
Idle2_1 | None | No | IdlingLevel2 | Blinks and moves wisp
Idle2_2 | None | No | IdlingLevel2 | Reads
Idle2_3 | None | No | IdlingLevel2 | Writes
Idle3_1 | Idle3_1Return | No | IdlingLevel3 | Falls asleep
Idle3_1Return | None | No | None | Returns to neutral position
Idle3_2 | None | No | IdlingLevel3 | Yawns
LookDown | None | No | None | Looks down
LookDownBlink | None | No | None | Looks down and blinks
LookDownReturn | None | No | None | Returns to neutral position
LookLeft | None | No | None | Looks left
LookLeftBlink | None | No | None | Looks left and blinks
LookLeftReturn | None | No | None | Returns to neutral position
LookRight | None | No | None | Looks right
LookRightBlink | None | No | None | Looks right and blinks
LookRightReturn | None | No | None | Returns to neutral position
LookUp | None | No | None | Looks up
LookUpBlink | None | No | None | Looks up and blinks
LookUpReturn | None | No | None | Returns to neutral position
MoveDown | MoveDownReturn | No | MovingDown | Flies down
MoveDownReturn | None | No | None | Returns to neutral position
MoveLeft | MoveLeftReturn | No | MovingLeft | Flies left
MoveLeftReturn | None | No | None | Returns to neutral position
MoveRight | MoveRightReturn | No | MovingRight | Flies right
MoveRightReturn | None | No | None | Returns to neutral position
MoveUp | MoveUpReturn | No | MovingUp | Flies up
MoveUpReturn | None | No | None | Returns to neutral position
Pleased | PleasedReturn | Yes | None | Clasps hands and smiles
PleasedReturn | None | No | None | Returns to neutral position
Processing | ProcessingReturn | No | None | Spins (*looping animation)
ProcessingReturn | None | No | None | Returns to neutral position
Read | None | Yes | None | Takes scroll out of vest, reads and looks up
ReadContinued | None | Yes | None | Reads and looks up
ReadReturn | None | No | None | Returns to neutral position
Reading | ReadingReturn | No | None | Reads (*looping animation)
ReadingReturn | None | No | None | Returns to neutral position
RestPose | None | Yes | Speaking | Neutral position
Sad | SadReturn | Yes | None | Sad expression
SadReturn | None | No | None | Returns to neutral position
Searching | SearchingReturn | No | None | Spins and looks through binoculars (*looping animation)
SearchingReturn | None | No | None | Returns to neutral position
Show | None | No | Showing | Appears in a puff of smoke
StartListening | StartListeningReturn | Yes | None | Puts hand to ear
StartListeningReturn | None | No | None | Returns to neutral position
StopListening | StopListeningReturn | Yes | None | Puts hands to ears
StopListeningReturn | None | No | None | Returns to neutral position
Suggest | SuggestReturn | Yes | None | Displays light bulb
SuggestReturn | None | No | None | Returns to neutral position
Surprised | SurprisedReturn | Yes | None | Looks surprised
SurprisedReturn | None | No | None | Returns to neutral position
Think | ThinkReturn | Yes | None | Looks up with hand on chin
ThinkReturn | None | No | None | Returns to neutral position
Uncertain | UncertainReturn | Yes | None | Raises eyebrow with hand on chin
UncertainReturn | None | No | None | Returns to neutral position
Wave | WaveReturn | Yes | None | Waves
WaveReturn | None | No | None | Returns to neutral position
Write | None | Yes | None | Takes scroll out of vest, writes and looks up
WriteContinued | None | Yes | None | Writes and looks up
WriteReturn | None | No | None | Returns to neutral position
Writing | WritingReturn | No | None | Writes (*looping animation)
WritingReturn | None | No | None | Returns to neutral position

* If you play a looping animation, you must use Stop to clear it before other animations in the character's queue will play.


Microsoft Agent Introduction

Microsoft Agent Microsoft Agent *

Introduction to Microsoft Agent

ActiveX™ Technology for Interactive Software Agents

August 1997
Microsoft Corporation

Note: This document is provided for informational purposes only and Microsoft makes no warranties, either expressed or implied, in this document. The entire risk of the use or the results of this document remains with the user.

Information in this document is subject to change without notice. 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.

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. Microsoft, MS, MS-DOS, Windows, Windows NT, and the Windows logo are either registered trademarks or trademarks of Microsoft Corporation in the U.S. and/or other countries. Other product and company names mentioned herein may be the trademarks of their respective owners.

Microsoft® Agent is a set of programmable software services that supports the presentation of interactive animated characters within the Microsoft Windows® interface. Developers can use characters as interactive assistants to introduce, guide, entertain, or otherwise enhance their Web pages or applications in addition to the conventional use of windows, menus, and controls.

Microsoft Agent enables software developers and Web authors to incorporate a new form of user interaction, known as conversational interfaces, that leverages natural aspects of human social communication. In addition to mouse and keyboard input, Microsoft Agent includes optional support for speech recognition so applications can respond to voice commands. Characters can respond using synthesized speech, recorded audio, or text in a cartoon word balloon.

The conversational interface approach facilitated by the Microsoft Agent services does not replace conventional graphical user interface (GUI) design. Instead, character interaction can be easily blended with the conventional interface components such as windows, menus, and controls to extend and enhance your application's interface.

Microsoft Agent's programming interfaces make it easy to animate a character to respond to user input. Animated characters appear in their own window, providing maximum flexibility for where they can be displayed on the screen. Microsoft Agent includes an ActiveX™ control that makes its services accessible to programming languages that support ActiveX, including Web scripting languages such as Visual Basic® Scripting Edition (VBScript). This means that character interaction can be programmed even from HTML pages using the <OBJECT> tag.


Microsoft Agent Licensing and Redistribution

August 1997
Microsoft Corporation

The following uses for Microsoft Agent Version 1 are currently royalty-free, subject to the End-User License Agreement, and do not require a redistribution license:

  • You can automatically cause Microsoft Agent to download from the Microsoft site by including the CLSID for Microsoft Agent in an HTML <OBJECT> tag on one of your site's pages.
  • You can also automatically cause the Microsoft Command and Control speech recognition engine and the Lernout & Hauspie® TruVoice Text-To-Speech Engine for Microsoft Agent to download from the Microsoft site, by including their CLSIDs in an HTML <OBJECT> tag on one of your site's pages, provided that these engines are only downloaded and installed for use with Microsoft Agent.
  • You can load Microsoft's designated characters or images from the Microsoft Web site in your script code using the Microsoft Agent Load and Get (Prepare) methods.

However, to add or include Microsoft Agent and any of its components to or with an application, or post Microsoft Agent and any of its components on a server, or distribute Microsoft Agent and any of its components using other electronic media, you must first obtain and submit a redistribution license for Microsoft Agent. The Microsoft Agent character files, the Microsoft Command and Control speech engine, and the Lernout & Hauspie TruVoice Text-To-Speech Engine cannot be redistributed without Microsoft Agent. This license for Microsoft Agent Version 1 is currently royalty-free to redistribute within your organization or to your customers. The license does not include the Microsoft Agent Character Editor or the Microsoft Linguistic Sound Editing Tool.

To request a redistribution license or further information, contact the Microsoft Agent Product Group at msagent@microsoft.com.


Microsoft Agent Linguistic Information Sound Editing Tool

Microsoft Agent Microsoft Agent *

Using the Microsoft Linguistic Information Sound Editing Tool

ActiveX™ Technology for Interactive Software Agents

August 1997
Microsoft Corporation

Note: This document is provided for informational purposes only and Microsoft makes no warranties, either expressed or implied, in this document. The entire risk of the use or the results of this document remains with the user.

Information in this document is subject to change without notice. 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.

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. Microsoft, MS, MS-DOS, Windows, Windows NT, and the Windows logo are either registered trademarks or trademarks of Microsoft Corporation in the U.S. and/or other countries. Other product and company names mentioned herein may be the trademarks of their respective owners.

Contents

Introduction

Installing the Sound Editor

Starting the Sound Editor

Creating a New Sound File

Loading an Existing Sound File

Generating Linguistic Information

Saving a Sound File

Command Reference

Toolbar buttons

Introduction

The Microsoft® Linguistic Information Sound Editing Tool enables you to generate phoneme and word-break information for enhancing Windows® sound (.WAV) files to support high-quality lip-syncing character animation.

You can use linguistically enhanced sound files generated with the sound editor to support lip-syncing Microsoft Agent character output. To do so, simply pass the file as a parameter to the Speak method. For further information, see Programming the Microsoft Agent Control or Programming the Microsoft Agent Server Interface.

Back to contents

Installing the Sound Editor

The recommended system configuration for using the sound editor is a PC with a Pentium® 166, at least 32 Megabytes of RAM, and a Windows compatible sound card. If you want to record spoken input with the tool, you will also need a compatible microphone.

To install the Microsoft Linguistic Sound Editing Tool, open its self-extracting installation file. This will automatically install the appropriate files on your system. If you download the sound editor from the Microsoft Agent Web site, you can choose to install the editor after downloading or save it to your disk to be subsequently opened and installed. The installation tool will propose to install itself in the Tools subdirectory of Microsoft Agent. We recommend that you use this location.

The Microsoft Command and Control Speech Engine (version. 3.0) must also be installed before you can use the sound editor. This normally gets installed with the sound editor, but if it was subsequently uninstalled, you can reinstall it from the Microsoft Agent Component Installation page. The sound editor can only generate linguistic information based on the language supported by the speech engine. To generate information for other languages, a compatible speech recognition engine for that language must be installed. Contact your speech engine vendor to determine whether they support the Microsoft Linguistic Sound Editing Tool.

Back to contents

Starting the Sound Editor

To run the Microsoft Linguistic Information Sound Editing Tool, choose it from the Start menu or double-click the sound editor's icon. The sound editor's window will open, displaying its menus, a toolbar for frequently used commands, a text box for entering the words the editor uses to process the sound file, and a display area for viewing and editing the audio and linguistic data.

Figure 1. Microsoft Linguistic Information Sound Editing Tool Window

Once the sound editor starts up, you can begin recording a new sound file or load an existing sound file.

Back to contents

Creating a New Sound File

When you first start the editor, you can create a new sound file by choosing Record on the Audio menu or the Record button on the sound editor's toolbar, and then speaking into the microphone attached to your system. Click the Stop button on the toolbar to stop recording. You can click the Play command on the Audio menu or toolbar to see how Microsoft Agent would process the sound file without linguistic enhancement. To create another new file, choose the New command on the File menu or on the editor's toolbar.

Back to contents

Loading an Existing Sound File

You can also load an existing Windows sound file (.WAV) or linguistically enhanced sound file (.LWV) by choosing the Open command on the File menu or the sound editor toolbar. This displays the Open dialog box. Select a file and click Open to load the file into the editor.

Figure 2. The Open Dialog Box

Back to contents

Generating Linguistic Information

Once you have recorded a new sound file or loaded an existing sound file, you can generate phonetic and word-break information by entering text that corresponds to your sound file in the Text Representation box. Then choose the Generate Linguistic Info command from the Edit menu or from the toolbar. The sound editor displays a progress message and begins processing your sound file. When it completes generating linguistic information, it displays a mapping of word and phoneme labels for the sound file in boxes in the Audio Representation box. Note that the Generate Linguistic Info command remains disabled until you enter a text representation for your sound file.

Figure 3. Word and Phoneme Labels Generated for a Sound File

If the editor doesn't produce an acceptable set of word or phoneme labels, choose the Generate Linguistic Info command again. If the editor does not generate any linguistic information, check your text representation to ensure that all the words are correctly ordered and spelled, and that you don't have any unnecessary spaces around punctuation. Then choose the Generate Linguistic Info command again. You can edit the text representation by selecting text in the Text Representation text box and using the Cut, Copy, and Paste commands on the Edit menu. If you are uncertain of the words the sound file includes, you can play the sound file by choosing Play from the Edit menu or the editor's toolbar. If the editor still fails to produce linguistic labels, try recording your sound file again. A poor quality recording, especially with excessive background noise, is likely to reduce the probability of generating reasonable linguistic information.

To see how the linguistic information could be used for lip-syncing character animation with Microsoft Agent, choose the Play button on the toolbar and the editor will play your sound file, animating a sample mouth image based on the generated label information.

You can change the phoneme label display to show the IPA (International Phonetic Alphabet) assignments by choosing the Phoneme Label Display command on the Edit menu, then the IPA command. This displays the byte value for the phoneme. To change back to the descriptive names, choose the Phoneme Label Display command again, then choose Name.

Playing a Sound File

You can play standard Windows sound files or linguistically enhanced sound files by choosing the Play command from the Audio menu or the editor's toolbar. The Pause and Stop commands enable you to pause or stop playing the sound file. As you play the file, the sample mouth image animates to show how the lip-sync information could be used by a Microsoft Agent character.

You can also play a selected portion of a sound file by dragging a selection in the Audio Representation or clicking a word or phoneme label, then choosing Play. You can extend an existing selection by pressing shift and clicking or pressing shift and dragging to the new location in the Audio Representation.

Editing Linguistic Information

You can edit a file's linguistic information in several ways. For example, you can adjust a word or phoneme label's boundary by moving the pointer to the edge of the box that defines the range of the label. When the pointer changes to the boundary move pointer, drag left or right. The editor automatically adjusts the adjacent word or phoneme boundary as well.

Figure 4. Adjusting a Word or Phoneme Label Boundary

Adjusting a phoneme label's boundary changes the timing of a phoneme when the audio plays. For characters developed for use with Microsoft Agent, changing the phoneme label boundary may change the timing or duration for a mouth image mapped to that phoneme. Changing the boundary of a word label changes the timing of the word's appearance in the character's word balloon.

You can also replace a phoneme assignment by selecting the phoneme label and choosing Replace Phoneme from the Edit menu, or right-clicking the phoneme label and choosing Replace Phoneme from the pop-up menu. The editor displays the Replace Phoneme dialog box and highlights the label's current phoneme assignment. You can choose a replacement phoneme by selecting one in the IPA list or by choosing another entry in the Name list. If more than one IPA translation is available for that name, choose an item in the IPA list. To enter an IPA designation for a phoneme that may not be directly included in the language, type in its hex value or multiple hex values, concatenated with a plus (+) character. Once you have selected the replacement phoneme information, choose OK, and the editor replaces the phoneme label you selected.

Figure 5. Replace Phoneme Dialog Box

Similarly, you can replace a word label by clicking the label's box and choosing Replace Word, or by right-clicking the label's box and choosing Replace Word from the pop-up menu. The editor displays the Replace Word dialog box. Enter the replacement word and choose OK.

Figure 6. Replace Word Dialog Box

For characters developed for use with Microsoft Agent, replacing a phoneme label may change the mouth image displayed when the sound file plays. Replacing a word replaces the text that appears in the character's word balloon when the Speak method is called.

You can also insert a new phoneme label or word by making a selection in the Audio Representation and choosing Insert Phoneme or Insert Word from the Edit menu, or right-clicking within the selection and choosing the commands from the pop-up menu. These commands bring up dialog boxes similar to the Replace Phoneme and Replace Word dialog boxes, except that the editor inserts the new word or phoneme rather than replacing the existing information.

Finally, you can delete a phoneme or word by selecting its label and choosing Delete Phoneme or Delete Word. This removes its linguistic information from the file.

Back to contents

Saving a Sound File

When you are ready to save your sound file, choose the Save command on the File menu or on the editor's toolbar. The editor displays the Save As dialog box and proposes a name and default file type based on whether you generated linguistic information for the file. If you save the file as a sound file (.WAV), the editor saves just the audio data. If you save the file information as a linguistically enhanced sound file (.LWV), the word and phoneme information are automatically included as part of a modified sound file. Once you have confirmed or edited the name, location, file type, and format, choose the Save button.

Figure 7. The Save As Dialog Box

If you want to save a sound file with a new name, different location, or different format, choose the Save As command on the File menu. When the Save As dialog box appears, type in the new filename and click the Save button.

You can also save a portion of the sound file. For example, you may want to save the file without excessive silence at its beginning or end. In the Audio Representation, select the portion of the file you want to save, and choose Save Selection As from the File menu. The command is enabled only when you have a selection in the Audio Representation.

Back to contents

Command Reference

The File Menu

New

Resets the sound editor for creating a new enhanced sound file. If an existing sound file is loaded and has unsaved edits, the sound editor displays a message to determine whether to save or discard unsaved changes.

Open

Displays the Open dialog box, enabling you to open an existing sound file. If an existing sound file is loaded and has unsaved edits, the sound editor displays a message to determine whether to save or discard unsaved changes.

Save

Saves a sound file. If the sound file does not exist (has not been named), the sound editor displays the Save As dialog box for input of the filename.

Save As

Displays the Save As dialog box, enabling you to enter a new name for the sound file.

Save Selection As

Displays the Save Selection As dialog box, enabling you to enter a name for the selected part of the sound file.

Most Recently Open Files

Keeps track of the recent character definition files you opened. Choosing a file automatically opens that file for editing. If an existing character is loaded and has unsaved edits to a file, the sound editor displays a message to determine whether to save or discard unsaved changes.

Exit

Quits the sound editor. If an existing file is loaded and has unsaved edits, the sound editor displays a message to determine whether to save or discard unsaved changes.

The Edit Menu

Undo

Removes a change made in the sound editor.

Redo

Reverses an undo action in the sound editor.

Cut

Removes the selected text and places it on the clipboard.

Copy

Copies the selected text to the clipboard.

Paste

Copies text on the clipboard to the insertion point or selection in the Text Representation text box.

Delete

Removes the selected text.

Select All

Selects the text in the Text Representation text box.

Generate Linguistic Info

Begins generating word-break and phoneme information for a sound file.

Insert Phoneme

Displays the Insert Phoneme dialog box that enables you to insert a selected phoneme label.

Replace Phoneme

Displays the Replace Phoneme dialog box that enables you to replace the selected phoneme label.

Delete Phoneme

Deletes the selected phoneme label.

Insert Word

Displays the Insert Word dialog box that enables you to insert a word label in the Audio Representation.

Replace Word

Displays the Replace Word dialog box that enables you to replace the selected word label in the Audio Representation.

Delete Word

Deletes the selected word label in the Audio Representation.

Phoneme Label Display

Changes the phoneme label display between descriptive names and IPA byte values.

Audio Menu

Play

Plays the sound file or selected portion of the sound file.

Record

Records a new sound file.

Pause

Pauses the play of the sound file or selected portion of the sound file. Use Play to resume playing.

Stop

Stops recording or playing the sound file or selected portion of the sound file.

The Help Menu

Help Topics

Displays the Help Topics dialog box, enabling you to select a sound editor help topic.

About Microsoft Linguistic Sound Editing Tool

Displays a dialog box with copyright and version information for the sound editor.

Back to contents

Toolbar buttons

New

Resets the sound editor for creating a new sound file. If an existing sound file is loaded and has unsaved edits, the sound editor displays a message to determine whether to save or discard unsaved changes.

Open

Displays the Open File dialog box, enabling you to open an existing sound file. If an existing sound file is loaded and has unsaved edits, the sound editor displays a message to determine whether to save or discard unsaved changes.

Save

Saves the sound file. If the file does not exist (has not been named), the editor displays the Save As dialog box for input of the filename.

Cut

Removes the selected text from the editor and places it on the Windows Clipboard.

Copy

Copies the selected text in the editor to the Windows Clipboard.

Paste

Copies text from the current Windows Clipboard to the selected location in the Text Representation text box.

Delete

Removes the selected text from the sound editor.

Undo

Removes a change made in the sound editor.

Redo

Reverses an undo action in the sound editor

Generate Linguistic Info

Generates phoneme and word labels for the sound file.

Pause

Pauses playing of the sound file.

Play

Plays the sound file or selected portion of the sound file.

Stop

Stops recording or playing the sound file or selected portion of the sound file.

Record

Starts recording a sound file.

Back to contents


Microsoft Agent Merlin Animation List

Microsoft Agent Microsoft Agent *

Microsoft Agent Animations for Merlin Character

ActiveX™ Technology for Interactive Software Agents

August 1997
Microsoft Corporation

Note: This document is provided for informational purposes only and Microsoft makes no warranties, either expressed or implied, in this document. The entire risk of the use or the results of this document remains with the user.

Information in this document is subject to change without notice. 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.

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. Microsoft, MS, MS-DOS, Windows, Windows NT, and the Windows logo are either registered trademarks or trademarks of Microsoft Corporation in the U.S. and/or other countries. Other product and company names mentioned herein may be the trademarks of their respective owners.

The Microsoft Agent Merlin Character is a copyrighted work of Microsoft Corporation. You may use the character subject to the terms of the End User License Agreement for Microsoft Agent.

Merlin supports the animations listed in the table below. Refer to Programming the Microsoft Agent Server Interface and Programming the Microsoft Agent Control for information on how to call the character's animations.

If accessing these character animations using the HTTP protocol and the control's Get or server's Prepare method, consider how you will download them. Instead of downloading all the animations at once, you may want to retrieve the Showing and Speaking state animations first. This will allow you to display the character quickly and have it speak while bringing down other animations asynchronously. In addition, to ensure that character and animation data load successfully, use the RequestComplete event. If a load request fails, you can retry loading the data or display an appropriate message.

Animation | Return Animation | Supports Speaking | Assigned to State | Description
Acknowledge | None | No | None | Nods head
Alert | AlertReturn | Yes | Listening | Straightens and raises eyebrows
AlertReturn | None | No | None | Returns to neutral position
Announce | AnnounceReturn | Yes | None | Raises trumpet and plays
AnnounceReturn | None | No | None | Returns to neutral position
Blink | None | No | IdlingLevel1 | Blinks eyes
Confused | ConfusedReturn | Yes | None | Scratches head
ConfusedReturn | None | No | None | Returns to neutral position
Congratulate | CongratulateReturn | Yes | None | Displays trophy
CongratulateReturn | None | No | None | Returns to neutral position
Congratulate 2 | PleasedReturn | Yes | None | Applauds
Decline | DeclineReturn | Yes | None | Raises hands and shakes head
DeclineReturn | None | No | None | Returns to neutral position
DoMagic1 | None | Yes | None | Raises magic wand
DoMagic2 | DoMagicReturn | No | None | Lowers wand, clouds appear
DoMagicReturn | None | No | None | Returns to neutral position
DontRecognize | DontRecognizeReturn | Yes | None | Holds hand to ear
DontRecognizeReturn | None | No | None | Returns to neutral position
Explain | ExplainReturn | Yes | None | Extends arms to side
ExplainReturn | None | No | None | Returns to neutral position
GestureDown | GestureDownReturn | Yes | GesturingDown | Gestures down
GestureDownReturn | None | No | None | Returns to neutral position
GestureLeft | GestureLeftReturn | Yes | GesturingLeft | Gestures left
GestureLeftReturn | None | No | None | Returns to neutral position
GestureRight | GestureRightReturn | Yes | GesturingRight | Gestures right
GestureRightReturn | None | No | None | Returns to neutral position
GestureUp | GestureUpReturn | Yes | GesturingUp | Gestures up
GestureUpReturn | None | No | None | Returns to neutral position
GetAttention | GetAttentionReturn | Yes | None | Leans forward and knocks
GetAttentionReturn | None | No | None | Returns to neutral position
GlanceDown | None | No | None | Looks down briefly
GlanceLeft | None | No | None | Looks left briefly
GlanceRight | None | No | None | Looks right briefly
GlanceUp | None | No | None | Looks up briefly
Greet | GreetReturn | Yes | None | Bows
GreetReturn | None | No | None | Returns to neutral position
Hear_1 | None | No | Hearing | Ears extend
Hear_2 | None | No | Hearing | Tilts head left
Hear_3 | None | No | Hearing | Turns head left
Hear_4 | None | No | Hearing | Turns head right
Hide | None | No | Hiding | Disappears under cap
Idle1_1 | None | No | IdlingLevel1 | Takes breath
Idle1_2 | None | No | IdlingLevel1 | Glances left and blinks
Idle1_3 | None | No | IdlingLevel1 | Glances right
Idle1_4 | None | No | IdlingLevel1 | Glances up to the right and blinks
Idle2_1 | None | No | IdlingLevel2 | Looks at wand and blinks
Idle2_2 | None | No | IdlingLevel2 | Holds hands and blinks
Idle3_1 | Idle3_1Return | No | IdlingLevel3 | Falls asleep
Idle3_1Return | None | No | None | Returns to neutral position
Idle3_2 | None | No | IdlingLevel3 | Yawns
LookDown | None | No | None | Looks down
LookDownBlink | None | No | None | Blinks looking down
LookDownReturn | None | No | None | Returns to neutral position
LookLeft | None | No | None | Looks left
LookLeftBlink | None | No | None | Blinks looking left
LookLeftReturn | None | No | None | Returns to neutral position
LookRight | None | No | None | Looks right
LookRightBlink | None | No | None | Blinks looking right
LookRightReturn | None | No | None | Returns to neutral position
LookUp | None | No | None | Looks up
LookUpBlink | None | No | None | Blinks looking up
LookUpReturn | None | No | None | Returns to neutral position
MoveDown | MoveDownReturn | No | MovingDown | Flies down
MoveDownReturn | None | No | None | Returns to neutral position
MoveLeft | MoveLeftReturn | No | MovingLeft | Flies left
MoveLeftReturn | None | No | None | Returns to neutral position
MoveRight | MoveRightReturn | No | MovingRight | Flies right
MoveRightReturn | None | No | None | Returns to neutral position
MoveUp | MoveUpReturn | No | MovingUp | Flies up
MoveUpReturn | None | No | None | Returns to neutral position
Pleased | PleasedReturn | Yes | None | Smiles and holds hands together
PleasedReturn | None | No | None | Returns to neutral position
Processing | ProcessingReturn | No | None | Stirs caldron (*looping animation)
ProcessingReturn | None | No | None | Returns to neutral position
Read | None | Yes | None | Opens book, reads and looks up
ReadContinued | None | Yes | None | Reads and looks up
ReadReturn | None | No | None | Returns to neutral position
Reading | ReadingReturn | No | None | Reads (*looping animation)
ReadingReturn | None | No | None | Returns to neutral position
RestPose | None | Yes | Speaking | Neutral position
Sad | SadReturn | Yes | None | Sad expression
SadReturn | None | No | None | Returns to neutral position
Searching | SearchingReturn | No | None | Looks into crystal ball (*looping animation)
SearchingReturn | None | No | None | Returns to neutral position
Show | None | No | Showing | Appears out of cap
StartListening | StartListeningReturn | Yes | None | Puts hand to ear
StartListeningReturn | None | No | None | Returns to neutral position
StopListening | StopListeningReturn | Yes | None | Puts hands to ears
StopListeningReturn | None | No | None | Returns to neutral position
Suggest | SuggestReturn | Yes | None | Displays light bulb
SuggestReturn | None | No | None | Returns to neutral position
Surprised | SurprisedReturn | Yes | None | Looks surprised
SurprisedReturn | None | No | None | Returns to neutral position
Think | ThinkReturn | Yes | None | Looks up with hand on chin
ThinkReturn | None | No | None | Returns to neutral position
Uncertain | UncertainReturn | Yes | None | Leans forward and raises eyebrow
UncertainReturn | None | No | None | Returns to neutral position
Wave | WaveReturn | Yes | None | Waves
WaveReturn | None | Yes | None | Returns to neutral position
Write | WriteReturn | Yes | None | Opens books, writes and looks up
WriteContinued | None | Yes | None | Writes and looks up
WriteReturn | None | No | None | Returns to neutral position
Writing | WritingReturn | No | None | Writes (*looping animation)
WritingReturn | None | No | None | Returns to neutral position

* If you play a looping animation, you must use Stop to clear it before other animations in the character's queue will play.


Microsoft Agent Robby Animation List

Microsoft Agent Microsoft Agent *

Microsoft Agent Animations for Robby Character

ActiveX™ Technology for Interactive Software Agents

August 1997
Microsoft Corporation

Note: This document is provided for informational purposes only and Microsoft makes no warranties, either expressed or implied, in this document. The entire risk of the use or the results of this document remains with the user.

Information in this document is subject to change without notice. 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.

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. Microsoft, MS, MS-DOS, Windows, Windows NT, and the Windows logo are either registered trademarks or trademarks of Microsoft Corporation in the U.S. and/or other countries. Other product and company names mentioned herein may be the trademarks of their respective owners.

The Microsoft Agent Robby Character is a copyright of Microsoft Corporation. You may use the character subject to the terms of the End User License Agreement for Microsoft Agent.

Robby supports the animations listed below. Refer to Programming the Microsoft Agent Server Interface and Programming the Microsoft Agent Control for information on how to call the character's animations.

If accessing these character animations using the HTTP protocol and the control's Get or server's Prepare method, consider how you will download them. Instead of downloading all the animations at once, you may want to retrieve the Showing and Speaking state animations first. This will allow you to display the character quickly and have it speak while bringing down other animations asynchronously. In addition, to ensure that character and animation data load successfully, use the RequestComplete event. If a load request fails, you can retry loading the data or display an appropriate message.

Animation | Return Animation | Supports Speaking | Assigned to State | Description
Acknowledge | None | No | None | Nods head
Alert | AlertReturn | No | Listening | Straightens and raises eyebrows
AlertReturn | None | No | None | Returns to neutral position
Announce | AnnounceReturn | Yes | None | Prints output and reads
AnnounceReturn | None | No | None | Returns to neutral position
Blink | None | No | IdlingLevel1 | Blinks eyes
Confused | ConfusedReturn | Yes | None | Scratches head
ConfusedReturn | None | No | None | Returns to neutral position
Congratulate | CongratulateReturn | Yes | None | Raises then clasps hands and smiles
CongratulateReturn | None | No | None | Returns to neutral position
Decline | DeclineReturn | Yes | None | Raises hands and shakes head
DeclineReturn | None | No | None | Returns to neutral position
DontRecognize | DontRecognizeReturn | Yes | None | Holds hand to ear
DontRecognizeReturn | None | No | None | Returns to neutral position
Explain | ExplainReturn | Yes | None | Extends arms to side
ExplainReturn | None | No | None | Returns to neutral position
GestureDown | GestureDownReturn | Yes | GesturingDown | Gestures down
GestureDownReturn | None | No | None | Returns to neutral position
GestureLeft | GestureLeftReturn | Yes | GesturingLeft | Gestures left
GestureLeftReturn | None | No | None | Returns to neutral position
GestureRight | GestureRightReturn | Yes | GesturingRight | Gestures right
GestureRightReturn | None | No | None | Returns to neutral position
GestureUp | GestureUpReturn | Yes | GesturingUp | Gestures up
GestureUpReturn | None | No | None | Returns to neutral position
GetAttention | GetAttentionReturn | Yes | None | Raises and shakes arms
GetAttentionReturn | None | No | None | Returns to neutral position
GlanceDown | None | No | None | Looks down briefly
GlanceLeft | None | No | None | Looks left briefly
GlanceRight | None | No | None | Looks right briefly
GlanceUp | None | No | None | Looks up briefly
Greet | GreetReturn | Yes | None | Waves
GreetReturn | None | No | None | Returns to neutral position
Hear_1 | None | No | Hearing | Turns head left
Hear_2 | None | No | Hearing | Turns head right
Hear_3 | None | No | Hearing | Tilts head right
Hear_4 | None | No | Hearing | Tilts head forward
Hide | None | No | Hiding | Disappears under cap
Idle1_1 | None | No | IdlingLevel1 | Glances right
Idle1_2 | None | No | IdlingLevel1 | Glances up to the left
Idle2_1 | None | No | IdlingLevel2 | Crosses arms
Idle2_2 | None | No | IdlingLevel2 | Removes head and makes adjustment
Idle3_1 | Idle3_1Return | No | IdlingLevel3 | Falls asleep
Idle3_1Return | None | No | None | Returns to neutral position
Idle3_2 | None | No | IdlingLevel3 | Yawns
LookDown | LookDownReturn | No | None | Looks down
LookDownReturn | None | No | None | Returns to neutral position
LookLeft | LookLeftReturn | No | None | Looks left
LookLeftReturn | None | No | None | Returns to neutral position
LookRight | LookRightReturn | No | None | Looks right
LookRightReturn | None | No | None | Returns to neutral position
LookUp | LookUpReturn | No | None | Looks up
LookUpReturn | None | No | None | Returns to neutral position
MoveDown | MoveDownReturn | No | MovingDown | Flies down
MoveDownReturn | None | No | None | Returns to neutral position
MoveLeft | MoveLeftReturn | No | MovingLeft | Flies left
MoveLeftReturn | None | No | None | Returns to neutral position
MoveRight | MoveRightReturn | No | MovingRight | Flies right
MoveRightReturn | None | No | None | Returns to neutral position
MoveUp | MoveUpReturn | No | MovingUp | Flies up
MoveUpReturn | None | No | None | Returns to neutral position
Pleased | PleasedReturn | Yes | None | Straightens body and smiles
PleasedReturn | None | No | None | Returns to neutral position
Processing | ProcessingReturn | No | None | Presses buttons (*looping animation)
ProcessingReturn | None | No | None | Returns to neutral position
Read | None | Yes | None | Tears off printout, reads and looks up
ReadContinued | None | Yes | None | Reads and looks up
ReadReturn | None | No | None | Returns to neutral position
Reading | ReadingReturn | No | None | Reads (*looping animation)
ReadingReturn | None | No | None | Returns to neutral position
RestPose | None | Yes | Speaking | Neutral position
Sad | SadReturn | Yes | None | Sad expression
SadReturn | None | No | None | Returns to neutral position
Searching | SearchingReturn | No | None | Looks through toolbox (*looping animation)
SearchingReturn | None | No | None | Returns to neutral position
Show | None | No | Showing | Appears through door
StartListening | StartListeningReturn | Yes | None | Puts hand to ear
StartListeningReturn | None | No | None | Returns to neutral position
StopListening | StopListeningReturn | Yes | None | Puts hands to ears
StopListeningReturn | None | No | None | Returns to neutral position
Suggest | SuggestReturn | Yes | No | Displays light bulb
SuggestReturn | None | No | None | Returns to neutral position
Surprised | SurprisedReturn | Yes | None | Looks surprised
SurprisedReturn | None | No | None | Returns to neutral position
Think | ThinkReturn | Yes | None | Tilts head and scratches
ThinkReturn | None | No | None | Returns to neutral position
Uncertain | UncertainReturn | Yes | None | Shrugs
UncertainReturn | None | No | None | Returns to neutral position
Wave | WaveReturn | Yes | None | Waves
WaveReturn | None | No | None | Returns to neutral position
Write | None | Yes | None | Takes out clipboard, writes and looks up
WriteContinued | None | Yes | None | Writes and looks up
WriteReturn | None | No | None | Returns to neutral position
Writing | WritingReturn | No | None | Writes (*looping animation)
WritingReturn | None | No | None | Returns to neutral position

* If you play a looping animation, you must use Stop to clear it before other animations in the character's queue will play.


Microsoft Agent Samples

Microsoft Agent Microsoft Agent *

Samples

• HTML Samples
• VB, C++, and Java Samples

HTML Samples

These HTML pages demonstrate how to use Microsoft Agent characters from VBScript and JScript. You can browse a sample by clicking its link below. Each sample will attempt to install its required components if they are not already installed. These samples download their character animations from http://activex.microsoft.com/characters/, so you must be connected to the internet.

• Hello World
Illustrates the most basic use of Microsoft Agent from VBScript.
Requires: Agent Core Components, Text-To-Speech Engine.

• Hello World 2
Illustrates the most basic use of Microsoft Agent from JScript.
Requires: Agent Core Components, Text-To-Speech Engine.

• Hello World 3
A revised version of the Hello World sample that uses Request objects and the RequestComplete event to manage errors and report progress.
Requires: Agent Core Components, Text-To-Speech Engine.

• Goodbye World
Demonstrates the basics of scripting a Microsoft Agent character to respond to voice commands on a web page.
Requires: Agent Core Components, Text-To-Speech Engine, Command and Control Engine.

VB, C++, and Java Samples

Each sample includes a Readme.txt file with further instructions for building and running the sample. The instructions assume that you are using Microsoft Visual Basic®, Microsoft Visual C++®, or Microsoft Visual J++™, as appropriate. The location given for each sample is a path relative to the location where you installed the Internet Client SDK.

• Hello World (VB) | Samples\MSAgent\VB\Hello\
Illustrates using Microsoft Agent from Visual Basic.
• Hello World (C++) | Samples\MSAgent\C\Hello\
Illustrates using Microsoft Agent from C++.
• Hello World 2 (C++) | Samples\MSAgent\C\Hello2\
Illustrates Hello World with AgentNotifySink. Demonstrates how to receive Agent events in C++.
• Hello World 3 (C++) | Samples\MSAgent\C\Hello3\
Illustrates Hello World with AgentNotifySink and two characters. Demonstrates how to use Agent events to coordinate multiple characters in C++.
• Hello World (Java) | Samples\MSAgent\Java\Hello\
Illustrates using Microsoft Agent from a Java applet.
• Hello World 2 (Java) | Samples\MSAgent\Java\Hello2\
Illustrates Hello World with AgentNotifySink. Demonstrates how to receive Agent events in Java.
• Hello World 3 (Java) | Samples\MSAgent\Java\Hello3\
Illustrates Hello World with AgentNotifySink and two characters. Demonstrates how to use Agent events to coordinate multiple characters in Java.


Programming the Microsoft Agent Server Interface

ActiveX™ Technology for Interactive Software Agents

August 1997
Microsoft Corporation

Note: This document is provided for informational purposes only and Microsoft makes no warranties, either expressed or implied, in this document. The entire risk of the use or the results of this document remains with the user.

Information in this document is subject to change without notice. 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.

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. Microsoft, MS, MS-DOS, Windows, Windows NT, and the Windows logo are either registered trademarks or trademarks of Microsoft Corporation in the U.S. and/or other countries. Other product and company names mentioned herein may be the trademarks of their respective owners.

Contents

Introduction

Adding Microsoft Agent Functionality to Your Application

Loading Character and Animation Data

Creating a Notification Sink

Accessing Services Using Java

Reference

Introduction

Microsoft Agent provides services that enable you to program animated characters from an application. These services are implemented as an OLE Automation server. OLE Automation enables an application to control another application's object programmatically. This document assumes an understanding of the Component Object Model (COM) and OLE. For an introduction to these services, see the Programming Interface Overview. Sample programs are available from the Samples page.

Adding Microsoft Agent Functionality to Your Application

To access Microsoft Agent services, create an instance of the server and request a pointer to a specific interface that the server supports using the standard COM convention. In particular, the COM library provides an API function, CoCreateInstance, that creates an instance of the object and returns a pointer to the requested interface of the object. Request a pointer to the IAgent interface in your CoCreateInstance call or in a subsequent call to QueryInterface.

The following code illustrates this in C/C++:

hRes = CoCreateInstance(CLSID_AgentServer,
                  NULL,
                  CLSCTX_SERVER,
                  IID_IAgent,
                  (LPVOID *)&pAgent);

If the Microsoft Agent server is running, this function connects to the server; otherwise, it starts up the server.

Functions that take pointers to BSTRs allocate memory using SysAllocString. It is the caller's responsibility to free this memory using SysFreeString.

Loading Character and Animation Data

Once you have a pointer to the IAgent interface, you can use the Load method to load a character and retrieve its IDispatch interface:

   // Create a variant to store the full path of the character to load

   VariantInit(&vPath);

   vPath.vt = VT_BSTR;
   vPath.bstrVal = SysAllocString(kpwszCharacter);

   // Load the character

   hRes = pAgent->Load(vPath, &lCharID, &lRequestID);

   // Get its IDispatch interface

   hRes = pAgent->GetCharacter(lCharID, &pdCharacter);

You can then use this information to request a pointer to the IAgentCharacter:

   // Query for IAgentCharacter

   hRes = pdCharacter->QueryInterface(IID_IAgentCharacter, (LPVOID *)&pCharacter);

// Release the IDispatch

   pdCharacter->Release();

You can use this interface to access the character's methods:

   // Show the character.  The first parameter tells Microsoft
   // Agent to show the character by playing an animation.

   hRes = pCharacter->Show(FALSE, &lRequestID);

   // Make the character speak

   bszSpeak = SysAllocString(L"Hello World!");

   hRes = pCharacter->Speak(bszSpeak, NULL, &lRequestID);

   SysFreeString(bszSpeak);

When you no longer need Microsoft Agent services, such as when your client application shuts down, release its interfaces. Note that releasing the character interface does not unload the character. Call the Unload method to do this before releasing the IAgent interface:

// Clean up

if (pCharacter) {

   // Release the character interface

   pCharacter->Release();

   // Unload the character.  NOTE:  releasing the character
   // interface does NOT make the character go away.  You must
   // call Unload.

   pAgent->Unload(lCharID);
}

// Release the Agent

pAgent->Release();

VariantClear(&vPath);

Creating a Notification Sink

To be notified of events by Microsoft Agent, you must implement the IAgentNotifySink interface, and create and register an object of that type following COM conventions:

// Create a notification sink

pSink = new AgentNotifySink;

pSink->AddRef();

// And register it with Microsoft Agent

hRes = pAgent->Register((IUnknown *)pSink, &lNotifySinkID);

Remember to unregister your notification sink when your application shuts down and releases Microsoft Agent's interfaces.

Accessing Services Using Java

You can also access Microsoft Agent services from a Java™ applet. Many of the functions accessible through the Microsoft Agent interfaces return values through parameters passed by reference. In order to pass these parameters from Java, it is necessary to create single-element arrays in your code and pass them as parameters to the appropriate function. If you're using Microsoft Visual J++™ and have run the Java Type Library Wizard on the Microsoft Agent server, refer to the summary.txt file to review which functions require array arguments. The procedure is similar to that in C; you use the IAgent interface to create an instance of the server, then load the character:

private IAgent            m_Agent = null;
private IAgentCharacter   m_Merlin[] = {null};
private int               m_MerlinID[] = {-1};
private int               m_RequestID[] = {0};
private final String      m_CharacterPath = "c:\\agentx\\agtchared\\merlin.acs";

public void start()
{
      // Start the Microsoft Agent Server

      m_Agent = (IAgent) new AgentServer();

      try
      {
         // The filespec parameter of the Load method is a
         // COM variant to accept alternate Agent data providers.
         // We want a standard provider so we can just specify
         // the filespec for our character.

         Variant characterPath = new Variant();
         characterPath.putString(m_CharacterPath);

         // Load the character

         m_Agent.Load(characterPath,
                   m_MerlinID,
                   m_RequestID);
      }

Then get the IAgentCharacter interface that enables you to access its methods:

// Get the IAgentCharacter interface for the loaded
// character by passing its ID to the Agent server.

m_Agent.GetCharacter(m_MerlinID[0], m_Merlin);

// Show the character

m_Merlin[0].Show(FALSE, m_RequestID);

// And speak hello

m_Merlin[0].Speak("Hello World!", "", m_RequestID);

Similarly, to be notified of events, you must implement the IAgentNotifySink interface, creating and registering an object of that type:

...
// Declare an Agent Notify Sink so that we can get
// notification callbacks from the Agent server.

private AgentNotifySink m_Sink = null;
private int            m_SinkID[] = {-1};

public void start()
   {
   ...
   // Create and register a notify sink

   m_Sink = new AgentNotifySink();

   m_Agent.Register(m_Sink, m_SinkID);
   ...
   // Give our notify sink access to the character

   m_Sink.SetCharacter(m_Merlin[0]);
   ...
   }

Reference

This reference contains the following sections:

Interfaces

Events

Interfaces

Microsoft Agent defines interfaces that allow applications to access its services, enabling an application to control the animation of a character, support user input events, and specify output.

The AgentServer.h file defines all the Microsoft Agent interfaces.

IAgent

IAgent defines an interface that allows applications to load characters, receive events, and check the current state of the Microsoft Agent Server.

Methods in Vtable Order

IAgent Methods | Description
Load | Loads a character's data file.
Unload | Unloads a character's data file.
Register | Registers a notification sink for the client.
Unregister | Unregisters a client's notification sink.
GetCharacter | Returns the IAgentCharacter interface for a loaded character.
GetSuspended | Returns whether the server is currently suspended.

IAgent::GetCharacter

HRESULT GetCharacter(
   long dwCharID  // character ID
);

Retrieves the IAgentCharacter for a loaded character.

  • Returns S_OK to indicate the operation was successful.
DwCharID

The character's ID.

IAgent::GetSuspended

HRESULT GetSuspended(
   long * pbSuspended  // address of variable for suspended flag
);

Retrieves whether the Microsoft Agent server is currently suspended.

  • Returns S_OK to indicate the operation was successful.
pbSuspended

Address of a variable that receives TRUE if the Microsoft Agent server is in the suspended state and FALSE if not.

Microsoft Agent loads in a suspended state when a client application attempts to start it up after the user has previously quit (by choosing the Exit command on the Microsoft Agent taskbar icon). In the suspended state Microsoft Agent handles connection requests, but returns failure on any animation methods. Therefore, a character cannot be displayed in this state. Client applications can advise users to restart the server (by choosing Restart on the taskbar pop-up menu), but cannot restart the server directly.

IAgent::Load

HRESULT Load(
   VARIANT vLoadKey,  // data provider
   long * pdwCharID,  // address of a variable for character ID
   long * pdwReqID    // address of a variable for request ID
);

Loads a character into the Characters collection.

  • Returns S_OK to indicate the operation was successful.
vLoadKey

A variant datatype that must be one of the following:

filespec | The local file location of the specified character's definition file.
URL | The HTTP address for the character's definition file.
provider | An alternate character definition provider.

pdwCharID

Address of a variable that receives the character's ID.

pdwReqID

Address of a variable that receives the Load request ID.

Microsoft Agent's data provider supports loading character data stored as a single structured file (.ACS) with character data and animation data together, or as separate character data (.ACF) and animation (.AAF) files. Generally, use the single structured .ACS file to load a character that is stored on a local disk drive or network and accessed using conventional file protocol (such as UNC pathnames). Use the separate .ACF and .AAF files when you want to load the animation files individually from a remote site where they are accessed using HTTP protocol.

For .ACS files, using the Load method provides access a character's animations. For .ACF files, you also use the Prepare method to load animation data. The Load method does not support downloading .ACS files from an HTTP site.

Loading a character does not automatically display the character. Use the Show method first to make the character visible.

The vLoadKey parameter also enables you specify your own data provider (that would be loaded separately) that can have its own methods for loading animation data. You need to create a data provider object only if you supply character data in special formats.

IAgent::Register

HRESULT Register(
   IUnknown * punkNotifySink  // address of IUnknown for client
);                            // notification sink

Registers a notification sink for the client application.

  • Returns S_OK to indicate the operation was successful.
IUnknown

Address of IUnknown for your notification sink interface.

You need to register your notification sink (also known as a notify sink or event sink) to receive events from the Microsoft Agent server.

See also IAgent::Unregister

IAgent::UnLoad

HRESULT UnLoad(
   long * dwCharID  //character ID
);

Unloads the character data for the specified character from the Characters collection.

  • Returns S_OK to indicate the operation was successful.
dwCharID

The character's ID.

Use this method when you no longer need a character, to free up memory used to store information about the character. If you access the character again, use the Load method.

See also IAgent::Load

IAgent::Unregister

HRESULT Unregister(
   long dwSinkID  //notification sink ID
);

Unloads the character data for the specified character from the Characters collection.

  • Returns S_OK to indicate the operation was successful.
dwSinkID

The notification sink ID.

Use this method when you no longer need Microsoft Agent services, such as when your application shuts down.

See also IAgent::Register

IAgentCharacter

IAgentCharacter defines an interface that allows applications to query character properties and play animations.

Methods in Vtable Order

IAgentCharacter Methods | Description
GetVisible | Returns whether the character (frame) is currently visible.
SetPosition | Sets the position of the character frame.
GetPosition | Returns the position of the character frame.
SetSize | Sets the size of the character frame.
GetSize | Returns the size of the character frame.
GetName | Returns the name of the character.
GetDescription | Returns the description for the character.
GetTTSSpeed | Returns the current TTS output speed setting for the character.
GetTTSPitch | Returns the current TTS pitch setting for the character.
Activate | Sets whether a client is active or a character is topmost.
SetInputActive | Sets the character to be input-active.
SetIdleOn | Sets the server's idle processing.
GetIdleOn | Returns the setting of the server's idle processing.
Prepare | Retrieves animation data for the character.
Play | Plays a specified animation.
Stop | Stops an animation for a character.
StopAll | Stops all animations for a character.
Wait | Holds the character's animation queue.
Interrupt | Interrupts a character's animation.
Show | Displays the character and plays the character's Showing state animation.
Hide | Plays the character's Hiding state animation and hides the character's frame.
Speak | Plays spoken output for the character.
MoveTo | Moves the character frame to the specified location.
GestureAt | Plays a gesturing animation based on the specified location.
GetMoveCause | Retrieves the cause of the character's last move.
GetVisibilityCause | Retrieves the cause of the last change to the character's visibility state.
HasOtherClients | Retrieves whether the character has other current clients.
SetSoundEffectsOn | Determines whether a character animation's sound effects play.
GetSoundEffectsOn | Retrieves whether a character's sound effects setting is enabled.
SetName | Sets the character's name.
SetDescription | Sets the character's description.
GetExtraData | Retrieves additional data stored with the character.

IAgentCharacter::Activate

HRESULT Activate(
   short sState, // topmost character or client setting
);

Sets whether a client is active or a character is topmost.

  • Returns S_OK to indicate the operation was successful.
  • Returns S_FALSE to indicate the operation was not successful.
sState

You can specify the following values for this parameter:

0 Set as not the active client.

1 Set as the active client.

2 Make the topmost character.

When multiple characters are visible, only one of the characters receives speech input at a time. Similarly, when multiple client applications share the same character, only one of the clients receives mouse input (for example, Microsoft Agent control click or drag events) at a time. The character set to receive mouse and speech input is the topmost character and the client that receives input is the character's active client. (The topmost character's window also appears at the top of the character window's z-order.) Typically, the user determines which character is topmost by explicitly selecting it. However, topmost activation also changes when a character is shown or hidden (the character becomes or is no longer topmost, respectively.)

You can also use this method to explicitly manage when your client receives input directed to the character, such as when your application itself becomes active. For example, setting State to 2 makes the character topmost, and your client receives all mouse and speech input events generated from user interaction with the character. Therefore, it also makes your client the input-active client of the character. However, you can also set the active client for a character without making the character topmost, by setting State to 1. This enables your client to receive input directed to that character when the character becomes topmost. Similarly, you can set your client to not be the active client (to not receive input) when the character becomes topmost, by setting State to 0. You can determine if a character has other current clients using IAgentCharacter::HasOtherClients.

Avoid calling this method directly after a Show method. Show automatically sets the input-active client. When the character is hidden, the Activate call may fail if it gets processed before the Show method completes.

If you call this method to a function, it returns a Boolean value that indicates whether the method succeeded. Attempting to call this method with the State parameter set to 2 when the specified character is hidden will fail. Similarly, if you set State to 0 and your application is the only client, this call fails because a character must always have a topmost client.

See also IAgentCharacter::HasOtherClients

IAgentCharacter::GestureAt

HRESULT GestureAt(
   short x,         // x-coordinate of specified location
   short y,         // y-coordinate of specified location
   long * pdwReqID  // address of a request ID
);

Plays the associated Gesturing state animation based on the specified location.

  • Returns S_OK to indicate the operation was successful. When the function returns, pdwReqID contains the ID of the request.
x

The x-coordinate of the specified location in pixels, relative to the screen origin (upper left).

y

The y-coordinate of the specified location in pixels, relative to the screen origin (upper left).

pdwReqID

Address of a variable that receives the GestureAt request ID.

The server automatically determines and plays the appropriate gesturing animation based on the character's current position and the specified location. When using the HTTP protocol to access character and animation data, use the Prepare method to ensure that the animations are available before calling this method.

IAgentCharacter::GetDescription

HRESULT GetDescription(
   BSTR * pbszDescription   // address of buffer for character description
);

Retrieves the description of the character.

  • Returns S_OK to indicate the operation was successful.
pbszDescription

The address of a BSTR that receives the value of the description for the character. A character's description is defined when it is compiled with the Microsoft Agent Character Editor. The description setting is optional and may not be supplied for all characters.

IAgentCharacter::GetExtraData

HRESULT GetExtraData(
   BSTR * pbszExtraData   // address of buffer for additional character data
);

Retrieves additional data stored as part of the character.

  • Returns S_OK to indicate the operation was successful.
pbszExtraData

The address of a BSTR that receives the value of the additional data for the character. A character's additional data is defined when it is compiled with the Microsoft Agent Character Editor. A character developer can supply this string by editing the .ACD file for a character. The setting is optional and may not be supplied for all characters, nor can the data be defined or changed at run time. In addition, the meaning of the data supplied is defined by the character developer.

IAgentCharacter::GetIdleOn

HRESULT GetIdleOn(
   long * pbOn  // address of idle processing flag
);

Indicates the automatic idle processing state for a character.

  • Returns S_OK to indicate the operation was successful.
pbOn

Address of a variable that receives TRUE if the Microsoft Agent server automatically plays Idling state animations for a character and FALSE if not.

See also IAgentCharacter::SetIdleOn

IAgentCharacter::GetMoveCause

HRESULT GetMoveCause(
   long * pdwCause  // address of variable for cause of character move
);

Retrieves the cause of the character's last move.

  • Returns S_OK to indicate the operation was successful.
pdwCause

Address of a variable that receives the cause of the character's last move and will be one of the following:

const unsigned short NeverMoved = 0; | Character has not been moved.
const unsigned short UserMoved = 1; | User dragged the character.
const unsigned short ProgramMoved = 2; | To Your application moved the character.
const unsigned short OtherProgramMoved = 3; | Another application moved the character.

See also IAgentNotifySink::Move

IAgentCharacter::GetName

HRESULT GetName(
   BSTR * pbszName   // address of buffer for character name
);

Retrieves the name of the character.

  • Returns S_OK to indicate the operation was successful.
pbszName

The address of a BSTR that receives the value of the name for the character. A character's default name is defined when it is compiled with the Microsoft Agent Character Editor. The name setting is optional and may not be supported for all characters. You can also set the character's name using IAgentCharacter:SetName; however, this changes the name for all current clients of the character.

See also IAgentCharacter::SetName

IAgentCharacter::GetPosition

HRESULT GetPosition(
   long * plLeft,  // address of variable for left edge of character
   long * plTop    // address of variable for top edge of character
);

Retrieves the character's animation frame position.

  • Returns S_OK to indicate the operation was successful.
plLeft

Address of a variable that receives the screen coordinate of the character animation frame's left edge in pixels, relative to the screen origin (upper left).

plTop

Address of a variable that receives the screen coordinate of the character animation frame's top edge in pixels, relative to the screen origin (upper left).

Even though the character appears in an irregularly shaped region window, the location of the character is based on its rectangular animation frame.

See also IAgentCharacter::SetPosition, IAgentCharacter::GetSize

IAgentCharacter::GetSize

HRESULT GetSize(
   long * plWidth,  // address of variable for character width
   long * plHeight  // address of variable for character height
);

Retrieves the size of the character's animation frame.

  • Returns S_OK to indicate the operation was successful.
plWidth

Address of a variable that receives the width of the character animation frame in pixels, relative to the screen origin (upper left).

plHeight

Address of a variable that receives the height of the character animation frame in pixels, relative to the screen origin (upper left).

Even though the character appears in an irregularly shaped region window, the location of the character is based on its rectangular animation frame.

See also IAgentCharacter::SetSize

IAgentCharacter::GetSoundEffectsOn

HRESULT GetSoundEffectsOn(
   long * pbOn  // address of variable for sound effects setting
);

Retrieves whether the character's sound effects setting is enabled.

  • Returns S_OK to indicate the operation was successful.
pbOn

Address of a variable that receives TRUE if the character's sound effects setting is enabled, FALSE if disabled.

The character's sound effects setting determines whether sound effects compiled as a part of the character are played when you play an associated animation. The setting is subject to the user's global sound effects setting in IAgentAudioOutputProperties::GetUsingSoundEffects.

See also IAgentCharacter::SetSoundEffectsOn, IAgentAudioOutputProperties::GetUsingSoundEffects

IAgentCharacter::GetTTSPitch

HRESULT GetTTSPitch(
   long * pdwPitch  // address of variable for character TTS pitch
);

Retrieves the character's TTS output pitch setting.

  • Returns S_OK to indicate the operation was successful.
pdwPitch

Address of a variable that receives the character's current TTS pitch setting in Hertz.

Although your application cannot write this value, you can include pitch tags in your output text that will temporarily increase the pitch for a particular utterance. This method applies only to characters configured for TTS output. If the speech synthesis (TTS) engine is not enabled (or installed) or the character does not support TTS output, this method returns zero (0).

IAgentCharacter::GetTTSSpeed

HRESULT GetTTSSpeed(
   long * pdwSpeed  // address of variable for character TTS output speed
);

Retrieves the character's TTS output speed setting.

  • Returns S_OK to indicate the operation was successful.
pdwSpeed

Address of a variable that receives the output speed of the character in words per minute.

Although your application cannot write this value, you can include speed tags in your output text that will temporarily speed up the output for a particular utterance.

This property returns the current speaking output speed setting for the character. For characters using TTS output, the property returns the actual TTS output for the character. If TTS is not enabled or the character does not support TTS output, the setting reflects the user setting for output speed.

IAgentCharacter::GetVisibilityCause

HRESULT GetVisibilityCause(
   long * pdwCause  // address of variable for cause of character visible state
);

Retrieves the cause of the character's visible state.

  • Returns S_OK to indicate the operation was successful.
pdwCause

Address of a variable that receives the cause of the character's last visibility state change and will be one of the following:

const unsigned short NeverShown = 0; | Character has not been shown.
const unsigned short UserHid = 1; | User hid the character.
const unsigned short UserShowed = 2; | User showed the character.
const unsigned short ProgramHid = 3; | Your application hid the character.
const unsigned short ProgramShowed = 4; | Your application showed the character.
const unsigned short OtherProgramHid = 5; | Another application hid the character.
const unsigned short OtherProgramShowed = 6; | Another application showed the character.

See also IAgentNotifySink::Hide, IAgentNotifySink::Show

IAgentCharacter::GetVisible

HRESULT GetVisible(
   long * pbVisible  // address of variable for character Visible setting
);

Determines whether the character's animation frame is currently visible.

  • Returns S_OK to indicate the operation was successful.
pbVisible

Address of a variable that receives TRUE if the character's frame is visible and FALSE if hidden.

You can use this method to determine whether the character's frame is currently visible. To make a character visible, use the Show method. To hide a character, use the Hide method.

IAgentCharacter::HasOtherClients

HRESULT HasOtherClients(
   long * pbHasOtherClients  // address of variable for whether character has
);                           // other clients

Retrieves whether a character has other clients.

  • Returns S_OK to indicate the operation was successful.
pbHasOtherClients

Address of a variable that receives TRUE if the character has other clients and FALSE if not.

IAgentCharacter::Hide

HRESULT Hide(
   long bFast,      // play Hiding state animation flag
   long * pdwReqID  // address of request ID
);

Hides the character.

  • Returns S_OK to indicate the operation was successful. When the function returns, pdwReqID contains the ID of the request.
bFast

Hiding state animation flag. If this parameter is TRUE, the Hiding animation does not play before the character frame is hidden; if FALSE, the animation plays.

pdwReqID

Address of a variable that receives the Hide request ID.

The server queues the animation associated with the Hide method in the character's queue. This allows you to use it to hide the character after a sequence of other animations. You can play the action immediately by using the Stop method before calling the Hide method.

When using the HTTP protocol to access character and animation data, use the Prepare method to ensure the availability of the Hiding state animation before calling this method.

Hiding a character can also result in triggering the ActivateInput event of another visible character.

Hidden characters cannot access the audio channel. The server will pass back a failure status in the RequestComplete event if you generate an animation request and the character is hidden.

See also IAgentCharacter::Show

IAgentCharacter::Interrupt

HRESULT Interrupt(
   long dwReqID,    // request ID to interrupt
   long * pdwReqID  // address of request ID
);

Interrupts the specified animation (request) of another character.

  • Returns S_OK to indicate the operation was successful. When the function returns, pdwReqID contains the ID of the request.
dwReqID

An ID of the request to interrupt.

pdwReqID

Address of a variable that receives the Interrupt request ID.

You can use this method to sync up animation between characters. For example, if another character is in a looping animation, this method will stop the looping animation and start the next animation in the character's queue.

Interrupt halts the existing animation, but does not flush the character's animation queue. It starts the next animation in the character's queue. To halt and flush a character's queue, use the Stop method.

You cannot use this method to have a character interrupt itself because the Microsoft Agent server queues the Interrupt method in the character's animation queue. Therefore, you can only use Interrupt to halt the animation of another character you have loaded.

IAgentCharacter::MoveTo

HRESULT MoveTo(
   short x,         // x-coordinate of new location
   short y,         // y-coordinate of new location
   long lSpeed,     // speed to move the character
   long * pdwReqID  // address of request ID
);

Plays the associated Moving state animation and moves the character frame to the specified location.

  • Returns S_OK to indicate the operation was successful. When the function returns, this variable contains the ID of the request.
x

The x-coordinate of the new position in pixels, relative to the screen origin (upper left). The location of a character is based on the upper left corner of its animation frame.

y

The y-coordinate of the new position in pixels, relative to the screen origin (upper left). The location of a character is based on the upper left corner of its animation frame.

lSpeed

A parameter specifying in milliseconds how quickly the character's frame moves. The recommended value is 1000. Specifying zero (0) moves the frame without playing an animation.

pdwReqID

Address of a variable that receives the MoveTo request ID.

When using the HTTP protocol to access character and animation data, use the Prepare method to ensure the availability of the Moving state animations before calling this method. Even if the animation is not loaded, the server still moves the frame.

See also IAgentCharacter::SetPosition

IAgentCharacter::Play

HRESULT Play(
   BSTR bszAnimation,  // name of an animation
   long * pdwReqID     // address of request ID
);

Plays the specified animation.

  • Returns S_OK to indicate the operation was successful. When the function returns, pdwReqID contains the ID of the request.
bszAnimation

The name of an animation.

pdwReqID

Address of a variable that receives the Play request ID.

An animation's name is defined when the character is compiled with the Microsoft Agent Character Editor. Before playing the specified animation, the server attempts to play the Return animation for the previous animation (if one has been assigned).

When a character's animation data is stored on the user's local machine, you can use the Play method and specify the name of the animation. When using the HTTP protocol to access animation data, use the Prepare method to ensure the availability of the animation before calling this method.

See also IAgentCharacter::Prepare

IAgentCharacter::Prepare

HRESULT Prepare(
   long dwType,     // type of animation data to load
   BSTR bszName,    // name of the animation
   long bQueue,     // queue the request
   long * pdwReqID  // address of request ID
);

Retrieves animation data for a character.

  • Returns S_OK to indicate the operation was successful. When the function returns, pdwReqID contains the ID of the request.
dwType

A value that indicates the animation data type to load that must be one of the following:

const unsigned short PREPARE_ANIMATION = 0; | A character's animation data.
const unsigned short PREPARE_STATE = 1; | A character's state data.
const unsigned short PREPARE_WAVE = 2 | A character's sound file (.WAV or .LWV) for spoken output.

bszName

The name of the animation or state.

The animation name is based on that defined for the character when it was saved using the Microsoft Agent Character Editor.

For states, the value can be one of the following:

"Gesturing" | To retrieve all Gesturing state animations.
"GesturingDown" | To retrieve GesturingDown animations.
"GesturingLeft" | To retrieve GesturingLeft animations.
"GesturingRight" | To retrieve GesturingRight animations.
"GesturingUp" | To retrieve GesturingUp animations.
"Hiding" | To retrieve the Hiding state animations.
"Hearing" | To retrieve the Hearing state animations.
"Idling" | To retrieve all Idling state animations.
"IdlingLevel1" | To retrieve all IdlingLevel1 animations.
"IdlingLevel2" | To retrieve all IdlingLevel2 animations.
"IdlingLevel3" | To retrieve all IdlingLevel3 animations.
"Listening" | To retrieve the Listening state animations.
"Moving" | To retrieve all Moving state animations.
"MovingDown" | To retrieve all Moving animations.
"MovingLeft" | To retrieve all MovingLeft animations.
"MovingRight" | To retrieve all MovingRight animations.
"MovingUp" | To retrieve all MovingUp animations.
"Showing" | To retrieve the Showing state animations.
"Speaking" | To retrieve the Speaking state animations.

For .WAV files, set bszName to the URL or file specification for the .WAV file. If the specification is not complete, it is interpreted as being relative to the specification used in the Load method.

bQueue

A Boolean specifying whether the server queues the Prepare request. TRUE queues the request and causes any animation request that follows it to wait until the animation data it specifies is loaded. FALSE retrieves the animation data asynchronously.

pdwReqID

Address of a variable that receives the Prepare request ID.

You can specify multiple animations and states by separating them with commas. However, you cannot mix types in the same Prepare statement.

IAgentCharacter::SetDescription

HRESULT SetDescription(
   BSTR bszDescription   // character description
);

Sets the description of the character.

  • Returns S_OK to indicate the operation was successful.
bszDescription

A BSTR that sets the description for the character. A character's default description is defined when it is compiled with the Microsoft Agent Character Editor. The description setting is optional and may not be supplied for all characters. You can change the character's description using IAgentCharacter::SetDescription; however, this value is not persistent (stored permanently). The character's description reverts to its default setting whenever the character is first loaded by a client.

See also IAgentCharacter::GetDescription

IAgentCharacter::SetIdleOn

HRESULT SetIdleOn(
   long bOn  // idle processing flag
);

Sets automatic idle processing for a character.

  • Returns S_OK to indicate the operation was successful.
bOn

Idle processing flag. If this parameter is TRUE, the Microsoft Agent automatically plays Idling state animations.

The server automatically sets a time out after the last animation played for a character. When this timer's interval is complete, the server begins the Idling states for a character, playing its associated Idling animations at regular intervals. If you want to manage the Idling state animations yourself, set the property to FALSE.

See also IAgentCharacter::GetIdleOn

IAgentCharacter::SetName

HRESULT SetName(
   BSTR bszName   // character name
);

Sets the name of the character.

  • Returns S_OK to indicate the operation was successful.
bszName

A BSTR that sets the character's name. A character's default name is defined when it is compiled with the Microsoft Agent Character Editor. You can change it using IAgentCharacter::SetName; however, this changes the character name for all current clients of the character. This property is not persistent (stored permanently). The character's name reverts to its default name whenever the character is first loaded by a client.

The server uses the character's name setting in parts of the Microsoft Agent's interface, such as the Commands Window title when the character is input-active and in the Microsoft Agent taskbar pop-up menu.

See also IAgentCharacter::GetName

IAgentCharacter::SetPosition

HRESULT SetPosition(
   long lLeft,  // screen coordinate of the left edge of character
   long lTop    // screen coordinate of the top edge of character
);

Sets the position of the character's animation frame.

  • Returns S_OK to indicate the operation was successful.
lLeft

Screen coordinate of the character animation frame's left edge in pixels, relative to the screen origin (upper left).

lTop

Screen coordinate of the character animation frame's top edge in pixels, relative to the screen origin (upper left).

Even though the character appears in an irregularly shaped region window, the location of the character is based on its rectangular animation frame.

Note Unlike the MoveTo method, this function is not queued.

See also IAgentCharacter::GetPosition

IAgentCharacter::SetSize

HRESULT SetSize(
   long * lWidth,  // width of the character frame
   long * lHeight  // height of the character frame
);

Sets the size of the character's animation frame.

  • Returns S_OK to indicate the operation was successful.
lWidth

The width of the character's animation frame in pixels.

lHeight

The height of the character's animation frame in pixels.

Changing the character's frame size scales the character to the size set with this method.

Even though the character appears in an irregularly shaped region window, the location of the character is based on its rectangular animation frame.

See also IAgentCharacter::GetSize

IAgentCharacter::SetSoundEffectsOn

HRESULT SetSoundEffectsOn(
   long bOn  // character sound effects setting
);

Determines whether the character's sound effects are played.

  • Returns S_OK to indicate the operation was successful.
bOn

Sound effects setting. If this parameter is TRUE, the sound effects for animations are played when the animation plays; if FALSE, sound effects are not played.

This setting determines whether sound effects compiled as a part of the character are played when you play an associated animation. The setting is subject to the user's global sound effects setting in IAgentAudioOutputProperties::GetUsingSoundEffects.

See also IAgentCharacter::GetSoundEffectsOn, IAgentAudioOutputProperties::GetUsingSoundEffects

IAgentCharacter::Show

HRESULT Show(
   long bFast,      // play Showing state animation flag
   long * pdwReqID  // address of request ID
);

Displays a character.

  • Returns S_OK to indicate the operation was successful. When the function returns, pdwReqID contains the ID of the request.
bFast

Showing state animation flag. If this parameter is TRUE, the Showing state animation plays after making the character visible; if FALSE, the animation does not play.

pdwReqID

Address of a variable that receives the Show request ID.

Avoid setting the bFast parameter to TRUE without playing an animation beforehand, otherwise, the character frame may be displayed, but have no image to display. In particular, note that that if you call MoveTo when the character is not visible, it does not play any animation. Therefore, if you call the Show method with bFast set to TRUE, no image will be displayed. Similarly, if you call Hide then Show with bFast set to TRUE, there will be no visible image.

When using the HTTP protocol to access character and animation data, use the Prepare method to ensure the availability of the Showing state animation before calling this method.

See also IAgentCharacter::Hide

IAgentCharacter::Speak

HRESULT Speak(
   BSTR bszText,    // text to speak
   BSTR bszURL,     // URL of a file to speak
   long * pdwReqID  // address of a request ID
);

Speaks the

  • Returns S_OK to indicate the operation was successful.
bszText

The text the character is to speak.

bszURL

The URL (or file specification) of a sound file to use for spoken output. This can be a standard sound file (.WAV) or linguistically enhanced sound file (.LWV).

pdwReqID

Address of a variable that receives the Speak request ID.

To use this method with a character configured to speak using a text-to-speech (TTS) engine; simply provide the bszText parameter. You can include vertical bar characters (|) in the bszText parameter to designate alternative strings, so that each time the server processes the method, it randomly choose a different string. Support of TTS output is defined when the character is compiled using the Microsoft Agent Character Editor.

If you want to use sound file output for the character, specify the location for the file in the bszURL parameter. When using the HTTP protocol to download a sound file, use the Prepare method to ensure the availability of the file before using this method. You can use the bszText parameter to specify the words that appear in the character's word balloon. If you specify a linguistically enhanced sound file (.LWV) for the bszURL parameter and do not specify text, the bszText parameter uses the text stored in the file.

The Speak method uses the last animation played to determine which speaking animation to play. For example, if you precede the Speak command with a Play "GestureRight", the server will play GestureRight and then the GestureRight speaking animation.

If you call Speak and the audio channel is busy, the character's audio output will not be heard, but the text will display in the word balloon. The word balloon's Enabled property must also be TRUE for the text to display.

See also IAgentCharacter::Play, IAgentBalloon::Enabled, IAgentCharacter::Prepare

IAgentCharacter::Stop

HRESULT Stop(
   long dwReqID  // request ID
);

Stops the specified animation (request) and removes it from the character's animation queue.

  • Returns S_OK to indicate the operation was successful.
dwReqID

The ID of the request to stop.

Stop can also be used to halt any queued Prepare calls.

See also IAgentCharacter::Prepare, IAgentCharacter::StopAll

IAgentCharacter::StopAll

HRESULT StopAll();
   long lType,  // request type

Stops all animations (requests) and removes them from the character's animation queue.

lType

A bit field that indicates the types of requests to stop (and remove from the character's queue), comprised from the following:

const unsigned long STOP_TYPE_ALL = 0xFFFFFFFF; | Stops all animation requests, including non-queued Prepare requests.
const unsigned long STOP_TYPE_PLAY = 0x00000001; | Stops all Play requests.
const unsigned long STOP_TYPE_MOVE = 0x00000002; | Stops all Move requests.
const unsigned long STOP_TYPE_SPEAK = 0x00000004; | Stops all Speak requests.
const unsigned long STOP_TYPE_PREPARE = 0x00000008; | Stops all queued Prepare requests.
const unsigned long STOP_TYPE_NONQUEUEDPREPARE = 0x00000010; | Stops all non-queued Prepare requests.
const unsigned long STOP_TYPE_VISIBLE = 0x00000020; | Stops all Hide or Show requests.

See also IAgentCharacter::Stop

IAgentCharacter::Wait

HRESULT Wait(
   long dwReqID,    // request ID
   long * pdwReqID  // address of request ID
);

Holds the character's animation queue at the specified animation (request) until another request for another character completes.

  • Returns S_OK to indicate the operation was successful.
dwReqID

The ID of the request to wait for.

pdwReqID

Address of a variable that receives the Wait request ID.

Use this method only when you support multiple (simultaneous) characters and want to sequence their interaction (as a single client). (For a single character, each animation request is played sequentially--after the previous request completes.) If you have two characters and want one character's animation request to wait until the other character's animation completes, set the Wait method to the other character's animation request ID.

IAgentCommands

The Microsoft Agent server maintains a list of commands that are currently available to the user. This list includes commands that the server defines for general interaction, such as Hide and Microsoft Agent Properties, the list of available (but non-input-active) clients, and the commands defined by the current active client. The first two sets of commands are global commands; that is, they are available at any time, regardless of the input-active client. Client-defined commands are available only when that client is input-active.

Retrieve an IAgentCommands interface by querying the IAgentCharacter interface for IAgentCommands. Each Microsoft Agent client application can define a collection of commands called a Commands collection. To add a Command to the collection, use the Add or Insert method. Although you can specify a Command's properties using IAgentCommand methods, for optimum code performance, specify all of a Command's properties in the IAgentCommands::Add or IAgentCommands::Insert methods when initially setting the properties for a new Command. You can use the IAgentCommand methods to query or change the property settings.

For each Command in the Commands collection, you can determine whether the command appears on the character's pop-up menu, in the Commands Window, in both, or in neither. For example, if you want a command to appear on the pop-up menu for the character, set the command's Caption and Visible properties. To display the command in the Commands Window, set the command's Caption and Voice properties.

A user can access the individual commands in your Commands collection only when your client application is input-active. Therefore, you will typically want to set the Caption and Voice properties for the Commands collection object as well as for the commands in the collection, because this places an entry for your Commands collection on a character's pop-up menu and in the Commands Window. When the user switches to your client by choosing its entry, the server automatically makes your client input-active and makes the Commands in its collection available. This enables the server to present and accept only the Commands that apply to the current input-active client's context. It also serves to avoid Command-name collisions between clients.

When a character's pop-up menu is displayed, changes to the properties of a Commands collection or the commands in its collection do not appear until the user redisplays the menu. However, when open, the Commands Window does display changes as they happen.

IAgentCommands defines an interface that allows applications to add, remove, set, and query properties for a Commands collection. A Commands collection can appear as a command in both the pop-up menu and the Commands Window for a character. To make the Commands collection appear, you must set its Caption property. The following table summarizes how the properties of a Commands collection affect its presentation.

Caption Property | Voice Property | Visible Property | Appears in Character's Pop-up Menu | Appears in Commands Window
Yes | Yes | True | Yes | Yes
Yes | Yes | False | No | Yes
Yes | No | True | Yes | No
Yes | No | False | No | No
No | Yes | True | No | No*
No | Yes | False | No | No*
No | No | True | No | No
No | No | False | No | No
*The command is still voice-accessible. If the client is input-active and has Commands in its collection, "(command undefined)" appears in the Commands Window.

Methods in Vtable Order

IAgentCommands Methods | Description
GetCommand | Retrieves a Command object from the Commands collection.
GetCount | Returns the value of the number of Commands in a Commands collection.
SetCaption | Sets the value of the Caption property for a Commands collection.
GetCaption | Returns the value of the Caption property of a Commands collection.
SetVoice | Sets the value of the Voice property for a Commands collection.
GetVoice | Returns the value of the Voice property of a Commands collection.
SetVisible | Sets the value of the Visible property for a Commands collection.
GetVisible | Returns the value of the Visible property of a Commands collection.
Add | Adds a Command object to a Commands collection.
Insert | Inserts a Command object in a Commands collection.
Remove | Removes a Command object in a Commands collection.
RemoveAll | Removes all Command objects from a Commands collection.

IAgentCommands::Add

HRESULT Add(
   BSTR bszCaption,  // Caption setting for Command
   BSTR bszVoice,    // Voice setting for Command
   long bEnabled,    // Enabled setting for Command
   long bVisible,    // Visible setting for Command
   long * pdwID      // address for variable for ID
);

Adds a Command to a Commands collection.

  • Returns S_OK to indicate the operation was successful.
bszCaption

A BSTR that specifies the value of the Caption text displayed for a Command in a Commands collection.

bszVoice

A BSTR that specifies the value of the Voice text setting for a Command in a Commands collection.

bEnabled

A Boolean expression that specifies the Enabled setting for a Command in a Commands collection. If the parameter is TRUE, the Command is enabled and can be selected; if FALSE, the Command is disabled.

bVisible

A Boolean expression that specifies the Visible setting for a Command in a Commands collection. If the parameter is TRUE, the Command will be visible in the character's pop-up menu (if the Caption property is also set).

pdwID

Address of a variable that receives the ID for the added Command.

See also IAgentCommand::SetCaption, IAgentCommand::SetEnabled, IAgentCommand::SetVisible, IAgentCommand::SetVoice, IAgentCommands::Insert, IAgentCommands::Remove, IAgentCommands::RemoveAll

IAgentCommands::GetCaption

HRESULT GetCaption(
   BSTR * pbszCaption  // address of Caption text for Commands collection
);

Retrieves the Caption for a Commands collection.

  • Returns S_OK to indicate the operation was successful.
pbszCaption

The address of a BSTR that receives the value of the Caption text setting displayed for a Commands collection.

See also IAgentCommand::SetCaption, IAgentCommand::GetVisible, IAgentCommand::GetVoice

IAgentCommands::GetCommand

HRESULT GetCommand(
   long dwCommandID,         // Command ID
   IUnknown ** ppunkCommand  // address of IUnknown interface
);

Retrieves a Command object from the Commands collection.

  • Returns S_OK to indicate the operation was successful.
dwCommandID

The ID of a Command object in the Commands collection.

IUnknown

The address of the IUnknown interface for the Command object.

See also IAgentCommand

IAgentCommands::GetCount

HRESULT GetCount(
   long * pdwCount  // address of count of commands
);

Retrieves the number of Command objects in a Commands collection.

  • Returns S_OK to indicate the operation was successful.
pdwCount

Address of a variable that receives the number of Commands in a Commands collection.

pdwCount includes only the number of Commands you define in your Commands collection. Server or other client entries are not included.

IAgentCommands::GetVisible

HRESULT GetVisible(
   long * pbVisible  // address of Visible setting for Commands collection
);

Retrieves the value of the Visible property for a Commands collection.

  • Returns S_OK to indicate the operation was successful.
pbVisible

The address of a variable that receives the value of the Visible property for a Commands collection.

See also IAgentCommand::SetVisible, IAgentCommands::SetCaption

IAgentCommands::GetVoice

HRESULT GetVoice(
   BSTR * pbszVoice  // address of Voice setting for Commands collection
);

Retrieves the value of the Voice property for a Commands collection.

  • Returns S_OK to indicate the operation was successful.
pbszVoice

The address of a BSTR that receives the value of the Voice text setting for a Commands collection.

See also IAgentCommands::SetVoice, IAgentCommands::GetCaption, IAgentCommand::GetVisible

IAgentCommands::Insert

HRESULT Insert(
   BSTR bszCaption,  // Caption setting for Command
   BSTR bszVoice,    // Voice setting for Command
   long bEnabled,    // Enabled setting for Command
   long bVisible,    // Visible setting for Command
   long dwRefID,     // reference Command for insertion
   long dBefore,     // insertion position flag
   long * pdwID      // address for variable for Command ID
);

Inserts a Command object in a Commands collection.

  • Returns S_OK to indicate the operation was successful.
bszCaption

A BSTR that specifies the value of the Caption text displayed for the Command.

bszVoice

A BSTR that specifies the value of the Voice text setting for a Command.

bEnabled

A Boolean expression that specifies the Enabled setting for a Command. If the parameter is TRUE, the Command is enabled and can be selected; if FALSE, the Command is disabled.

bVisible

A Boolean expression that specifies the Visible setting for a Command. If the parameter is TRUE, the Command will be visible in the character's pop-up menu (if the Caption property is also set).

dwRefID

The ID of a Command used as a reference for the relative insertion of the new Command.

dBefore

A Boolean expression that specifies where to place the Command. If this parameter is TRUE, the new Command is inserted before the referenced Command; if FALSE, the new Command is placed after the referenced Command.

pdwID

Address of a variable that receives the ID for the inserted Command.

See also IAgentCommand::Add, IAgentCommands::Remove, IAgentCommands::RemoveAll

IAgentCommands::Remove

HRESULT Remove(
   long dwID  // Command ID
);

Removes the specified Command from a Commands collection.

  • Returns S_OK to indicate the operation was successful.
dwID

The ID of a Command to remove from the Commands collection.

Removing a Command from a Commands collection also removes it from the pop-up menu and the Commands Window when your application is input-active.

See also IAgentCommand::Add, IAgentCommands::Insert, IAgentCommands::RemoveAll

IAgentCommands::RemoveAll

HRESULT Remove();

Removes all Commands from a Commands collection.

  • Returns S_OK to indicate the operation was successful.
Removing all Commands from a Commands collection also removes them from the pop-up menu and the Commands Window when your application is input-active. RemoveAll does not remove server or other client's entries.

See also IAgentCommand::Add, IAgentCommands::Insert, IAgentCommands::Remove

IAgentCommands::SetCaption

HRESULT SetCaption(
   BSTR bszCaption  // Caption setting for Commands collection
);

Sets the Caption text displayed for a Commands collection.

  • Returns S_OK to indicate the operation was successful.
bszCaption

A BSTR that specifies the value for the Caption property for a Commands collection.

A Commands collection with its Caption property set and its Visible property set to TRUE appears in the character's pop-up menu. If its Voice property is also set, it appears in the Commands Window. If you define commands for a Commands collection that have their Caption, Enabled, and Voice properties set, you typically also define Caption and Voice settings for the associated Commands collection. If the Commands collection has no Voice or no Caption setting and is currently input-active, but the Commands in its collection have Caption and Voice settings, the Commands appear in the Commands Window tree view under "(undefined command)" when your client application becomes input-active.

See also IAgentCommands::GetCaption, IAgentCommands::SetVisible, IAgentCommands::SetVoice

IAgentCommands::SetVisible

HRESULT SetVisible(
   long bVisible  // the Visible setting for Commands collection
);

Sets the value of the Visible property for a Commands collection.

  • Returns S_OK to indicate the operation was successful.
bVisible

A Boolean value that determines the Visible property of a Commands collection. TRUE sets the Commands collection's Caption to be visible when the character's pop-up menu is displayed; FALSE does not display it.

A Commands collection must have its Caption property set and its Visible property set to TRUE to appear on the character's pop-up menu. The Visible property must also be set to TRUE for commands in the collection to appear when your client application is input-active.

See also IAgentCommands::GetVisible, IAgentCommands::SetCaption

IAgentCommands::SetVoice

HRESULT SetVoice(
   BSTR bszVoice  // the Voice setting for Command collection
);

Sets the Voice text property for a Command.

  • Returns S_OK to indicate the operation was successful.
bszVoice

A BSTR that specifies the value for the Voice text property of a Commands collection.

A Commands collection must have its Voice text property set to be voice-accessible. It also must have its Caption property set to appear in the Commands Window and its Visible property set to TRUE to appear on the character's pop-up menu.

The BSTR expression you supply can include square bracket characters ([ ]) to indicate optional words and vertical bar characters (|) to indicate alternative strings. Alternates must be enclosed in parentheses. For example, "(hello [there] | hi)" tells the speech engine to accept "hello," "hello there," or "hi" for the command. Remember to include appropriate spaces between the text that's in brackets or parentheses and the text that's not in brackets or parentheses.

You can also use an ellipsis (…) to support word spotting, that is, telling the speech recognition engine to ignore words spoken in this position in the phrase (sometimes called garbage words). When you use ellipses, the speech engine recognizes only specific words in the string regardless of when spoken with adjacent words or phrases. For example, if you set this property to "…check mail…" the speech recognition engine will match phrases like "please check mail" or "check mail please" to this command. Ellipses can be used anywhere within a string. However, be careful using this technique as voice settings with ellipses may increase the potential of unwanted matches.

When defining the words and grammar for your command, always make sure that you include at least one word that is required; that is, avoid supplying only optional words. In addition, make sure that the word includes only pronounceable words and letters. For numbers, it is better to spell out the word rather than using the numeric representation. Also, omit any punctuation or symbols. For example, instead of "the #1 $10 pizza!", use "the number one ten dollar pizza". Including non-pronounceable characters or symbols for one command may cause the speech engine to fail to compile the grammar for all your commands. Finally, make your voice parameter as distinct as reasonably possible from other voice commands you define. The greater the similarity between the voice grammar for commands, the more likely the speech engine will make a recognition error. You can also use the confidence scores to better distinguish between two commands that may have similar or similar-sounding voice grammar.

The operation of this property depends on the state of Microsoft Agent server's speech recognition state. For example, if speech recognition is disabled or not installed, this function has no immediate effect. If speech recognition is enabled during a session, however, the command will become accessible when its client application is input-active.

See also IAgentCommands::GetVoice, IAgentCommands::SetCaption, IAgentCommands::SetVisible

IAgentCommand

A Command object is an item in a Commands collection. The server provides the user access to your commands your client application becomes input active. To retrieve a Command, call IAgentCommands::GetCommand.

IAgentCommand defines an interface that allows applications to set and query properties for Command objects that can appear in a character's pop-up menu and in the Commands Window. A Command object is an item in a Commands collection. The server provides the user access to your commands when your client application becomes input active.

A Command may appear in either or both the character's pop-up menu and the Commands Window. To appear in the pop-up menu, it must have a Caption and have the Visible property set to TRUE. The Visible property for its Commands collection object must also be set to TRUE for the command to appear in the pop-up menu when your client application is input-active. To appear in the Commands Window, a Command must have its Caption and Voice properties set.

A character's pop-up menu entries do not change while the menu is displayed. If you add or remove Commands or change their properties while the character's popup menu is displayed, the menu displays those changes when redisplayed. However, the Commands Window does display changes as you make them.

The following table summarizes how the properties of a command affect its presentation.

Caption Property | Voice Property | Visible Property | Enabled Property | Appears in Character's Pop-up Menu | Appears in Commands Window
Yes | Yes | True | True | Normal | Yes
Yes | Yes | True | False | Disabled | No
Yes | Yes | False | True | Does not appear | Yes
Yes | Yes | False | False | Does not appear | No
Yes | No | True | True | Normal | No
Yes | No | True | False | Disabled | No
Yes | No | False | True | Does not appear | No
Yes | No | False | False | Does not appear | No
No | Yes | True | True | Does not appear | No*
No | Yes | True | False | Does not appear | No
No | Yes | False | True | Does not appear | No*
No | Yes | False | False | Does not appear | No
No | No | True | True | Does not appear | No
No | No | True | False | Does not appear | No
No | No | False | True | Does not appear | No
No | No | False | False | Does not appear | No
*The command is still voice-accessible.

Generally, if you define a Command with a Voice setting, you also define Caption and Voice settings for its associated Commands collection. If the Commands collection for a set of commands has no Voice or no Caption setting and is currently input-active, but the Commands have Caption and Voice settings, the Commands appear in the Commands Window tree view under "(undefined command)" when your client application becomes input active.

When the server receives input that matches one of the Command objects you defined for your Commands collection, it sends a IAgentNotifySink::Command event, and passes back the ID of the command as an attribute of the IAgentUserInput object. You can then use conditional statements to match and process the command.

Methods in Vtable Order

IAgentCommand Methods | Description
SetCaption | Sets the value for the Caption for a Command object.
GetCaption | Returns the value of the Caption property of a Command object.
SetVoice | Sets the value for the Voice text for a Command object.
GetVoice | Returns the value of the Caption property of a Command object.
SetEnabled | Sets the value of the Enabled property for a Command object.
GetEnabled | Returns the value of the Enabled property of a Command object.
SetVisible | Sets the value of the Visible property for a Command object.
GetVisible | Returns the value of the Visible property of a Command object.
SetConfidenceThreshold | Sets the value of the Confidence property for a Command object.
GetConfidenceThreshold | Returns the value of the Confidence property of a Command object.
SetConfidenceText | Sets the value of the ConfidenceText property for a Command object.
GetConfidenceText | Returns the value of the ConfidenceText property of a Command object.
GetID | Returns the ID of a Command object.

IAgentCommand::GetCaption

HRESULT GetCaption(
   BSTR * pbszCaption  // address of Caption for Command
);

Retrieves the Caption for a Command.

  • Returns S_OK to indicate the operation was successful.
pbszCaption

The address of a BSTR that receives the value of the Caption text displayed for a Command.

See also IAgentCommand::SetCaption, IAgentCommand::SetEnabled, IAgentCommand::SetVisible, IAgentCommand::SetVoice, IAgentCommands::Add, IAgentCommands::Insert

IAgentCommand::GetConfidenceText

HRESULT GetConfidenceText(
   BSTR * pbszTipText  // address of ConfidenceText setting for Command
);

Retrieves the Listening Tip text previously set for a Command.

  • Returns S_OK to indicate the operation was successful.
pbszTipText

The address of a BSTR that receives the value of the Listening Tip text for a Command.

See also IAgentCommand::SetConfidenceThreshold, IAgentCommand::GetConfidenceThreshold, IAgentCommand::SetConfidenceText, IAgentUserInput::GetItemConfidence

IAgentCommand::GetConfidenceThreshold

HRESULT GetConfidenceThreshold(
long * plConfidenceThreshold  // address of ConfidenceThreshold
);                            // setting for Command

Retrieves the value of the ConfidenceThreshold property for a Command.

  • Returns S_OK to indicate the operation was successful.
plConfidenceThreshold

The address of a variable that receives the value of the ConfidenceThreshold property for a Command.

See also IAgentCommand::SetConfidenceThreshold, IAgentCommand::SetConfidenceText, IAgentUserInput::GetItemConfidence

IAgentCommand::GetEnabled

HRESULT GetEnabled(
   long * pbEnabled  // address of Enabled setting for Command
);

Retrieves the value of the Enabled property for a Command.

  • Returns S_OK to indicate the operation was successful.
pbEnabled

The address of a variable that receives TRUE if the Command is enabled, or FALSE if it is disabled. A disabled Command cannot be selected.

See also IAgentCommand::SetCaption, IAgent::SetVisible, IAgentCommand::SetVoice, IAgentCommands::Add, IAgentCommands::Insert

IAgentCommand::GetID

HRESULT GetID(
   long * pdwID  // address of ID for Command
);

Retrieves the ID for a Command.

  • Returns S_OK to indicate the operation was successful.
pdwID

The address of a variable that receives the ID of a Command.

See also IAgentCommands::Add, IAgentCommands::Insert, IAgentCommands::Remove

IAgentCommand::GetVisible

HRESULT GetVisible(
   long * pbVisible  // address of Visible setting for Command
);

Retrieves the value of the Visible property for a Command.

  • Returns S_OK to indicate the operation was successful.
pbVisible

The address of a variable that receives the Visible property for a Command.

See also IAgentCommand::SetVisible, IAgent::SetCaption, IAgentCommands::Add, IAgentCommands::Insert

IAgentCommand::GetVoice

HRESULT GetVoice(
   BSTR * pbszVoice  // address of Voice setting for Command
);

Retrieves the value of the Voice text property for a Command.

  • Returns S_OK to indicate the operation was successful.
pbszVoice

The address of a BSTR that receives the Voice text property for a Command.

A Command with its Voice property set and its Enabled property set to TRUE will be voice-accessible. If its Caption property is also set it appears in the Commands Window. If its Visible property is set to TRUE, it appears in the character's pop-up menu.

See also IAgentCommand::SetVoice, IAgentCommands::Add, IAgentCommands::Insert

IAgentCommand::SetCaption

HRESULT SetCaption(
   BSTR bszCaption  // Caption setting for Command
);

Sets the Caption text displayed for a Command.

  • Returns S_OK to indicate the operation was successful.
bszCaption

A BSTR that specifies the text for the Caption property for a Command.

A Command with its Caption property set and its Visible property set to TRUE appears in the character's pop-up menu. If its Voice property is also set, it appears in the Commands Window. To make it accessible, you must also set its Enabled property to TRUE.

See also IAgentCommand::GetCaption, IAgentCommand::SetEnabled, IAgentCommand::SetVisible, IAgentCommand::SetVoice, IAgentCommands::Add, IAgentCommands::Insert

IAgentCommand::SetConfidenceThreshold

HRESULT SetConfidenceThreshold(
   long lConfidence  // Confidence setting for Command
);

Sets the value of the Confidence property for a Command.

  • Returns S_OK to indicate the operation was successful.
lConfidence

The value for the Confidence property of a Command.

If the confidence value returned of the best match returned in the Command event does not exceed the value set for the ConfidenceThreshold property, the text supplied in SetConfidenceText is displayed in the Listening Tip.

See also IAgentCommand::GetConfidenceThreshold, IAgentCommand::SetConfidenceText, IAgentUserInput::GetItemConfidence

IAgentCommand::SetConfidenceText

HRESULT SetConfidenceText(
   BSTR bszTipText  // ConfidenceText setting for Command
);

Sets the value of the Listening Tip text for a Command.

  • Returns S_OK to indicate the operation was successful.
bszTipText

A BSTR that specifies the text for the ConfidenceText property of a Command.

If the confidence value returned of the best match returned in the Command event does not exceed the value set for the ConfidenceThreshold property, the text supplied in bszTipText is displayed in the Listening Tip.

See also IAgentCommand::SetConfidenceThreshold, IAgentCommand::GetConfidenceThreshold, IAgentCommand::GetConfidenceText, IAgentUserInput::GetItemConfidence

IAgentCommand::SetEnabled

HRESULT SetEnabled(
   long bEnabled  // Enabled setting for Command
);

Sets the Enabled property for a Command.

  • Returns S_OK to indicate the operation was successful.
bEnabled

A Boolean value that sets the value of the Enabled setting of a Command. TRUE enables the Command; FALSE disables it. A disabled Command cannot be selected.

A Command must have its Enabled property set to TRUE to be selectable. It also must have its Caption property set and its Visible property set to TRUE to appear in the character's pop-up menu. To make the Command appear in the Commands Window, you must set its Voice property.

See also IAgentCommand::GetCaption, IAgentCommand::SetVoice, IAgentCommands::Add, IAgentCommands::Insert

IAgentCommand::SetVisible

HRESULT SetVisible(
   long bVisible  // Visible setting for Command
);

Sets the value of the Visible property for a Command.

  • Returns S_OK to indicate the operation was successful.
bVisible

A Boolean value that determines the Visible property of a Command. TRUE shows the Command; FALSE hides it.

A Command must have its Visible property set to TRUE and its Caption property set to appear in the character's pop-up menu.

See also IAgentCommands::SetVisible, IAgent::SetCaption, IAgentCommands::Add, IAgentCommands::Insert

IAgentCommand::SetVoice

HRESULT SetVoice(
   BSTR bszVoice  // voice text setting for Command
);

Sets the Voice property for a Command.

  • Returns S_OK to indicate the operation was successful.
bszVoice

A BSTR that specifies the text for the Voice property of a Command.

A Command must have its Voice property and Enabled property set to be voice-accessible. It also must have its Caption property set to appear in the Commands Window.

The BSTR expression you supply can include square bracket characters ([ ]) to indicate optional words and vertical bar characters (|) to indicate alternative strings. Alternates must be enclosed in parentheses. For example, "(hello [there] | hi)" tells the speech engine to accept "hello," "hello there," or "hi" for the command. Remember to include appropriate spaces between the text that's in brackets or parentheses and the text that's not in brackets or parentheses.

You can also use an ellipsis (…) to support word spotting, that is, telling the speech recognition engine to ignore words spoken in this position in the phrase (sometimes called garbage words). Therefore, the speech engine recognizes only specific words in the string regardless of when spoken with adjacent words or phrases. For example, if you set this property to "…check mail…" the speech recognition engine will match phrases like "please check mail" or "check mail please" to this command. Ellipses can be used anywhere within a string. However, be careful using this technique, because voice settings with ellipses may increase the potential of unwanted matches.

When defining the words and grammar for your command, always make sure that you include at least one word that is required; that is, avoid supplying only optional words. In addition, make sure that the word includes only pronounceable words and letters. For numbers, it is better to spell out the word rather than using the numeric representation. Also, omit any punctuation or symbols. For example, instead of "the #1 $10 pizza!", use "the number one ten dollar pizza". Including non-pronounceable characters or symbols for one command may cause the speech engine to fail to compile the grammar for all your commands. Finally, make your voice parameter as distinct as reasonably possible from other voice commands you define. The greater the similarity between the voice grammar for commands, the more likely the speech engine will make a recognition error. You can also use the confidence scores to better distinguish between two commands that may have similar or similar-sounding voice grammar.

The operation of this property depends on the state of Microsoft Agent server's speech recognition state. For example, if speech recognition is disabled or not installed, this function has no immediate effect. If speech recognition is enabled during a session, however, the command will become accessible when its client application is input-active.

See also IAgentCommand::GetVoice, IAgent::SetCaption, IAgentCommand::SetEnabled, IAgentCommands::Add, IAgentCommands::Insert

IAgentUserInput

When a Command event occurs, the Microsoft Agent server returns information through the UserInput object. IAgentUserInput defines an interface that allows applications to query these values.

Methods in Vtable Order

IAgentUserInput Methods | Description
GetCount | Returns the number of command alternatives returned in a Command event.
GetItemId | Returns the ID for a specific Command alternative.
GetItemConfidence | Returns the value of the Confidence property for a specific Command alternative.
GetItemText | Returns the value of Voice text for a specific Command alternative.
GetAllItemData | Returns the data for all Command alternatives.

IAgentUserInput::GetAllItemData

HRESULT GetAllItemData(
   VARIANT * pdwItemIndices,  // address of variable for alternative IDs
   VARIANT * plConfidences,   // address of variable for confidence scores
   VARIANT * pbszText         // address of variable for voice text
);

Retrieves the data for all Command alternatives passed to an IAgentNotifySink::Command callback.

  • Returns S_OK to indicate the operation was successful.
pdwItemIndices

Address of a variable that receives the IDs of Commands passed to the IAgentNotifySink::Command callback.

plConfidences

Address of a variable that receives the confidence scores for Command alternatives passed to the IAgentNotifySink::Command callback.

pbszText

Address of a variable that receives the voice text for Command alternatives passed to the IAgentNotifySink::Command callback.

If voice input was not the source for the Command, for example, if the user selected the command from the character's pop-up menu, the Microsoft Agent server returns the ID of the Command selected, with a confidence score of 100 and voice text as NULL. The other alternatives return as NULL with confidence scores of zero (0) and voice text as NULL.

See also IAgentUserInput::GetItemConfidence, IAgentUserInput::GetItemText, IAgentUserInput::GetItemID

IAgentUserInput::GetCount

HRESULT GetCount(
   long * pdwCount  // address of a variable for number of alternatives
);

Retrieves the number of Command alternatives passed to an IAgentNotifySink::Command callback.

  • Returns S_OK to indicate the operation was successful.
pdwCount

Address of a variable that receives the count of Commands alternatives identified by the server.

If voice input was not the source for the command, for example, if the user selected the command from the character's pop-up menu, GetCount returns 1. If GetCount returns zero (0), the speech recognition engine detected spoken input but determined that there was no matching command.

IAgentUserInput::GetItemConfidence

HRESULT GetItemConfidence(
   long dwItemIndex,    // index of Command alternative
   long * plConfidence  // address of confidence value for Command
);

Retrieves the confidence value for a Command passed to an IAgentNotifySink::Command callback.

  • Returns S_OK to indicate the operation was successful.
dwItemIndex

The index of a Command alternative passed to the IAgentNotifySink::Command callback.

plConfidence

Address of a variable that receives the confidence score for a Command alternative passed to the IAgentNotifySink::Command callback.

If voice input was not the source for the command, for example, if the user selected the command from the character's pop-up menu, the Microsoft Agent server returns the confidence value of the best match as 100 and the confidence values for all other alternatives as zero (0).

See also IAgentUserInput::GetItemID, IAgentUserInput::GetAllItemData, IAgentUserInput::GetItemText

IAgentUserInput::GetItemID

HRESULT GetItemID(
   long dwItemIndex,    // index of Command alternative
   long * pdwCommandID  // address of a variable for number of alternatives
);

Retrieves the identifier of a Command alternative passed to an IAgentNotifySink::Command callback.

  • Returns S_OK to indicate the operation was successful.
dwItemIndex

The index of the Command alternative passed to the IAgentNotifySink::Command callback.

pdwCommandID

Address of a variable that receives the ID of a Command.

If voice input triggers the IAgentNotifySink::Command callback, the server returns the IDs for any matching Commands defined by your application.

See also IAgentUserInput::GetItemConfidence, IAgentUserInput::GetItemText, IAgentUserInput::GetAllItemData

IAgentUserInput::GetItemText

HRESULT GetItemText(
   Long dwItemIndex,  // index of Command alternative
   BSTR * pbszText    // address of voice text for Command
);

Retrieves the voice text for a Command alternative passed to the IAgentNotifySink::Command callback.

  • Returns S_OK to indicate the operation was successful.
dwItemIndex

The index of a Command alternative passed to the IAgentNotifySink::Command callback.

pbszText

Address of a BSTR that receives the value of the voice text for the Command.

If voice input was not the source for the command, for example, if the user selected the command from the character's pop-up menu, the server returns NULL for the Command's voice text.

See also IAgentUserInput::GetItemConfidence, IAgentUserInput::GetItemID, IAgentUserInput::GetAllItemData

IAgentCommandWindow

IAgentCommandWindow defines an interface that allows applications to set and query the properties of the Commands Window. The Commands Window is a shared resource primarily designed for allowing users to view voice-enabled commands. If speech recognition is disabled or not installed, the Commands Window is not accessible. Attempting to set or query its properties will result in an error.

Methods in Vtable Order

IAgentCommandWindow Methods | Description
SetVisible | Sets the value of the Visible property of the Commands Window.
GetVisible | Returns the value of the Visible property of the Commands Window.
GetPosition | Returns the position of the Commands Window.
GetSize | Returns the size of the Commands Window.

IAgentCommandWindow::GetPosition

HRESULT GetPosition(
   long * plLeft,  // address of variable for left-edge of Commands Window
   long * plTop    // address of variable for top-edge of Commands Window
);

Retrieves the Commands Windows' position.

  • Returns S_OK to indicate the operation was successful.
plLeft

Address of a variable that receives the screen coordinate of the left edge of the Commands Window in pixels, relative to the screen origin (upper left).

plTop

Address of a variable that receives the screen coordinate of the top edge of the Commands Window in pixels, relative to the screen origin (upper left).

See also IAgentCommandWindow::GetSize

IAgentCommandWindow::GetSize

HRESULT GetSize(
   long * plWidth,  // address of variable for Commands Window width
   long * plHeight  // address of variable for Commands Window height
);

Retrieves the current size of the Commands Window.

  • Returns S_OK to indicate the operation was successful.
plWidth

Address of a variable that receives the width of the Commands Window in pixels, relative to the screen origin (upper left).

plHeight

Address of a variable that receives the height of the Commands Window in pixels, relative to the screen origin (upper left).

See also IAgentCommandWindow::GetPosition

IAgentCommandWindow::GetVisible

HRESULT GetVisible(
   long * pbVisible  // address of variable for Visible setting for
);                   // Commands Window

Determines whether the Commands Window is visible or hidden.

  • Returns S_OK to indicate the operation was successful.
pbVisible

Address of a variable that receives TRUE if the Commands Window is visible, or FALSE if hidden.

See also IAgentCommandWindow::SetVisible

IAgentCommandWindow::SetVisible

HRESULT SetVisible(
   long bVisible  // Commands Window Visible setting
);

Set the Visible property for the Commands Window.

  • Returns S_OK to indicate the operation was successful.
bVisible

Visible property setting. A value of TRUE displays the Commands Window; FALSE hides it.

The user can override this property.

See also IAgentCommandWindow::GetVisible

IAgentSpeechInputProperties

IAgentSpeechInputProperties provides access to the speech recognition properties maintained by the server. Most of the properties are read-only for client applications, but the user can change them in the Microsoft Agent Property Sheet. The Microsoft Agent server only returns values if a compatible speech engine has been installed and is enabled. Querying these properties attempts to start the speech engine.

Methods in Vtable Order

IAgentSpeechInputProperties Methods | Description
GetInstalled | Returns whether a compatible speech recognition engine has been installed.
GetEnabled | Returns whether the speech recognition engine is enabled.
GetHotKey | Returns the current key assignment of the listening hot key.
GetLCID | Returns the locale (language) ID of the selected speech recognition engine.
GetEngine | Returns the ID of the selected speech recognition engine.
SetEngine | Sets the ID for the selected speech recognition engine.
GetListeningTip | Returns whether the Listening Tip is enabled.

IAgentSpeechInputProperties::GetEnabled

HRESULT GetEnabled(
   long * pbEnabled  // address of variable for speech recognition engine
);                   // Enabled setting

Retrieves a value indicating whether the installed speech recognition engine is enabled.

  • Returns S_OK to indicate the operation was successful.
pbEnabled

Address of a variable that receives TRUE if the speech engine is currently enabled and FALSE if disabled.

If GetInstalled returns FALSE, querying this setting returns an error.

See also IAgentSpeechInput::GetInstalled

IAgentSpeechInputProperties::GetEngine

HRESULT GetEngine(
BSTR * pbszEngine  // address of variable for speech engine mode ID
);

Retrieves the mode ID for the current selected speech recognition engine.

  • Returns S_OK to indicate the operation was successful.
pbszEngine

Address of a BSTR that receives a string representation of the CLSID for the selected speech recognition engine.

If GetInstalled and GetEnabled return FALSE, querying this setting returns an error.

See also IAgentSpeechInput::SetEngine

IAgentSpeechInputProperties::GetHotKey

HRESULT GetHotKey(
BSTR * pbszHotCharKey  // address of variable for listening hotkey
);

Retrieves the current keyboard assignment for the speech input listening hot key.

  • Returns S_OK to indicate the operation was successful.
pbszHotCharKey

Address of a BSTR that receives the current hot key setting used to open the audio channel for speech input.

If GetInstalled and GetEnabled return FALSE, querying this setting raises an error.

See also IAgentSpeechInput::GetEnabled, IAgentSpeechInput::GetInstalled

IAgentSpeechInputProperties::GetInstalled

HRESULT GetInstalled(
long * pbInstalled  // address of variable for speech recognition engine
);                  // installation flag

Retrieves a value indicating whether a speech recognition engine has been installed.

  • Returns S_OK to indicate the operation was successful.
pbInstalled

Address of a variable that receives TRUE if a compatible speech recognition engine has been installed and FALSE if no engine is installed.

If GetInstalled and GetEnabled return FALSE, querying any other speech input properties returns an error.

See also IAgentSpeechInput::GetEnabled

IAgentSpeechInputProperties::GetLCID

HRESULT GetLCID(
LCID * plcidCurrent  // address of variable for locale ID
);

Retrieves the current setting for the locale ID.

  • Returns S_OK to indicate the operation was successful.
plcidCurrent

Address of LCID that receives the current locale setting. The locale setting determines the language of the speech recognition engine.

If GetInstalled and GetEnabled return FALSE, querying this setting returns an error.

See also IAgentSpeechInput::GetEnabled, IAgentSpeechInput::GetInstalled

IAgentSpeechInputProperties::GetListeningTip

HRESULT GetListeningTip(
long * pbListeningTip  // address of variable for listening tip flag
);

Retrieves a value indicating whether the Listening Tip is enabled for display.

  • Returns S_OK to indicate the operation was successful.
pbInstalled

Address of a variable that receives TRUE if the Listening Tip is enabled for display, or FALSE if the Listening Tip is disabled.

If GetInstalled and GetEnabled return FALSE, querying any other speech input properties returns an error.

See also IAgentSpeechInput::GetEnabled, IAgentSpeechInput::GetInstalled

IAgentSpeechInputProperties::SetEngine

HRESULT SetEngine(
BSTR bszEngine  // speech engine mode ID
);

Sets the selected speech recognition engine.

  • Returns S_OK to indicate the operation was successful.
bszEngine

A BSTR that contains a string representation of the CLSID for the desired speech recognition mode (engine).

If GetInstalled and GetEnabled return FALSE, setting this property returns an error.

See also IAgentSpeechInput::GetEngine

IAgentAudioOutputProperties

IAgentAudioOutputProperties provides access to audio output properties maintained by the Microsoft Agent server. The properties are read-only, but the user can change them in the Microsoft Agent Property Sheet.

Methods in Vtable Order

IAgentAudioOutputProperties Methods | Description
GetEnabled | Returns whether audio output is enabled.
GetUsingSoundEffects | Returns whether sound-effect output is enabled.

IAgentAudioOutputProperties::GetEnabled

HRESULT GetEnabled(
long * pbEnabled  // address of variable for audio output Enabled setting
);

Retrieves a value indicating whether character speech output is enabled.

  • Returns S_OK to indicate the operation was successful.
pbEnabled

Address of a variable that receives TRUE if the speech output is currently enabled and FALSE if disabled.

Because this setting affects spoken output (TTS and sound file) for all characters, only the user can change this property in the Microsoft Agent property sheet.

IAgentAudioOutputProperties::GetUsingSoundEffects

HRESULT GetUsingSoundEffects(
long * pbUsingSoundEffects  // address of variable sound effects output
);                          // setting

Retrieves a value indicating whether sound effects output is enabled.

  • Returns S_OK to indicate the operation was successful.
pbUsingSoundEffects

Address of a variable that receives TRUE if the sound effects output is currently enabled and FALSE if disabled.

Sound effects for a character's animation are assigned in the Microsoft Agent Character Editor. Because this setting affects sound effects output for all characters, only the user can change this property in the Microsoft Agent property sheet.

IAgentPropertySheet

IAgentPropertySheet defines an interface that allows applications to set and query properties for the Microsoft Agent property sheet (window).

Methods in Vtable Order

IAgentPropertySheet Methods | Description
GetVisible | Returns whether the Microsoft Agent property sheet is visible.
SetVisible | Sets the Visible property of the Microsoft Agent property sheet.
GetPosition | Returns the position of the Microsoft Agent property sheet.
GetSize | Returns the size of the Microsoft Agent property sheet.
GetPage | Returns the current page for the Microsoft Agent property sheet.
SetPage | Sets the current page for the Microsoft Agent property sheet.

IAgentPropertySheet::GetPage

HRESULT GetPage(
BSTR * pbszPage  // address of variable for current property page
);

Retrieves the current page of the Microsoft Agent property sheet.

  • Returns S_OK to indicate the operation was successful.
pbszPage

Address of a variable that receives the current page of the property sheet (last viewed page if the window is not open). The parameter can be one of the following:

"Speech" | The Speech Recognition page.
"Output" | The Output page.
"Copyright" | The Copyright page.

See also IAgentPropertySheet::SetPage

IAgentPropertySheet::GetPosition

HRESULT GetPosition(
   long * plLeft,  // address of variable for left-edge of property sheet
   long * plTop    // address of variable for top-edge of property sheet
);

Retrieves the Microsoft Agent's property sheet window position.

  • Returns S_OK to indicate the operation was successful.
plLeft

Address of a variable that receives the screen coordinate of the left edge of the property sheet in pixels, relative to the screen origin (upper left).

plTop

Address of a variable that receives the screen coordinate of the top edge of the property sheet in pixels, relative to the screen origin (upper left).

See also IAgentPropertySheet::GetSize

IAgentPropertySheet::GetSize

HRESULT GetSize(
   long * plWidth,  // address of variable for property sheet width
   long * plHeight  // address of variable for property sheet height
);

Retrieves the size of the Microsoft Agent property sheet window.

  • Returns S_OK to indicate the operation was successful.
plWidth

Address of a variable that receives the width of the property sheet in pixels, relative to the screen origin (upper left).

plHeight

Address of a variable that receives the height of the property sheet in pixels, relative to the screen origin (upper left).

See also IAgentPropertySheet::GetPosition

IAgentPropertySheet::GetVisible

HRESULT GetVisible(
   long * pbVisible  // address of variable for property sheet
);                   // Visible setting

Determines whether the Microsoft Agent property sheet is visible or hidden.

  • Returns S_OK to indicate the operation was successful.
pbVisible

Address of a variable that receives TRUE if the property sheet is visible and FALSE if hidden.

See also IAgentPropertySheet::SetVisible

IAgentPropertySheet::SetPage

HRESULT SetPage(
   BSTR bszPage  // current property page
);

Sets the current page of the Microsoft Agent property sheet.

  • Returns S_OK to indicate the operation was successful.
bszPage

A BSTR that sets the current page of the property. The parameter can be one of the following.

"Speech" | The Speech Recognition page.
"Output" | The Output page.
"Copyright" | The Copyright page.

See also IAgentPropertySheet::GetPage

IAgentPropertySheet::SetVisible

HRESULT SetVisible(
   long bVisible  // property sheet Visible setting
);

Sets the Visible property for the Microsoft Agent property sheet.

  • Returns S_OK to indicate the operation was successful.
bVisible

Visible property setting. A value of TRUE displays the property sheet; a value of FALSE hides it.

See also IAgentPropertySheet::GetVisible

IAgentBalloon

IAgentBalloon defines an interface that allows applications to query properties for the Microsoft Agent word balloon.

Initial defaults for a character's word balloon are set in the Microsoft Agent Character Editor, but once the application is running, the user may override the Enabled and font properties. If a user changes the balloon's properties, the change affects all characters.

Methods in Vtable Order

IAgentBalloon Methods | Description
GetEnabled | Returns whether the word balloon is enabled.
GetNumLines | Returns the number of lines displayed in the word balloon.
GetNumCharsPerLine | Returns the average number of characters per line displayed in the word balloon.
GetFontName | Returns the name of the font displayed in the word balloon.
GetFontSize | Returns the size of the font displayed in the word balloon.
GetFontBold | Returns whether the font displayed in the word balloon is bold.
GetFontItalic | Returns whether the font displayed in the word balloon is italic.
GetFontStrkethru | Returns whether the font displayed in the word balloon is displayed as strikethrough.
GetFontUnderline | Returns whether the font displayed in the word balloon is underlined.
GetForeColor | Returns the foreground color displayed in the word balloon.
GetBackColor | Returns the background color displayed in the word balloon.
GetBorderColor | Returns the border color displayed in the word balloon.
SetVisible | Sets the word balloon to be visible.
GetVisible | Returns the visibility setting for the word balloon.
SetFontName | Sets the font used in the word balloon.
SetFontSize | Sets the font size used in the word balloon.
SetFontCharSet | Sets the character set used in the word balloon.
GetFontCharSet | Returns the character set used in the word balloon.

IAgentBalloon::GetBackColor

HRESULT GetBackColor(
   long * plBGColor  // address of variable for background color displayed
);                   // in word balloon

Retrieves the value for the background color displayed in a word balloon.

  • Returns S_OK to indicate the operation was successful.
plBGColor

The address of a variable that receives the color setting for the balloon background.

The background color used in a character word balloon is defined in the Microsoft Agent Character Editor. It cannot be changed by an application. However, the user can change the background color of the word balloons for all characters through the Microsoft Agent property sheet.

See also IAgentBalloon::GetForeColor

IAgentBalloon::GetBorderColor

HRESULT GetBorderColor (
  long * plBorderColor// address of variable for border color displayed
);                    // for word balloon

Retrieves the value for the border color displayed for a word balloon.

  • Returns S_OK to indicate the operation was successful.
plBorderColor

The address of a variable that receives the color setting for the balloon border.

The border color for a character word balloon is defined in the Microsoft Agent Character Editor. It cannot be changed by an application. However, the user can change the border color of the word balloons for all characters through the Microsoft Agent property sheet.

See also IAgentBalloon::GetBackColor, IAgentBalloon::GetForeColor

IAgentBalloon::GetEnabled

HRESULT GetEnabled(
  long * pbEnabled  // address of variable for Enabled setting
);                  // for word balloon

Retrieves the value of the Enabled property for a word balloon.

  • Returns S_OK to indicate the operation was successful.
pbEnabled

The address of a variable that receives TRUE when the word balloon is enabled and FALSE when it is disabled.

The Microsoft Agent server automatically displays the word balloon for spoken output, unless it is disabled. The word balloon can be disabled for a character in the Microsoft Agent Character Editor, or for all characters by the user, in the Microsoft Agent property sheet. If the user disables the word balloon, the client cannot restore it.

IAgentBalloon::GetFontBold

HRESULT GetFontBold(
   long * pbFontBold  // address of variable for bold setting for
);                    // font displayed in word balloon

Indicates whether the font used in a word balloon is bold.

  • Returns S_OK to indicate the operation was successful.
pbFontBold

The address of a value that receives TRUE if the font is bold and FALSE if not bold.

The font style used in a character word balloon is defined in the Microsoft Agent Character Editor. It cannot be changed by an application. However, the user can override the font settings for all characters through the Microsoft Agent property sheet.

IAgentBalloon::GetFontCharSet

HRESULT GetFontCharSet(
   short * psFontCharSet  // character set displayed in word balloon
);

Indicates the character set of the font displayed in a word balloon.

  • Returns S_OK to indicate the operation was successful.
psFontCharSet

The address of a value that receives the font's character set. The following are some common settings for value:

0 | Standard Windows® characters (ANSI).
1 | Default character set.
2 | The symbol character set.
128 | Double-byte character set (DBCS) unique to the Japanese version of Windows.
129 | Double-byte character set (DBCS) unique to the Korean version of Windows.
134 | Double-byte character set (DBCS) unique to the Simplified Chinese version of Windows.
136 | Double-byte character set (DBCS) unique to the Traditional Chinese version of Windows.
255 | Extended characters normally displayed by DOS applications.

For other character set values, consult the Microsoft Win32® documentation.

The default character set used in a character's word balloon is defined in the Microsoft Agent Character Editor. You can change it using IAgentBalloon::SetFontCharSet. However, the user can override the character set setting for all characters using the Microsoft Agent property sheet.

See also IAgentBalloon::SetFontCharSet

IAgentBalloon::GetFontItalic

HRESULT GetFontItalic(
   long * pbFontItalic  // address of variable for italic setting for
);                      // font displayed in word balloon

Indicates whether the font used in a word balloon is italic.

  • Returns S_OK to indicate the operation was successful.
pbFontItalic

The address of a value that receives TRUE if the font is italic and FALSE if not italic.

The font style used in a character's word balloon is defined in the Microsoft Agent Character Editor. It cannot be changed by an application. However, the user can override the font settings for all characters through the Microsoft Agent property sheet.

IAgentBalloon::GetFontName

HRESULT GetFontName(
   BSTR * pbszFontName  // address of variable for font displayed
);                      // in word balloon

Retrieves the value for the font displayed in a word balloon.

  • Returns S_OK to indicate the operation was successful.
pbszFontName

The address of a BSTR that receives the font name displayed in a word balloon.

The default font used in a character word balloon is defined in the Microsoft Agent Character Editor. You can change it with IAgentBalloon::SetFontName. The user can override the font setting for all characters using the Microsoft Agent property sheet.

IAgentBalloon::GetFontSize

HRESULT GetFontSize(
   long * plFontSize  // address of variable for font size
);                    // for font displayed in word balloon

Retrieves the value for the size of the font displayed in a word balloon.

  • Returns S_OK to indicate the operation was successful.
plFontSize

The address of a value that receives the size of the font.

The default font size used in a character word balloon is defined in the Microsoft Agent Character Editor. You can change it with IAgentBalloon::SetFontSize. However, the user can override also the font-size settings for all characters using the Microsoft Agent property sheet.

IAgentBalloon::GetFontStrikethru

HRESULT GetFontStrikethru(
   long * pbFontStrikethru  // address of variable for strikethrough setting
);                          // for font displayed in word balloon

Indicates whether the font used in a word balloon has the strikethrough style set.

  • Returns S_OK to indicate the operation was successful.
pbFontStrikethru

The address of a value that receives TRUE if the font strikethrough style is set and FALSE if not.

The font style used in a character word balloon is defined in the Microsoft Agent Character Editor. It cannot be changed by an application. However, the user can override the font settings for all characters using the Microsoft Agent property sheet.

IAgentBalloon::GetFontUnderline

HRESULT GetFontUnderline(
   long * pbFontUnderline  // address of variable for underline setting
);                         // for font displayed in word balloon

Indicates whether the font used in a word balloon has the underline style set.

  • Returns S_OK to indicate the operation was successful.
pbFontUnderline

The address of a value that receives TRUE if the font underline style is set and FALSE if not.

The font style used in a character word balloon is defined in the Microsoft Agent Character Editor. It cannot be changed by an application. However, the user can change the font settings for all characters using the Microsoft Agent property sheet.

IAgentBalloon::GetForeColor

HRESULT GetForeColor(
   long * plFGColor // address of variable for foreground color displayed
);                  // in word balloon

Retrieves the value for the foreground color displayed in a word balloon.

  • Returns S_OK to indicate the operation was successful.
plFGColor

The address of a variable that receives the color setting for the balloon foreground.

The foreground color used in a character word balloon is defined in the Microsoft Agent Character Editor. It cannot be changed by an application. However, the user can change the foreground color of the word balloons for all characters through the Microsoft Agent property sheet.

See also IAgentBalloon::GetBackColor

IAgentBalloon::GetNumCharsPerLine

HRESULT GetNumCharsPerLine(
   long * plCharsPerLine  // address of variable for characters per line
);                        // displayed in word balloon

Retrieves the value for the average number of characters per line displayed in a word balloon.

  • Returns S_OK to indicate the operation was successful.
pbCharsPerLine

The address of a variable that receives the number of characters per line.

The Microsoft Agent server automatically scrolls the lines displayed for spoken output in the word balloon. The average number of characters per line for a character's word balloon is defined in the Microsoft Agent Character Editor. It cannot be changed by an application.

See also IAgentBalloon::GetNumLines

IAgentBalloon::GetNumLines

HRESULT GetNumLines(
   long * pbcLines  // address of variable for number of lines
);                  // displayed in word balloon

Retrieves the value of the number of lines displayed in a word balloon.

  • Returns S_OK to indicate the operation was successful.
pbcLines

The address of a variable that receives the number of lines displayed.

The Microsoft Agent server automatically scrolls the lines displayed for spoken output in the word balloon. The number of lines for a character word balloon is defined in the Microsoft Agent Character Editor. It cannot be changed by an application.

See also IAgentBalloon::GetNumCharsPerLine

IAgentBalloon::GetVisible

HRESULT GetVisible(
   long * pbVisible  // address of variable for word balloon
);                   // Visible setting

Determines whether the word balloon is visible or hidden.

  • Returns S_OK to indicate the operation was successful.
pbVisible

Address of a variable that receives TRUE if the word balloon is visible and FALSE if hidden.

See also IAgentBalloon::SetVisible

IAgentBalloon::SetFontCharSet

HRESULT SetFontCharSet(
   short sFontCharSet  // character set displayed in word balloon
);

Sets the character set of the font displayed in the word balloon.

  • Returns S_OK to indicate the operation was successful.
sFontCharSet

The character set of the font. The following are some common settings for value:

0 | Standard Windows characters (ANSI).
1 | Default character set.
2 | The symbol character set.
128 | Double-byte character set (DBCS) unique to the Japanese version of Windows.
129 | Double-byte character set (DBCS) unique to the Korean version of Windows.
134 | Double-byte character set (DBCS) unique to the Simplified Chinese version of Windows.
136 | Double-byte character set (DBCS) unique to the Traditional Chinese version of Windows.
255 | Extended characters normally displayed by DOS applications.

For other character set values, consult the Microsoft Win32 documentation.

The default character set used in a character's word balloon is defined in the Microsoft Agent Character Editor. You can change it with IAgentBalloon::SetFontCharSet. However, the user can override the character set setting for all characters using the Microsoft Agent property sheet.

See also IAgentBalloon::GetFontCharSet

IAgentBalloon::SetFontName

HRESULT SetFontName(
   BSTR bszFontName  // font displayed in word balloon
);

Sets the font displayed in the word balloon.

  • Returns S_OK to indicate the operation was successful.
bszFontName

A BSTR that sets the font displayed in the word balloon.

The default font used in a character's word balloon is defined in the Microsoft Agent Character Editor. You can change it with IAgentBalloon::SetFontName. However, the user can override the font setting for all characters using the Microsoft Agent property sheet.

See also IAgentBalloon::GetVisible

IAgentBalloon::SetFontSize

HRESULT SetFontSize(
   long lFontSize  // font size displayed in word balloon
);

Sets the size of the font displayed in the word balloon.

  • Returns S_OK to indicate the operation was successful.
lFontSize

The size of the font.

The default font size used in a character's word balloon is defined in the Microsoft Agent Character Editor. You can change it with IAgentBalloon::SetFontSize. However, the user can override the font size setting for all characters using the Microsoft Agent property sheet.

See also IAgentBalloon::GetFontSize

IAgentBalloon::SetVisible

HRESULT SetVisible(
   long bVisible  // word balloon Visible setting
);

Sets the Visible property for the word balloon.

  • Returns S_OK to indicate the operation was successful.
bVisible

Visible property setting. A value of TRUE displays the word balloon; a value of FALSE hides it.

See also IAgentBalloon::GetVisibleEvents

Events

Microsoft Agent provides several events for tracking user interaction and server states. This section describes the event methods exposed by the IAgentNotifySink interface.

Methods in Vtable Order

IAgentNotifySink | Description
Command | Occurs when the server processes a client-defined command.
ActivateInputState | Occurs when a character becomes or ceases to be input-active.
Restart | Occurs when the server restarts.
Shutdown | Occurs when the user exits the server.
VisibleState | Occurs when the character's Visible state changes.
Click | Occurs when a character is clicked.
DblClick | Occurs when a character is double-clicked.
DragStart | Occurs when a user starts dragging a character.
DragComplete | Occurs when a user stops dragging a character.
RequestStart | Occurs when the server begins processing a Request object.
RequestComplete | Occurs when the server completes processing a Request object.
Bookmark | Occurs when the server processes a bookmark.
Idle | Occurs when the server starts or ends idle processing.
Move | Occurs when a character has been moved.
Size | Occurs when a character has been resized.
BalloonVisibleState | Occurs when the visibility state of a character's word balloon changes.

IAgentNotifySink::ActivateInputState

HRESULT ActivateInputState(
   long dwCharID,   // character ID
   long bActivated  // input activation flag
);

Notifies a client application that a character's input active state changed.

  • No return value.
dwCharID

Identifier of the character whose input activation state changed.

bActivated

Input active flag. This Boolean value is TRUE if the character referred to by dwCharID became input active; and FALSE if the character lost its input active state.

See also IAgentCharacter::SetInputActive, IAgentCharacter::GetInputActive

IAgentNotifySink::BalloonVisibleState

HRESULT BalloonVisibleState(
   long dwCharID,  // character ID
   long bVisible   // visibility flag
);

Notifies a client application when the visibility state of the character's word balloon changes.

  • No return value.
dwCharID

Identifier of the character whose word balloon's visibility state has changed.

bVisible

Visibility flag. This Boolean value is TRUE when character's word balloon becomes visible; and FALSE when it becomes hidden.

This event is sent to all clients of the character.

IAgentNotifySink::Bookmark

HRESULT Bookmark(
   long dwBookMarkID  // bookmark ID
);

Notifies a client application when its bookmark completes.

  • No return value.
dwBookMarkID

Identifier of the bookmark that resulted in triggering the event.

When you include bookmark tags in a Speak method, you can track when they occur with this event.

See also IAgentCharacter::Speak, Speech Output Tags

IAgentNotifySink::Click

HRESULT Click(
   long dwCharID,  // character ID
   short fwKeys,   // mouse button and modifier key state
   long x,         // x coordinate of mouse pointer
   long y          // y coordinate of mouse pointer
);

Notifies a client application when the user clicks a character.

  • No return value.
dwCharID

Identifier of the clicked character.

fwKeys

A parameter that indicates the mouse button and modifier key state. The parameter can return any combination of the following:

0x0001 Left Button

0x0010 Middle Button

0x0002 Right Button

0x0004 Shift Key Down

0x0008 Control Key Down

0x0020 Alt Key Down

x

The x-coordinate of the mouse pointer in pixels, relative to the screen origin (upper left).

y

The y-coordinate of the mouse pointer in pixels, relative to the screen origin (upper left).

IAgentNotifySink::Command

HRESULT Command(
   long dwCommandID,         // Command ID of the best match
   IUnknown * punkUserInput  // address of IAgentUserInput object
);

Notifies a client application that a Command was selected by the user.

  • No return value.
dwCommandID

Identifier of the best match command alternative.

punkUserInput

Address of the IUnknown interface for the IAgentUserInput object.

Use QueryInterface to retrieve the IAgentUserInput interface.

See also IAgentUserInput

IAgentNotifySink::DblClick

HRESULT DblClick(
   long dwCharID,  // character ID
   short fwKeys,   // mouse button and modifier key state
   long x,         // x coordinate of mouse pointer
   long y          // y coordinate of mouse pointer
);

Notifies a client application when the user double-clicks a character.

  • No return value.
dwCharID

Identifier of the double-clicked character.

fwKeys

A parameter that indicates the mouse button and modifier key state. The parameter can return any combination of the following:

0x0001 Left Button

0x0010 Middle Button

0x0002 Right Button

0x0004 Shift Key Down

0x0008 Control Key Down

0x0020 Alt Key Down

x

The x-coordinate of the mouse pointer in pixels, relative to the screen origin (upper left).

y

The y-coordinate of the mouse pointer in pixels, relative to the screen origin (upper left).

IAgentNotifySink::DragComplete

HRESULT DragComplete(
   long dwCharID,  // character ID
   short fwKeys,   // mouse button and modifier key state
   long x,         // x coordinate of mouse pointer
   long y          // y coordinate of mouse pointer
);

Notifies a client application when the user stops dragging a character.

  • No return value.
dwCharID

Identifier of the dragged character.

fwKeys

A parameter that indicates the mouse button and modifier key state. The parameter can return any combination of the following:

0x0001 Left Button

0x0010 Middle Button

0x0002 Right Button

0x0004 Shift Key Down

0x0008 Control Key Down

0x0020 Alt Key Down

x

The x-coordinate of the mouse pointer in pixels, relative to the screen origin (upper left).

y

The y-coordinate of the mouse pointer in pixels, relative to the screen origin (upper left).

IAgentNotifySink::DragStart

HRESULT DragStart(
   long dwCharID,  // character ID
   short fwKeys,   // mouse button and modifier key state
   long x,         // x coordinate of mouse pointer
   long y          // y coordinate of mouse pointer
);

Notifies a client application when the user starts dragging a character.

  • No return value.
dwCharID

Identifier of the dragged character.

fwKeys

A parameter that indicates the mouse button and modifier key state. The parameter can return any combination of the following:

0x0001 Left Button

0x0010 Middle Button

0x0002 Right Button

0x0004 Shift Key Down

0x0008 Control Key Down

0x0020 Alt Key Down

x

The x-coordinate of the mouse pointer in pixels, relative to the screen origin (upper left).

y

The y-coordinate of the mouse pointer in pixels, relative to the screen origin (upper left).

IAgentNotifySink::Idle

HRESULT Idle(
   long dwCharID,  // character ID
   long bStart     // start flag
);

Notifies a client application when a character's Idling state has changed.

  • No return value.
dwCharID

Identifier of the request that started.

bStart

Start flag. This Boolean value is TRUE when the character begins idling and FALSE when it stops idling.

This event enables you to track when the Microsoft Agent server starts or stops idle processing for a character.

See also IAgentCharacter::GetIdleOn, IAgentCharacter::SetIdleOn

IAgentNotifySink::Move

HRESULT Move(
   long dwCharID,  // character ID
   long x,         // x-coordinate of new location
   long y          // y-coordinate of new location
   long dwCause    // cause of move state
);

Notifies a client application when the character has been moved.

  • No return value.
dwCharID

Identifier of the character that has been moved.

x

The x-coordinate of the new position in pixels, relative to the screen origin (upper left). The location of a character is based on the upper left corner of its animation frame.

y

The y-coordinate of the new position in pixels, relative to the screen origin (upper left). The location of a character is based on the upper left corner of its animation frame.

dwCause

The cause of the character move. The parameter may be one of the following:

const unsigned short NeverMoved = 0; | Character has not been moved.
const unsigned short UserMoved = 1; | User dragged the character.
const unsigned short ProgramMoved = 2; | Your application moved the character.
const unsigned short OtherProgramMoved = 3; | Another application moved the character.

This event is sent to all clients of the character.

See also IAgentCharacter::GetMoveCause , IAgentCharacter::MoveTo

IAgentNotifySink::RequestComplete

HRESULT RequestComplete(
   long dwRequestID,  // request ID
   long hrStatus      // status code
);

Notifies a client application when a request completes.

  • No return value.
dwRequestID

Identifier of the request that started.

hrStatus

Status code. This parameters returns the status code for the request.

This event enables you to track when a queued method completes.

See also IAgentNotifySink::RequestStart, IAgent::Load, IAgentCharacter::GestureAt, IAgentCharacter::Hide, IAgentCharacter::Interrupt, IAgentCharacter::MoveTo, IAgentCharacter::Prepare, IAgentCharacter::Play, IAgentCharacter::Show, IAgentCharacter::Speak, IAgentCharacter::Wait

IAgentNotifySink::RequestStart

HRESULT RequestStart(
   long dwRequestID  // request ID
);

Notifies a client application when a request begins.

  • No return value.
dwRequestID

Identifier of the request that started.

This event enables you to track when a queued request begins.

See also IAgentNotifySink::RequestComplete, IAgent::Load, IAgentCharacter::GestureAt, IAgentCharacter::Hide, IAgentCharacter::Interrupt, IAgentCharacter::MoveTo, IAgentCharacter::Prepare, IAgentCharacter::Play, IAgentCharacter::Show, IAgentCharacter::Speak, IAgentCharacter::Wait

IAgentNotifySink::Restart

HRESULT Restart();

Notifies a client application that the Microsoft Agent server restarted.

  • No return value.
See also IAgentNotifySink::Shutdown

IAgentNotifySink::Shutdown

HRESULT Shutdown();

Notifies a client application that the Microsoft Agent server shut down.

  • No return value.
This event fires only when the user explicitly chooses the Exit command on the pop-up menu of the Microsoft Agent taskbar icon. Requests sent after the server shuts down will fail.

See also IAgentNotifySink::Restart

IAgentNotifySink::Size

HRESULT Size(
   long dwCharID,  // character ID
   long lWidth,    // new width
   long lHeight,   // new height
);

Notifies a client application when the character has been resized.

  • No return value.
dwCharID

Identifier of the character that has been resized.

lWidth

The width of the character's animation frame in pixels.

lHeight

The height of the character's animation frame in pixels.

This event is sent to all clients of the character.

See also IAgentCharacter::GetSize, IAgentCharacter::SetSize

IAgentNotifySink::VisibleState

HRESULT VisibleState(
   long dwCharID,  // character ID
   long bVisible   // visibility flag
   long dwCause    // cause of visible state
);

Notifies a client application when the visibility state of the character changes.

  • No return value.
dwCharID

Identifier of the character whose visibility state is changed.

bVisible

Visibility flag. This Boolean value is TRUE when character becomes visible and FALSE when the character becomes hidden.

dwCause

Cause of last change to the character's visibility state. The parameter may be one of the following:

const unsigned short NeverShown = 0; | Character has not been shown.
const unsigned short UserHid = 1; | User hid the character.
const unsigned short UserShowed = 2; | User showed the character.
const unsigned short ProgramHid = 3; | Your application hid the character.
const unsigned short ProgramShowed = 4; | Your application showed the character.
const unsigned short OtherProgramHid = 5; | Another application hid the character.
const unsigned short OtherProgramShowed = 6; | Another application showed the character.

See also IAgentCharacter::GetVisible, IAgentCharacter::SetVisible, IAgentCharacter::GetVisibilityCause


Microsoft Agent Support

Microsoft Agent Microsoft Agent *

Support

For peer support and general troubleshooting questions, use the public newsgroup: microsoft.public.msagent.

For reporting bugs, obtaining updates, and reading the latest Microsoft Agent news, visit our web site at http://www.microsoft.com/workshop/prog/agent/.

For information on redistributing or licensing Microsoft Agent, contact us through our e-mail alias: msagent@microsoft.com. (We are not able to answer troubleshooting questions via this e-mail alias.)


Microsoft Agent Speech Output Tags

Microsoft Agent Microsoft Agent *

Speech Output Tags

ActiveX™ Technology for Interactive Software Agents

August 1997
Microsoft Corporation

Note: This document is provided for informational purposes only and Microsoft makes no warranties, either expressed or implied, in this document. The entire risk of the use or the results of this document remains with the user.

Information in this document is subject to change without notice. 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.

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. Microsoft, MS, MS-DOS, Windows, Windows NT, and the Windows logo are either registered trademarks or trademarks of Microsoft Corporation in the U.S. and/or other countries. Other product and company names mentioned herein may be the trademarks of their respective owners.

The Microsoft Agent services support modifying speech output through special tags inserted in the speech text string. These tags help you change the characteristics of the output expression of the character.

Speech output tags use the following rules of syntax:

  • All tags begin and end with a backslash character (\).
  • The single backslash character is not enabled within a tag. To include a backslash character in a text parameter of a tag, use a double backslash (\\).
  • Tags are case-insensitive. For example, \pit\ is the same as \PIT\.
  • Tags are whitespace-dependent. For example, \Rst\ is not the same as \ Rst \.
Unless otherwise specified or modified by another tag, the speech output retains the characteristic set by the tag within the text specified in a single Speak method. Speech output is automatically reset through the user-defined parameters after a Speak method is completed.

Some tags include quoted strings. For some programming languages, such as Visual Basic® Scripting Edition (VBScript) and Visual Basic®, this means that you may have to use two quote marks to designate the tag's parameter or concatenate a double-quote character as part of the string. The latter is shown in this Visual Basic example:

Agent1.Characters("Genie").Speak "This is \map=" + chr(34) + "Spoken text" _
+ chr(34) + "=" + chr(34) + "Balloon text" + chr(34) + "\."

For C, C++, and Java™ programming, precede backslashes and double quotes with a backslash. For example:

BSTR bszSpeak = SysAllocString(L"This is \\map=\"Spoken text\"=\"Balloon text\"\\");

pCharacter->Speak(bszSpeak, ......);

For foreign languages that support double-byte character set (DBCS) characters, you can use double-byte characters to specify string parameters. However, use single-byte characters for all other parameters and characters that are used to define the tag, including the tag itself.

The following tags are supported:

Chr, Ctx, Emp, Lst, Map, Mrk, Pau, Pit, Rst, Spd, Vol

The tags are primarily designed for adjusting text-to-speech (TTS)-generated output. Only the Mrk and Map tags can be used with sound file-based spoken output.

Note: Microsoft Agent does not support all the tags documented in the Microsoft Speech SDK. Parameters may also vary depending on the TTS engine installed.

Chr Tag

Description

Sets the character of the voice.

Syntax

\Chr=string\

Part Description
string A string specifying the character of the voice.

"Normal" (Default) A normal tone of voice.

"Monotone" A monotone voice.

"Whisper" A whispered voice.

Remarks

This tag is supported only for TTS-generated output. The range of values for the parameter may vary depending on the installed TTS engine.

Ctx Tag

Description

Sets the context of the output text.

Syntax

\Ctx=string\

Part Description
string A string specifying the context of the text that follows, which determines how symbols or abbreviations are spoken.

"Address" Addresses and/or phone numbers.

"Email" Electronic mail.

"Unknown" (Default) Context is unknown.

Remarks

This tag is supported only for TTS-generated output. The range of values for the parameter may vary depending on the installed TTS engine.

Emp Tag

Description

Emphasizes the next word spoken. This tag must immediately precede the word.

Syntax

\Emp\

Remarks

This tag is supported only for TTS-generated output. The range of values for the parameter may vary depending on the installed TTS engine.

Lst Tag

Description

Repeats last spoken statement for the character.

Syntax

\Lst\

Remarks

This tag enables a character repeat its last spoken statement. This tag must appear by itself in the Speak method; no other text or parameters can be included. When the spoken text is repeated, any other tags included in the original text are repeated, except for bookmarks. Any .WAV and .LWV files included in the text are also repeated.

Map Tag

Description

Maps spoken text to text displayed in the word balloon.

Syntax

\Map="spokentext"="balloontext"\

Part | Description
spokentext | A string specifying the text for spoken output.
balloontext | A string specifying the text for word balloon output.

Remarks

This tag enables you to use different spoken text than that displayed in the word balloon.

Mrk Tag

Description

Defines a bookmark in the spoken text.

Syntax

\Mrk=number\

Part | Description
number | A Long integer value that identifies the bookmark.

Remarks

When the server processes a bookmark, it generates a bookmark event. You must specify a number greater than zero (0) and not equal to 2147483647 or 2147483646.

See Also

Bookmark event

Pau Tag

Description

Pauses speech for the specified number of milliseconds.

Syntax

\Pau=number\

Part | Description
number | The number of milliseconds to pause.

Remarks

This tag is supported only for TTS-generated output. The range of values for the parameter may vary depending on the installed TTS engine. The speech engine supplied with Microsoft Agent supports values from 10 (0.01sec) to 2550 (2.55sec).

Pit Tag

Description

Sets the baseline pitch of the output to the specified value in hertz.

Syntax

\Pit=number\

Part | Description
number | The pitch in hertz.

Remarks

This tag is supported only for TTS-generated output. The range of values for the parameter may vary depending on the installed TTS engine. The speech engine supplied with Microsoft Agent supports values from 50 to 400.

Rst Tag

Description

Resets all tags to the default settings.

Syntax

\Rst\

Spd Tag

Description

Sets the baseline average talking speed of the speech output.

Syntax

\Spd=number\

Part | Description
number | Baseline average talking speed, in words per minute.

Remarks

This tag is supported only for TTS-generated output. The range of values for the parameter may vary depending on the installed TTS engine. The speech engine supplied with Microsoft Agent supports values from 50 to 250.

Vol Tag

Description

Sets the baseline speaking volume of the speech output.

Syntax

\Vol=number\

Part | Description
number | Baseline speaking volume: 0 is silence and 65535 is maximum volume.

Remarks

The volume setting affects both left and right channels. You cannot set the volume of each channel separately. This tag is supported only for TTS-generated output.

Back to list of tags


Technical FAQ

Microsoft Agent Microsoft Agent *

Microsoft Agent Technical FAQ

August 1997
Microsoft Corporation

Questions

General

  • With the release of Microsoft Agent, will my pages built with previous beta releases still work?
  • Can I define my own character?
  • Will Microsoft Agent be available for platforms other than Windows 95 and Windows NT?
  • Will Microsoft Agent be available in other languages?

Programming/Scripting

  • When I use Microsoft Visual Basic (or other development tools) for scripting Microsoft Agent, I do not see all the properties and events used in your samples. How do I access them?
  • When I try to host the Microsoft Agent control on the same page as a Java applet, it doesn't seem to work.
  • The Map tag (or some other tag) doesn't seem to work.
  • I seem to get RequestStart and RequestComplete events in my scripts even though I don't set any requests.
  • I don't seem to get RequestStart and RequestComplete events in my script (or program).
  • I am using the Microsoft Agent control with other ActiveX™ controls on my Web page and I don't seem to get any events.
  • What programming languages can I use to program the Microsoft Agent control?
  • Can I access the parameters returned from Microsoft Agent using JavaScript™ (JScript™)?
  • Can Microsoft Agent be used with speech recognition or speech synthesis (text-to-speech, or TTS) engines other than those supplied by Microsoft?
  • When I attempt to access the Lernout & Hauspie® TruVoice Text-To-Speech Engine modes from the Microsoft Speech SDK tools, I get a message indicating that a password is required.
  • After calling the MoveTo method, my character seems to freeze even though I have Return animations assigned to Moving state animations.
  • When running under Internet Explorer 4.0 Preview 1 or 2, events don't fire after Microsoft Agent has been running, or the character leaves behind parts of its animation.

Licensing

  • Can I redistribute Microsoft Agent and its characters?
  • Can I redistribute the speech engines that are supplied with Microsoft Agent with my own applications?
  • Can I redistribute the Microsoft Agent Character Editor and Microsoft Linguistic Information Sound Editing Tool?

General

With the release of Microsoft Agent, will my pages built with previous beta releases still work?

The final commercial release of Microsoft Agent is not compatible with any previous beta releases. You should uninstall any beta releases and update to the final release. Any pages or applications authored for a beta release should also be updated to the final release.

When updating to the final release of Microsoft Agent, the following methods will ensure a clean, reliable installation:

Uninstall any previous beta release before installing the commercial release.

Do not install the beta releases over the commercial release. This will create an unreliable installation.

Can I define my own character?

Yes. You can use any animation rendering package, provided that you can produce your images in a 2-bit (monochrome), 4-bit, or 8-bit color Windows® bitmap format. Then you can use the Microsoft Agent Character Editor, available for download at this site, to assemble and compile your animations.

Will Microsoft Agent be available for platforms other than Windows 95 and Windows NT®?

We are investigating the feasibility of and demand for this technology on other platforms.

Will Microsoft Agent be available in other languages?

Microsoft Agent will be available in the following languages in addition to English (US): French, German, Italian, Spanish, Simplified Chinese, Traditional Chinese, Korean, and Japanese. These versions of Microsoft Agent will include only the core services, not the speech input or output components. However, because Microsoft Agent supports the Microsoft SAPI interface, you may be able to use other speech engines. Contact your speech vendor to determine whether they are compatible with the SAPI interfaces required by Microsoft Agent. Availability of Microsoft Agent in other languages has not yet been determined.

Back to list of questions

Programming/Scripting

When I use Microsoft Visual Basic® (or other development tools) for scripting Microsoft Agent, I do not see all the properties and events used in your samples. How do I access them?

Most of the events, methods, and properties supported by the Microsoft Agent control are exposed only at run time. Consult Programming the Microsoft Agent Control for further information.

When I try to host the Microsoft Agent control on the same page as a Java applet, it doesn't seem to work.

This is a problem in the Internet Explorer Java™ VM that has been addressed in the Microsoft Java 2.0 SDK, which can be downloaded at http://www.microsoft.com/java/pre-sdk/default.htm. This version of the Java VM is expected to be included in a release of the Internet Explorer later this year.

The Map tag (or some other tag) doesn't seem to work.

Some tags include quoted strings. For some programming languages, such as Visual Basic® Scripting Edition (VBScript) and Visual Basic®, you may have to use two quote marks to designate the tag's parameter or concatenate a double-quote character as part of the string. The latter is shown in this Visual Basic example:

Agent1.Characters("Genie").Speak "This is \map=" + chr(34) + "Spoken text" _
+ chr(34) + "=" + chr(34) + "Balloon text" + chr(34) + "\."

For C, C++, and Java™ programming, precede backslashes and double quotes with a backslash. For example:

BSTR bszSpeak = SysAllocString(L"This is \\map=\"Spoken text\"=\"Balloon text\"\\");

pCharacter->Speak(bszSpeak, ......);

Note that Microsoft Agent does not support all the tags specified in the Microsoft Speech API. In addition, support for some parameters may depend on the text-to-speech engine installed. For further information, see Speech Output Tags.

I seem to get RequestStart and RequestComplete events in my scripts even though I don't set any requests.

This is a problem in Visual Basic® Scripting Edition (VBScript) 1.0. It has been addressed in VBScript 2.0, which can be downloaded at http://microsoft.com/msdownload/scripting.htm.

I don't seem to get RequestStart and RequestComplete events in my script (or program).

This could be caused by one of the following problems:

  • Your programming language doesn't support ActiveX™ controls. Check your documentation to ensure that it supports the ActiveX interface and events for ActiveX objects.
  • On a scripted Web page, another control has failed to install or load. Check to ensure that all other controls are installed and loading properly without Microsoft Agent.
  • On a scripted Web page with frames, you have the <OBJECT> tag for the Microsoft Agent control on one page, and the events scripted on another page. Events are sent only to the page that hosts the control.

I am using the Microsoft Agent control with other ActiveX controls on my Web page, and I don't seem to get any events.

Check to see if the other controls are correctly installed. If another ActiveX control fails to correctly register itself, the Microsoft Agent control may receive its events.

What programming languages can I use to program the Microsoft Agent control?

Microsoft Agent should be supportable from any language that supports the ActiveX interface. Beta 2 includes code samples for Microsoft Visual Basic®, VBScript, JavaScript™, C/C++, and Java.

Can I access the parameters returned from Microsoft Agent using JavaScript (JScript)?

Yes, but currently the only way to do this is using the <SCRIPT LANGUAGE="JScript" FOR="object" EVENT="event()"> syntax. Although this syntax is supported for Microsoft Internet Explorer, it is not supported by other browsers, so you may want to avoid using JavaScript/JScript for this part of your page's script.

Can Microsoft Agent be used with speech recognition or speech synthesis (text-to-speech, or TTS) engines other than those supplied by Microsoft?

Yes, provided that the engine supports the Microsoft Speech API (SAPI) interfaces required by Microsoft Agent. Check with the engine supplier. Speech engine suppliers can contact the Microsoft Agent Product Group at msagent@microsoft.com for details on SAPI requirements.

My page includes HTML Object tags for Microsoft Agent, the Lernout & Hauspie® TruVoice TTS engine, and the Microsoft Command and Control speech recognition engine, but not all the components install.

We are investigating why this failure occurs. Typically, the problem can be corrected by refreshing the page. As a general practice, it is best to specify the Microsoft Agent Control Object tag first, then the Lernout & Hauspie® TruVoice engine, then the Command and Control Engine.

When I attempt to access the Lernout & Hauspie® TruVoice Text-To-Speech Engine modes from the Microsoft Speech SDK tools, I get a message indicating that a password is required.

The text-to-speech engine included with Microsoft Agent does not support direct SAPI access. You can access the engine only by using the interfaces supported by Microsoft Agent. If you want to program the Lernout & Hauspie® TruVoice engine with Microsoft SAPI, contact Lernout & Hauspie®.

After calling the MoveTo method, my character seems to freeze even though I have Return animations assigned to Moving state animations.

When you play an animation, the animation services continue to display its last frame until another animation is called. Therefore, you should play another animation after calling MoveTo. If you defined a Return animation for the Moving state animation, the server will play it first.

When running under Internet Explorer 4.0 Preview 1 or 2, events don't fire after Microsoft Agent has been running, or the character leaves behind parts of its animation.

These problems are related to the IE 4.0 Preview 1 and 2. Install the official commercial release of IE 4.0.

Back to list of questions

Licensing

Can I redistribute Microsoft Agent and its characters?

Microsoft Agent can be downloaded directly from the Microsoft site by including the Microsoft Agent control's CLSID in an HTML <OBJECT> tag on your Web page, which will automatically offer to download and install the control when a user loads the page. Details on licensing and use are included in the Microsoft Agent End User License agreement that displays when Microsoft Agent is installed. This license does not include provisions for redistribution. Application developers who wish to include Microsoft Agent and any of its components as part of their application must obtain a redistribution license. For more information about redistribution licenses, see the Licensing and Redistribution document.

Can I redistribute the speech engines that are supplied with Microsoft Agent with my own applications?

The Microsoft Agent license agreement includes a license to use the Microsoft Command and Control speech recognition engine and the special version of the Lernout & Hauspie® TruVoice Text-To-Speech Engine, subject to the same provisions and restrictions as Microsoft Agent, and only when used with Microsoft Agent. For redistribution of these engines, contact the Microsoft Agent Product Group at msagent@microsoft.com. For redistribution of the speech engines only, contact the speech engine vendors directly.

Can I redistribute the Microsoft Agent Character Editor and Microsoft Linguistic Information Sound Editing Tool?

Redistribution of these tools is limited to downloading them from the Microsoft Web site or dispensing them as part of any software development kit Microsoft may provide. For other forms of redistribution, contact the Microsoft Agent Product Group at msagent@microsoft.com.

Back to list of questions


Troubleshooting Microsoft Agent

August 1997
Microsoft Corporation

If you have difficulty running Microsoft Agent on your machine, please refer to the following list of symptoms and try the suggested steps to isolate and solve the problem. If these suggestions don't resolve the problem, let us know by sending us a bug report.

Questions

Page Loading or Installation Problems

When I attempt to load a page scripted for Microsoft Agent, nothing happens.

When I attempt to load a page scripted for Microsoft Agent, I get the message, "Unable to initialize Microsoft Agent."

When I attempt to load a page scripted for Microsoft Agent, I get a scripting error: "Microsoft VBScript Runtime Error, Object required."

When I attempt to install Microsoft Agent on Microsoft Windows NT®, I get a message indicating that I need to be an administrator.

When I attempt to install Microsoft Agent under NT 4.0, I get the following error: Process (Regsvr32 /s Progra~1\Micros~2\AgentCtl.dll). Error while creating this file. Can not find this file.

When I attempt to load a page scripted for Microsoft Agent using Netscape Navigator (or other Internet browsers), I get errors.

How do I remove Microsoft Agent from my system?

Does Microsoft Agent work in Internet Explorer 4.0?

Speech Input Problems

The character does not respond to voice commands that I used to train it.

The character does not respond to voice commands on a sample page.

The character does not respond to my voice input.

The character does not respond to voice input, but I can hear my voice through my speakers when I talk into my microphone.

Page Loading and Installation Problems

When I attempt to load a page scripted for Microsoft Agent, nothing happens.

  • This can occur if one of the following conditions exists:
  • Check your browser's security options. Your browser must be set to enable the loading of ActiveX™ scripts and playing of ActiveX controls.
  • If you are accessing pages scripted with Microsoft Agent and using Microsoft Internet Explorer, you must have version 3.0 or later (download the latest version of Internet Explorer). In Microsoft Internet Explorer, open the View menu, choose Options, click the Security tab, and check all the Active Content check boxes.
  • A Java applet on the page can also cause this error. To run Microsoft Agent on the same page as a Java applet requires version 2.0 of the Microsoft Java VM. For more information, see our Technical FAQ.

When I attempt to load a page scripted for Microsoft Agent, I get the message, "Unable to initialize Microsoft Agent."

This usually occurs when you don't have Microsoft Agent or some other control that page uses installed, and choose No when you are prompted to install the control. Try refreshing the page, though the page may work only if you install all the components it requires.

When I attempt to load a page scripted for Microsoft Agent, I get a scripting error: "Microsoft VBScript Runtime Error, Object required."

  • One of the following conditions may cause the message to display:
  • Your security options for Microsoft Internet Explorer must be set to enable ActiveX controls and plug-ins. Check your browser's security page. In Microsoft Internet Explorer, open the View menu, choose Options, click the Security tab, and make sure the Enable ActiveX Controls And Plug-Ins check box is checked.
  • You are running on a dual-boot Windows® 95/Windows NT system and you have installed Microsoft Agent on one operating system but are trying to access the page from the other operating system. Although the operating systems may share directories and files, the registry information used by Microsoft Agent is not shared, so you must install Microsoft Agent on the operating system you use to access Web pages scripted with the character.

When I attempt to install Microsoft Agent on Microsoft Windows NT, I get a message indicating that I need to be an administrator.

Because Microsoft Agent writes files to your system directory when it installs, you must have administrator (not user) privileges to install.

When I attempt to install Microsoft Agent under NT 4.0, I get the following error: Process (Regsvr32 /s Progra~1\Micros~2\AgentCtl.dll). Error while creating this file. Can not find this file.

Installation of Microsoft Agent requires Regsvr32.exe (and other OLE dlls) being properly installed. The best way to ensure that all the correct system files are present is to install Microsoft Internet Explorer 3.02 or later.

When I attempt to load a page scripted for Microsoft Agent using Netscape Navigator (or other Internet browsers), I get errors.

Microsoft Agent is implemented using ActiveX interfaces. You can use it only with a browser (such as Microsoft Internet Explorer) that supports embedding ActiveX objects through script on a page, and only on systems running Microsoft Windows 95 and Windows NT 4.0. If you are not using Microsoft Internet Explorer, check with your browser vendor for further information on ActiveX support.

How do I remove Microsoft Agent from my system?

To uninstall Microsoft Agent, open the Control Panel, then open the Add/Remove Programs object. You should find Microsoft Agent included in the list. Select the entry, then click the Add/Remove button.

The Microsoft Agent uninstall utility removes only the Microsoft Agent services. If you also installed the Lernout & Hauspie® TruVoice Text-To-Speech Engine for Microsoft Agent, select this and click the Add/Remove button. In addition, if you also installed Microsoft Command and Control speech engine and you know that no other application uses it, you should select and remove the following entries:

Microsoft Command and Control Engine

Microsoft Speech Lexicon

Microsoft Speech API (3.0)

Does Microsoft Agent work in Internet Explorer 4.0?

Please note that Microsoft Agent will not run in Internet Explorer 4.0 Platform Preview, due to a bug in the Internet Explorer 4.0 Preview version. This should be corrected in the next beta release of Internet Explorer 4.0, which will be released soon. Until then we recommend that you use IE 3.02 for accessing Microsoft Agent.

Back to list of questions

Speech Input Problems

The character does not respond to voice commands that I used to train it.

Voice training does not teach the character new commands. It does help the speech engine better recognize your voice input. The only way to teach the character new commands is to define voice commands as part of your Web page (application). Consult Programming the Microsoft Agent Control for further information on how to do this.

The character does not respond to voice commands on a sample page.

Not all sample pages support speech input. The Goodbye World sample on this site's sample page does (click the HTML Sample Pages link in the left pane to see the Goodbye World sample). To speak to the character, press and hold the Scroll Lock key. If the character does not respond to any of these commands, check the following sections on troubleshooting voice input for additional recommendations.

The character does not respond to my voice input.

This symptom may be caused by a number of problems. Try the following to isolate the problem:

  • Verify that your microphone is correctly plugged in. It is a good idea to test it with another sound input application to ensure that it works properly.
  • Verify that a compatible speech engine is installed. When running a Microsoft Agent sample page, right-click the Microsoft Agent icon in the taskbar (near the clock display) and choose Microsoft Agent Properties. If the Speech Input page is disabled, a compatible speech engine is not installed. You can install the Microsoft Command and Control Engine from the Component Installation page.
  • Verify that your sound card is compatible with Microsoft Windows 95 or Windows NT.
The best way to do this is to run the Sound Recorder application that comes with Windows. It can usually be found on the Start menu. Click the Start button, then Programs, then Accessories, then Multimedia, and then Sound Recorder. When the Sound Recorder window displays, click the Record button and talk into your microphone. The line in the window should animate in response to your voice input.

If the Sound Recorder application doesn't work on your system, contact the sound card manufacturer's technical support department for assistance. Your sound card may not be compatible with Windows or there may be a problem with the software drivers for your sound card.

  • Verify that your sound input for speech input is set properly.
  1. Load a page scripted for Microsoft Agent. When the character appears, right-click on it and choose Microsoft Agent Properties from the pop-up menu.
  2. When the property sheet displays, select the Speech Input page.
  3. Choose the Adjust Microphone button. If this button appears disabled, a compatible speech engine is not installed or the speech engine you installed may not support automatic adjustment.
  • If you followed the steps above but still have problems with speech input, verify that your sound card and driver software is compatible with the speech engine you are using. Check with the technical support for your sound card and your speech engine manufacturer. If you installed the Microsoft Command and Control engine, check the troubleshooting information at http://www.research.microsoft.com/stg/sndcard.htm.

The character does not respond to voice input, but I can hear my voice through my speakers when I talk into my microphone.

Your sound card is not set up properly for use with Microsoft Agent. Choose the Adjust Microphone options on the Speech Input page of the Microsoft Agent property sheet. See the previous section for information on how to access this button.

Back to list of questions


The Microsoft Agent User Interface

Microsoft Agent Microsoft Agent *

User Interface

ActiveX™ Technology for Interactive Software Agents

August 1997
Microsoft Corporation

Note: This document is provided for informational purposes only and Microsoft makes no warranties, either expressed or implied, in this document. The entire risk of the use or the results of this document remains with the user.

Information in this document is subject to change without notice. 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.

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. Microsoft, MS, MS-DOS, Windows, Windows NT, and the Windows logo are either registered trademarks or trademarks of Microsoft Corporation in the U.S. and/or other countries. Other product and company names mentioned herein may be the trademarks of their respective owners.

Contents

The Character Window

The Taskbar Icon

The Commands Window

The Word Balloon

The Listening Tip

The Agent Property Sheet

The Character Window

Microsoft Agent displays animated characters in their own windows that always appear at the top of the window z-order (that is, always on top). A user can move a character's window by dragging the character with the left mouse button. The character image moves with the pointer. In addition, an application can move a character using the MoveTo method.

When the user right-clicks a character, a pop-up menu appears that displays the following commands:

Open | Close Commands Window
Hide

Command*
…
OtherHostingApplicationCaption**
…

*Commands listed are based on the input-active client. For more information on defining commands that appear in the pop-up menu, see The Microsoft Agent Programming Interface Overview.

**Entries listed are all other applications currently hosting the character. For more information on defining this entry, see The Microsoft Agent Programming Interface Overview.

The Open | Close Commands Window command controls the display of the Commands Window of the current active character. If speech recognition services are disabled, this command is disabled. If speech recognition services are not installed, this command does not appear.

The Hide command hides the character. The animation assigned to the character's Hiding state plays and hides the character. The first letter of the character name becomes its access key (mnemonic).

The commands for the application(s) currently hosting the character follow the Hide command, preceded by a separator. Then the names of other applications using the character appear, also preceded by a separator.

Back to contents

The Taskbar Icon

When Microsoft Agent runs, its icon appears in the notification area of the taskbar. This icon provides access to Microsoft Agent's properties as well as user control of hiding and showing characters.

Figure 1. The Microsoft Agent Taskbar Icon

Moving the pointer over the taskbar icon displays a tip window that reflects the current state of Microsoft Agent. For example, during the normal operating state, the tip window might display "Say the name of a character to display it" or "Microsoft Agent is running."

Single-clicking the taskbar icon has no effect. However, double-clicking the icon displays the Microsoft Agent property sheet.

Right-clicking the icon displays a pop-up menu that has the following commands:

Hide | Show CharacterName
…
Hide All Characters

Open | Close Commands Window

Microsoft Agent Properties

Exit Microsoft Agent

The Hide | Show CharacterName command lists all characters that have been loaded. The command plays the character's Hiding state animation and hides the character. The Show CharacterName entry makes the character visible and plays the character's Showing state animation.

The Hide All Characters command hides all the characters, playing their associated Hiding animation.

Microsoft Agent Properties displays the Microsoft Agent property sheet. This command appears as bold text to indicate that this is the default command for the menu.

The Exit command quits the Microsoft Agent services. Because applications may depend on these services, the Exit command prompts for confirmation, informing the user that exiting Microsoft Agent can have unexpected results. If the user confirms the exit process, Microsoft Agent removes all characters and its taskbar icon and stops running. However, if another application starts up and requests Microsoft Agent's services, Microsoft Agent partially restarts, displaying its suspended icon in the taskbar notification area. It also displays a message that offers to resume full operation. If the user confirms restarting, Microsoft Agent resumes full operation. If the user declines, Microsoft Agent exits. The user can choose whether to be notified again through a check box in the message.

In the "suspended" state, right-clicking the taskbar displays the following menu items:

Restart Microsoft Agent
Exit Microsoft Agent

Restarting Microsoft Agent fully restores the server and displays the normal (non-suspended) Microsoft Agent icon. It also resets the notification message option to always prompt and resets the contents of the right-click pop-up menu for the taskbar icon to its normal configuration. Choosing Exit in the suspended state quits Microsoft Agent until another application requests its services.

Back to contents

The Commands Window

If a compatible speech engine is installed, Microsoft Agent supplies a special window called the Commands Window that displays the commands that have been voice-enabled for speech recognition. The Commands Window serves as a visual prompt for what can be spoken as input (commands cannot be selected with the mouse).

Figure 2. The Commands Window

The window appears when a user selects the Open Commands Window command, either by speaking the command or right-clicking the character and choosing the command from the character's pop-up menu. However, if the user disables speech input, the Commands Window is not accessible.

The Commands Window displays voice-enabled commands as a tree. If the current hosting application supplies voice commands, they appear expanded and at the top of the window. Entries also appear for other applications using the character. The window also includes the global voice commands supplied by Microsoft Agent. If the current hosting application has no voice commands, the global voice commands appear expanded and at the top of the window.

The user can size and move the Commands Window. Microsoft Agent remembers the last location of the window and redisplays it at that location if the user closes and re-opens the window. If the entries in the window exceed the current display size of the window, scroll bars appear.

Back to contents

The Word Balloon

In addition to spoken audio output, the Microsoft Agent interface also supports textual captioning in the form of text output in cartoon-style word balloons. Words appear in the balloon as they are spoken. The balloon hides when spoken output is completed. The Microsoft Agent property sheet provides options to disable the balloon's display as well as control attributes related to its appearance.

Figure 3. The Word Balloon

Back to contents

The Listening Tip

If speech is enabled, a special tooltip window appears when the user presses the push-to-talk key to begin voice input. The Listening Tip displays contextual information related to the current input state of Microsoft Agent. If compatible speech recognition has not been installed or has been disabled, the Listening Tip does not appear.

Figure 4. The Listening Tip

Back to contents

The Agent Property Sheet

Selecting the Microsoft Agent Properties command displays the Microsoft Agent property sheet. This window provides access to configuration options that affect interaction with all characters. Microsoft Agent stores your settings and uses them when Microsoft Agent runs. Microsoft Agent remembers the last page viewed and displays that page when the property sheet appears.

The Output Page

This page includes properties that control character output. For example, the user can determine whether to display output in the word balloon, determine how balloon output should appear, play spoken output as audio, play character sound effects, display the restart prompt, and adjust the speaking speed.

Figure 5. Output Property Page

The Speech Input Page

A user can adjust speech input options on this property page. The user can disable speech input, set the listening input key, choose whether to display the Listening Tip, and choose to play a MIDI to indicate when you can speak. The user can also select a speech recognition engine, adjust sound-card and microphone settings, or access any advanced settings provided by the selected speech recognition. This page appears if a compatible (Microsoft Speech Application Programming Interface [SAPI]-compliant) speech recognition engine is installed.

Figure 6. Speech Input Property Page

The Copyright Page

This page displays the copyright and version information for Microsoft Agent.

Figure 7. Copyright Page

Back to contents


ADISAPI (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

ADISAPI

Remote Data Service Internet Server application programming interface. An ISAPI DLL that provides parsing, Automation control, Recordset marshaling, and MIME packaging. The ADISAPI component works through the API provided by Internet Information Server (IIS).


proxy (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

proxy

An interface-specific object that provides the parameter marshaling and communication required for a client to call an application object that is running in a different execution environment, such as on a different thread or in another process. The proxy is located with the client and communicates with a corresponding stub that is located with the application object that is being called.


(Untitled)

Microsoft Remote Data Service Microsoft Remote Data Service *

Remote Data Service

A high-performance Web-based technology that brings database connectivity and corporate data publishing capabilities to Internet and intranet applications.


context object (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

context object

An object that maintains state that is implicitly associated with a given Microsoft® Transaction Server object. Context contains information about the object's execution environment, such as the identity of the object's creator and, optionally, the transaction encompassing the work of the object. An object's context is similar in concept to the process context that an operating system maintains for an executing program. The Microsoft Transaction Server run-time environment manages a context for each object.


Transaction Server object (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

Transaction Server object

A COM object that executes in the Microsoft® Transaction Server run-time environment and follows the Transaction Server programming and deployment model.


disconnected recordset (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

disconnected recordset

A recordset in a client cache that no longer has a live connection to the server. If you need to do something with the original data source, such as updating data, you need to re-establish the connection.


middle tier (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

middle tier

Also known as application server tier. The logical layer between a user interface or Web client and the database. This is typically where the Web server resides, and where business objects are instantiated. The middle tier is a collection of business rules and functions that generate and operate upon information. They accomplish this through business rules, which can change frequently, and are thus encapsulated into components that are physically separate from the application logic itself. See also client tier, data source tier.


client tier (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

client tier

A logical layer that represents a local computer where browser software displays a Web page. See also middle tier, data source tier.


data source tier (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

data source tier

A logical layer that represents a computer running a DBMS, such as a SQL Server database. See also client tier, middle tier.


data provider (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

data provider

Software that implements OLE DB methods and interfaces.


keyset (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

keyset

A set of values used to access specific rows (records) in a database. A keyset recordset includes enough columns to ensure unique records in an updatable recordset.


alias (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

alias

An alternate name you give to a column or expression in a SELECT statement, often shorter or more meaningful. For example, BobSales is the alias in the following SELECT statement: "Select wr-Sales as BobSales from SalesDB". An alias can be used to dynamically assign columns to control bindings on the RDS.DataControl object.


run time (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

run time

The time during which an application is running. During run time, you can interact with an application. In contrast, during design time, you create objects and modify their design.

When you are authoring Web pages, you can set properties at design time in an object's OBJECT tags in HTML. You can set properties at run time in your scripting code (for instance, VBScript).


design time (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

design time

The time during which you build an application in the development environment by adding controls, setting control or form properties, and so on. In contrast, during run time, you interact with the application as a user would.

When you are authoring Web pages, you can set properties at design time in an object's OBJECT tags. You can set properties at run time in your scripting code (for instance, VBScript).


single-threaded control (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

single-threaded control

A model in which all objects are executed on a single thread.


component (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

component

A discrete unit of code built on ActiveX™ technologies that delivers a well-specified set of services through well-specified interfaces. Components provide the objects that clients request at run time. In Remote Data Service, components are also referred to as business objects when they include key logic for supporting business processes.


business object (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

business object

An ActiveX™ component that retrieves and processes the data. Business objects are usually on the middle tier.

Remote Data Service provides a default middle-tier business object, RDSServer.DataFactory, that receives client requests and provides read and write access to specified data sources, but that does not contain any validation or business rules logic.

You can create custom business objects that can provide the same functionality as RDSServer.DataFactory, as well as encapsulate your application's business rules.


ActiveX control (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

ActiveX control

An object created using ActiveX™ technology. ActiveX controls usually have an .ocx extension. Remote Data Service can use ActiveX controls to display recordset data on a client Web page.


apartment thread (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

apartment thread

A thread used to execute calls to objects of components configured as "apartment threaded." Each object "lives in an apartment" (thread) for the life of the object. All calls to that object execute on the apartment thread.


class ID (CLSID) (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

class ID (CLSID)

A universally unique identifier (UUID) that identifies a COM component. Each COM component has its CLSID in the Windows Registry so that it can be loaded by other applications.


DCOM (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

DCOM (Distributed Component Object Model)

An object protocol that enables ActiveX™ components to communicate directly with each other across a network. DCOM is language neutral, so any language that produces ActiveX components can also produce DCOM applications.


Microsoft Transaction Server (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

Microsoft Transaction Server

A component-based transaction processing system for developing, deploying, and managing high performance, scalable, and robust enterprise, Internet, and intranet server applications. Transaction Server defines an application programming model for developing distributed, component-based applications. It also provides a run-time infrastructure for deploying and managing these applications.


ODBC (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

ODBC (Open Database Connectivity)

A standard programming language interface used to connect to a variety of data sources. This is usually accessed through Control Panel, where data source names (DSNs) can be assigned to use specific ODBC drivers.


data source (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

data source

The name that applications use to request a connection to a system ODBC data source. It specifies the computer name and (optionally) database that the data source name (DSN) maps to.

A System data source is a data source that is available to anyone using the computer. Data sources that will be used with a Web server need to be System data sources.


in-process component (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

in-process component

A component that runs in a client's process space. This is typically a dynamic-link library (DLL).


cursor (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

cursor

A piece of software that returns rows of data to the application. A cursor on a result set indicates the current position in the result set.


object variable (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

object variable

A variable that contains a reference to an object. For example, objCustomObject is a variable that points to an object of type CustomObject:

Set objCustomObject = ADS1.CreateObject("CustomObject", _
    "http://SalesWeb")


marshaling (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

marshaling

The process of packaging and sending interface method parameters across thread or process boundaries.


rowset (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

rowset

The set of rows returned in a single fetch by a block cursor.


OLE DB (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

OLE DB

A general-purpose set of interfaces designed to let developers build data access tools as components using the Component Object Model (COM). OLE DB enables applications to have uniform access to data stored in DBMS and non-DBMS information containers, while continuing to take advantage of the benefits of database technology without having to transfer data from its place of origin to a DBMS.


Remote Procedure Call (RPC) (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

Remote Procedure Call (RPC)

A standard that allows one process to make calls to functions that are executed in another process. The process can be on the same computer or on a different computer in the network.


connection pooling (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

connection pooling

A performance optimization based on using collections of pre-allocated resources, such as objects or database connections. Pooling results in more efficient resource allocation.


MIME (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

MIME

A standard that allows binary data to be published and read on the Internet. The header of a file with binary data contains the MIME type of the data; this informs client programs (Web browsers and mail packages, for instance) that they will need to handle the data some way other than they handle straight text. For example, the header of a Web document containing a JPEG graphic contains the MIME type specific to the JPEG file format. This allows a browser to display the file with its JPEG viewer, if one is present.


ISAPI (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

ISAPI

A set of functions for Internet servers, such as a Windows NT® Server running Microsoft® Internet Information Server (IIS).


Component Object Model (COM) (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

Component Object Model (COM)

An open architecture for cross-platform development of client/server applications based on object-oriented technology. Clients have access to an object through interfaces implemented on the object. COM is language neutral, so any language that produces ActiveX™ components can also produce COM applications.


business rule (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

business rule

The combination of validation edits, logon verifications, database lookups, policies, and algorithmic transformations that constitute an enterprise's way of doing business. Also known as business logic.


transaction context object (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

transaction context object

An object used to allow a client to dynamically include one or more objects in one transaction.


Web server (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

Web server

A computer that provides Web services and pages to intranet and Internet users. This is where you have Internet Information Server installed, and server-side business objects are typically instantiated here.


data-aware control (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

data-aware control

A control that is able to use data from a database. Once you bind the control to a database via the RDS.DataControl object, the control is referred to as a bound control.


recordset (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

recordset

A rowset provided through ActiveX™ Data Objects (ADO).


stub (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

stub

An interface-specific object that provides the parameter marshaling and communication required for an application object to receive calls from a client that is running in a different execution environment, such as on a different thread or in another process. The stub is located with the application object and communicates with a corresponding proxy that is located with the client that calls it.


ActiveX (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

ActiveX

A set of technologies that enables software components to interact with one another in a networked environment, regardless of the language in which they were created. ActiveX™ is built on the Component Object Model (COM).


DLL (dynamic-link library) (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

DLL (dynamic-link library)

A file that contains one or more functions that are compiled, linked, and stored separately from the processes that use them. The operating system maps the DLLs into the address space of the calling process when the process is starting or while it's running.


Virtual Table Manager (VTM) (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

Client Cursor Engine

A set of structures that caches, in memory, the set of query results retrieved from a DBMS, as well as client updates to those results.


AdvancedDataControl object (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

AdvancedDataControl object

The name used in previous versions of RDS for the RDS.DataControl object. RDS 1.5 still recognizes AdvancedDataControl for backward compatibility.


AdvancedDataFactory object (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

AdvancedDataFactory object

The name used in previous versions of RDS for the RDSServer.DataFactory object. RDS 1.5 still recognizes AdvancedDataFactory for backward compatibility.


AdvancedDataSpace object (definition)

Microsoft Remote Data Service Microsoft Remote Data Service *

AdvancedDataSpace object

The name used in previous versions of RDS for the RDS.DataSpace object. RDS 1.5 still recognizes AdvancedDataSpace for backward compatibility.


Glossary

ActiveX

ActiveX control

ADISAPI

AdvancedDataControl

AdvancedDataFactoryl

AdvancedDataSpace

alias

apartment thread

business object

business rule

class ID (CLSID)

Client Cursor Engine

client tier

component

Component Object Model (COM)

connection pooling

context object

cursor

data provider

data source

data source tier

data-aware control

DCOM

design time

disconnected recordset

DLL (dynamic-link library)

in-process component

ISAPI

keyset

marshaling

Remote Data Service

Microsoft Transaction Server

middle tier

MIME

object variable

ODBC

OLE DB

proxy

recordset

Remote Procedure Call (RPC)

rowset

run time

single-threaded control

stub

transaction context object

Transaction Server object

Web server


(Untitled)

Microsoft Remote Data Service Microsoft Remote Data Service *

Remote Data Service Developer's Guide

The Remote Data Service (RDS) is designed for building data-centric Web applications. It incorporates existing technologies, such as ActiveX™, Internet Information Server (IIS), VBScript, JScript, and OLE DB, and introduces innovations such as enhanced data binding for Web pages, client-side caching, and the ability to invoke custom business objects.

There are many related technologies that you use in an RDS application. The Developer's Guide describes the various parts of a three-tiered RDS application and provides code examples to show you how to use those technologies.

This section contains information about:

  • Understanding Remote Data Service Applications
  • Developing Remote Data Service Applications
  • Appendixes


(Untitled)

Microsoft Remote Data Service Microsoft Remote Data Service *

Understanding Remote Data Service Applications

This chapter describes the architecture and components of Remote Data Service technology. It shows how the RDS client- and server-side components work together to:

  • Bring data over the Internet or your intranet to your Web page.

  • Allow updated information to be sent back across the network and merged into your database.

This section contains information about:

  • Three-Tiered Applications

  • How a Remote Data Service Application Works

  • Client Tier

  • Middle Tier

  • Data Source Tier

Three-Tiered Applications

The key to using Remote Data Service technology lies in understanding the three-tiered client/server model. This approach separates the various components of a client/server system into three "tiers":

  • Client tier — a local computer on which either a Web browser displays a Web page that can display and manipulate data from a remote data source, or (in non-Web-based applications) a stand-alone compiled front-end application.

  • Middle tier — a Microsoft Windows NT® Server computer that hosts components which encapsulate an organization's business rules. Middle-tier components can either be Active Server Page scripts executed on Internet Information Server, or (in non-Web-based applications) compiled executables.

  • Data source tier — a computer hosting a database management system (DBMS), such as a Microsoft SQL Server database. (In a two-tier application, the middle-tier and data source tier are combined.)

These tiers don't necessarily correspond to physical locations on the network. For example, all three tiers may exist on only two machines. One machine could be a Windows 95 computer running Internet Explorer 4.0 as its browser. The second machine could be a Windows NT Server computer running both Internet Information Server and Microsoft SQL Server. Designing applications this way gives you greater flexibility when deploying processes and data on the network for maximum performance and ease of maintenance.

The following illustration shows how these tiers make up an RDS application.

How a Remote Data Service Application Works

When you create a Remote Data Service application, you can partition your application into two or three logical tiers. The following illustration shows how a Web-based RDS application handles a user request to display information from a database. The client-side components are typically hosted in an Internet Explorer browser, using HTTP to communicate with the server components. Internet Explorer 4.0 already includes the RDS client components, thus simplifying your deployment.

Once the user enters a request, the client-side RDS components send the query to the Web server. The server-side RDS components process the request and send it to the DBMS. The DBMS responds to the request, sending back the data. The RDS components on the Web server transform that data into an ADO Recordset object. The data is converted for transport to the client and sent back across the network to the client computer. It may be displayed in a data-aware control, such as a text box or grid, that is bound to the data by the RDS.DataControl object. One RDS.DataControl can channel data to many data-aware controls.

The resulting data is cached on the client computer, reducing the number of connections to the Web and making it easier for a user to manipulate the data. The only calls requiring a trip to the server are calls to the business object (such as updates to the data server or requests for new data).

To learn how to implement a simple scenario like this, complete the Address Book tutorial. You can also consult "Developing Remote Data Service Applications" for helpful code examples and task-oriented information.

Client Tier

The client tier provides the visual interface for presenting information and gathering data. In a Web-based RDS application, the client tier usually consists of the following components:

  • A Web page that has an RDS.DataControl object and one or more data-aware controls.

  • Business object proxies and the RDS.DataSpace object for instantiating middle-tier objects.

  • A client-side data cache.

The following illustration shows how RDS client-side components communicate with each other and the middle tier of a Web-based application.

Data, in the form of Recordset objects, is made available to Web page bound controls, and can be transported via HTTP or DCOM to the middle tier as an update, through the OLEDB provider. The RDS.DataControl is designed to consume Recordset objects, navigating to their underlying rowset.

Remote Data Service Web Pages

The Web page represents a Remote Data Service application front end. You can bind data-aware controls to data from remote servers, and view, edit, and update data from the Web page.

RDS.DataControl Object

The RDS.DataControl object is the data-binding mechanism for displaying query results on a Web page in Internet Explorer. Each RDS.DataControl object binds one Recordset object, representing the results of a single query, to one or more visual controls (for example, a text box, combo box, grid control, and so forth). There may be more than one RDS.DataControl object on each page. Each RDS.DataControl object can be connected to a different data source and contain the results of a separate query.

Business Object Proxies and the RDS.DataSpace Object

The Remote Data Service uses business object proxies so that client-side components can communicate with business objects located on the middle tier (IIS Web server). Proxies facilitate the packaging, unpackaging, and transport (marshaling) of the application's data across process or machine boundaries.

If you use the RDS.DataControl to obtain a disconnected Recordset, RDS calls the RDSServer.DataFactory object; you don't need to explicitly call RDSServer.DataFactory or RDS.DataSpace. The business object proxy is dynamically created whenever an instance of its middle-tier business object counterpart is created.

See Also For more information about creating business object proxies to call a custom business object, see "CreateObject Method" and "Getting a Recordset to the Client."

RDSServer.DataFactory vs. Custom Business Objects

There are two ways to pass a Recordset object back from your server to the client with the Remote Data Service. You can:

  • Use the RDSServer.DataFactory object.

    – or –

  • Create a custom business object that exposes data access methods.

RDS contains a server-side business object (ActiveX DLL) called RDSServer.DataFactory that sends SQL statements to a DBMS, and passes the results back across the Internet or an intranet. RDSServer.DataFactory is the default ActiveX DLL that you can use to provide live data on your Web page, with little programming.

If you don't want to use the RDSServer.DataFactory object to pass Recordset objects back to the client, you can create your own custom ActiveX DLLs that will run on the server. The custom DLLs could also contain methods that aren't provided by the simple RDSServer.DataFactory ActiveX DLL. These methods don't have to be related to data access — they could just encompass a business rule.

Client-Side Data Cache

One of the most important features of the Remote Data Service is its in-memory data caching on both the client and middle tiers. The data cache:

  • Reduces the number of requests for data between the client-side application components and the database server. The performance improvement is especially noticeable for data access across the Internet.

  • Makes data immediately available to the client-side application logic, without the application having to wait for data to travel across the network.

Using disconnected Recordset objects eliminates the contention for OLE DB connections that occurs when multiple Internet clients simultaneously access a data source.

The client-side data cache is made up of:

  • ActiveX Data Objects

  • Client Cursor Engine

ActiveX Data Objects

You can use ActiveX™ Data Objects (ADO) to write a client application that can access and manipulate data in a database server through a provider (database interface). When you use the RDS.DataControl object to send a query to a database, the Remote Data Service server-side components return an ADO Recordset object to the client. You don't necessarily have to write any ADO-specific code to make this happen — RDS handles this for you when you use the RDS.DataControl object. RDS uses ADO as a programming interface between the code and the data exposed by the underlying OLE DB provider. Because RDS is already using ADO, extending RDS functionality with ADO is easy.

ADO vs. Remote Data Service

ActiveX Data Objects (ADO) is a collection of Automation objects that can retrieve, update, and create records in any OLE DB provider, which includes ODBC databases. The Remote Data Service provides client-side caching of Recordset objects that minimizes the amount of network roundtrips, and it also provides a data-binding mechanism to display Recordset objects in data-bound controls on a Web page.

RDS is suitable for applications in which the client needs to browse records or connect to live data. Because the data is cached on the client workstation, a user can quickly scroll through the data. RDS can also spare users from needing details about the data source.

ADO is suitable for applications that need a high degree of database programmability. With ADO, you specify what type of Recordset object to create, which provides more flexibility than using RDS. Also, because ADO can execute on the Web server in an ASP page, it doesn't require any particular set of components on the client in Web-based applications. Further, ADO can maintain database connections, while RDS always works with disconnected data.

When you create an application, decide which technology is most appropriate for you. You can use RDS, ADO, or a combination of both technologies in the same application. For example, your application can combine a custom business object that uses ADO to manage data manipulation with the data source, and RDS to transfer remote data to the middle tier where the user can interact with it.

ADOR vs. ADODB Recordset Objects

ActiveX™ Data Objects (ADO) can exist in both the client and middle tiers. ADOR and ADODB are "ProgID's" or prefixes that indicate where the Recordset object will exist and be manipulated. If the Recordset exists on the middle tier, use the ADODB ProgID when writing code. If the Recordset exists and is manipulated on the client, use the ADOR ProgID. A Recordset on either tier behaves almost identically. There are slight differences in the availability and behavior of some Recordset methods and properties; these differences are noted in the relevant ADO method and property reference topics.

OLE DB

The Remote Data Service uses an OLE DB interface to communicate with any data source (including relational and nonrelational databases, Microsoft Excel spreadsheets, mail, flat files, and so forth) that can communicate with OLE DB and expose its tabular data through the OLE DB standard. Such data sources are known as providers.

A variety of providers are currently available, including the Microsoft ODBC Provider, which exposes any ODBC database through OLE DB, and the Microsoft Jet Database Engine Provider, which exposes Microsoft Access and other desktop databases through OLEDB.

Usually, you use Microsoft Visual Basic or VBScript to access ADO Recordset objects, so the OLE DB layer will be invisible. ADO and RDS use OLE DB "behind the scenes."

See Also For more information about using OLE DB, see the OLE DB Web site (http://www.microsoft.com/oledb/).

Client Cursor Engine

The Client Cursor Engine is a set of data structures that caches, in memory (or temporarily on disk for large sets of data), the set of query results retrieved from a DBMS, as well as client updates to those results. The Client Cursor Engine is an underlying technology that is invisible to you — Remote Data Service calls the Client Cursor Engine to perform various tasks for you automatically.

The Client Cursor Engine contains buffers for meta data such as tables, rows, columns, keys, and timestamps, as well as the actual table data itself. To manage the cache, the Client Cursor Engine can:

  • Create and delete temporary tables.

  • Populate tables.

  • Manage updates to the data values.

  • Provide schema information (such as base tables, key columns, updatable columns, special columns, and computed columns).

  • Provide the mechanism to send batched updates to the server with minimum network traffic, by sending only the modified records.

Middle Tier

The middle tier is the "bridge" between client computers and database servers. The components on the middle tier respond to requests from the user (or other business services) in order to execute a business task.

In an RDS application, business objects on the middle tier handle the data request from the client sent through a transport protocol such as HTTP. That request is sent to the data source tier through an OLE DB provider to complete the requested transaction(s). The middle tier usually consists of the following components:

  • Internet Information Server and ADISAPI

  • Business objects

  • Server-side data cache

The following illustration shows the various components on the middle tier.

Internet Information Server

Microsoft® Internet Information Server (IIS) enhances the functionality of Windows NT® Server 4.0. IIS includes a complete set of tools for building server-based Web applications and creating rich and dynamic content. The underlying Remote Data Service code uses one of these tools, the Internet Information Server API (ISAPI), to help create server-side stubs to communicate with client-side business object proxies (through the RDS Advanced Data ISAPI, or ADISAPI).

ADISAPI provides parsing, Automation control, Recordset object marshaling, and tabular data packaging, streaming, and unpackaging. This extension library performs the necessary work to instantiate business objects, invoke their services through Automation interfaces, and process the return parameters for transport back to the calling client through the tabular data streaming protocol.

Note The business object proxy and the ADISAPI components are responsible for marshaling data across the process or machine boundaries. The marshaled data is copied by value, rather than by reference, using a data format designed to marshal tabular (rowset) data, based on the OLE DB standard of exposing the metadata information. The proxy uses this format when marshaling rowsets across process or machine boundaries.

Active Server Pages

Internet Information Server (IIS) contains a feature, called Active Server Pages (ASP), that allows server-side scripting. Whereas VBScript and the ActiveX controls on HTML pages are interpreted and rendered by the client-side browser, Active Server Pages scripting is processed by an engine on the Web server, before the HTML page is sent to the browser.

You can use Active Server Pages to write server pages (.asp files) that can be referred to as URLs from any Internet browser. These pages are composed of text, HTML tags, and script commands. The script commands consist of Visual Basic-like code embedded within the <% and %> tags.

You can use ASP pages as components of a Remote Data Service application, as in the Address Book example in Getting Started. The HTML and VBScript code for that example is written in an .asp file, and Active Server Pages script is used to request the name of a server.

See Also For more information about IIS and ASP, see the IIS Web site, http://www.microsoft.com/iis/, or IIS 4.0 documentation.

Business Objects

The main application components on the middle tier are business objects that contain information such as application logic, business rules, and the data access code from underlying databases. The client-side components access these server-side business objects through business object proxies. Business objects can be any generic Automation objects created with Visual Basic®, Visual C++®, etc.

The Remote Data Service supplies a default business object, the RDSServer.DataFactory object, that provides read and write access to data sources, but contains no business rules or application logic. You may use the methods of this default object in your own custom business objects that contain other business rules.

The ADISAPI component performs the actual communication with business objects for you, and is responsible for creating instances of objects, invoking methods, and releasing them. Your business objects can use ADO to query and update the underlying databases. In RDS, the lifespan of a business object is as long as the execution of a method call invoked by the client. Instances of the business objects are created with each method call, and no interim state is maintained.

See Also For more information about business objects, see "Getting a Recordset to the Client" and "RDSServer.DataFactory vs. Custom Business Objects."

DCOM and Microsoft Transaction Server

You can implement Remote Data Service applications on an intranet without using HTTP. If the client- and middle-tier components are on computers within a LAN (local-area network), you can use DCOM to marshal the interfaces and method arguments across the network.

In an intranet/LAN application using RDS, the business object proxy and the ADISAPI components are replaced, respectively, by COM proxies and stubs. Except for rowsets, the arguments being marshaled don't need to be packaged in multi-part MIME packets. Instead, they are transported in the native DCE/NDR format, implemented by COM marshaling code.

When business objects on the middle tier are implemented as Microsoft Transaction Server components, they can use Transaction Server context objects to maintain their state across multiple client calls. This scenario is possible with DCOM, which is typically implemented between trusted clients and servers (that is, an intranet).

See Also For more information on using Transaction Server, see "MTS Resource Dispensers" and "Running Business Objects in Microsoft Transaction Server." You can also visit the Transaction Server Web site at http://www.microsoft.com/transaction/, or refer to the Microsoft Transaction Server documentation provided with Microsoft Windows NT 4.0 Option Pack.

RDSServer.DataFactory Object

The RDSServer.DataFactory object is a SQL query and update control used in coordination with the RDS.DataControl object to retrieve and post data to back-end data sources that support OLE DB. When you use some of the RDS.DataControl object's methods and properties, the Remote Data Service is calling RDSServer.DataFactory behind the scenes. You can use it as a utility object, or as a template to create business objects that are compatible with RDS applications.

The RDSServer.DataFactory object resides on a Web server and is instantiated by the ADISAPI component. The RDSServer.DataFactory object provides read/write access to specified data sources, but doesn't contain any validation or business rules logic.

Server-Side Data Cache

The server-side data cache is similar to the data cache on the client tier. For more information on the data caching mechanism, see "Client-Side Data Cache."

Data Source Tier

The data source tier defines, maintains, accesses, and updates data, and manages and satisfies middle-tier requests for data. Separating data source services from the other application components allows the data structure and access mechanisms to be maintained, modified, and even re-architected when necessary without affecting application components on the client or middle tier.

The data source services may be physically implemented in a particular database management system (DBMS), or by a heterogeneous collection of databases which may reside on multiple platforms and combinations of servers and mainframe computers. Your DBMS can be a Microsoft SQL Server database, for example, and you can use Microsoft ODBC and OLE DB technology to handle all data similarly on the client side, regardless of its source. This eliminates the need to use targeted client-side drivers for each data source. This also means you can easily modify Remote Data Service applications to suit different network and DBMS configurations.


(Untitled)

Microsoft Remote Data Service Microsoft Remote Data Service *

Developing Remote Data Service Applications

When you write code for your Web-based data access application, you need to understand the various components involved if you want to use the Remote Data Service’s data binding and remoting features.

The previous section, "Understanding Remote Data Service Applications," introduces the architecture of a three-tiered RDS application, and explains how the client-side and server-side components communicate with each other to send data between clients and servers.

This section contains information on:

  • Getting a Recordset to the Client

  • Passing Updated Recordsets to the Middle Tier

  • Defining a Recordset

  • Sorting and Filtering

  • Navigating Through Recordsets

  • Displaying Data Through a Bound Control


Getting a Recordset to the Client

One of the most important features of Remote Data Service is data caching on the client. It reduces the number of requests for data between the client-side application components and the database server, which improves both the actual performance and the user’s perceived performance of the application.

There are three ways to pass a Recordset back from your server to the client with RDS. You can:

  • Use the RDS.DataControl methods and properties that automatically call the RDSServer.DataFactory object.

  • Manually call the RDSServer.DataFactory object.

  • Create a custom ActiveX DLL that performs data access functions.

This section explains how to pass Recordset objects using any of these methods, and it also contains information on:

  • Transport protocols

  • Connection pooling

  • Running business objects in Microsoft Transaction Server

Getting a Recordset with the RDS.DataControl Object

You can open a disconnected Recordset by setting the RDS.DataControl object's Connect, Server, and SQL properties.

The following code shows how to set these properties at design time:

<OBJECT CLASSID="clsid:BD96C556-65A3-11D0-983A-00C04FC29E33" ID="ADC1">
    <PARAM NAME="SQL" VALUE="Select * from Products">
    <PARAM NAME="Connect" VALUE="DSN=AdvWorks;">
    <PARAM NAME="Server" VALUE="http://SalesWeb/">
</OBJECT>

Calling the Refresh method after setting these properties on the RDS.DataControl automatically calls the RDSServer.DataFactory object "behind the scenes," and Remote Data Service returns a Recordset object to the client. You don't have to actually write any code to use the RDSServer.DataFactory, but if you do want to do this, see "Getting a Recordset with the RDSServer.DataFactory Object."

Asynchronous Population

You can open and populate a disconnected Recordset object asynchronously. This improves performance by leaving the client free to execute other tasks while records are still being returned. Three properties of the RDS.DataControl object make this possible:

  • The ExecuteOptions property of the RDS.DataControl object indicates the type of asynchronous execution. This property can be set to adcSyncExecute (the default) which causes data refresh to occur synchronously, or to adcAsyncExecute, which causes asynchronous execution of the next Refresh of the Recordset.

  • The FetchOptions property indicates whether the fetching of records into an RDS.DataControl object’s Recordset is to occur asynchronously. Asynchronous fetching is the default setting.

  • The ReadyState property returns the state of the RDS.DataControl object's Recordset. Your code can check this property to see whether an asynchronous operation is complete,

Here is a VBScript code snippet that shows the use of these properties:

ADC1.Connect = "UID=sa;PWD=permission;DSN=Pubs"
ADC1.SQL = "select * from authors A1, authors A2, authors A3"
ADC1.Server = "http://SERVER_NAME"

ADC1.ExecuteOptions = adcExecAsync
ADC1.FetchOptions = adcFetchAsync

ADC1.Refresh

… … …
select case ADC1.ReadyState
    case adcReadyStateLoaded: MsgBox "Executing"
    case adcReadyStateInteractive: MsgBox "Fetching in background"
    case adcReadyStateComplete: MsgBox "All records fetched"
end select
  • The Cancel method cancels the currently running asynchronous execution. For example, if it is taking too long to complete, your code can just cancel an asynchronous task,

Getting a Recordset with the RDSServer.DataFactory Object

Remote Data Service contains a server-side business object (ActiveX DLL) called RDSServer.DataFactory that sends commands to a data source and passes the results back across the Internet or an intranet for you. RDSServer.DataFactory is the default ActiveX DLL that you can use to provide live data on your Web page with little programming.

The following example shows how to call the RDSServer.DataFactory object from a VBScript Web page. You use the RDS.DataSpace object on the client to instantiate the RDSServer.DataFactory object on the server.

<HTML>
<HEAD></HEAD>
<BODY>

<!-- RDS.DataControl -->
<OBJECT classid="clsid:BD96C556-65A3-11D0-983A-00C04FC29E33" ID=ADC1>
</OBJECT>
<!-- RDS.DataSpace -->
<OBJECT ID="ADS1" WIDTH=1 HEIGHT=1
  CLASSID="CLSID:BD96C556-65A3-11D0-983A-00C04FC29E36">
</OBJECT>
.
.
.
<SCRIPT LANGUAGE="VBScript">
Option Explicit
Sub Window_OnLoad()
  Dim ADF1, myRS
  Set ADF1 = ADS1.CreateObject("RDSServer.DataFactory", _
  "http://<%=Request.ServerVariables("SERVER_NAME")%>")
  Set myRS = _
    ADF1.Query("DSN=pubs;UID=sa;PWD=permission;", _
    "Select * From Authors")
  ' Assign the returned recordset to SourceRecordset.
  ADC1.SourceRecordset = myRS
End Sub
</SCRIPT>
</BODY>
</HTML>

Security and your Web Server

If you use the RDSServer.DataFactory object on your Internet Web server, remember that doing so creates a potential security risk. External users who obtain valid data source name (DSN), user ID, and password information could write pages to send any query to that data source. If you want more restricted access to a data source, one option is to unregister and delete the RDSServer.DataFactory object (msadcf.dll), and instead use custom business objects with hard-coded queries. The next section describes how to do this.

Getting a Recordset with a Custom Business Object

If you don't want to use the RDSServer.DataFactory object to pass Recordset objects back to the client, you can create your own custom business object that will run on the server. The DLL (dynamic-link library) can be any generic Automation object created with Visual Basic®, Visual C++®, and so forth, or a server-side HTML page with Active Server Pages scripting code. Clients and Web front-end applications call the business objects to perform a particular function, and those middle-tier business objects in turn can communicate with back-end databases.

The custom DLLs could also contain methods that aren't provided by the simple RDSServer.DataFactory ActiveX DLL. These methods don't have to be related to data access — they could just encompass a business rule.

This section contains information on:

  • Writing Code to Pass Recordsets with a Custom Business Object

  • Required Custom Business Object Registry Entry

  • Marking Business Objects as "Safe for Scripting"

  • Client-Side Registry Entries for Business Objects with DCOM

Writing Code to Pass Recordset Objects with a Custom ActiveX DLL

The following client VBScript code performs the same action as the previous RDSServer.DataFactory code, except that it uses a custom business object. You still use the RDS.DataSpace object on the client to instantiate the business object (in this case, MyCustomBusinessObject) on the server.

<HTML>
<HEAD></HEAD>
<BODY>

<!-- RDS.DataControl -->
<OBJECT classid="clsid:BD96C556-65A3-11D0-983A-00C04FC29E33" ID=ADC1>
</OBJECT>
<!-- RDS.DataSpace -->
<OBJECT ID="ADS1" WIDTH=1 HEIGHT=1
  CLASSID="CLSID:BD96C556-65A3-11D0-983A-00C04FC29E36">
</OBJECT>
.
.
.
<SCRIPT LANGUAGE="VBScript">
Option Explicit
Sub GetRecords()
  Dim objMyCustomBusinessObject, myRS
  Set objMyCustomBusinessObject = _
    ADS1.CreateObject("MyCustomBusinessObject", _
    "http://<%=Request.ServerVariables("SERVER_NAME")%>")
  ' Assume MyCustomBusinessObject has a method called
  ' GetData that takes connection string and SQL
  ' parameters.
  Set myRS = _
    objCustomBusinessObject.GetData _
    ("DSN=pubs;UID=sa;PWD=permission;", _
    "Select * From Authors")
  ' Assign the returned recordset to SourceRecordset.
  ADC1.SourceRecordset = myRS
End Sub
</SCRIPT>
</BODY>
</HTML>

Assuming you use Visual Basic to create the MyCustomBusinessObject ActiveX DLL that is located on the middle tier, the code in the GetData method of the MyCustomBusinessObject class could look something like this. Notice that you can use ActiveX™ Data Objects (ADO) directly.

' Returns an ADO resultset.
Public Function GetData(szCnStr As String, szSQL _
  As String) As Object

  Dim cn As New ADODB.Connection
  Dim rs As New ADODB.Recordset

  cn.Open szCnStr
  ' The ADODB.Recordset should generate Recordset
  ' objects that can be disconnected and later
  ' reconnected to process batch updates.
  rs.CursorLocation = adUseClientBatch
  ' Using the Unspecified parameters, an ADO/R
  ' recordset is returned.
  rs.Open szSQL, cn, _
    adOpenUnspecified, adLockUnspecified, _
    adCmdUnspecified
  Set GetData = rs
End Function

Tips

Always place one simple method in your server component to test for minimum functionality before attempting to pass Recordset objects back.

Build a simple client application to test your server component before deploying and testing it with Internet Explorer.

It is easier to develop your application on a local test Web server. You will need to copy and register the .dll on the test server after each compile.

The DSN passed to your business object will need to be a System DSN on your server. If it doesn't exist or is set up improperly, your component will fail. It is a good idea to test the DSN on the server with another ODBC application such as MSQuery to make sure the DSN is set up properly.

Method names on custom business objects cannot exceed 255 characters. This allows compatibility across all RDS-supported protocols (HTTP, HTTPS, DCOM, and running in-process).

If you used Visual Basic to create a custom business object that uses early binding with the ADOR 1.0 type library, you should rebuild you custom business object to use the ADOR 1.5 type library.

Required Custom Business Object Registry Entry

To successfully launch a custom business object (DLL or EXE) through the Web server, the business object's ProgID must be entered into the registry as explained in this procedure. This RDS feature protects the security of your Web server by running only sanctioned executables. The default business object, RDSServer.DataFactory, is already fully registered.

To register a custom business object

  1. From the Start menu, click Run.

  2. Type RegEdit and click OK.

  3. In the Registry Editor, navigate to the HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\W3SVC\Parameters\ADCLaunch registry key.

  4. Select the ADCLaunch key, and then on the Edit menu, point to New, and click Key.

  5. Type the ProgID of your custom business object and click Enter. Leave the Value entry blank.

Marking Business Objects as "Safe for Scripting"

To help ensure a secure Internet environment, you need to mark any business objects instantiated with the RDS.DataSpace object's CreateObject method as "safe for scripting." You need to ensure they are marked as such in the License area of the system registry before they can be used in DCOM.

To manually mark your business object as safe for scripting, create a text file with a .reg extension that contains the following text shown in capitals. The following two numbers enable the safe-for-scripting feature:

[HKEY_CLASSES_ROOT\CLSID\<MyActiveXGUID>\Implemented Categories\{7DD95801-9882-11CF-9FA9-00AA006C42C4}]

[HKEY_CLASSES_ROOT\CLSID\<MyActiveXGUID>\Implemented Categories\{7DD95802-9882-11CF-9FA9-00AA006C42C4}]

where <MyActiveXGUID> is the hexadecimal GUID number of your business object. Save it and merge it into your registry by using the Registry Editor or double-clicking directly the .reg file in the Windows Explorer.

Business objects created in Visual Basic® 5.0 can be automatically marked as "safe for scripting" with the Application Setup Wizard.

To mark business objects safe for scripting in Visual Basic 5.0:

  1. Start the Visual Basic 5.0 Application Setup Wizard.

  2. On step one, choose your project, and then click Create Internet Download Setup.

  3. On step four, click Safety and select Safe for initialization and Safe for scripting.

  4. On the last step, the Application Setup Wizard creates an .htm and a .cab file. You can then copy these two files to the target computer and double-click the .htm file to load the page and correctly register the server.

  5. Because the business object will be installed in the Windows\System32\Occache directory by default, you should move it to the Windows\System32 directory and change HKEY_CLASSES_ROOT\CLSID\<MyActiveXGUID>\InprocServer32 registry key to match the correct path.

  6. If you find that your business object isn't working at this point, check the .inf file that is included in the \Support directory under the Application Setup Wizard installation directory. It should contain "RegisterServer=yes" and the [AddSafeToScript] section.

See Also The ActiveX SDK Web page at http://www.microsoft.com/intdev/sdk/ contains more information about this standard and how to implement it. The safe-for-scripting information is under the Signing/Marking Controls topic (signmark.htm).

Passing Parameters to Business Objects

Remote Data Service 1.5 supports passing of parameters to and from business objects (ActiveX components) by reference. This allows your business object to modify a referenced input parameter and return it as an "out" parameter back to the client code. This parameter can be passed in addition to a return value allowed by a function.

To use this feature, you need to be aware of how the business object accepts arguments so you can optimize the code for functionality and performance. If it is not important to return an extra output argument, you will want to specify that the method is accepting the argument by value. This is especially important in Microsoft Visual Basic because it accepts parameters by reference by default.

The following is a Visual Basic example of how you can accept parameters "by value" and "by reference":

' This function returns one return value to the client.
Function TestByVal(ByVal arg1 As Variant) As Variant
  TestByVal = "A copy of a new return value."
End Function

' This function returns one return value and
' one out parameter to the client.
Function TestByRef(ByRef arg1 As Variant) As Variant
  arg1 = "This value will be returned as an output parameter."
  TestByRef = "A copy of a new return value."
End Function

You also need to pay attention to the data type of the ByRef arguments. For example, VBScript does not let you specify the variable type, so you will always be passing a Variant. When using HTTP, RDS will allow you to pass a Variant to a method that expects a non-Variant if you invoke it with the CreateObject method of the RDS.DataSpace object. When using DCOM or an in-process server, you will need to make sure you match the parameter types to be the same on each side or you will receive a "Type Mismatch" error.

Client Impersonation and Security

If the Password Authentication property for your IIS Web server is set to Windows NT Challenge/Response, then business objects are invoked under the client's security context. This is a new feature in RDS 1.5 that allows Client Impersonation over HTTP. When working in this mode, the login to the Web server (IIS) is not anonymous but uses the user ID and password the client computer is running under. If the ODBC DSNs are set up to use Trusted Connection, then access to databases like SQL Server also happens under the client's security context. But this only works if the database is on the same computer as the IIS; the client credentials cannot be carried over to yet another computer.

For example, a client, John Doe, with userid="JohnD" and password="secret" is logged on a client computer. He runs a browser-based application that needs to access the RDSServer.DataFactory object to create an ADOR.Recordset by executing a SQL Query on the "MyServer" computer running IIS. MyServer is set up to use "Windows NT Challenge/Response" for Password Authentication, its ODBC DSN has "Use Trusted Connection" checked, and the server also contains the SQL Server data source. When a request is received on the Web server, it asks the client for the user ID and password. Thus the request is logged on MyServer as coming from "JohnD"/"Secret" instead of IUSER_MyServer (which is the default when Anonymous Password Authentication is on). Similarly, when logging on to SQL Server, "JohnD"/"Secret" is used.

Consequently, the IIS NT Challenge/Response authentication mode allows HTML pages to be created without the user being explicitly prompted for the user ID and password information needed to log on to the database. If the IIS Basic Authentication was being used, then this would be also be required.

Password Authentication

RDS 1.5 can communicate with an IIS Web server running in any one of the three Password Authentication modes: Anonymous, Basic, or NT Challenge/Response. These settings define how a Web server controls access through it, such as requiring that a client computer have explicit access privileges on the NT Web server.

Client-side Registry Entries for Business Objects with DCOM

Custom business objects need to ensure that the client side can map their program name (ProgId) to an identifier (CLSID) that can be used over DCOM. For this reason, the ProgID of the DCOM object must be in the client side registry and map to the class ID of the server-side business object. For the other supported protocols (HTTP, HTTPS, and in-process), this isn't necessary.

For example, if you expose a server-side business object called MyBObj with a specific class ID, for instance, "{00112233-4455-6677-8899-00AABBCCDDEE}", you should make sure the following entries are added to the client-side registry:

[HKEY_CLASSES_ROOT]
\MyBObj
    \Clsid
    (Default) "{00112233-4455-6677-8899-00AABBCCDDEE}"

Transport Protocols

When a client-side component invokes a server-side component, there are a number of ways that you can use to send the request. These include:

  • HTTP and HTTPS protocols

  • DCOM protocol

  • Running In-process

When the client-side component and the server-side component reside on different computers (that is, you will use the HTTP, HTTPS, or DCOM protocol), a client-side proxy must be created for each server-side business object stub to ensure proper marshaling. How the proxy is created depends on which protocol you are using.

HTTP and HTTPS Protocols

If you use the HTTP or HTTPS protocol, client-side components can't access remote server-side components directly. Therefore, Remote Data Service provides a proxy creation method (CreateObject) on the client side. A business object proxy is created for every server-side business object invoked from the client side. This RDS mechanism takes care of packaging and receiving remote application parts. This means that you don't have to write a lot of code to use custom business objects over HTTP or HTTPS.

Business object proxies are Automation objects and can be called from within Visual Basic® and Visual C++® applications, or any application that enables ActiveX™ technology. No type checking is done on the client side, instead RDS assumes that each method supports a variable number of variant arguments. An instance of the business object is created on the server-side only when the first method call is made, so no round trip is made just to instantiate the object.

When you use HTTP, the business object proxy packages and unpackages the parameters it sends and receives in MIME format. Each argument is packaged into a separate MIME subpart. The proxy can handle all Automation data types and ADODB.Recordset and ADOR.Recordset objects. The proxy translates the method invocation into HTTP Post format, which it passes to the Advanced Data ISAPI DLL (ADISAPI) on the Web server.

DCOM Protocol

You can also implement Remote Data Service applications on an intranet without using HTTP. If the client-side and server-side components are on different computers, you can use DCOM to marshal the interfaces and method arguments across the network. When you do this, the business object proxies and ADISAPI components are replaced, respectively, by COM proxies and stubs.

Running In-Process

If your client-side and server-side components reside on the same computer, they can access each other directly. There is no need for a proxy-stub mechanism.

Connection Pooling

To improve the speed with which you open Recordset objects and establish connections, use:

  • The Connection Pooling options

  • Microsoft Transaction Server resource dispensers

The Connection Pooling Options

If you're using an ODBC data source, you can use the Connection Pooling option in Internet Information Server (IIS) to achieve high performance handling of client load. Connection Pooling is a resource manager for connections, maintaining the open state on frequently used connections.

To enable Connection Pooling, refer to the Internet Information Server documentation.

Please note that enabling Connection Pooling may subject the Web server to other restrictions, as noted in the Microsoft Internet Information Server documentation.

Microsoft SQL Server — Performance and Stability with Connection Pooling

To ensure connection pooling is stable and provides additional performance gains, you must configure Microsoft SQL Server to use the TCP/IP Socket network library.

To do this, you need to:

  • Configure the SQL Server computer to use TCP/IP Sockets.

  • Configure the Web server to use TCP/IP Sockets.

Configuring the SQL Server Computer to Use TCP/IP Sockets

On the SQL Server computer, run the SQL Server Setup program so that interactions with the data source use the TCP/IP Socket network library.

To specify the TCP/IP Socket network library on the SQL Server computer

  1. From the Start menu, point to Programs, point to Microsoft SQL Server 6.5, then click SQL Setup.

  2. Click Continue twice. The Microsoft SQL Server 6.5 — Options dialog box appears.

  3. Select Change Network Support, and click Continue.

  4. Make sure the TCP/IP Sockets check box is selected, and click OK.

  5. Click Continue to finish, and exit setup.

Configuring the Web Server to Use TCP/IP Sockets

There are two options for configuring the Web server to use TCP/IP Sockets. What you do depends on whether:

  • All SQL Servers are accessed from the Web server

    – or –

  • Only a specific SQL Server is accessed from the Web server.

If all SQL Servers are accessed from the Web server, you need to run the SQL Server Client Configuration Utility on the Web server computer. The following steps change the default network library for all SQL Server connections made from this IIS Web server to use the TCP/IP Sockets network library.

To configure the Web server (all SQL Servers)

  1. From the Start menu, point to Programs, point to Microsoft SQL Server 6.5, and then click SQL Client Configuration Utility.

  2. Select the Net Library tab.

  3. In the Default Network box, select TCP/IP Sockets.

  4. Click Done to save changes and exit the utility.

If a specific SQL Server is accessed from a Web server, you need to run the SQL Server Client Configuration Utility on the Web server computer. To change the network library for a specific SQL Server connection, on the Web server computer, configure the SQL Server Client software as follows.

To configure the Web server (a specific SQL Server)

  1. From the Start menu, point to Programs, Microsoft SQL Server 6.5, and then click SQL Client Configuration Utility.

  2. Select the Advanced tab.

  3. In the Server box, type the name of the server to connect to using TCP/IP Sockets.

  4. In the DLL Name box, select TCP/IP Sockets.

  5. Click Add/Modify. All data sources pointing to this server will now use TCP/IP Sockets.

  6. Click Done.

Microsoft Transaction Server Resource Dispensers

In a three-tiered environment, clients can share database connections if you use Microsoft Transaction Server on the middle tier. You can use the RDSServer.DataFactory object or create an ActiveX component DLL that can set up ODBC connections for clients to share; the sharing mechanism comes into play when you run the RDSServer.DataFactory or custom business object in the Transaction Server run-time environment. Instead of using thousands of database connections, you could get away with hundreds, still supporting thousands of clients. This is a feature of the ODBC resource dispenser in Microsoft Transaction Server.

See Also For more information about using Transaction Server, see "Running Business Objects in Transaction Server" or visit the Transaction Server Web site (http://www.microsoft.com/transaction/).

Running Business Objects in Microsoft Transaction Server

Business objects can be executable files (.exe) or dynamic-link libraries (.dll). The configuration you use to run the business object depends on whether the object is a .dll or .exe file:

  • Business objects created as .exe files can be called through DCOM. If these business objects are used through Internet Information Server (IIS), they are subject to additional marshaling of data, which will slow client performance.

  • Business objects created as .dll files can be used via IIS (and therefore HTTP), and over DCOM only via Microsoft® Transaction Server. Business object DLLs will need to be registered on the IIS computer to give you accessibility via IIS. The RDSServer.DataFactory object is a DLL that is the default business object provided by Remote Data Service, and it is also subject to the conditions in this section. (For steps on how to configure a DLL to run on DCOM, see the next section, "Enabling a DLL to Run on DCOM.")

By running the RDSServer.DataFactory object or your custom business object in the MTS run-time environment, you can also boost your performance and scalability by using the MTS resource dispenser. Because these business objects call ADO, which indirectly calls ODBC, you can take advantage of the MTS ODBC resource dispenser.

Resource dispensers automatically pool and recycle resources. Therefore, when RDSServer.DataFactory or your custom business object releases a database connection, the connection is returned to a pool. When a method is called to create a connection again, it requests the same database connection. Instead of creating a new connection, the ODBC resource dispenser recycles the pooled connection, which saves time and server resources.

Note When business objects on the middle tier are implemented as Microsoft Transaction Server components (using GetObjectContext, SetComplete, and SetAbort), they can use Transaction Server context objects to maintain their state across multiple client calls. This scenario is possible with DCOM, which is typically implemented between trusted clients and servers (an intranet). In this case, the RDS.DataSpace object and CreateObject method on the client side are replaced by the transaction context object and CreateInstance method (provided by the ITransactionContext interface), implemented by Microsoft Transaction Server.

Enabling a DLL to Run on DCOM

The following steps outline how to enable a business object DLL to use both DCOM and Internet Information Server (HTTP) via Microsoft Transaction Server.

  1. Create a new empty package in the Transaction Server Explorer.

    You will use the Transaction Server Explorer to create a package and add the DLL into this package. This makes the DLL accessible through DCOM, but it removes the accessibility through IIS. (If you check in the registry for the DLL, the Inproc key is now empty; setting the Activation attribute, explained later in this topic, adds a value in the Inproc key.)

  2. Install a business object into the package.

    -or-

    Import the RDSServer.DataFactory object into the package.

  3. Set the Activation attribute for the component to In the creator's process.

    To make the DLL accessible through DCOM and IIS on the same computer you must set the component's Activation attribute in the Microsoft Transaction Server Explorer. After you set the attribute to In the creator's process, you will notice that an Inproc server key in the registry has been added that points to a Microsoft Transaction Server surrogate DLL.

See Also For more information about Transaction Server and how to perform these steps, visit the Transaction Server Web site at http://www.microsoft.com/transaction/ or refer to the Microsoft Transaction Server documentation.


Passing Updated Recordsets to the Middle Tier

Microsoft Remote Data Service Microsoft Remote Data Service *

Passing Updated Recordset Objects to the Middle Tier

You can pass updated Recordset objects from client computers to the middle tier and the database server by using:

  • The RDS.DataControl object.

  • ADO with a middle-tier custom business object.

Using RDS.DataControl to Pass Updated Disconnected Recordset Objects Back to the Middle Tier

Data-bound controls enable the user to visually edit, add, or delete records. All changes by the user are stored locally until the user explicitly submits or cancels the update.

Typically, you will bind a grid control to an RDS.DataControl object, and then add, edit, and delete records in the client-side Recordset via the user interface. After you update the client-side data, you need to save the changed information to the database by using the SubmitChanges method with the RDS.DataControl object. The SubmitChanges method submits pending changes of the locally cached updatable Recordset to the OLE DB data source specified in the RDS.DataControl object's Connect property.

The following code example shows how to do this:

Sub Update_OnClick
    ADC1.SubmitChanges
End Sub

Only the changed records are sent for modification, and either all of the changes succeed or all of them fail together.

You can also include a Cancel button to cancel changes to the Recordset:

Sub Cancel_OnClick
    ADC1.CancelUpdate
End Sub

Notes

  • The Connect, Server, and SQL properties must be set before you can use the SubmitChanges method with the RDS.DataControl object. These properties are used to reconnect to the data source.

  • If you call the CancelUpdate method after you have called SubmitChanges for the same Recordset object, the CancelUpdate call fails because the changes have already been committed.

Multiuser Issues and Record Locking

Because users are working with disconnected Recordset objects on a client-side cache, there may be multiuser issues. For instance, when two different users try to update the same record, Remote Data Service simply allows the user who updates the record first to "win." The second user's update request will fail with an error.

Using ADO to Pass Recordset Objects to the Middle Tier

You can use the ADOR.Recordset object to marshal recordsets from a client Web page to a middle-tier business object. For example, suppose a user connects to a virtual shopping mall and selects a number of items to purchase. The selected items appear in the virtual shopping cart that is implemented with the RDS.DataControl object and buffered in a rowset. When the client clicks the purchase button, an ADOR.Recordset object is created and passed to an application server as an input parameter to a business function (ApplyUpdates). This causes the Recordset to be marshaled across to the server. The ApplyUpdates business function then connects to the Sales database and applies the updates.

' Code on a client Web page.
Sub PurchaseItem_OnClick
    Set rst = ADC1.Recordset

    ' The following option tells the recordset to send
    ' back changed records only when working with
    ' updates.
    ' This makes the roundtrips more lightweight.
    ' The value of 1 is the same as setting it to
    ' adMarshalModifiedOnly.
    rst.MarshalOptions = 1

    ' Call the ApplyUpdates function on the MyObj
    ' business object and pass the ADOR.Recordset
    ' object as an input parameter.
    MyObj.ApplyUpdates rst

End Sub

' VB code in the business object.
' ApplyUpdates is a method in a
' middle-tier business object.
Sub ApplyUpdates(rst As ADOR.Recordset)

    Dim rs As New ADODB.Recordset

    rs.ActiveConnection =  _
        "DSN=SalesDB;UID=SMgr;PWD=password

    rs.Open rso

    ' Call a method on the ADODB.Recordset to save
    ' updates.
    rs.UpdateBatch

End Sub

Database Updatability Features

Updatability is defined as being able to insert and delete records, and update the contents of one or more records.

With Remote Data Service 1.5, you can update a number of databases, including Microsoft® SQL Server, Microsoft Access, Oracle, and so forth. This is different from previous versions, which supported updatability only with SQL Server databases.

The table being updated must contain a key or index column to specify record uniqueness.

Updating in multi-table joins are supported in RDS version 1.5. The cursor engine allows arbitrarily complex inserts, updates, or deletes, requiring each base table to have a key field included in the projection to identify the row. It executes an appropriate update statement once for each base table. It has a property that allows you specify a DELETE followed by an INSERT rather than doing an UPDATE for update handling.

In general, avoid retrieving updatable Recordset objects that can contain duplicate records, because this can lead to data corruption. A status return code of DB_S_ERRORSOCCURED will occur if the WHERE clause identifies duplicate records. If this happens, then more columns should be added to the query so that uniqueness can be achieved. Computed fields, Long Binary fields, and Text fields aren't used in record identification for updating, so at least one column of another type should be included in the query.


Defining a Recordset

You can create an ADODB.Recordset object and specify the column information. You can then insert data into the Recordset object; the underlying rowset buffers the inserts.

The following code example shows how to define a Recordset by using the RDSServer.DataFactory object. This can also be done with the RDS.DataControl object.

Sub RsDefineShape()

    Dim vntRecordSape(3)
    Dim vntField1Shape(3)
    Dim vntField2Shape(3)
    Dim vntField3Shape(3)
    Dim vntField4Shape(3)

    ' For each field, specify the name,
    ' type, size, and nullability.

    vntField1Shape(0) = "Name"	' Column name.
    vntField1Shape(1) = CInt(129)	' Column type.
    vntField1Shape(2) = CInt(40)	' Column size.
    vntField1Shape(3) = False		' Nullable?

    vntField2Shape(0) = "Age"
    vntField2Shape (1) = CInt(3)
    vntField2Shape (2) = CInt(-1)
    vntField2Shape (3) = True

    vntField3Shape (0) = "DateOfBirth"
    vntField3Shape (1) = CInt(7)
    vntField3Shape (2) = CInt(-1)
    vntField3Shape (3) = True

    vntField4Shape (0) = "Balance"
    vntField4Shape (1) = CInt(6)
    vntField4Shape (2) = CInt(-1)
    vntField4Shape (3) = True

    ' Put all fields into an array of arrays.
    vntRecordShape(0) = vntField1Shape
    vntRecordShape(1) = vntField2Shape
    vntRecordShape(2) = vntField3Shape
    vntRecordShape(3) = vntField4Shape

    ' Use the RDSServer.DataFactory to create an empty
    ' recordset. It takes an array of variants where
    ' every element is itself another array of
    ' variants, one for every column required in the
    ' recordset.
    ' The elements of the inner array are the column's
    ' name, type, size and nullability.

    Dim NewRs

    ' You could just use the RDS.DataControl object
    ' instead of the RDSServer.DataFactory object. In
    ' that case, the following code would be Set NewRs
    ' = ADC1.CreateRecordset(vntRecordShape)
    Set NewRS = ADF.CreateRecordset(vntRecordShape)

    Dim fields(3)
    fields(0) = vntField1Shape(0)
    fields(1) = vntField2Shape (0)
    fields(2) = vntField3Shape (0)
    fields(3) = vntField4Shape (0)

    ' Populate the new recordset with data values.
    Dim fieldVals(3)

    ' Use AddNew to add the records.
    fieldVals(0) = "Joe"
    fieldVals(1) = 5
    fieldVals(2) = CDate(#1/5/96#)
    fieldVals(3) = 123.456
    NewRS.AddNew fields, fieldVals

    fieldVals(0) = "Mary"
    fieldVals(1) = 6
    fieldVals(2) = CDate(#6/5/96#)
    fieldVals(3) = 31
    NewRS.AddNew fields, fieldVals

    fieldVals(0) = "Alex"
    fieldVals(1) = 13
    fieldVals(2) = CDate(#1/6/96#)
    fieldVals(3) = 34.0001
    NewRS.AddNew fields, fieldVals

    fieldVals(0) = "Susan"
    fieldVals(1) = 13
    fieldVals(2) = CDate(#8/6/96#)
    fieldVals(3) = 0.0
    NewRS.AddNew fields, fieldVals

    x.MoveFirst

    ' Set the newly created and populated Recordset to
    ' the SourceRecordset property of the
    ' RDS.DataControl to bind to visual controls.
    Set ADC1.SourceRecordset = NewRS

End Sub


(Untitled)

Microsoft Remote Data Service Microsoft Remote Data Service *

Sorting and Filtering

You can sort and filter a Recordset object using the RDS.DataControl sort and filter properties and methods. Sorting orders the records in the Recordset in a specific order (for example, by first name or invoice number), and filtering restricts the result set of records that meet some criteria (for example, employee records whose title is manager).

Tip When you already know how you want to sort and filter your data, it's faster to sort and filter the Recordset by using an SQL string that uses an ORDER BY and WHERE clause.

Sorting a Recordset

You can set the SortColumn and SortDirection properties of the RDS.DataControl object, and then call the Reset method to sort the Recordset on the client-side cache and refresh the results that are displayed in the data-bound controls. The Reset method will execute the criteria and replace the current Recordset with a read-only Recordset.

Filtering a Recordset

You can use the FilterValue, FilterCriterion, and FilterColumn properties of the RDS.DataControl object, and then call the Reset method to filter a Recordset on the client-side cache and refresh the results that are displayed in the data-bound controls. Again, the Reset method will execute the criteria and replace the current Recordset with a read-only Recordset.

Navigating through Recordset Objects

Navigation through Recordset objects is based on the concept of a current record. You can imagine that the current record as the particular record that is highlighted by an invisible cursor as you move through the Recordset.

You can use the Move methods with the RDS.DataControl object to navigate through the data records displayed in the data-bound controls on a Web page. For example, suppose you display a Recordset in a grid by binding to an RDS.DataControl object. You can then include First, Last, Next, and Previous buttons that users can click to move to the first, last, next, or last record in the displayed Recordset. You do this by calling the MoveFirst, MoveLast, MoveNext, and MovePrevious methods of the RDS.DataControl object in the OnClick procedures for the First, Last, Next, and Previous buttons, respectively:

' Move to the first record in the bound recordset.
Sub First_OnClick
    ADC1.Recordset.MoveFirst
End Sub

' Move to the next record from the current position
' in the bound recordset.
Sub Next_OnClick
    ADC1.Recordset.MoveNext
End Sub

' Move to the previous record from the current position
' in the bound recordset.
Sub Previous_OnClick
    ADC1.Recordset.MovePrevious
End Sub

' Move to the last record in the bound recordset.
Sub Last_OnClick
    ADC1.Recordset.MoveLast
End Sub


(Untitled)

Microsoft Remote Data Service Microsoft Remote Data Service *

Displaying Data Through a Bound Control

Bound controls are the data-aware controls through which you access information in a database. When a control is bound to the RDS.DataControl object, Remote Data Service applies field values from the current database record to that control. In turn, the control displays data to you and accepts your changes.

With Internet Explorer 4.0, you can bind to simple HTML controls. Other ActiveX data-aware controls are available from third parties, such as Sheridan.

Two relationships are key to data binding with Internet Explorer 4.0: source and consumer. Data consumers specify binding by referencing the data source to which they are bound. To achieve this, your data consumers (controls such as text boxes or grids) specify the source of the data and the type of the data being bound.

Most bound controls are characterized by the following data-aware parameters of the <OBJECT> tag. These parameters are the HTML data-binding extensions available with Internet Explorer 4.0.
Parameter | Description
DATASRC | Indicates the data source (RDS.DataControl object) for data binding.
DATAFLD | Indicates a column of a data set.
DATAFORMATAS | (Optional) Indicates the type of data being bound.

You can have more than one bound control for a particular field, but you don't need to provide a bound control for each field in the table.

When you access your Web page front end, the RDS.DataControl works together with the database to give you access to a Recordset. You can then navigate the Recordset with navigation buttons that use the RDS.DataControl object's MoveFirst, MoveLast, MoveNext, and MovePrevious methods. (For more information, see "Navigating through Recordsets.") You can also send updates to the database by using the RDS.DataControl object's SubmitChanges method.

See Also For more information on using the Internet Explorer data-binding extensions, see the Internet Client SDK at http://www.microsoft.com/intdev/inetsdk/inetsdk.htm. To see some examples of data-binding, see the tutorials.


(Untitled)

Microsoft Remote Data Service Microsoft Remote Data Service *

Appendixes (Remote Data Service Developer's Guide)

Appendix A: Troubleshooting Remote Data Service

Appendix B: Detailed Control Flow


Troubleshooting Remote Data Service

Microsoft Remote Data Service Microsoft Remote Data Service *

Appendix A: Troubleshooting Remote Data Service

If you have problems running the Remote Data Service, first make sure you have met the hardware and software requirements for RDS. Then, make sure you have installed Remote Data Service correctly (see "Validating Setup" to validate your installation).

The following sections describe workarounds for more specific errors.

"Internet Server Error: Access Denied"

If you get this error, it usually means that Microsoft Internet Information Server (IIS) returned the following status:

HTTP_STATUS_DENIED 401.

Make sure the directories accessed by IIS have proper permissions. RDS 1.5 can communicate with an IIS Web server running in any one of the three Password Authentication modes: Anonymous, Basic, or NT Challenge/Response. Unlike previous versions, the Allow Anonymous setting is no longer required. (For more information, see "HTTP Protocol Permissions Setting.") Also, the Web server must have permissions to the data source computer if it is a Windows NT® computer.

"Unexpected Error" Message When Running the Sample Applications

Server Checklist

  • If you re-install IIS, you must re-install Remote Data Service afterwards.

  • If you are using Microsoft SQL Server as your back-end data source, use Microsoft SQL Server 6.5, Service Pack 2 or later.

  • Ensure that the ODBC DSNs are System DSNs and not User DSNs. The Anonymous user logging on through IIS can view only System DSNs.

  • Check that the anonymous account your WWW service uses is a user on your domain that has NTFS permissions to all the relevant servers and directories. Lastly, check that the password for this anonymous account hasn't expired.

  • Because Remote Data Service is installed in the C:\Program Files\Common Files\System\MSADC directory, check that the Anonymous user from the IIS Service Manager can access this directory. It should have both Read and Execute access.

  • If you have trouble with Remote Data Service DLLs and sample applications, re-register the DLLs by using Regsvr32.exe.

  • If you are writing your own business objects, place your Active Server Pages script files (.asp) in a directory that gives the Anonymous user (in IIS) execute permission.

Using the RDS.DataControl with the Sheridan Combo Box Control

The Sheridan combo box has two properties that can be bound to RDS.DataControl data. Just binding the combo box to RDS.DataControl doesn't automatically populate the "Text" portion, a non-bindable property, which shows the currently selected item. As a result, old data may still be displayed after the Refresh method is called.

A workaround is to use code like either of the following two sample Visual Basic® Scripting Edition Sub procedures. Both clear the Text property when the Refresh method is called. SSCombo is the name of the Sheridan combo box control in these examples.

Sub SSCombo_InitColumnProps()
    SSCombo.Text=""
End Sub

Sub Refresh_OnClick
    ADC1.Refresh
    SSCombo.Text=""
End Sub

Sorting Client-side Recordset Data

To sort on a Recordset, any pending changes must first be saved. If you are using the RDS.DataControl, you can use the SubmitChanges method. For example, if your RDS.DataControl is named ADC1, your code would be ADC1.SubmitChanges. If you are using an ADO Recordset, you can use its UpdateBatch method. Using UpdateBatch is the recommended method for Recordset objects created with the CreateRecordset method. For example, your code could be myRS.UpdateBatch or ADC1.Recordset.UpdateBatch.

Deadlocks With Read Repeatable Isolation Level

If a custom business object uses an isolation level of read repeatable to access a SQL Server, and the business object is called simultaneously by two clients that send a query and update in the same transaction, a deadlock is possible. Remote Data Service is built to allow one of the processes to timeout to release the deadlock, but this will fail the update for that client.

You can add a registry entry on the Web server to modify the length of the timeout. The default is 30 seconds (or 30,000 milliseconds).

To modify the timeout value

  1. From the Start menu, click Run.

  2. Type RegEdit and click OK.

  3. In the Registry Editor, navigate to the HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\W3SVC\Parameters key.

  4. Select the Parameters key, and then from the Edit menu, point to New, and select DWORD Value.

  5. In the Name column, type ADCUpdateTimeout and press ENTER.

  6. Double-click the new entry. In the Edit DWORD Value dialog box, enter the new value in milliseconds in the Value data box. The value must be greater than or equal to zero.

RDS.DataControl and Multiple Recordset Requests

If you query for multiple results, only the first Recordset is returned. If multiple result sets are needed, assign each to its own RDS.DataControl. An example of a query for multiple results could be "Select * from Authors Select * from Topics".

What's the difference between ADOR.Recordset and ADODB.Recordset?

Remote Data Service applications use ADOR.Recordset objects on the client side. This makes it possible to access OLE DB data sources with Visual Basic and VBScript code (rather than C), and get data to the client. If ADODB.Recordset is already registered on the client, it will use the full-featured ADODB.Recordset instead of ADOR.Recordset.

Active Data Objects (ADO) can exist in both the client and middle tiers, but the ADOR.Recordset objects that Remote Data Service uses on the client side are leaner, and implement only the Recordset semantics. The ADO layer on the middle tier uses ADODB.Recordset objects and implements the Connection object and all other ADO semantics.

See Also For more information about ADOR vs. ADODB, see ADOR.Recordset vs. ADODB.Recordset Object.

Using ADO in Custom Business Objects

If you used Visual Basic to create a custom business object that uses early binding with the ADOR 1.0 type library, you should rebuild your custom business object to use the ADOR 1.5 type library.

SQL Server — Ensuring Sufficient TempDB Space

If errors occur while handling Recordset objects that need processing space on SQL Server, you may need to increase the size of the TempDB. (Some queries require temporary processing space; for example, a query with an ORDER BY clause requires a sort of the Recordset, which requires some temporary space.)

Important Read through this procedure first before performing the actions because it isn't as easy to shrink a device once it is expanded.

To increase the TempDB space on SQL Server

  1. Start Microsoft® SQL Server Enterprise Manager, open the tree for the Server, and then open the Database Devices tree.

  2. Select a (physical) device to expand, such as Master, and double-click the device to open the Edit Database Device dialog box.

    This dialog shows how much space the current databases are using.

  3. In the Size scroll box, increase the device to the desired amount. For example, 50 megabytes (MB) of hard disk space.

  4. Click Change Now to increase the amount of space to which the (logical) TempDB can expand.

  5. Open the Databases tree on the server, and then double-click TempDB to open the Edit Database dialog box. The Database tab lists the amount of space currently allocated to TempDB (Data Size). By default, this is 2 MB.

  6. Under the Size group, click Expand. The graphs show the available and allocated space on each of the physical devices. The bars in maroon color represent available space.

  7. Select a Log Device, such as Master to display the available size in the Size (MB) box.

  8. Click Expand Now to allocate that space to the TempDB database.

    The Edit Database dialog displays the new allocated size for TempDB.

See Also For more information about this topic, search the Microsoft SQL Server Enterprise Manager Help file for "Expand Database dialog box."

SQL Server — Minimizing Log File Space Usage

A log file may fill quickly (thus halting the server) if there is large volume activity on a SQL Server database. You can set the Log file to Truncate on Checkpoint to significantly extend the life of the log file for a database.

To enable Truncate on Checkpoint

  1. Run Microsoft SQL Server Enterprise Manager.

  2. Open the tree for the Server.

  3. Open the Databases tree.

  4. Double-click the name of the database on which this feature will be enabled.

  5. On the Database tab, click Truncate.

  6. On the Options tab, check Truncate Log on Checkpoint, and then click OK.

See Also For more information about the Truncate on Checkpoint feature, see the Microsoft SQL Server documentation.

Outdated Class IDs

If you get an error that an RDS.DataSpace or RDS.DataControl object doesn't load, make sure you are using the correct class ID. The class IDs for these objects have changed from version 1.0 and 1.1. The correct class IDs are listed as follows:
Object | Class ID
RDS.DataControl | BD96C556-65A3-11D0-983A-00C04FC29E33
RDS.DataSpace | BD96C556-65A3-11D0-983A-00C04FC29E36


Detailed Control Flow

Microsoft Remote Data Service Microsoft Remote Data Service *

Appendix B: Detailed Control Flow

This section contains a control flow description of the programming events that occur when the Remote Data Service processes a user event.

The following illustration shows the detailed control flow of a simple RDS application that uses the default RDSServer.DataFactory business object. The numbered labels correspond to processes in the control flow and are described as follows.

  1. The user enters query text in a visual control. That query text will eventually be sent to the Web server for processing.

  2. When a user event occurs on the Web page (such as an OnClick event on a Search button), the RDS creates a business object proxy on the client. If you use the default business object, RDSServer.DataFactory, you will get a generic proxy for the RDSServer.DataFactory object.

  3. The business object proxy translates the request into an HTTP sendable format. The parameters to the method are passed across the Internet via HTTP to the Web server (Internet Information Server, or IIS) specified in the RDS.DataControl object's Server property. IIS then passes the HTTP request to a server extension called the Advanced Data Internet Server API (ADISAPI).

  4. ADISAPI examines the contents of the call. It creates an instance of the business object and makes the requested method call. (If you use the RDSServer.DataFactory object, it calls the Query method.)

    The remaining steps describe the process flow when the Query method of the RDSServer.DataFactory object is called. A similar process happens when methods on a custom business object are called.

  5. The RDSServer.DataFactory object executes the user's query via OLE DB (and ODBC) by passing in the SQL statement and DSN information. It sets the properties for the requested rowset so that OLE DB uses the Client Cursor Engine as its buffering component.

  6. OLE DB passes the rowset containing the results of the query to the Client Cursor Engine. The Client Cursor Engine populates its buffers with the rowset data and stores all of the meta data information for all base tables that are part of the result set. It also implements the marshaling interfaces for the rowset.

  7. The Client Cursor Engine passes the marshalable rowset back to the RDSServer.DataFactory object.

  8. The RDSServer.DataFactory object creates an instance of an ADO Recordset and passes it the Client Cursor Engine marshalable rowset. ADO wraps the rowset into a Recordset, which is then returned as the return value of the original Query method call from Step 4.

  9. The RDSServer.DataFactory passes the Recordset back to ADISAPI, which packages the return value of the Recordset into MIME format by calling the Client Cursor Engine.

  10. ADISAPI sends the Recordset over HTTP as multi-part MIME packets to the business object proxy on the client side.

  11. The client-side business object proxy unpacks the results of the method call from HTTP format, and recreates the Recordset in the client-side Client Cursor Engine.

  12. The RDS.DataControl object binds the data in the Client Cursor Engine to the visual controls.

After the preceding steps have taken place, the user now has access to the Recordset object, representing the results of the query (displayed through the visual controls). He or she can perform tasks such as examining the record data, making changes, inserting new records, or deleting existing records.

When the user makes an update request, only the changed records are sent back via a process similar to that described previously. When an attempt is made to save the updated data, either all the changes will be written back to the data source, or, if any individual change cannot be saved, none of the changes will be saved.

For a custom business object, one difference to the steps outlined previously is that an RDS.DataSpace.CreateObject method is called on the client page to instantiate the business object proxy (Step 2). Also, if you write your business object in Visual Basic or Java, it cannot communicate directly with OLE DB, so the business object sends a request to ADO, which then sends the request to OLE DB (Steps 5 and 6). Business objects created with Visual C++ can access OLE DB directly.


Microsoft Remote Data Service

Microsoft Remote Data Service Microsoft Remote Data Service *

Welcome to Microsoft Remote Data Service

Remote Data Service is a high-performance Web-based technology that brings database connectivity and corporate data publishing capabilities to Internet and intranet applications.

This documentation contains the following sections:

What's New in Remote Data Service 1.5

Getting Started

Tutorials

Developer's Guide

API Reference

Remote Data Service Glossary


Getting Started with Remote Data Service

Remote Data Service brings high-performance database connectivity to Web-based applications.

You can use Remote Data Service to build intelligent multi-user Web and LAN-based applications that let users access and update data from any OLE DB Provider, including ODBC-compliant database management systems (DBMS). Because you can implement Remote Data Service with familiar technology — off-the-shelf visual controls, HTML, and Microsoft® Visual Basic® Scripting Edition (VBScript) — Remote Data Service integrates seamlessly with existing Visual Basic applications, letting you transport them to the Web.

Getting Started contains the following sections:

Setting Up Remote Data Service

Other Remote Data Service Configuration Information

Getting Assistance While You Work

Introduction to Remote Data Service

Sample and Demo Applications for Remote Data Service


Setting Up Remote Data Service (Getting Started)

Microsoft Remote Data Service Microsoft Remote Data Service *

Setting Up Remote Data Service

To properly install Remote Data Service, you should read the information in the following sections:

  • Before You Run Setup

    Hardware Requirements

    Software Requirements

  • Installing Remote Data Service

    Installing Remote Data Service Server Components on Your Web Servers

    Installing Remote Data Service Client Components on Your Client Computers

  • Validating Setup

Before You Run Setup

Before you install Remote Data Service, make sure that your client and server computers meet the minimum hardware and software requirements.

For the latest information on supported platforms and hardware and software requirements, see the Readme.txt file.

Hardware Requirements

To install Remote Data Service, you must meet certain hardware requirements, which include:

  • Any Windows NT® x86-compatible or Alpha computer.

  • A hard disk with a minimum of 8 megabytes (MB) available space for a full installation.

  • Any display supported by Windows NT version 4.0.

  • A minimum of 12 MB of RAM for client computers.

  • A minimum of 24 MB of RAM for server computers (32 MB of RAM recommended).

Software Requirements

Before you install Remote Data Service on a server computer, your server computer must meet the following software requirements:

  • Microsoft Windows NT Server version 4.0 Service Pack (SP) 3 or later. Remote Data Service currently supports the x86/Intel and Alpha platforms.

  • Microsoft Internet Information Server (IIS) 3.0 or later, including Microsoft Active Server Pages.

  • Microsoft SQL Server 6.5 with Service Pack 2 or later (or other ODBC Level 2 compliant data source).

To access Remote Data Service applications from client computers, client computers must meet the following software requirements:

  • Any of the following platforms: Windows® 95, Windows NT Workstation 4.0 or later, or Windows NT Server 4.0 SP 3 or later.

  • Microsoft Internet Explorer version 3.0, 4.0 or later.

Note Remote Data Service hasn't been tested with the Netscape browser technology.

To build client Web pages, you can use typical HTML authoring tools, such as Notepad or the more fully featured Microsoft ActiveX™ Control Pad.

To program server-side business objects, you can use any ActiveX/COM -compatible development tool, such as Microsoft Visual Basic® 5.0 or Microsoft Visual C++®.

Installing Remote Data Service

For Remote Data Service to work correctly, you should ensure that the Remote Data Service server and client components are installed correctly on server and client computers, respectively.

Installing Remote Data Service Server Components on Your Web Servers

Remote Data Service 1.5 is installed automatically, along with the rest of the Microsoft Data Access Components, when you install Microsoft Internet Information Server 4.0 using either the "Typical" or "Minimum" installation options.

You may want to install Remote Data Service by itself on a version 3.0 Internet Information Service, as an upgrade to Advanced Data Connector version 1.x. To do so, follow these steps. This setup procedure assumes that your computer meets all of the software requirements.

Important Before you install Remote Data Service 1.5, you should uninstall previous versions of Remote Data Service (formerly called Advanced Data Connector) on your computer. You can do this by using the Add/Remove Programs applet in Control Panel.

To install Remote Data Service server components

  1. From your Web server computer, connect to the Remote Data Service World Wide Web site at http://www.microsoft.com/adc/.

  2. Click the Download button, and scroll down to Download Files and Sites.

  3. Click the appropriate Server and Help Files (msadc15.exe for the Windows NT 4.0 paltform, msadc15a.exe for the Alpha platform, or msadc1595.exe for the Windows 95 platform) to install the software, documentation, and core samples. This web site also gives you the option of installing RDS version 1.1, which maintains backward compatibility with Internet Explorer version 3.0.

  4. Follow the Setup instructions on the screen.

The Setup program installs the program files to the <device>:\Program Files\Common Files\System\MSADC directory. (This location is adjacent to other complementary Microsoft technologies such as ActiveX Data Objects and OLE DB.) The following subdirectories are created under the \MSADC directory with the setup program.
Subdirectory | Description
..\MSADC\Docs | Contains the documentation.
..\MSADC\Samples | Contains the sample files.

The server installation program also creates a Microsoft Internet Information Server virtual root on your Web server computer. The root is designated //<servername>/msadc and you can run files from there on a client browser. If for some reason this root is deleted or is otherwise non-existent, either reinstall or manually re-create this root.

Once you have run the setup program on your Web server computer, you can validate your installation.

Installing Remote Data Service Client Components on Your Client Computers

Microsoft Internet Explorer 4.0 already includes the necessary Remote Data Service client components. Therefore, you don't need to include a .cab file on your Web page because client computers will already have the Remote Data Service client component DLLs. See the Microsoft Data Access Components README for a complete list of component files.

To manually download client-side files for use with Microsoft Internet Explorer 3.0, see the Remote Data Service web page at http://www.microsoft.com/adc/.

Validating Setup

You can use the ADCTest.asp sample application to validate your Remote Data Service installation.

To validate setup with ADCTest

  1. Start Internet Explorer, and enter the following address:

    http://servername/MSADC/Samples/adctest.asp

    where servername is the name of your Web server.

    This should display the Remote Data Service Query Page. You'll notice that the server, connection, and query information is already provided for you.

  2. Click the Run! button to execute the query.

    If the grid displays a result set, your installation is correct.

If you run into any problems, review the setup instructions and see "Troubleshooting Remote Data Service" and "Other Remote Data Service Configuration Information."


Other Remote Data Service Configuration Information

After you install Remote Data Service, you may need to configure some other system settings. When the data source is on a computer that is different from the application Web server, the Web server computer needs to have guest privileges on the data source computer if it is running Windows NT®.

To grant guest privileges to a Web server computer

  1. On the Windows NT® data source computer, click Start, point to Programs, and click Administrative Tools.

  2. Run User Manager for Domains.

  3. On the User menu, click Select Domain. Enter the current computer name, and click OK.

  4. In the lower window, double-click the Guests group and click Add to add the computer name account, which by default would be IUSR_MYWEBSVR (where MYWEBSVR is the name of your Web server).


Getting Assistance While You Work (Remote Data Service)

You can get assistance while you work by:

  • Consulting the documentation.

  • Contacting Microsoft® Technical Support.

  • Visiting the Remote Data Service home page on the World Wide Web.

  • Joining the Remote Data Service public newsgroup.

  • Exploring the Microsoft Knowledge Base.

Consulting the Documentation

The Remote Data Service documentation includes the following pieces.
Piece | Description
Getting Started | Explains how to install Remote Data Service and gives a brief tour of the product and documentation.
Tutorials | Show how to build simple, data-aware Web applications.
Developer's Guide | Discusses Remote Data Service technology in greater detail. It describes the architectural underpinnings, components, and data flow mechanisms, and how to customize the RDS server-side components.
API Reference | Provides reference topics for all of the Remote Data Service objects, methods, and properties, including syntax, quick reference information, and code examples.
Sample applications | Demonstrates how to use Remote Data Service to build intranet and Internet applications.
Readme.txt | Explains how to install the Remote Data Service client and server components and specifies the hardware and software requirements. It also provides late-breaking product information not included in the core documentation, and lists known problems.

Contacting Microsoft Technical Support

For technical support on Remote Data Service, the following options are available.

In the United States and Canada, Microsoft Technical Support provides Pay-Per-Incident, call back only support for the Remote Data Service.

  • Call (800) 936-5800; $95 (U.S.) per incident, billed to your VISA card, MasterCard, or American Express card.

  • Call (900) 555-2300; $95 (U.S.) per incident. Charges appear on your telephone bill.

Visiting the Remote Data Service Web Site

You can visit the Remote Data Service home page on the World Wide Web for documentation updates and information about other related technologies. The address is http://www.microsoft.com/adc/.

Joining the Remote Data Service Public Newsgroup

To facilitate discussion, information sharing, and tips trading, Microsoft has set up a public newsgroup: microsoft.public.adc. You are welcome to post articles and messages to this unmoderated, unsupported newsgroup. Microsoft doesn't guarantee responses or direct support. For more information, visit the Remote Data Service Web site, http://www.microsoft.com/adc/.

Exploring the Microsoft Knowledge Base

You can consult the Microsoft Knowledge Base to access a comprehensive collection of more than 70,000 detailed articles with technical information about Microsoft products, bug and fix lists, and answers to commonly asked technical questions.

To get information about Remote Data Service and Internet Information Server

  1. Go to the http://www.microsoft.com/ home page, and click the Support icon.

  2. Click Microsoft Technical Support, and then click Knowledge Base.

  3. Choose the Internet Information Server product, and enter a search phrase, such as "Remote Data Service."


Introduction to Remote Data Service

Remote Data Service brings database connectivity and corporate data publishing capabilities to Internet and intranet applications. With Remote Data Service, you can:

  • Bind data-aware controls to data from remote servers.

  • View, edit, and update live data from a Web application. (For more information about updatability, click here.)

  • Take advantage of a transparent, client-side caching architecture. This boosts performance by retrieving large result sets in binary formats and caching data on the client system, avoiding expensive data refetching and resulting in fewer roundtrips. Such performance improvements are especially noticeable for data access across the Internet.

  • Use familiar technology to implement Remote Data Service. Because you implement Remote Data Service with familiar technology — off-the-shelf visual controls, HTML, and Microsoft® Visual Basic® Scripting Edition (VBScript) — Remote Data Service integrates seamlessly with existing Visual Basic applications, letting you transport them to the Web.

  • Partition your application into three tiers. You can use familiar languages such as Visual Basic, Visual C++®, and VBScript to build business logic into encapsulated objects. These middle-tier business objects can receive requests from front-end clients and Web applications and communicate with back-end database components such as Microsoft SQL Server through Open Database Connectivity (ODBC).

  • Use Microsoft ODBC and OLE DB technology. Remote Data Service uses these technologies to handle all data similarly on the client side, regardless of its source. This eliminates the need to use targeted client-side drivers for each data source. This also means you can easily modify Remote Data Service applications to suit different network and DBMS configurations.

  • Ensure secure access to corporate data via Secured Socket Layer (SSL). (This is an optional feature to use with Remote Data Service.)

In addition, you can use Remote Data Service with other Microsoft technologies, including Internet Information Server (IIS) 3.0 and 4.0 and Microsoft Transaction Server.

See Also For more information about how Remote Data Service applications work, see "Understanding Remote Data Service Applications."


Sample and Demo Applications

Microsoft® Remote Data Service includes useful sample and demo applications that are valuable learning tools. Throughout the documentation, you'll find sample code and applications that illustrate programming techniques. You can copy any part of them into your own applications and modify them as necessary.

Remote Data Service provides the following sample applications that demonstrate how to use this technology to build intranet and Internet applications. These are provided in .ASP format for ease in running the samples (your host server name is automatically provided), but can easily be modified to run as HTML pages.

Sample application

Description

Address Book

A simple company directory application.

For detailed information about this application, see the Address Book Sample Application.

ADCTest

A simple .asp file that you can use to validate your Remote Data Service installation. See the Tutorials for information on how to create a simple application like this.

Query Builder

An application that shows you how to access the remote data sources available through the host Web server.

Selector

Shows how to implement various Remote Data Service application configurations on the client, middle, and data source tiers. You will see how to use a VBScript Web page or Visual Basic client application on the client tier, the RDSServer.DataFactory or custom business object on the middle tier, or a Microsoft SQL Server or Microsoft Access database on the data source tier.

Note Companies, names, and data used in examples are fictitious unless otherwise noted.

Modifying the Samples to Run in HTML format

To modify the samples to run as HTML pages perform the following steps:

  1. Open the .ASP file in a text editor, such as Notepad.
  2. Search for the following string:
    <%=Request.ServerVariables("SERVER_NAME")%>
  3. Replace it with the name of your Web server.
  4. Save the file with an .HTM extension.


Remote Data Service Objects

This API reference documents the following objects (and their properties and methods) that you use with Remote Data Service:

  • RDS.DataControl

  • RDSServer.DataFactory

  • RDS.DataSpace

It also includes appendixes that provide detailed technical information for advanced users.

See Also

Getting Stated with Remote Data Service, Remote Data Service Developer's Guide

Note This reference doesn't contain information about all of the ADO semantics. For detailed information about ADO Objects, see the Microsoft ActiveX Data Objects documentation.


DataControl Object (API Reference)

Microsoft Remote Data Service Microsoft Remote Data Service *

RDS.DataControl Object

The RDS.DataControl object binds a data query Recordset to one or more controls (for example, a text box, grid control, or combo box) to display the ADOR.Recordset data on a Web page.

Syntax

<OBJECT CLASSID="clsid:BD96C556-65A3-11D0-983A-00C04FC29E33" ID="DataControl"

<PARAM NAME="Connect" VALUE="DSN=DSNName; UID=usr;PWD=pw;">

<PARAM NAME="Server" VALUE="http://awebsrvr">

<PARAM NAME="SQL" VALUE="QueryText">

</OBJECT>

Methods

Cancel, CancelUpdate, CreateRecordset, MoveFirst, MoveLast, MoveNext, MovePrevious, Refresh, Reset, SubmitChanges

Properties

Connect, ExecuteOptions, FetchOptions, FilterColumn, FilterCriterion, FilterValue, ReadyState, Recordset, Server, SQL, SortColumn, SortDirection, SourceRecordset

Remarks

The class ID for the RDS.DataControl object is BD96C556-65A3-11D0-983A-00C04FC29E33.

For a basic scenario, you only need to set the SQL, Connect, and Server properties of the RDS.DataControl object, which will automatically call the default business object, RDSServer.DataFactory.

All the properties in the RDS.DataControl are optional because custom business objects can replace their functionality.

Use one RDS.DataControl object to link the results of a single query to one or more visual controls. For example, suppose you code a query that requests customer data such as Name, Residence, Place of Birth, Age, and Priority Customer Status. You can use a single RDS.DataControl object to display a customer's Name, Age, and Region in three separate text boxes, Priority Customer Status in a check box, and all the data in a grid control.

Use different RDS.DataControl objects to link the results of multiple queries to different visual controls. For example, suppose you use one query to obtain information about a customer, and a second query to obtain information about merchandise the customer has purchased. You want to display the results of the first query in three text boxes and one check box, and the results of the second query in a grid control. If you use the default business object (RDSServer.DataFactory object), you need to do the following:

  • Add two RDS.DataControl objects to your Web page.

  • Write two queries, one for each SQL property of the two RDS.DataControl objects. One RDS.DataControl object will contain a SQL query requesting customer information, the second will contain a query requesting a list of merchandise the customer has purchased.

  • In each of the bound control's OBJECT tags, specify the DATAFLD value to set the values for the data you want to display in each visual control.

There is no count restriction on the number of RDS.DataControl objects that you can embed via OBJECT tags on a single Web page.

When you define the RDS.DataControl object on a Web page, use non-zero Height and Width values such as 1 (to avoid the inclusion of extra space).

Remote Data Service 1.5 client components are already included as part of the Internet Explorer 4.0 installation, therefore you don't need to include a CODEBASE parameter in your RDS.DataControl object tag.

Microsoft Visual Basic Users The RDS.DataControl is only used in Web-based applications. A Visual Basic client application has no need for it.

Example

See Also

Client-Side Data Cache, Client Tier, Developing Remote Data Service Applications, Displaying Data Through a Bound Control


Connect Property

Sets or returns the database name from which the query and update operations are run.

You can set the Connect property at design time in the RDS.DataControl object's OBJECT tags, or at run time in scripting code (for instance, VBScript).

Syntax
Syntax
Design time | <PARAM NAME="Connect" VALUE="DSN=DSNName;UID=usr;PWD=pw;">
Run time | DataControl.Connect = "DSN=DSNName;UID=usr;PWD=pw;"

Part | Description
DSNName | A String that specifies the system data source name that identifies a specific database.
usr | A String that represents a valid user account on the server.
pw | A String that represents a valid password for the user account.
DataControl | An object variable that represents an RDS.DataControl object.

Applies To

RDS.DataControl

Example

See Also

Getting a Recordset to the Client, Query Method, Refresh Method, SubmitChanges Method, Using RDS.DataControl to Pass Updated Disconnected Recordset Objects Back to the Middle Tier


ExecuteOptions Property

Indicates whether or not asynchronous execution is enabled.

Settings

The ExecuteOptions property can be either of the following values.
Value | Description
adcExecSync | Executes the next refresh of the Recordset synchronously.
adcExecAsync | Default. Executes the next refresh of the Recordset asynchronously.

Note Each client-side executable file that uses these constants must provide declarations for them. You can cut and paste the constant declarations you want from the file adcvbs.inc, located in the C:\Program Files\Common Files\System\MSADC folder.

Applies To

RDS.DataControl

Remarks

If ExecuteOptions is set to adExecAsync, then this asynchronously executes the next Refresh call on the RDS.DataControl object’s Recordset.

If you try to call Reset, Refresh, SubmitChanges, CancelUpdate, or Recordset while another asynchronous operation is executing that might change the RDS.DataControl object's Recordset, an error occurs.

If an error occurs during an asynchronous operation, the RDS.DataControl object’s ReadyState value changes from adcReadyStateLoaded to adcReadyStateComplete, and the Recordset property value remains Nothing.

Example

See Also

Asynchronous Population, Cancel Method


FetchOptions Property

Sets or returns the type of asynchronous fetching.

Settings

The FetchOptions property can be any of the following values.
Value | Description
adcFetchUpFront | All the records of the Recordset are fetched before control is returned to the application. The complete Recordset is fetched before the application is allowed to do anything with it.
adcFetchBackground | Control can return to the application as soon as the first batch of records has been fetched. A subsequent read of the Recordset that attempts to access a record not fetched in the first batch will be delayed until the sought record is actually fetched, at which time control returns to the application.
adcFetchAsync | Default. Control returns immediately to the application while records are fetched in the background. If the application attempts to read a record that hasn't yet been fetched, the record closest to the sought record will be read and control will return immediately, indicating that the current end of the Recordset has been reached. For example, a call to MoveLast will move the current record position to the last record actually fetched, even though more records will continue to populate the Recordset.

Note Each client-side executable file that uses these constants must provide declarations for them. You can cut and paste the constant declarations you want from the file adcvbs.inc, located in the C:\Program Files\Common Files\System\MSADC folder.

Applies To

RDS.DataControl

Remarks

In a web application, you will usually want to use adcFetchAsync (the default value), because it provides better performance. In a compiled client application, you will usually want to use adcFetchBackground.

Example

See Also

Asynchronous Population, Cancel Method


FilterColumn Property

Sets or returns which column to evaluate the filter criteria on.

Syntax

DataControl.FilterColumn = String
Part | Description
DataControl | An object variable that represents an RDS.DataControl object.
String | A String value specifying the column to evaluate the filter criteria on. The filter criteria is specified in the FilterCriterion property.

Applies To

RDS.DataControl

Remarks

The SortColumn, SortDirection, FilterValue, FilterCriterion, and FilterColumn properties provide sorting and filtering functionality on the client-side cache. The sorting functionality orders records by values from one column. The filtering functionality displays a subset of records based on a find criteria, while the full recordset is maintained in the cache. The Reset method will execute the criteria and replace the current recordset with a read-only recordset.

Example

See Also

Sorting and Filtering


FilterCriterion Property

Sets or returns which evaluation operator to use in the filter value.

Syntax

DataControl.FilterCriterion = String
Part | Description
DataControl | An object variable that represents an RDS.DataControl object.
String | A String value that specifies the evaluation operator of the FilterValue to the records. Can be any one of the following: <, <=, >, >=, =, <>.

Applies To

RDS.DataControl

Remarks

The SortColumn, SortDirection, FilterValue, FilterCriterion, and FilterColumn properties provide sorting and filtering functionality on the client-side cache. The sorting functionality orders records by values from one column. The filtering functionality displays a subset of records based on a find criteria, while the full recordset is maintained in the cache. The Reset method will execute the criteria and replace the current recordset with a read-only recordset.

The != operator is invalid for FilterCriterion; instead, use <>.

If both the filter and sort properties are set and you call the Reset method, the rowset is first filtered and then it is sorted. For ascending sorts, the NULLs are at the top, descending sorts NULLs are at the bottom (ascending is default behavior).

Example

See Also

Sorting and Filtering


FilterValue Property

Sets or returns which value to filter records with.

Syntax

DataControl.FilterValue = String
Part | Description
DataControl | An object variable that represents an RDS.DataControl object.
String | A String value that represents a data value to filter records with (for example, 'Programmer' or 125).

Applies To

RDS.DataControl

Remarks

The SortColumn, SortDirection, FilterValue, FilterCriterion, and FilterColumn properties provide sorting and filtering functionality on the client-side cache. The sorting functionality orders records by values from one column. The filtering functionality displays a subset of records based on a find criteria, while the full recordset is maintained in the cache. The Reset method will execute the criteria and replace the current recordset with a read-only recordset.

Example

See Also

Sorting and Filtering


Recordset, SourceRecordset Properties

The SourceRecordset and Recordset properties of the RDS.DataControl indicate the ADOR.Recordset object that is returned from a custom business object.

You can set the SourceRecordset property or read the Recordset property at run time in scripting code (for instance, VBScript).

Syntax

DataControl.SourceRecordset = Recordset

DataControl.Recordset
Part | Description
DataControl | An object variable that represents an RDS.DataControl object.
Recordset | An object variable that represents an ADOR.Recordset object.

Applies To

RDS.DataControl

Remarks

SourceRecordset is a write-only property, in contrast to the Recordset property, which is a read-only property.

You can set the SourceRecordset property to a Recordset returned from a custom business object.

These properties allow an application to handle the binding process by means of a custom process. They receive a rowset wrapped in a Recordset so that you can interact directly with the Recordset, performing actions such as setting properties or iterating through the Recordset.

Example

See Also

Defining a Recordset, Query Method, CreateRecordset Method, Getting a Recordset with the RDS.DataControl Object, Getting a Recordset to the Client


Server Property

Sets or returns the Internet Information Server (IIS) name and communication protocol.

You can set the Server property at design time in the RDS.DataControl object's OBJECT tags, or at run time in scripting code (for example, VBScript).

Syntax
Protocol | Design-time syntax
HTTP | <PARAM NAME="Server" VALUE="http://awebsrvr:port">
HTTPS | <PARAM NAME="Server" VALUE="https://awebsrvr:port">
DCOM | <PARAM NAME="Server" VALUE="machinename">
In-process | <PARAM NAME="Server" VALUE="">

Protocol | Run-time syntax
HTTP | DataControl.Server="https://awebsrvr:port"
HTTPS | DataControl.Server="https://awebsrvr:port"
DCOM | DataControl.Server="machinename"
In-process | DataControl.Server=""

Part | Description
awebsrvr or machinename | A String that contains a valid Internet or intranet path and server name.
port | Optional. A port that is used to connect to an IIS server. The port number is set in Internet Explorer (on the View menu, click Options, and then select the Connection tab) or in IIS.
DataControl | An object variable that represents an RDS.DataControl object.

Applies To

RDS.DataControl

Remarks

The server location is where the server-side objects are created (as opposed to where the data is located, if they differ).

Example

See Also

Connect Property, SQL Property, SubmitChanges Method, Transport Protocols


SortColumn Property

Sets or returns which column to sort the records by.

Syntax

DataControl.SortColumn = String
Part | Description
DataControl | An object variable that represents an RDS.DataControl object.
String | A String value that represents the name or alias of the column to sort the records by.

Applies To

RDS.DataControl

Remarks

The SortColumn, SortDirection, FilterValue, FilterCriterion, and FilterColumn properties provide sorting and filtering functionality on the client-side cache. The sorting functionality orders records by values from one column. The filtering functionality displays a subset of records based on a find criteria, while the full recordset is maintained in the cache. The Reset method will execute the criteria and replace the current recordset with a read-only recordset.

To sort on a Recordset, you must first save any pending changes. If you are using the RDS.DataControl, you can use the SubmitChanges method. For example, if your RDS.DataControl is named ADC1, your code would be ADC1.SubmitChanges. If you are using an ADO Recordset, you can use its UpdateBatch method. Using UpdateBatch is the recommended method for Recordset objects created with the CreateRecordset method. For example, your code could be myRS.UpdateBatch or ADC1.Recordset.UpdateBatch.

Example

See Also

Sorting and Filtering


SortDirection Property

Sets or returns a Boolean value that indicates if a sort order is ascending or descending.

Syntax

DataControl.SortDirection = value
Part | Description
DataControl | An object variable that represents an RDS.DataControl object.
value A Boolean value that can set or return one of the following values:
  • True — Ascending order

  • False — Descending order

Applies To

RDS.DataControl

Remarks

The SortColumn, SortDirection, FilterValue, FilterCriterion, and FilterColumn properties provide sorting and filtering functionality on the client-side cache. The sorting functionality orders records by values from one column. The filtering functionality displays a subset of records based on a find criteria, while the full recordset is maintained in the cache. The Reset method will execute the criteria and replace the current recordset with a read-only recordset.

Example

See Also

Sorting and Filtering


SQL Property

Sets or returns the query string used to retrieve the Recordset.

You can set the SQL property at design time in the RDS.DataControl object's OBJECT tags, or at run time in scripting code (for instance, VBScript).

Syntax
Syntax
Design time | <PARAM NAME="SQL" VALUE="QueryString">
Run time | DataControl.SQL = "QueryString"

Part | Description
QueryString | A String containing a valid SQL data request.
DataControl | An object variable that represents an RDS.DataControl object.

Applies To

RDS.DataControl

Remarks

In general, this is an SQL statement (using the dialect of the database server), such as "Select * from NewTitles". To ensure that records are matched and updated accurately, an updatable query must contain a field other than a Long Binary field or a computed field.

The SQL property is optional if a custom server-side business object retrieves the data for the client.

Example

See Also

Connect Property, Query Method, Refresh Method, SubmitChanges Method


ReadyState Property

Returns the state of the RDS.DataControl object's Recordset.

Settings

The ReadyState property can have one of the following values.
Value | Description
adcReadyStateLoaded | The RDS.DataControl object's Recordset is open but no data has been retrieved.
adcReadyStateInteractive | The RDS.DataControl object's Recordset is still retrieving data.
adcReadyStateComplete | The RDS.DataControl object's Recordset has completed retrieving data.

Note Each client-side executable file that uses these constants must provide declarations for them. You can cut and paste the constant declarations you want from the file adcvbs.inc, located in the C:\Program Files\Common Files\System\MSADC folder.

Applies To

RDS.DataControl

Remarks

If an error occurs during an asynchronous operation, the ReadyState value changes from adStateExecuting to adStateClosed, and the Recordset property value remains Nothing.

Example

See Also

Asynchronous Population, Cancel Method, ExecuteOptions Property


Cancel Method

Cancels the currently running asynchronous execution or fetch.

Syntax

DataControl.Cancel

Applies To

RDS.DataControl

Remarks

When you call Cancel, ReadyState is automatically set to adcReadyStateLoaded, and the Recordset will be empty.

Example

See Also

Asynchronous Population, CancelUpdate Method, ExecuteOptions Property


CancelUpdate Method

Discards all the pending changes associated with the specified Recordset object, thus restoring the values since the last Refresh method call.

Syntax

DataControl.CancelUpdate
Part | Description
DataControl | An object variable that represents an RDS.DataControl object.

Applies To

RDS.DataControl

Remarks

The Client Cursor Engine keeps both a copy of the original values and a cache of changes. When you call CancelUpdate, the cache of changes is reset to empty, and the bound controls are refreshed with the original data.

Example

See Also

Address Book Command Buttons, Cancel Method, Refresh Method, SubmitChanges Method, Using RDS.DataControl to Pass Updated Disconnected Recordset Objects Back to the Middle Tier


MoveFirst, MoveLast, MoveNext, MovePrevious Methods (DataControl)

Microsoft Remote Data Service Microsoft Remote Data Service *

MoveFirst, MoveLast, MoveNext, MovePrevious Methods

Moves to the first, last, next, or previous record in a displayed Recordset.

Syntax

DataControl.Recordset.{MoveFirst | MoveLast | MoveNext | MovePrevious}
Part | Description
DataControl | An object variable that represents an RDS.DataControl object.

Applies To

RDS.DataControl

Remarks

You can use the Move methods with the RDS.DataControl object to navigate through the data records in the data-bound controls on a Web page. For example, suppose you display a Recordset in a grid by binding to an RDS.DataControl object. You can then include First, Last, Next, and Previous buttons that users can click to move to the first, last, next, or last record in the displayed Recordset. You do this by calling the MoveFirst, MoveLast, MoveNext, and MovePrevious methods of the RDS.DataControl object in the onClick procedures for the First, Last, Next, and Previous buttons, respectively. The Address Book example shows how to do this.

Example

See Also

Navigating Through Recordset Objectss


Refresh Method

Requeries the ODBC data source specified in the Connect property and updates the query results.

Syntax

DataControl.Refresh
Part | Description
DataControl | An object variable that represents an RDS.DataControl object.

Applies To

RDS.DataControl

Remarks

You must set the Connect, Server, and SQL properties before you use the Refresh method. All data-bound controls on the form associated with an RDS.DataControl object will reflect the new set of records. Any pre-existing Recordset object is released, and any unsaved changes are discarded. The Refresh method automatically makes the first record the current record.

It's a good idea to call the Refresh method periodically when you work with data. If you retrieve data, and then leave it on your client machine for a while, it is likely to become out of date. It's possible that any changes you make will fail, because someone else might have changed the record and submitted changes before you.

Example

See Also

CancelUpdate Method, SubmitChanges Method, Address Book Command Buttons, Using RDS.DataControl to Pass Updated Disconnected Recordset Objects Back to the Middle Tier


Reset Method

Executes the sort or filter on a client-side Recordset based on the specified sort and filter properties.

Syntax

DataControl.Reset(value)
Part | Description
DataControl | An object variable that represents an RDS.DataControl object.
value | Optional. A Boolean value that is True (default) if you want to filter on the current "filtered" rowset. False indicates that you filter on the original rowset, removing any previous filter options.

Applies To

RDS.DataControl

Remarks

The SortColumn, SortDirection, FilterValue, FilterCriterion, and FilterColumn properties provide sorting and filtering functionality on the client-side cache. The sorting functionality orders records by values from one column. The filtering functionality displays a subset of records based on a find criteria, while the full recordset is maintained in the cache. The Reset method will execute the criteria and replace the current recordset with a read-only recordset.

If there are changes to the original data which haven't yet been submitted, the Reset method will fail. First, use the SubmitChanges method to save any changes in a read/write Recordset, and then use the Reset method to sort or filter the records.

If you want to perform more than one filter on your rowset, you can use the optional Boolean argument with the Reset method. The following example shows how to do this:

ADC.SQL = "Select au_lname from authors"
ADC.Refresh		' Get the new rowset.

ADC.FilterColumn = "au_lname"
ADC.FilterCriterion = "<"
ADC.FilterValue = "'M'"
ADC.Reset			' Rowset now has all Last Names < "M".

ADC.FilterCriterion = ">"
ADC.FilterValue = "'F'"
' Passing True is not necessary, as it is the default
' filter on the current "filtered" rowset.
ADC.Reset(TRUE)		' Rowset now has all Last
                        ' Names < "M" and > "F".

ADC.FilterCriterion = ">"
ADC.FilterValue = "'T'"
' Filter on the original rowset, throwing out the
' previous filter options.
ADC.Reset(FALSE)	' Rowset now has all Last Names
                        ' > "T".

Example

See Also

Sorting and Filtering, SubmitChanges Method


SubmitChanges Method

Submits pending changes of the locally cached updatable Recordset to the ODBC data source specified in the Connect property.

Syntax

DataControl.SubmitChanges

DataFactory.SubmitChanges Connection, Recordset
Part | Description
DataControl | An object variable that represents an RDS.DataControl object.
DataFactory | An object variable that represents an RDSServer.DataFactory object.
Connection | A String value that represents the connection created with the RDS.DataControl object's Connect property.
Recordset | An object variable that represents a Recordset object.

Applies To

RDS.DataControl, RDSServer.DataFactory

Remarks

The Connect, Server, and SQL properties must be set before you can use the SubmitChanges method with the RDS.DataControl object.

If you call the CancelUpdate method after you have called SubmitChanges for the same Recordset object, the CancelUpdate call fails because the changes have already been committed.

Only the changed records are sent for modification, and either all of the changes succeed or all of them fail together.

You can use SubmitChanges only with the default RDSServer.DataFactory object. Custom business objects can't use this method.

Example

See Also

Refresh Method, CancelUpdate Method, Address Book Command Buttons, Using RDS.DataControl to Pass Updated Disconnected Recordset Objects Back to the Middle Tier, Tutorial: Building a Simple Remote Data Service Application


DataFactory Object (API Reference)

Microsoft Remote Data Service Microsoft Remote Data Service *

RDSServer.DataFactory Object

This default server-side business object implements methods that provide read/write data access to specified data sources for client-side applications.

Methods

ConvertToString, CreateRecordset, Query, SubmitChanges

Remarks

The RDSServer.DataFactory object is designed as a server-side Automation object that receives client requests. In an Internet implementation, it resides on a Web server and is instantiated by the ADISAPI component. The RDSServer.DataFactory object provides read and write access to specified data sources, but doesn't contain any validation or business rules logic.

If you use a method that is available in both the RDSServer.DataFactory and RDS.DataControl objects, Remote Data Service uses the RDS.DataControl version by default. The default assumes a basic programming scenario, where the RDSServer.DataFactory serves as a generic server-side business object.

If you want your Web application to handle task-specific server-side processing, you can replace the RDSServer.DataFactory with a custom business object.

You can create server-side business objects that call the RDSServer.DataFactory methods, such as Query and CreateRecordset. This is helpful if you want to add functionality to your business objects, but take advantage of existing Remote Data Service technologies.

The class ID for the RDSServer.DataFactory object is 9381D8F5-0288-11D0-9501-00AA00B911A5.

Example

See Also

Getting a Recordset to the Client, Business Object Proxies and the RDS.DataSpace object, Client Tier, Defining a Recordset , Middle Tier, RDSServer.DataFactory vs. Custom Business Objects, RDSServer.DataFactory Object (Three-Tiered Applications), Appendix B: Detailed Control Flow


ConvertToString Method

Converts a Recordset to a MIME string that represents the recordset data.

Syntax

DataFactory.ConvertToString(Recordset)
Part | Description
DataFactory | An object variable that represents an RDSServer.DataFactory object.
Recordset | An object variable that represents a Recordset object.

Applies To

RDSServer.DataFactory

Remarks

With .asp files, use ConvertToString to embed the Recordset on an HTML page generated on the server to transport it to a client computer.

ConvertToString first loads the Recordset into Client Cursor Engine tables, and then generates a stream in MIME format.

On the client, Remote Data Service can convert the MIME string back into a fully functioning Recordset. It works well for handling less than 400 rows of data with no more that 1024 bytes width per row. You shouldn't use it for streaming BLOB data and large result sets over HTTP. No wire compression is performed on the string, so very large data sets will take considerable time to transport over HTTP when compared to the wire-optimized tablegram format defined and deployed by Remote Data Service as its native transport protocol format.

Note If you are using Active Server Pages to embed the resulting MIME string in a client HTML page, note that versions of VBScript earlier than version 2.0 limit the string's size to 32K. If this limit is exceeded, an "Out of string space" error is returned. Keep the query scope relatively small when using MIME embedding via .asp files. To fix this, download the latest version of VBScript from http://www.microsoft.com/vbscript.

Example


Query Method

Uses a valid SQL query string to return a Recordset.

Syntax

Set Recordset = DataFactory.Query Connection, Query
Part | Description
Recordset | An object variable that represents a Recordset object.
DataFactory | An object variable that represents an RDSServer.DataFactory object.
Connection | A String containing the server connection information. This is similar to the Connect property.
Query | A String containing the SQL query.

Applies To

RDSServer.DataFactory

Remarks

The query should use the SQL dialect of the database server. A result status is returned if there is an error with the query that was executed. The Query method doesn't perform any syntax checking on the Query string.

Example

See Also

Getting a Recordset to the Client, Appendix B: Detailed Control Flow


CreateRecordset Method

Creates an empty, disconnected ADODB.Recordset.

Syntax

object.CreateRecordset(ColumnInfos)
Part | Description
object | An object variable that represents an RDSServer.DataFactory or RDS.DataControl object.
ColumnsInfos A Variant array of arrays defining each column in the Recordset being created. Each column definition contains an array of four required attributes:
  • Name — Name of the column header.

  • Type — Integer of data type.

  • Size — Integer of width in characters, regardless of data type.

  • Nullability — Boolean value.

The set of column arrays is then grouped into an array, which defines the Recordset.

Applies To

RDSServer.DataFactory, RDS.DataControl

Remarks

The server-side business object can populate the resulting ADODB.Recordset with data from a non-OLE DB data provider, such as an operating system file containing stock quotes.

To sort on a Recordset, any pending changes must first be saved. If you are using the RDS.DataControl, you can use the SubmitChanges method. For example, if your RDS.DataControl is named ADC1, your code would be ADC1.SubmitChanges. If you are using an ADO Recordset, you can use its UpdateBatch method. Using UpdateBatch is the recommended method for Recordset objects created with the CreateRecordset method. For example, your code could be myRS.UpdateBatch or ADC1.Recordset.UpdateBatch.

The following table lists the data types supported by the RDSServer.DataFactory object's CreateRecordset method. The number listed is the reference number used to define fields.

Each of the data types is either fixed length or variable length. Fixed length types should be defined with a size of –1, because the size is predetermined and a size definition is still required. Variable length data types allow a size from 1 to 32767.

For some of the variable data types, the type may be coerced to the type noted in the Substitution column. You won't see the substitutions until after the Recordset is created and filled. Then you can check for the actual data type, if necessary.
Length | Constant | Number | Substitution
Fixed | adTinyInt | 16
Fixed | adSmallInt | 2
Fixed | adInteger | 3
Fixed | adBigInt | 20
Fixed | adUnsignedTinyInt | 17
Fixed | adUnsignedSmallInt | 18
Fixed | adUnsignedInt | 19
Fixed | adUnsignedBigInt | 21
Fixed | adSingle | 4
Fixed | adDouble | 5
Fixed | adCurrency | 6
Fixed | adDecimal | 14
Fixed | adNumeric | 131
Fixed | adBoolean | 11
Fixed | adError | 10
Fixed | adGuid | 72
Fixed | adDate | 7
Fixed | adDBDate | 133
Fixed | adDBTime | 134
Fixed | adDBTimestamp | 135 | 7
Variable | adBSTR | 8 | 130
Variable | adChar | 129 | 200
Variable | adVarChar | 200
Variable | adLongVarChar | 201 | 200
Variable | adWChar | 130
Variable | adVarWChar | 202 | 130
Variable | adLongVarWChar | 203 | 130
Variable | adBinary | 128
Variable | adVarBinary | 204
Variable | adLongVarBinary | 205 | 204

Example

See Also

Defining a Recordset


DataSpace Object (API Reference)

Microsoft Remote Data Service Microsoft Remote Data Service *

RDS.DataSpace Object

The RDS.DataSpace object creates client-side proxies to custom business objects located on the middle tier.

Method

CreateObject

Remarks

Remote Data Service needs business object proxies so that client-side components can communicate with business objects located on the middle tier. Proxies facilitate the packaging, unpackaging, and transport (marshaling) of the application's recordset data across process or machine boundaries.

Remote Data Service uses the RDS.DataSpace object's CreateObject method to create business object proxies. The business object proxy is dynamically created whenever an instance of its middle-tier business object counterpart is created. Remote Data Service supports the following protocols: HTTP, HTTPS (HTTP Secure Sockets), DCOM, and in-process (client components and the business object reside on the same computer).

The class ID for the RDS.DataSpace object is BD96C556-65A3-11D0-983A-00C04FC29E36.

Example

See Also

Getting a Recordset to the Client, Transport Protocols, Business Object Proxies and the RDS.DataSpace Object, Appendix B: Detailed Control Flow


CreateObject Method

Creates the proxy for the target business object and returns a pointer to it. The proxy packages and marshals data to the server-side stub for communications with the business object to send requests and data over the Internet. For in-process component objects, no proxies are used, so just a pointer to the object is provided.

Syntax

Remote Data Service supports the following protocols: HTTP, HTTPS (HTTP over Secure Socket Layer ), DCOM, and in-process.
Protocol | Syntax
HTTP | Set object = DataSpace.CreateObject("ProgId", "http://awebsrvr")
HTTPS | Set object = DataSpace.CreateObject("ProgId", "https://awebsrvr")
DCOM | Set object = DataSpace.CreateObject("ProgId", "machinename")
In-process | Set object = DataSpace.CreateObject("ProgId", "")

Part | Description
object | An object variable that evaluates to an object that is the type specified in ProgID.
DataSpace | An object variable that represents an RDS.DataSpace object used to instantiate the new object.
ProgID | A String that is the programmatic ID that identifies a server-side business object that implements your application's business rules.
awebsrvr or machinename | A String that represents a URL identifying the Internet Information Server (IIS) Web server where an instance of the server business object is created.

Applies To

RDS.DataSpace

Example

See Also

Getting a Recordset to the Client, Transport Protocols, Business Object Proxies and the RDS.DataSpace Object, Appendix B: Detailed Control Flow


Remote Data Service API Reference

Use these reference topics to learn how to use all of the RDS objects, methods, and properties.

  • Objects
  • Methods
  • Properties
  • Examples
  • Appendixes


Remote Data Service Methods

Use these reference topics to learn how to use all of the RDS methods.

  • Cancel
  • CancelUpdate
  • ConvertToString
  • CreateObject
  • CreateRecordset
  • MoveFirst, MoveLast, MoveNext, MovePrevious
  • Query
  • Refresh
  • Reset
  • SubmitChanges


Remote Data Service Properties

Use these reference topics to learn how to use all of the RDS properties.

  • Connect Property
  • ExecuteOptions
  • FetchOptions
  • FilterColumn
  • FilterCriterion
  • FilterValue
  • ReadyState
  • Recordset
  • Server
  • SortColumn
  • SortDirection
  • SourceRecordset
  • SQL
  • Cancel Method Example
  • CancelUpdate Method Example
  • Connect Property Example
  • ConvertToString Method Example
  • CreateRecordset Method Example
  • ExecuteOptions and FetchOptions Properties Example
  • FilterColumn, FilterCriterion, FilterValue, SortColumn, and SortDirection Properties and Reset Method Example
  • RDS.DataControl Object Example
  • RDS.DataSpace Object and CreateObject Method Example
  • RDSServer.DataFactory Object, Query Method, and CreateObject Method Example
  • ReadyState Property Example
  • Recordset and SourceRecordset Properties Example
  • Refresh Method Example
  • SQL Property Example


Remote Data Services Appendixes

Microsoft Remote Data Service Microsoft Remote Data Service *

Appendixes, Remote Data Service Reference

Use these appendixes for information about the following topics:

Appendix A: Error Codes

Appendix B: Tested Data-Aware ActiveX Controls


Error Codes

Microsoft Remote Data Service Microsoft Remote Data Service *

Appendix A: Error Codes

The following table lists the Remote Data Service error codes. Both decimal and hexadecimal error code values are shown.

For generic client errors such as "Internet Client Error" and "Unexpected Error," the HRESULT is also listed.
RDS.DataControl Error Codes Number Description
IDS_UpdatesFailed 4098

0x800A1002

Unable to update database.
IDS_CantConnect 4099

0x800A1003

Unable to connect to server.
IDS_CantCreateObject 4100

0x800A1004

Unable to create business object.
IDS_CantInvokeMethod 4101

0x800A1005

Unable to invoke method on business object.
IDS_CantFindDataspace 4102

0x800A1006

Dataspace property is not valid.
IDS_ObjectNotSafe 4103

0x800A1007

Object not safe for scripting & initialization.
IDS_RowsetNotUpdateable 4104

0x800A1008

Rowset not updateable.
IDS_BadInlineTablegram 4105

0x800A1009

Bad Inline tablegram.
IDS_InvalidADCClientVersion 4106

0x800A1010

Invalid RDS Client Version - Client is newer than server.
IDS_AsyncPending 4107

0x800A1011

Can’t perform operation with an async operation pending.
IDS_ResetInvalidField 4108

0x800A1012

The column specified in SortColumn or FilterColumn does not exist.
IDS_RecordsetNotOpen 4109

0x800A1013

The Recordset is not in an open state.
IDS_InvalidParam 4110

0x800A1014

One or more arguments are invalid.
IDS_UnexpectedError 4351

0x800A10FF

Unexpected error.

Internet Explorer (Wininet) Errors Number Description
IDS_WinInet_Error 8193

0x800A2001

Internet Client Error.
IDS_WinInet_Timeout 8194

0x800A2002

Internet Client Error: Request Timeout.
IDS_WinInet_CantConnect 8195

0x800A2003

Internet Client Error: Can’t Connect to Server.
IDS_WinInet_SSLPostLimitation 8196

0x800A2004

Internet Client Error: SSL Error (possibly 32K data upload limitation).
IDS_WinInet_InvalidServerResponse 8430

0x800A20EE

Internet Client Error: Invalid Server Response.
IDS_WinInet_ConnectionReset 12031

0x800A2EFF

Internet Client Error: Connection Reset.

Internet Information Server Errors Number Description
IDS_IIS_AccessDenied 8208

0x800A2010

Internet Server Error: Access Denied.
IDS_IIS_ObjectNotFound 8209

0x800A2011

Internet Server Error: Object/module not found.
IDS_IIS_RequestForbidden 8210

0x800A2012

Internet Server Error: Request Forbidden.
IDS_IIS_UnexpectedError 8447

0x800A20FF

Internet Server Error.


Tested Data-Aware ActiveX Controls

Microsoft Remote Data Service Microsoft Remote Data Service *

Appendix B: Tested Data-Aware ActiveX Controls

The following table lists the data-aware controls that have been tested to work with the RDS.DataControl object and associated client-side components of the Remote Data Service framework. Other controls may also work with Remote Data Service, but they have not been tested.
Control name | File name | Class ID (CLSID)
SSDBGrid | SSDATB32.ocx (Sheridan) | AC05DC80-7DF1-11d0-839E-00A024A94B3A

With Internet Explorer 4.0, you can bind to data by using HTML controls and ActiveX™ controls only if they are marked as apartment model controls.

The controls listed are not distributed with Remote Data Service, but may be purchased as part of Microsoft® Visual Basic®, Enterprise Edition or from Sheridan Systems, Inc.

Important You may not redistribute the ActiveX controls that are deployed as a part of Remote Data Service samples in any way. They are provided as part of the sample applications and may not be redistributed to other parties under any circumstances.


Remote Data Service Examples

  • Cancel Method Example
  • CancelUpdate Method Example
  • Connect Property Example
  • ConvertToString Method Example
  • CreateRecordset Method Example
  • ExecuteOptions and FetchOptions Properties Example
  • FilterColumn, FilterCriterion, FilterValue, SortColumn, and SortDirection Properties and Reset Method Example
  • RDS.DataControl Object Example
  • RDS.DataSpace Object and CreateObject Method Example
  • RDSServer.DataFactory Object, Query Method, and CreateObject Method Example
  • ReadyState Property Example
  • Recordset and SourceRecordset Properties Example
  • Refresh Method Example
  • SQL Property Example


(Untitled)

Microsoft Remote Data Service Microsoft Remote Data Service *

RDS.DataControl Object Example

The following code shows how to set the RDS.DataControl parameters at design time and bind it to a data aware control using an ODBC data source called ADCDemo. If you followed directions, ADCDemo is installed on your server as a SQL Server ODBC data source. Cut and paste this code between the <Body></Body> tags in a normal HTML document and name it ADCapi1.asp. ASP script will identify your server.

<Center><H2>API Code Examples RDS 1.5</H2>
<HR><BR>
<H3>Remote Data Service</H3>
<Object CLASSID="clsid:AC05DC80-7DF1-11d0-839E-00A024A94B3A"
    CODEBASE="http://<%=Request.ServerVariables("SERVER_NAME")%>/MSADC/Samples/Sheridan.cab"
    ID=GRID1
        datasrc=#ADC
        HEIGHT=125
        WIDTH=495>
    <PARAM NAME="AllowAddNew"   VALUE="TRUE">
    <PARAM NAME="AllowDelete"   VALUE="TRUE">
    <PARAM NAME="AllowUpdate"   VALUE="TRUE">
</OBJECT>
<!-- Remote Data Service with Parameters set at Design Time -->
<OBJECT classid="clsid:BD96C556-65A3-11D0-983A-00C04FC29E33"
    ID=ADC>
    <PARAM NAME="SQL" VALUE="Select * from Employee for browse">
    <PARAM NAME="SERVER" VALUE="http://<%=Request.ServerVariables("SERVER_NAME")%>">
    <PARAM NAME="CONNECT" VALUE="dsn=ADCDemo;UID=ADCDemo;PWD=ADCDemo;">
</OBJECT><BR><HR></Center>

The following example shows how to set the necessary parameters of RDS.DataControl at run time. To test this example, cut and paste this code between the <Body></Body> tags in a normal HTML document and name it ADCapi2.asp. ASP script will identify your server.

<Center><H2>API Code Examples RDS 1.5</H2>
<HR><BR>
<H3>Remote Data Service Run Time</H3>
<Object CLASSID="clsid:AC05DC80-7DF1-11d0-839E-00A024A94B3A"
    CODEBASE="http://<%=Request.ServerVariables("SERVER_NAME")%>/MSADC/Samples/Sheridan.cab"
    ID=GRID1
        datasrc=#ADC
        HEIGHT=125
        WIDTH=495>
    <PARAM NAME="AllowAddNew" VALUE="TRUE">
    <PARAM NAME="AllowDelete" VALUE="TRUE">
    <PARAM NAME="AllowUpdate" VALUE="TRUE">
    <PARAM NAME="Caption" VALUE="Remote Data Service Run Time">
</OBJECT>

<!-- RDS.DataControl with no parameters set at design time -->
<OBJECT classid="clsid:BD96C556-65A3-11D0-983A-00C04FC29E33"
    ID=ADC>
    </OBJECT>
<HR>
<Input Size=70 Name="txtServer" Value="http://<%=Request.ServerVariables("SERVER_NAME")%>"><BR>
<Input Size=70 Name="txtConnect" Value="dsn=ADCDemo;UID=ADCDemo;PWD=ADCDemo;">
<BR>
<Input Size=70 Name="txtSQL" Value="Select * from Employee">
<HR>
<INPUT TYPE=BUTTON NAME="Run" VALUE="Run"><BR>
<H4>Fill Grid with these values or change them to see data from another ODBC data source on your server</H4>
</Center>
<Script Language="VBScript">
<!--
' Set parameters of RDS.DataControl at Run Time
Sub Run_OnClick
    ADC.Server = txtServer.Value
    ADC.SQL = txtSQL.Value
    ADC.Connect = txtConnect.Value
    ADC.Refresh
End Sub
-->
</Script>


(Untitled)

Microsoft Remote Data Service Microsoft Remote Data Service *

Connect Property Example

The following code shows how to set the Connect property at design time:

<OBJECT CLASSID="clsid:BD96C556-65A3-11D0-983A-00C04FC29E33" ID="ADC1">
.
.
.
    <PARAM NAME="SQL" VALUE="Select * from Sales">
    <PARAM NAME="Connect" VALUE="DSN=pubs;UID=sa;PWD=;">
    <PARAM NAME="Server" VALUE="http://MyWebServer">
.
.
.
</OBJECT>

The following example shows how to set the Connect property at run time in VBScript code:

To test this example, cut and paste this code between the <Body></Body> tags in a normal HTML document and name it ADCapi3.asp. ASP script will identify your server.

<Center><H2>API Code Examples RDS 1.5</H2>
<HR>
<H3>Set Connect Property at Run Time</H3>
<!-- RDS.DataControl with no parameters set at design time -->
<OBJECT classid="clsid:BD96C556-65A3-11D0-983A-00C04FC29E33"
    ID=ADC>
    </OBJECT>
<Object classid="clsid:AC05DC80-7DF1-11d0-839E-00A024A94B3A"
    CODEBASE="http://<%=Request.ServerVariables("SERVER_NAME")%>/MSADC/Samples/Sheridan.cab"
    ID=GRID1
        datasrc=#ADC
        HEIGHT=125
        WIDTH=495>
    <PARAM NAME="AllowAddNew" VALUE="TRUE">
    <PARAM NAME="AllowDelete" VALUE="TRUE">
    <PARAM NAME="AllowUpdate" VALUE="TRUE">
    <PARAM NAME="Caption" VALUE="Remote Data Service Connect Property at Run Time">
</OBJECT>
<HR>
<Input Size=70 Name="txtServer" Value="http://<%=Request.ServerVariables("SERVER_NAME")%>"><BR>
<Input Size=70 Name="txtConnect"><BR>
<Input Size=70 Name="txtSQL" Value="Select * from Employee">
<HR>
<INPUT TYPE=BUTTON NAME="Run" VALUE="Run"><BR>
<H4>To Fill Grid enter Connect String in middle text box<BR>
Try dsn=ADCDemo;UID=ADCDemo;PWD=ADCDemo;</H4>
</Center>
<Script Language="VBScript">
<!--
' Set parameters of RDS.DataControl at Run Time
Sub Run_OnClick
    ADC.Server = txtServer.Value
    ADC.SQL = txtSQL.Value
    ADC.Connect = txtConnect.Value
    ADC.Refresh
End Sub
-->
</Script>


(Untitled)

Microsoft Remote Data Service Microsoft Remote Data Service *

ExecuteOptions and FetchOptions Properties Example

The following code shows how to set the ExecuteOptions and FetchOptions properties at design time. If left unset, ExecuteOptions defaults to adcExecSync. This setting indicates that when the ADC.Refresh method is called it will be executed on the current calling thread, that is, synchronously.

<OBJECT CLASSID="clsid:BD96C556-65A3-11D0-983A-00C04FC29E33" ID="ADC1">
.
.
.
<PARAM NAME="SQL" VALUE="Select * from Sales">
<PARAM NAME="Connect" VALUE="DSN=pubs;UID=sa;PWD=;">
<PARAM NAME="Server" VALUE="http://MyWebServer">
<PARAM NAME="ExecuteOptions"VALUE="1">
<PARAM NAME="FetchOptions"VALUE="3">

.
.
</OBJECT>

The following example shows how to set the ExecuteOptions and FetchOptions properties at run time in VBScript code: See the Refresh method for a working example of these properties.

<Script Language="VBScript">
<!--
Sub ExecuteHow
' Execute next refresh of Recordset asynchronously to the calling thread
ADC1.ExecuteOptions = 1
ADC1.FetchOptions = 3
ADC.Refresh
End Sub
-->
</Script>


(Untitled)

Microsoft Remote Data Service Microsoft Remote Data Service *

Recordset and SourceRecordset Properties Example

The following example shows how to set the necessary parameters of RDSServer.DataFactory default business object at run time. To test this example, cut and paste this code between the <Body></Body> tags in a normal HTML document and name it ADCapi4.asp. ASP script will identify your server.

<Center><H2>API Code Examples ADC 1.5</H2>
<HR>
<H3>Using SourceRecordset and Recordset with RDSServer.DataFactory</H3>
<!-- RDS.DataSpace ID ADS1 -->
<OBJECT ID="ADS1" WIDTH=1 HEIGHT=1
CLASSID="CLSID:BD96C556-65A3-11D0-983A-00C04FC29E36">
</OBJECT>

<!-- RDS.DataControl with parameters set at run time -->
<OBJECT classid="clsid:BD96C556-65A3-11D0-983A-00C04FC29E33"
    ID=ADC>
</OBJECT>

<Object CLASSID="clsid:AC05DC80-7DF1-11d0-839E-00A024A94B3A"
    CODEBASE="http://<%=Request.ServerVariables("SERVER_NAME")%>/MSADC/Samples/Sheridan.cab"
    ID=GRID1
        datasrc=#ADC
        HEIGHT=125
        WIDTH=495>
    <PARAM NAME="AllowAddNew" VALUE="TRUE">
    <PARAM NAME="AllowDelete" VALUE="TRUE">
    <PARAM NAME="AllowUpdate" VALUE="TRUE">
    <PARAM NAME="Caption" VALUE="RDSServer.DataFactory Run Time">
</OBJECT>
<HR>
<Input Size=70 Name="txtServer" Value="http://<%=Request.ServerVariables("SERVER_NAME")%>"><BR>
<Input Size=70 Name="txtConnect" Value="dsn=ADCDemo;UID=ADCDemo;PWD=ADCDemo;"><BR>
<Input Size=70 Name="txtSQL" Value="Select * from Employee">
<HR>
<INPUT TYPE=BUTTON NAME="Run" VALUE="Run"><BR>
<H4>Fill Grid with these values or change them to see data from another ODBC data source on your server
<BR>Try dsn=pubs;uid=sa;pwd=; and Select * From Authors</H4>
</Center>
<Script Language="VBScript">
<!--
Dim ADF
Dim strServer
strServer = "http://<%=Request.ServerVariables("SERVER_NAME")%>"

Sub Run_OnClick()
    Dim objADORs			' Create RDSServer.DataFactory Object
Set ADF = ADS1.CreateObject("RDSServer.DataFactory", strServer)					' Get Recordset
Set objADORs = ADF.Query(txtConnect.Value,txtSQL.Value)

' Set parameters of RDS.DataControl at Run Time
    ADC.Server = txtServer.Value
    ADC.SQL = txtSQL.Value
    ADC.Connect = txtConnect.Value
    ADC.Refresh
End Sub
-->
</Script>


(Untitled)

Microsoft Remote Data Service Microsoft Remote Data Service *

Server Property Example

The following code shows how to set the RDS.DataControl parameters at design time and bind it to a data aware control using an ODBC system data source called ADCDemo. If you followed directions, ADCDemo is installed on your server as a SQL Server ODBC system data source. Cut and paste this code between the <Body></Body> tags in a normal HTML document and name it ADCapi1.asp. ASP script will identify your server.

<Center><H2>API Code Examples RDS 1.5</H2>
<HR><BR>
<H3>Remote Data Service</H3>
<Object CLASSID="clsid:AC05DC80-7DF1-11d0-839E-00A024A94B3A"
    CODEBASE="http://<%=Request.ServerVariables("SERVER_NAME")%>/MSADC/Samples/Sheridan.cab"
    ID=GRID1
        datasrc=#ADC
        HEIGHT=125
        WIDTH=495>
    <PARAM NAME="AllowAddNew" VALUE="TRUE">
    <PARAM NAME="AllowDelete" VALUE="TRUE">
    <PARAM NAME="AllowUpdate" VALUE="TRUE">
</OBJECT>
<!-- Remote Data Service with Parameters set at Design Time -->
<OBJECT classid="clsid:BD96C556-65A3-11D0-983A-00C04FC29E33"
    ID=ADC>
    <PARAM NAME="SQL" VALUE="Select * from Employee for browse">
    <PARAM NAME="SERVER" VALUE="http://<%=Request.ServerVariables("SERVER_NAME")%>">
    <PARAM NAME="CONNECT" VALUE="dsn=ADCDemo;UID=ADCDemo;PWD=ADCDemo;">
</OBJECT><BR><HR></Center>

The following example shows how to set the necessary parameters of RDS.DataControl at run time. To test this example, cut and paste this code between the <Body></Body> tags in a normal HTML document and name it ADCapi4.asp. ASP script will identify your server.

<Center><H2>API Code Examples RDS 1.5</H2>
<HR><H3>Remote Data Service Server Property Set at Run Time</H3>
<!-- RDS.DataControl with no parameters set at design time -->
<OBJECT classid="clsid:BD96C556-65A3-11D0-983A-00C04FC29E33"
    ID=ADC>
</OBJECT>
<Object CLASSID="clsid:AC05DC80-7DF1-11d0-839E-00A024A94B3A"
    CODEBASE="http://<%=Request.ServerVariables("SERVER_NAME")%>/MSADC/Samples/Sheridan.cab"
    ID=GRID1
        datasrc=#ADC
        HEIGHT=125
        WIDTH=495>
    <PARAM NAME="AllowAddNew" VALUE="TRUE">
    <PARAM NAME="AllowDelete" VALUE="TRUE">
    <PARAM NAME="AllowUpdate" VALUE="TRUE">
    <PARAM NAME="Caption" VALUE="Remote Data Service Run Time">
</OBJECT><HR>
<Input Size=70 Name="txtServer"><BR>
<Input Size=70 Name="txtConnect" Value="dsn=ADCDemo;UID=ADCDemo;PWD=ADCDemo;">
<BR>
<Input Size=70 Name="txtSQL" Value="Select * from Employee">
<HR>
<INPUT TYPE=BUTTON NAME="Run" VALUE="Run"><BR>
<H4>Fill top text box with your Web server name in the form http://Myserver</H4>
</Center>
<Script Language="VBScript">
<!--
' Set parameters of RDS.DataControl at Run Time
Sub Run_OnClick
    ADC.Server = txtServer.Value
    ADC.SQL = txtSQL.Value
    ADC.Connect = txtConnect.Value
    ADC.Refresh
End Sub
-->
</Script>


(Untitled)

Microsoft Remote Data Service Microsoft Remote Data Service *

FilterColumn, FilterCriterion, FilterValue, SortColumn, and SortDirection Properties and Reset Method Example

The following code shows how to set the RDS.DataControl Server parameter at design time and bind it to a data-aware control using an ODBC data source called pubs. Pubs ships with SQL Server 6.5. To try the example you will need rich text controls named txtSortcolumn, txtSortdirection, txtFiltercolumn, txtCriterion, txtFilterValue and an HTML Form Input Button named SortFilter.

<OBJECT CLASSID="clsid:BD96C556-65A3-11D0-983A-00C04FC29E33"
ID=ADC HEIGHT=10 WIDTH=10>
<PARAM NAME="SQL" VALUE="Select * from Sales ">
<PARAM NAME="SERVER" VALUE="http://MyWebServer">
<PARAM NAME="CONNECT" VALUE="dsn=pubs;UID=sa;PWD=;">
</OBJECT>

<!-- Sheridan Grid -->
<Object CLASSID="clsid:AC05DC80-7DF1-11d0-839E-00A024A94B3A"
    CODEBASE="http://MyWebServer
/MSADC/Samples/Sheridan.cab"
    ID=GRID1
        datasrc=#ADC
        HEIGHT=125
        WIDTH=495>
    <PARAM NAME="AllowAddNew"   VALUE="TRUE">
    <PARAM NAME="AllowDelete"   VALUE="TRUE">
    <PARAM NAME="AllowUpdate"   VALUE="TRUE">
    <PARAM NAME="BackColor"     VALUE="-2147483643">
    <PARAM NAME="BackColorOdd"  VALUE="-2147483643">
    <PARAM NAME="ForeColorEven" VALUE="0">
</OBJECT>

<Script Language="VBScript">
<!--
Sub SortFilter_OnClick

    ' Set the values. txtSortcolumn is a rich text box
    ' control. The value of SortColumn will be the text
    ' value of what the user specifies in the
    ' txtSortcolumn box.
    If(txtSortcolumn.text <> "") then
        ADC.SortColumn = txtSortcolumn.text
    End If

    ' txtSortdirection is a rich text box
    ' control. The value of SortDirection will be the
    ' text value of what the user specifies in the
    ' txtSortdirection box.
    Select Case UCASE(txtSortDirection.text)
    Case "TRUE"
        ADC.SortDirection = TRUE
    Case "FALSE"
        ADC.SortDirection = FALSE
    Case Else
        MsgBox "Only true or false are accepted for sort direction"
    End Select

    ' txtFiltercolumn is a rich text box
    ' control. The value of FilterColumn will be the
    ' text value of what the user specifies in the
    ' txtFiltercolumn box.
    If (txtFiltercolumn.text <> "") Then
        ADC.FilterColumn = txtFiltercolumn.text
    End If

    ' txtCriterion is a rich text box
    ' control. The value of FilterCriterion will be the
    ' text value of what the user specifies in the
    ' txtCriterion box.
    If (txtCriterion.text <> "") Then
        ADC.FilterCriterion = txtCriterion.text
    End If

    ' txtFilterValue is a rich text box
    ' control. The value of FilterValue will be the
    ' text value of what the user specifies in the
    ' txtFilterValue box.
    If (txtFilterValue.text <> "") Then
        ADC.FilterValue = txtFilterValue.text
    End If

    ' Execute the sort and filter on a client-side
    ' Recordset based on the specified sort and filter
    ' properties. Calling Reset refreshes the result set
    ' that is displayed in the data-bound controls to
    ' display the filtered, sorted recordset.
    ADC.Reset

End Sub
-->
</Script>


(Untitled)

Microsoft Remote Data Service Microsoft Remote Data Service *

SQL Property Example

The following code shows how to set the RDS.DataControl parameters at design time and bind it to a data aware control using an ODBC data source called pubs that ships with SQL Server 6.5.

<!—- RDS.DataControl -- >
<OBJECT classid="clsid:BD96C556-65A3-11D0-983A-00C04FC29E33" ID=ADC HEIGHT=10 WIDTH=10>
    <PARAM NAME="SQL" VALUE="Select * from Authors">
    <PARAM NAME="SERVER" VALUE="http://MyWebServer">
<PARAM NAME="CONNECT" VALUE="dsn=pubs;UID=sa;PWD=;">
</OBJECT>

<!-- Data Grid -- >
<Object CLASSID="clsid:AC05DC80-7DF1-11d0-839E-00A024A94B3A"
    CODEBASE="http://MyWebServer
/MSADC/Samples/Sheridan.cab"
    ID=GRID1
        datasrc=#ADC
        HEIGHT=125
        WIDTH=495>
    <PARAM NAME="AllowAddNew"   VALUE="TRUE">
    <PARAM NAME="AllowDelete"   VALUE="TRUE">
    <PARAM NAME="AllowUpdate"   VALUE="TRUE">
    <PARAM NAME="BackColor"     VALUE="-2147483643">
    <PARAM NAME="BackColorOdd"  VALUE="-2147483643">
    <PARAM NAME="ForeColorEven" VALUE="0">
</OBJECT>

The following example shows how to set the necessary parameters of RDS.DataControl at run time. To test this example, cut and paste this code between the <Body></Body> tags in a normal HTML document and name it ADCapi5.asp. ASP script will identify your server.

<Center><H2>API Code Examples RDS 1.5</H2>
<HR><H3>Remote Data Service SQL Property Set at Run Time</H3>

<!-- RDS.DataControl with no parameters set at design time -->
<OBJECT classid="clsid:BD96C556-65A3-11D0-983A-00C04FC29E33"
    ID=ADC>
</OBJECT>
<Object CLASSID="clsid:AC05DC80-7DF1-11d0-839E-00A024A94B3A"
    CODEBASE="http://<%=Request.ServerVariables("SERVER_NAME")%>/MSADC/Samples/Sheridan.cab"
    ID=GRID1
        datasrc=#ADC
        HEIGHT=125
        WIDTH=495>
    <PARAM NAME="AllowAddNew"   VALUE="TRUE">
    <PARAM NAME="AllowDelete"   VALUE="TRUE">
    <PARAM NAME="AllowUpdate"   VALUE="TRUE">
    <PARAM NAME="Caption" VALUE="Remote Data Service Run Time">
</OBJECT>
<HR>
<Input Size=70 Name="txtServer" Value= "http://<%=Request.ServerVariables("SERVER_NAME")%>">
<BR>
<Input Size=70 Name="txtConnect" Value="dsn=ADCDemo;UID=ADCDemo;PWD=ADCDemo;">
<BR>
<Input Size=70 Name="txtSQL">
<HR>
<INPUT TYPE=BUTTON NAME="Run" VALUE="Run"><BR>
<H4>Fill bottom text box with an SQL string<BR>
Try ... Select * from Employee</H4>
</Center>
<Script Language="VBScript">
<!--
' Set parameters of RDS. at Run Time
Sub Run_OnClick
    ADC.Server = txtServer.Value
    ADC.SQL = txtSQL.Value
    ADC.Connect = txtConnect.Value
    ADC.Refresh
End Sub
-->
</Script>


(Untitled)

Microsoft Remote Data Service Microsoft Remote Data Service *

ReadyState Property Example

The following example shows how to read the ReadyState property of the RDS.DataControl object at run time in VBScript code. ReadyState is a read-only property.

To test this example, cut and paste this code between the <Body></Body> tags in a normal HTML document and name it ADCapi9.asp. ASP script will identify your server.

<Center><H2>API Code Examples RDS 1.5</H2>
<HR>
<H3> RDS.DataControl ReadyState property</H3></Center>
<!-- RDS.DataControl with parameters set at design time -->
<OBJECT classid="clsid:BD96C556-65A3-11D0-983A-00C04FC29E33"
    ID=ADC>
    <PARAM NAME="SQL" VALUE="Select * from Employee for browse">
    <PARAM NAME="SERVER" VALUE="http://<%=Request.ServerVariables("SERVER_NAME")%>">
    <PARAM NAME="CONNECT" VALUE="dsn=ADCDemo;UID=ADCDemo;PWD=ADCDemo;">
<PARAM NAME="ExecuteOptions" VALUE="adcExecAsync">
<PARAM NAME="FetchOptions" VALUE="adcFetchAsync">
</OBJECT>

<Script Language="VBScript">

Sub Window_OnLoad
Select Case ADC1.ReadyState
    case 2: MsgBox "Executing Query"
    case 3: MsgBox "Fetching records in background"
    case 4: MsgBox "All records fetched"
End Select
End Sub
</Script>


(Untitled)

Microsoft Remote Data Service Microsoft Remote Data Service *

Cancel Method Example

The following example shows how to read the Cancel method at run time in VBScript code.

<Script Language="VBScript">
<!--
Sub cmdCancelAsync
ADC.Cancel
' Terminates currently running AsyncExecute,
' ReadyState property set to adcReadyStateLoaded,
' Recordset set to Nothing
End Sub
-->
</Script>


(Untitled)

Microsoft Remote Data Service Microsoft Remote Data Service *

CancelUpdate Method Example

To test this example, cut and paste this code between the <Body></Body> tags in a normal HTML document and name it ADCapi6.asp. ASP script will identify your server.

<Center><H2>API Code Examples RDS 1.5</H2>
<HR><H3>Remote Data Service SubmitChanges and CancelUpdate Methods</H3>

<!-- RDS.DataControl with parameters set at design time -->
<OBJECT classid="clsid:BD96C556-65A3-11D0-983A-00C04FC29E33"
    ID=ADC>
    <PARAM NAME="SQL" VALUE="Select * from Employee for browse">
    <PARAM NAME="SERVER" VALUE="http://<%=Request.ServerVariables("SERVER_NAME")%>">
    <PARAM NAME="CONNECT" VALUE="dsn=ADCDemo;UID=ADCDemo;PWD=ADCDemo;">
</OBJECT>

<Object classid="clsid:AC05DC80-7DF1-11d0-839E-00A024A94B3A"
    CODEBASE="http://<%=Request.ServerVariables("SERVER_NAME")%>/MSADC/Samples/Sheridan.cab"
    ID=GRID1
        datasrc=#ADC
        HEIGHT=125
        WIDTH=495>
    <PARAM NAME="AllowAddNew"   VALUE="TRUE">
    <PARAM NAME="AllowDelete"   VALUE="TRUE">
    <PARAM NAME="AllowUpdate"   VALUE="TRUE">
    <PARAM NAME="Caption" VALUE="Remote Data Service Run Time">
</OBJECT>
<HR>
<INPUT TYPE=BUTTON NAME="SubmitChange" VALUE="Submit-Changes"><INPUT TYPE=BUTTON NAME="CancelChange" VALUE="Cancel-Update"><BR>
<H4>Add a new person or alter a current entry on the grid. Move off that Row. <BR>
Submit the Changes to your DBMS or cancel the updates. </H4>
</Center>
<Script Language="VBScript">
<!--
' Set parameters of RDS.DataControl at Run Time
Sub SubmitChange_OnClick
    ADC.SubmitChanges
    ADC.Refresh
End Sub

Sub CancelUpdate_OnClick
    ADC.CancelUpdate
End Sub
-->
</Script>


(Untitled)

Microsoft Remote Data Service Microsoft Remote Data Service *

Refresh Method Example

The following example shows how to set the necessary parameters of RDS.DataControl at run time. The manner in which a Recordset is retrieved using the Refresh method is determined by the settings of the ExecuteOptions and FetchOptions properties. To test this example, cut and paste this code between the <Body></Body> tags in a normal HTML document and name it ADCapi2.asp. ASP script will identify your server.

<HTML>
<HEAD>
<TITLE>Refresh / ExecuteOptions</TITLE>
</HEAD>
<BODY>
<Center><H2>API Code Examples RDS 1.5</H2>
<HR>
<Object CLASSID="clsid:AC05DC80-7DF1-11d0-839E-00A024A94B3A"
    CODEBASE="http://<%=Request.ServerVariables("SERVER_NAME")%>/MSADC/Samples/Sheridan.cab"
    ID=GRID1
        datasrc=#ADC
        HEIGHT=125
        WIDTH=495>
    <PARAM NAME="AllowAddNew"   VALUE="TRUE">
    <PARAM NAME="AllowDelete"   VALUE="TRUE">
    <PARAM NAME="AllowUpdate"   VALUE="TRUE">
    <PARAM NAME="Caption" VALUE="Remote Data Service Run Time">
</OBJECT>

<!-- RDS.DataControl with no parameters set at design time -->
<OBJECT classid="clsid:BD96C556-65A3-11D0-983A-00C04FC29E33"
    ID=ADC>
    </OBJECT>
<HR>
<Input Size=70 Name="txtServer" Value="http://<%=Request.ServerVariables("SERVER_NAME")%>"><BR>
<Input Size=70 Name="txtConnect" Value = "dsn=ADCDemo;UID=ADCDemo;PWD=ADCDemo;"><BR>
<Input Size=70 Name="txtSQL" Value="Select * from Employee">
<BR>
Choose if you want the Recordset brought back Synchronously on the current calling thread or Asynchronously on another thread
<Input Type="Radio" Name="optExecuteOptions" Checked OnClick="SetExO('adcExecSync')">
<Input Type="Radio" Name="optExecuteOptions"  OnClick="SetExO('adcExecAsync')"><BR>
Fetch Up Front, Background Fetch with Blocking or Background Fetch without Blocking
<Input Type="Radio" Name="optFetchOptions"  OnClick="SetFO('adcFetchUpFront')">
<Input Type="Radio" Name="optFetchOptions" Checked OnClick="SetFO('adcFetchBackground')">
<Input Type="Radio" Name="optFetchOptions"  OnClick="SetFO('adcFetchAsync')">

<HR>
<INPUT TYPE=BUTTON NAME="Run" VALUE="Run"><BR>
<H4>Fill Grid with these values or change them to see data from another ODBC data source on your server</H4>
</Center>
<Script Language="VBScript">
<!--
Dim EO 			'ExecuteOptions
Dim FO			'FetchOptions
EO = "adcExecSync"	'Default value
FO = "adcFetchBackground"	'Default value
Sub SetExO(NewEO)
    EO = NewEO
End Sub
Sub SetFO(NewFO)
    FO = NewFO
End Sub

' Set parameters of RDS.DataControl at Run Time
Sub Run_OnClick
    ADC.Server = txtServer.Value
    ADC.SQL = txtSQL.Value
    ADC.Connect = txtConnect.Value
If EO = "adcExecSync" Then		'Determine which ExecuteOption chosen
    ADC.ExecuteOptions = adcExecSync
        MsgBox "Recordset brought in on current calling thread Syncronously"
Else
    ADC.ExecuteOptions = adcExecAsync
            MsgBox "Recordset brought in on another thread Asyncronously"
End If

If FO = "adcFetchBackground" Then		'Determine 										‘which FetchOption chosen
    ADC.FetchOptions = adcFetchBackground
        MsgBox "Control goes back to user after first batch of records returned"
ElseIf FO = " adcFetchUpFront" Then
    ADC.FetchOptions = adcFetchUpFront
            MsgBox "All records returned before control goes back to user"
Else
    ADC.FetchOptions = adcFetchAsync
            MsgBox "Control goes back to user immediately"
End If

ADC.Refresh

End Sub
-->
</Script>
</BODY>
</HTML>


(Untitled)

Microsoft Remote Data Service Microsoft Remote Data Service *

SubmitChanges Method Example

The following code fragment shows how to use the SubmitChanges method with a RDS.DataControl object:

To test this example, cut and paste this code between the <Body></Body> tags in a normal HTML document and name it ADCapi6.asp. ASP script will identify your server.

<Center><H2>API Code Examples RDS 1.5</H2>
<HR>
<H3>Remote Data Service SubmitChanges and CancelUpdate Methods</H3>
<!-- RDS.DataControl with parameters set at design time -->
<OBJECT classid="clsid:BD96C556-65A3-11D0-983A-00C04FC29E33"
    ID=ADC>
    <PARAM NAME="SQL" VALUE="Select * from Employee for browse">
    <PARAM NAME="SERVER" VALUE="http://<%=Request.ServerVariables("SERVER_NAME")%>">
    <PARAM NAME="CONNECT" VALUE="dsn=ADCDemo;UID=ADCDemo;PWD=ADCDemo;">   </OBJECT>

<Object classid ="clsid:AC05DC80-7DF1-11d0-839E-00A024A94B3A"
    CODEBASE="http://<%=Request.ServerVariables("SERVER_NAME")%>/MSADC/Samples/Sheridan.cab"
    ID=GRID1
        datasrc=#ADC
        HEIGHT=125
        WIDTH=495>
    <PARAM NAME="AllowAddNew"   VALUE="TRUE">
    <PARAM NAME="AllowDelete"   VALUE="TRUE">
    <PARAM NAME="AllowUpdate"   VALUE="TRUE">
    <PARAM NAME="Caption" VALUE="Remote Data Service Run Time">
</OBJECT>
<HR>
<INPUT TYPE=BUTTON NAME="SubmitChange" VALUE="Submit-Changes"><INPUT TYPE=BUTTON NAME="CancelChange" VALUE="Cancel-Update"><BR>
<H4>Add a new person or alter a current entry on the grid. Move off that Row. <BR>
Submit the Changes to your DBMS or cancel the updates. </H4>
</Center>
<Script Language="VBScript">
<!--
' Set parameters of RDS.DataControl at Run Time
Sub SubmitChange_OnClick
    ADC.SubmitChanges
    ADC.Refresh
End Sub

Sub CancelUpdate_OnClick
    ADC.CancelUpdate
End Sub
-->
</Script>

The following code fragment shows how to use the SubmitChanges method with a RDSServer.DataFactory object. You may want to submit changes to the DRSServer.DataFactory if you are working on a Visual Basic project where the RDS.DataControl isn't used. To create this project, open a Visual Basic form and place on it a List box (List1), two Text boxes (txtConnect and txtGetRecordset), and two Command buttons (cmdGetRecordset and cmdSubmitChanges).

Dim ads As Object	' RDS.DataSpace object
Dim adf As Object	' RDSServer.DataFactory object

Private Sub UserDocument_Initialize()
    Call Form_Load
End Sub

Private Sub Form_Load()
    txtConnect.Text = "Dsn=pubs;Uid=sa;Pwd=;"
    txtGetRecordset.Text = "Select au_lname from authors"
End Sub

Private Sub cmdGetRecordset_Click()
    Dim Server As String
    Server = txtServer.Text

    ' Create RDS.DataSpace using CreateObject Method of RDS.DataSpace
    Set ads = CreateObject("RDS.DataSpace")
    Set adf = ads.CreateObject("RDSServer.DataFactory", Server)

    ' Populate ListBox with Recordset
    MousePointer = vbHourglass
    Dim objADORs As Object
    Set objADORs = adf.Query(CStr(txtConnect.Text), CStr(txtGetRecordset.Text))
    List1.Clear
    While Not objADORs.EOF
        List1.AddItem objADORs(0).Value
        objADORs.MoveNext
    Wend
    MousePointer = vbNormal
End Sub
Sub cmdSubmitChanges_OnClick

adf.SubmitChanges " Dsn=pubs;Uid=sa;Pwd=;",_

    objADORs
End Sub


(Untitled)

Microsoft Remote Data Service Microsoft Remote Data Service *

RDSServer.DataFactory Object, Query Method, and CreateObject Method Example

This example creates a RDSServer.DataFactory object using the CreateObject method of the RDS.DataSpace object. To test this example, cut and paste this code between the <Body></Body> tags in a normal HTML document and name it ADCapi7.asp. ASP script will identify your server.

<Center><H2>API Code Examples RDS 1.5</H2>
<HR><H3>Using Query Method of RDSServer.DataFactory</H3>

<!-- RDS.DataSpace  ID ADS1-->
<OBJECT ID="ADS1" WIDTH=1 HEIGHT=1
CLASSID="CLSID:BD96C556-65A3-11D0-983A-00C04FC29E36">
</OBJECT>

<!-- RDS.DataControl with parameters set at run time -->
<OBJECT classid="clsid:BD96C556-65A3-11D0-983A-00C04FC29E33"
    ID=ADC>
</OBJECT>

<Object classid ="clsid:AC05DC80-7DF1-11d0-839E-00A024A94B3A"
    CODEBASE="http://<%=Request.ServerVariables("SERVER_NAME")%>/MSADC/Samples/Sheridan.cab"
    ID=GRID1
        datasrc=#ADC
        HEIGHT=125
        WIDTH=495>
    <PARAM NAME="AllowAddNew"   VALUE="TRUE">
    <PARAM NAME="AllowDelete"   VALUE="TRUE">
    <PARAM NAME="AllowUpdate"   VALUE="TRUE">
    <PARAM NAME="Caption" VALUE=" RDSServer.DataFactory Run Time">
</OBJECT>
<HR>
<INPUT TYPE=BUTTON NAME="Run" VALUE="Run"><BR>
<H4>Click Run. The CreateObject Method of the RDS.DataSpace Object Creates an instance of the RDSServer.DataFactory.
The Query Method of the RDSServer.DataFactory is used to bring back a Recordset. </H4>
</Center>
<Script Language="VBScript">
<!--
Dim ADF
Dim strServer
Dim strConnect
Dim strSQL

strServer = "http://<%=Request.ServerVariables("SERVER_NAME")%>"
strConnect = "dsn=ADCDemo;UID=ADCDemo;PWD=ADCDemo;"
strSQL = "Select * from Employee"

Sub Run_OnClick()
    Dim objADORs		'Create RDSServer.DataFactory Object
Set ADF = ADS1.CreateObject("RDSServer.DataFactory", strServer)				'Get Recordset
Set objADORs = ADF.Query(strConnect, strSQL)
' Set parameters of RDS.DataControl at Run Time

    ADC.Server = strServer
    ADC.SQL = strSQL
    ADC.Connect = strConnect
    ADC.Refresh
End Sub
-->
</Script>


(Untitled)

Microsoft Remote Data Service Microsoft Remote Data Service *

ConvertToString Method Example

Sub QueryRecordset_OnClick()
    Dim objADORs
        strServer = "http://<%=Request.ServerVariables("SERVER_NAME")%>"
        Set ADF = ADS1.CreateObject("RDSServer.DataFactory", strServer)	Set objADORs = ADF.Query(txtConnect.Value,txtQueryRecordset.Value)

ADF.ConvertToString(objADORs)

End Sub


(Untitled)

Microsoft Remote Data Service Microsoft Remote Data Service *

CreateRecordset Method Example

This code example creates an ADODB.Recordset on the server side. It has two columns with four rows each.

Sub CreateARecordSet
    Dim ColInfo(1), c0(3), c1(3)

    c0(0) = "Name"			' Column name.
    c0(1) = CInt(129)		' Column type (129 = adChar).
    c0(2) = CInt(40)		' Column size.
    c0(3) = False			' Is the column nullable?

    c1(0) = "Age"			' Column name.
    c1(1) = CInt(3)		' Column type (3 = adInteger).
    c1(2) = CInt(-1)		' Column size.
    c1(3) = True			' Is the column nullable?

    ' Add the columns to the recordset definition.
    ColInfo(0) = c0
    ColInfo(1) = c1

    ADC1.SourceRecordset = ADF1.CreateRecordset(ColInfo)
End Sub


(Untitled)

Microsoft Remote Data Service Microsoft Remote Data Service *

RDS.DataSpace Object and CreateObject Method Example

The following example shows how to use the CreateObject method of the RDS.DataSpace with the default business object, RDSServer.DataFactory. To test this example cut and paste this code between the <Body></Body> tags in a normal HTML document and name it ADCapi8.asp. ASP script will identify your server.

<Center><H2>API Code Examples RDS 1.5</H2>
<HR><H3>Using Query Method of RDSServer.DataFactory</H3>

<!-- RDS.DataSpace  ID ADS1-->
<OBJECT ID="ADS1" WIDTH=1 HEIGHT=1
CLASSID="CLSID:BD96C556-65A3-11D0-983A-00C04FC29E36">
</OBJECT>

<!-- RDS.DataControl with parameters set at run time -->
<OBJECT classid="clsid:BD96C556-65A3-11D0-983A-00C04FC29E33"
    ID=ADC>
</OBJECT>

<Object CLASSID="clsid:AC05DC80-7DF1-11d0-839E-00A024A94B3A"
    CODEBASE="http://<%=Request.ServerVariables("SERVER_NAME")%>/MSADC/Samples/Sheridan.cab"
    ID=GRID1
        datasrc=#ADC
        HEIGHT=125
        WIDTH=495>
    <PARAM NAME="AllowAddNew"   VALUE="TRUE">
    <PARAM NAME="AllowDelete"   VALUE="TRUE">
    <PARAM NAME="AllowUpdate"   VALUE="TRUE">
    <PARAM NAME="Caption" VALUE="RDSServer.DataFactory Run Time">
</OBJECT>
<HR>
<INPUT TYPE=BUTTON NAME="Run" VALUE="Run"><BR>
<H4>Click Run. The CreateObject Method of the RDS.DataSpace Object Creates an instance of the RDSServer.DataFactory.
The Query Method of the RDSServer.DataFactory is used to bring back a Recordset. </H4>
</Center>
<Script Language="VBScript">
<!--
Dim ADF
Dim strServer
Dim strConnect
Dim strSQL
strServer = "http://<%=Request.ServerVariables("SERVER_NAME")%>"
strConnect = "dsn=ADCDemo;UID=ADCDemo;PWD=ADCDemo;"
strSQL = "Select * from Employee"

Sub Run_OnClick()
    Dim objADORs		'Create Recordset Object
Set ADF = ADS1.CreateObject("RDSServer.DataFactory", strServer)				'Get Recordset
Set objADORs = ADF.Query(strConnect, strSQL)
' Use  RDS.DataControl to bind Recordset to Data
‘ Aware Grid Control

    ADC.SourceRecordset = objADORs

End Sub
-->
</Script>

The following example shows how to use the CreateObject method to instantiate a custom business object, VbBusObj.VbBusObjCls. It also uses the Active Server Pages scripting to identify the Web server name. To see the complete example, choose “VBScript in Internet Explorer” in the Client Tier column and “Custom Visual Basic Business Object” in the Middle Tier column from the sample applications selector.

Sub Window_OnLoad()
    strServer = "http://<%=Request.ServerVariables("SERVER_NAME")%>"
    Set BO = ADS1.CreateObject("VbBusObj.VbBusObjCls", strServer)
    txtConnect.Value = "dsn=pubs;uid=sa;pwd=;"
    txtGetRecordset.Value = "Select * From authors for Browse"
End Sub


(Untitled)

Microsoft Remote Data Service Microsoft Remote Data Service *

Remote Data Service Tutorials

The Remote Data Service tutorials provide step-by-step procedures that walk you through using the most common data access features.

  • Building a Simple Remote Data Service Application. This tutorial walks you through building a simple Remote Data Service application that provides access to live data in a Microsoft® Access database.

  • Address Book. This tutorial shows you how to create a simple Remote Data Service application that provides access and updatability to a Microsoft SQL Server database.


(Untitled)

Microsoft Remote Data Service Microsoft Remote Data Service *

Building a Simple Remote Data Service Application

You can use the RDS.DataControl object to create a simple Active Server Pages file that accesses a live database — and you don't have to write a lot of code to do it. You can also use it with ActiveX™ Data Objects to create robust applications that give you a high degree of programming control over the behavior of your application's data.

This tutorial takes the "minimal code" approach, and the Developer's Guide provides more information for using the RDS.DataControl with ActiveX Data Objects and other advanced features. In this tutorial, you will connect to a Microsoft® Access database, display a result set in a data-bound grid, and add the ability to navigate through the displayed Recordset. The following procedure outlines the steps you'll take to create this simple application:

  1. Identify the database.

  2. Insert the grid and the RDS.DataControl object.

  3. Add HTML controls.

  4. Add code to send a query to the database.

  5. Add code to submit changes to the database.

  6. Add code to move through the displayed Recordset.

  7. See the code in action.

To see a finished version of this sample application with a number of enhancements not described in this tutorial, visit http://<webservername>/MSADC/Samples/ADCTest.asp, where <webservername> is the name of your Web server.


(Untitled)

Microsoft Remote Data Service Microsoft Remote Data Service *

Identify the Database

Before you create your .asp file, you must identify the database in the ODBC applet in Control Panel. In this example, you will use a Microsoft® Access database that is provided with Remote Data Service.

  1. At the computer running your Web server, open Control Panel.

  2. Double-click the ODBC icon, and then click System DSN.

    There are two types of data sources: User, which is available only to you, and System, which is available to anyone using the computer. Data sources for use with the Web server need to be System data sources.

  3. Click Add, choose Microsoft Access Driver, and then click Finish.

  4. In the Data Source Name box, type AdvWorks, and click Select. Select the C:\Program Files\Common Files\System\MSADC\Samples\AdvWorks.mdb file, and click OK.

  5. Click OK to close the dialog boxes.


(Untitled)

Microsoft Remote Data Service Microsoft Remote Data Service *

Insert the Grid and the RDS.DataControl Object

  1. Use your text editor to open the Tutorial.asp file in the C:\Program Files\Common Files\System\MSADC\Samples\Tutorial folder.

  2. Search for the words "Tutorial: RDS.DataControl Object." Copy the following script and paste it under this comment.
    <OBJECT classid="clsid:BD96C556-65A3-11D0-983A-00C04FC29E33"
    ID=ADC HEIGHT=1 WIDTH = 1>
</OBJECT>
  3. Search for the words "Tutorial: Data Bound Grid Control." Copy the following script and paste it under this comment.
    <BR>
<Center>
<OBJECT ID="GRID" WIDTH=600 HEIGHT=200 Datasrc="#ADC"
 CODEBASE="http://<%=Request.ServerVariables("SERVER_NAME")%>/MSADC/Samples/sheridan.cab"
 CLASSID="CLSID:AC05DC80-7DF1-11d0-839E-00A024A94B3A">
    <PARAM NAME="_Version"	    VALUE="131072">
    <PARAM NAME="BackColor"     VALUE="-2147483643">
    <PARAM NAME="BackColorOdd"  VALUE="-2147483643">
    <PARAM NAME="ForeColorEven" VALUE="0">
    <PARAM NAME="AllowAddNew"   VALUE="TRUE">
    <PARAM NAME="AllowDelete"   VALUE="TRUE">
    <PARAM NAME="AllowUpdate"   VALUE="TRUE">
</OBJECT>
<BR>

    The DATASRC parameter in the grid control's OBJECT tag indicates that the data source will be the RDS.DataControl object ADC. This binds the grid to the returned Recordset and causes the grid to display data when the RDS.DataControl gets a Recordset. The AllowAddNew, AllowDelete, and AllowUpdate parameters enable the grid to take record additions, changes, and deletions from the user.


(Untitled)

Microsoft Remote Data Service Microsoft Remote Data Service *

Add HTML Controls

  1. Search for the words "Tutorial: HTML Controls to Get Recordsets." Copy the following script and paste it under this comment.
    <BR>
<table>
    <tr><td>RDS Server:<td><INPUT NAME=Server SIZE=70>
    <tr><td>Connection:<td><INPUT NAME=Connect SIZE=70>
    <tr><td>Query:<td><INPUT NAME=SQL SIZE=70>
</table>

    This adds some text boxes for users to specify an SQL query to send to a database (specified in the data source name) that will return a disconnected Recordset to the client.

  2. Search for the words "Tutorial: HTML Controls to Navigate the Recordset and Run the Query." Copy the following script and paste it under this comment.
    <BR>
<BR>
<INPUT TYPE=BUTTON NAME="First" VALUE="First" >
<INPUT TYPE=BUTTON NAME="Next" VALUE="Next" >
<INPUT TYPE=BUTTON NAME="Prev" VALUE="Previous" >
<INPUT TYPE=BUTTON NAME="Last" VALUE="Last" >
<INPUT TYPE=BUTTON NAME="Run" VALUE="Run!" >
<INPUT TYPE=BUTTON NAME="Submit" VALUE="Submit Changes" >
</CENTER>

    The First, Next, Previous, and Last buttons will eventually provide a mechanism for users to navigate through the displayed Recordset.


(Untitled)

Microsoft Remote Data Service Microsoft Remote Data Service *

Add Code to Send a Query to the Database

Search for the words "Tutorial: Send a Query to the Database." Copy the following script and paste it under the comment.

<Script Language= "VBScript">
SUB Window_OnLoad
    Server.Value = "http://<%=Request.ServerVariables("SERVER_NAME")%>"
       Connect.Value = "DSN=AdvWorks"
       SQL.Value = "Select * from Products"
END SUB

SUB Run_OnClick
    ADC.Server = Server.Value
    ADC.Connect = Connect.Value
    ADC.SQL = SQL.Value

    ADC.Refresh
END SUB

Note When you specify the data source through the Connect property, you will usually provide a data source name, user ID, and password (for example, "DSN=SalesDB;UID=Manager;PWD=secret;"). With Microsoft Access databases, you don't need to specify a user ID (UID) or password (PWD).


(Untitled)

Microsoft Remote Data Service Microsoft Remote Data Service *

Add Code to Submit Changes to the Database

Search for the words "Tutorial - Submit Changes to the Database." Copy the following script and paste it under the comment.

SUB Submit_OnClick  ' Submit Changes button clicked.
  ADC.SubmitChanges ' Send changes to the DBMS.
  ADC.Refresh	     ' Refresh the recordset.
End Sub

When ADC.SubmitChanges executes, Remote Data Service packages all the update information and sends it to the server via HTTP. The update is all-or-nothing; if a part of the update isn't successful, none of the changes are made, and a status message is returned.


(Untitled)

Microsoft Remote Data Service Microsoft Remote Data Service *

Add Code to Move through the Displayed Recordset

You can use the Move methods with the Recordset in the RDS.DataControl object to navigate through the data records displayed in the data-bound controls on a Web page. For example, suppose you display a Recordset in a grid by binding to an RDS.DataControl object. You can then include First, Last, Next, and Previous buttons that users can click to move to the first, last, next, or previous record in the displayed Recordset. You do this by calling the MoveFirst, MoveLast, MoveNext, and MovePrevious methods of the RDS.DataControl object in the OnClick procedures for the First, Last, Next, and Previous buttons, respectively.

Search for the words "Tutorial: Move Through the Displayed Recordset." Copy the following script and paste it under the comment.

SUB First_OnClick
    ADC.Recordset.MoveFirst
END SUB

SUB Next_OnClick
    If ADC.Recordset.EOF Then	'can not move beyond bottom record
        ADC.Recordset.MoveFirst
        Exit Sub
    End If

    ADC.Recordset.MoveNext
END SUB

SUB Prev_OnClick
    If ADC.Recordset.BOF Then	'can not move beyond top ‘record
        ADC.Recorset.MoveFirst	'Get out of BOF buffer
        ADC.Recordset.MoveLast
        Exit Sub
    End If
    ADC.Recordset.MovePrevious
END SUB

SUB Last_OnClick
    ADC.Recordset.MoveLast
END SUB
</Script>


(Untitled)

Microsoft Remote Data Service Microsoft Remote Data Service *

See the Code in Action

  1. Save the changes to the Tutorial.asp file as a text file and exit your text editor. Be sure your text editor doesn't replace the .asp file name extension. An .asp file is an Active Server Pages script file.

  2. To verify the ASP page you've created works, point your browser to http://<webservername>/MSADC/Samples/Tutorial/Tutorial.asp, where <webservername> is the actual name of your Web server.

Note You must access your ASP page by pointing to the address. It won't open correctly if you use the Open command on the File menu, or double-click the .asp file.

When you load the page, click Run! to fill the grid with data. You can change the query or other parameters and click Run! again to see other data.


Tutorial: Address Book

This sample application shows you how to use Remote Data Service to build a simple, data-aware Web application — an online corporate address book. This tutorial is useful for Visual Basic®, Scripting Edition (VBScript) and ActiveX™ programmers who want to learn how to use data-aware ActiveX controls with Remote Data Service, and for more experienced application developers who want to build data-centric Web applications.

This tutorial assumes you know how to use basic HTML layout tags and program with ActiveX controls.

The Address Book tutorial lessons will guide you through:

  • Making sure you meet the system requirements to run this application.

  • Setting up the environment to connect to a database, and running an SQL query to copy the sample data.

  • Setting up the HTML framework on the Web page, and writing VBScript code to handle user events.

Introduction to Address Book

The Address Book sample application is an online address book that you can use to publish a directory over an intranet. The address book is designed so that a user can enter a search string in one or more fields to request information about employees. To show you the basic features of Remote Data Service, the sample application is intentionally kept small, with a minimum number of objects and search fields.

The application front end consists of the following parts:

  • Text boxes that act as search fields for different kinds of information about an employee.

  • Command buttons to build queries, clear search fields, update the database with employee information, or cancel pending changes.

  • A spreadsheet-like grid that displays the search results and is bound to a back-end database through a nonvisual RDS.DataControl data-binding object.

  • Buttons that let you navigate the rows of data displayed in the grid.


Address Book Example: Running the Address Book Sample Application

Microsoft Remote Data Service Microsoft Remote Data Service *

Running the Address Book Sample Application

To get the Address Book application up and running quickly, follow this procedure.

To run this application

  1. Make sure you meet the system requirements.

  2. Set up the ODBC System DSN.

  3. Run the SQL script to load the data into your Microsoft SQL Server database.

  4. Make sure that Microsoft® SQL Server is running. Click Start, point to Programs, point to Microsoft SQL Server 6.5, and then click SQL Service Manager. If the stoplight is green, then SQL Server is running. If it isn't, click Start/Continue.

  5. In Microsoft Internet Explorer 4.0 or later, type the following address:

    http://webserver/msadc/samples/AddressBook/AddrBook.asp

    where webserver is the name of the Web server where the Remote Data Service server components are installed, and where you created the System DSN.

  6. You can then try various scenarios in the Address Book sample application, such as looking for a person based on his or her e-mail name, listing all persons with the title "Program Manager," or editing and updating existing records. Click on the Find Button to fill the data grid with all the available names.

See Also To learn more about the code behind the objects in the Address Book sample application, see "Address Book Sample Application Code Overview."


System Requirements for the Address Book Application

To set up the Address Book sample application, you need to meet the following software and database requirements.

Software Requirements

The server computer software requirements for running this Web application include:

  • Microsoft® Windows NT® Server x86, version 4.0 Service Pack 3 or later.

  • Microsoft Internet Information Server (IIS) 3.0 or later, with Active Server Pages.

  • Server-side DLLs for Remote Data Service. (Remote Data Service setup does this for you automatically.)

The client computer software requirements for running this Web application include:

  • Microsoft Internet Explorer 4.0 or later.

  • Microsoft Windows NT Workstation or Microsoft Windows® 95.

  • Client-side DLLs for Remote Data Service installed on the client computer. They are already included as part of the Internet Explorer 4.0 installation.

See Also For more information about installing Remote Data Service, see "Setting Up Remote Data Service."

Database Requirements

To use this sample, you must have:

  • An operational Microsoft SQL Server version 6.5 database.

  • Access permissions to the database.

  • Write privileges to populate the database with the sample data.

  • Verification of the populated data through Enterprise Manager or ISQL utilities.

If you don't have privileges, your database administrator may need to set up the system and give you access permission to the database, or set up the database for you.

Once you meet these database requirements, follow the instructions in "Running the Address Book SQL Script" and "Setting Up an ODBC Connection for Address Book.”


Address Book Example: Running the Address Book SQL Script

Microsoft Remote Data Service Microsoft Remote Data Service *

Running the Address Book SQL Script

You must use either the ISQL command-line utility or the SQL Server Enterprise Manager to run an SQL script that:

  • Creates a new database, AddrBookDB, on the default device.

  • Connects to the correct database (AddrBookDB; if you rename your database, make sure you change the Database Name in the ODBC connection DSN setup).

  • Creates an Employee table.

  • Populates the table with sample data.

  • Runs a simple SELECT statement to verify the population of the database table.

  • Sets up a user account called "ADCDemo" with a password of "ADCDemo."

You must run the supplied SQL script file (Sampleemp.sql) to create and populate the Employee table. By default, the Employee table is created in a newly created database, AddrBookDB, on the local SQL server.

To run the Sampleemp.sql script

  1. Click Start, point to Programs, then point to Microsoft SQL Server 6.5. Click SQL Enterprise Manager.

  2. From the Tools menu choose SQL Query Tool.

  3. Click the Load SQL Script button (the open folder on the toolbar) and browse to Program Files\Common Files\System\MSADC\Samples\AddressBook.

  4. Choose the file sampleemp.sql. Click Open. Click the Execute Query button (the green arrow on the tool bar.

  5. After it executes close the Query and Enterprise Manager windows.


Address Book Example: Setting Up an ODBC Connection for Address Book

Microsoft Remote Data Service Microsoft Remote Data Service *

Setting Up an ODBC Connection for Address Book

You need to set up an ODBC System data source name (DSN) on the Web server where the Remote Data Service server components will be installed.

This setup assumes that the Employee table was created in the AddrBookDB database on a local SQL Server running on the Web server by running the SQL script. If you want to use another database or another SQL Server running on a separate server, then you must change the values for Server and Database Name in the ODBC SQL Server Setup dialog box. If you do so, you will also have to make small changes in the included AddrBook page.

To set up the DSN for a Windows NT® client

  1. On the Web server, click Start, point to Settings, and then click Control Panel.

  2. In Control Panel, double-click the ODBC icon.

  3. On the System DSN tab, click Add.

  4. In the Create New Data Source box, select SQL Server and click Finish.

  5. Follow the instructions in the "Create a New Data Source to SQL Server" wizard. If you need assistance, click Help in the wizard dialog box.

  6. When you are finished, click OK to return to the ODBC Data Source Administrator dialog box. Click Close to exit ODBC setup.

To set up the DSN for a Windows 95® client

  1. On the Web server, click Start, point to Settings, and then click Control Panel.

  2. In Control Panel, double-click the ODBC icon.

  3. Click System DSN.

  4. In the System Data Sources box, click Add, select SQL Server, and click OK.

  5. Follow steps 5 and 6 in the previous Windows NT client procedure.


Address Book Sample Application Code Overview

The program code for the Address Book application is organized into the following sections. Each section highlights a group of the application's major components, shows the source code for the components, and describes how the code works.

Each section also includes the VBScript code that is executed in response to user events, such as a click. The VBScript part of the Address Book application assembles search text into queries, sends the requests to the server, identifies where to display received results from the server, and handles all button click events.
Code section | Description
HTML framework | Contains the HTML skeleton enclosing the application code.
Text boxes | Act as search fields for different kinds of information about an employee.
Command buttons | Build queries, clear search fields, update the database with employee information, or cancel pending changes.
Spreadsheet-like grid | Displays the search results and is bound to a back-end database through a nonvisual RDS.DataControl data-binding object.
RDS.DataControl data-binding object | Binds data from the Microsoft® SQL Server database to the grid on the client HTML page.
Navigation buttons | Used to navigate the rows of data displayed in the grid.
VBScript initialization code | Initializes the data grid column headings and grid title.

The Address Book sample application is structured so that you will learn how to build a simple Remote Data Service Web application in incremental steps, adding functionality at each step. For ease of presentation, the tutorial omits repetitive code, and does not always describe code portions according to their sequence in the program. Click here if you want to view the complete source code for the Address Book application.

Copy and paste the code from the tutorial topics into your project using a text editor such as Notepad. Save the project as Tutorial2.asp in your Program Files\Common Files\System\Msadc\Samples\Tutorial directory. To view it, in Internet Explorer 4.0, type http://webserver/msadc/samples/Tutorial/Tutorial2.asp

Where webserver is the name given to your Windows NT® Web server running Internet Information Server and ASP.


HTML Framework for Address Book

The first step in building a Remote Data Service application is to set up the standard HTML Web page framework. The HTML skeleton contains the program code for the application objects you use, such as buttons, text boxes, and data-aware controls.

The following code fragment shows the HTML skeleton for the Address Book application. This part includes the standard HTML heading and page structure tags, comments identifying the application, and Web page text, font, and color information.

Comments are added at locations where the application objects (such as buttons, text boxes, data-aware controls) are located. These are places where you can drop in your own application components. Click those placeholder comments to take you to descriptions of those parts of the application.

Note Most of the common HTML tags, and those that define the Web page background attributes, will not be defined here. The SCRIPT tag indicates that control is passed to a scripting language, which in this case, is VBScript.

<HTML>
<HEAD>
<TITLE>Corporate Address Book</TITLE>
</HEAD>

<!--
    Purpose:	To provide a company directory search service for Web users.
    Written By:	Microsoft Remote Data Service Team, Microsoft Corp.
    Date:		April, 1997
-->

<BODY BACKGROUND="Arcadia.gif" LANGUAGE="VBScript" onload="Load">
<tr>
    <td align="center" width="40%">
        <table border="2" cellpadding="7" cellspacing="7">
            <tr>
                <td width="100%"><font color="#160B5A"><font
                size="4"><strong>Arcadia Bay Corporate Phone Directory</strong></font></font></td>
            </tr>
        </table>
        </td>
</tr>

<hr>
<h2><font color = "#160B5A">Search Parameters</h2>
<h5><font color = "#160B5A">Please enter one or more search patterns and press FIND to search.</h5>

<PRE>First Name
<!-- HTML CODE FOR TEXT BOXES GOES HERE -->

<!-- HTML CODE FOR COMMAND BUTTONS GOES HERE GOES HERE-->
<hr>
<h2><font color = "#400040">Search Results</h2>
</B>
<br>
<!-- HTML CODE FOR DATA GRID GOES HERE -->
<!-- HTML CODE FOR NAVIGATION BUTTONS GOES HERE -->

<!-- CODE FOR RDS.DATACONTROL OBJECT GOES HERE -->

<SCRIPT Language="VBScript">

<!-- VBSCRIPT CODE FOR INITIALIZING CLEARING TEXT BOXES, SUBMITTING A QUERY, NAVIGATING THROUGH THE DISPLAYED RECORDSET, SAVING CHANGES TO A RECORD, AND CANCELING ANY PENDING  CHANGES GOES HERE. -->
</SCRIPT>

<BR>
<font color = "#400040">This site powered by Microsoft Remote Data Service. </font>
</BODY>
</HTML>


Address Book Text Boxes

The Address Book application contains four text boxes for entering search phrases (for example, the First Name box). The following HTML code defines the text box objects:

<PRE> First Name     <INPUT NAME=SFirst SIZE=30> </PRE>

<PRE> Last Name      <INPUT NAME=SLast  SIZE=30> </PRE>

<PRE> Title          <INPUT NAME=STitle SIZE=30> </PRE>

<PRE> E-mail Alias   <INPUT NAME=SEmail SIZE=30> </PRE>

The intrinsic INPUT control is built into HTML. The NAME parameter defines what it will be called in code. For example, the VBScript code can check SFirst.Value for text in the First Name box. The SIZE parameter lets you adjust the length of the text box, in characters.


Address Book Data-Binding Object

The Address Book application uses the RDS.DataControl object to bind data from the SQL Server database to a visual object (in this case, a grid display) in the application's client HTML page. The event-driven VBScript program logic uses the RDS.DataControl to:

  • Query the database, send updates to the database, and refresh the data grid.

  • Let users move to the first, next, previous, or last record in the data grid.

The following code defines the RDS.DataControl component:

<OBJECT classid="clsid:BD96C556-65A3-11D0-983A-00C04FC29E33"
    ID=SControl Width=1 Height=1>
    <PARAM NAME="SERVER" VALUE="http://<%=Request.ServerVariables("SERVER_NAME")%>">
    <PARAM NAME="CONNECT" VALUE="dsn=ADCDemo;UID=ADCDemo;PWD=ADCDemo;">
</OBJECT>

The OBJECT tag defines the RDS.DataControl component in the program. The tag includes two types of parameters:

  • Those associated with the generic OBJECT tag.

  • Those specific to the RDS.DataControl object.

Generic OBJECT Tag Parameters

The following tables describes the parameters associated with the OBJECT tag.
Parameter | Description
CLASSID | A unique, 128-bit number that identifies the type of embedded object to the system. This identifier is maintained in the local computer's system registry. (For the class IDs of the RDS.DataControl object, see the RDS.DataControl Object in the API Reference.)
ID | Defines a document-wide identifier for the embedded object that is used to identify it in code.

RDS.DataControl Tag Parameters

The following table describes the parameters specific to the RDS.DataControl object. (For a complete list of the RDS.DataControl object parameters, and when to implement them, see the RDS.DataControl object in the API Reference.)
Parameter | Description
SERVER | If you are using HTTP, the value is the name of the server computer preceded by HTTP://.
CONNECT | The first part of this VALUE indicates the System DSN that points to the data source; the second and third parts specify the user ID and password needed to access the data source (for example, "DSN=ADCDEMO;UID=adcdemo;PWD=adcdemo;"). If you need assistance, your system database administrator can probably provide the information for you.
SQL | Sets or returns the query string used to retrieve the Recordset.


Address Book Command Buttons

The Address Book application includes the following command buttons:

  • A Find button to submit a query to the database.

  • A Clear button to clear the text boxes before starting a new search.

  • An Update Profile button to save changes to an employee record.

  • A Cancel Changes button to discard changes.

Find Button

The following HTML statement defines the Find button. This HTML statement appears before the VBScript section of the program. Copy and past this control just following the Comment for HTML Command Buttons.

<INPUT TYPE=BUTTON NAME="Find" 	VALUE="Find">

Find_OnClick Sub Procedure

Clicking the Find button activates the VBScript Find_OnClick Sub procedure, which builds and sends the SQL query. When you complete the project click this button to fill the data grid.

Building the SQL Query

The first part of the Find_OnClick Sub procedure builds the SQL query, a phrase at a time, by appending text strings to a global SQL SELECT statement. It begins by setting the variable myQuery to an SQL SELECT statement that requests all rows of data from the data source table. Copy and paste this code beneath the opening <Script> tag.

Sub Find_OnClick

myQuery = "Select FirstName, LastName, Title, Type, Email, " _

& "ManagerEmail, Building, Room, Phone from Employee"

Next, the Sub procedure scans each of the four input boxes of the Address Book. Copy and paste this code within the Find sub routine.

    If (SFirst.Value <> "") Then
        myQuery = myQuery + " where FirstName like '" + SFirst.Value + "%'"
    End If

    IF (SLast.Value <> "") Then
        myQuery = myQuery + " where LastName like '" + SLast.Value + "%'"
    End If

    If (STitle.Value <> "") Then
        myQuery = myQuery + " where Title like '" + STitle.Value + "%'"
    End If

    If (SEmail.Value <> "") Then
        myQuery = myQuery + " where Email like '" + SEmail.Value + "%'"
    End If

Each If statement scans its corresponding text box for text. If the text box contains text, the Then statement executes, appending the quoted text to the global SELECT statement contained in the variable myQuery. Because the program uses the word like in building the SQL statements, the queries are substring searches rather than exact matches.

For example, if the Last Name box contained the entry "Berge" and the Title box contained the entry "Program Manager", the SQL statement (value of myQuery) would read:

Select FirstName, LastName, Title, Email, Building, Room, Phone from Employee where lastname like 'Berge%' and title like 'Program Manager%'

If the query was successful, all persons with a last name containing the text "Berge" (such as Berge and Berger), with a title containing the words "Program Manager" (for example, Program Manager, Advanced Technologies) are displayed in the data grid.

Preparing and Sending the Query

The last part of the Find_OnClick Sub procedure consists of two statements. The first statement assigns the SQL query property of the RDS.DataControl object equal to the dynamically built SQL query. The second statement causes the RDS.DataControl object (SControl) to query the database, and then display the new results of the query in the grid. Copy and paste this code to the Find subroutine.

    SControl.SQL = myQuery
    SControl.Refresh
End Sub

Clear Button

The following HTML statement defines the Clear button. This HTML statement appears before the VBScript section of the program. Copy and paste this code just following the Find HTML button.

<INPUT TYPE=BUTTON NAME="Clear" 	VALUE="Clear">

The INPUT tag defines an element, such as a button, option button, check box, or text. You use the TYPE parameter to specify the element, which in this case, is a button. The NAME parameter defines what the button will be called in code. The VALUE parameter specifies the labels associated with the button (Clear) that will be displayed on the page.

Clear_OnClick Sub Procedure

Clicking the Clear button activates the VBScript Clear_OnClick Sub procedure. Copy and paste this code within the <Script> </Script> tags.

Sub Clear_OnClick
    SFirst.Value=""
    SLast.Value=""
    STitle.Value=""
    SEmail.Value=""
End Sub

When the Sub procedure is executed, it initializes each of the four HTML input boxes, which it identifies by the NAME parameter of the ID tag. The property .Value indicates characters in the text box object that are displayed on the Web page. The procedure replaces any text with a zero length string ("") in preparation for a new find.

Update Profile Button

The following code defines the Update Profile button. This HTML statement appears before the VBScript section of the program. Copy and paste this HTML control just following the Clear button.

<INPUT TYPE=BUTTON NAME="Update" 	VALUE="Update Profile">

The INPUT tag defines an element, such as a button, option button, check box, or text. The NAME parameter defines what the button will be called in code. You use the TYPE parameter to specify the type of form element, which in this case, is a button. The VALUE parameter specifies the label associated with the button (Update Profile).

Update_OnClick Sub Procedure

Clicking the Update Profile button activates the VBScript Update_OnClick Sub procedure, which executes the RDS.DataControl object's (SControl) SubmitChanges and Refresh methods. Copy and paste this code within the <Script> </Script> tags.

Sub Update_OnClick
    SControl.SubmitChanges
    SControl.Refresh
End Sub

When SControl.SubmitChanges executes, the program packages all the update information and sends it to the server via HTTP. The update is all-or-nothing; if a part of the update isn't successful, none of the changes are made, and a status message is returned. SControl.Refresh isn't necessary after SubmitChanges with Remote Data Service 1.5, but it ensures the data is fresh.

Cancel Changes Button

The following code defines the Cancel Changes button. This HTML statement appears before the VBScript section of the program. Copy and paste this HTML control just following the Update button.

<INPUT TYPE=BUTTON NAME="Cancel" 	VALUE="Cancel Changes">

Cancel_OnClick Sub Procedure

Clicking Cancel Changes activates the VBScript Cancel_OnClick Sub procedure, which executes the RDS.DataControl object's (SControl) CancelUpdate method. Copy and paste this code within the <Script> </Script> tags.

Sub Cancel_OnClick
      SControl.CancelUpdate
End Sub

When SControl.CancelUpdate executes, it discards any edits that a user has made to an employee record on the data grid since the last query or update. It restores the original values.


Address Book Data Grid

The grid control is a spreadsheet-like object. The Address Book application uses it to display data returned from queries.

The following HTML code defines the grid control. Copy and paste this code just following the comment tag which refers to it.

<OBJECT CLASSID="clsid:AC05DC80-7DF1-11d0-839E-00A024A94B3A"
    CODEBASE="http://<%=Request.ServerVariables("SERVER_NAME")%>/MSADC/Samples/Sheridan.cab"
    ID=GRID1
DATASRC=#SControl
HEIGHT=125
WIDTH=495>
    <PARAM NAME="AllowAddNew"   VALUE="TRUE">
    <PARAM NAME="AllowDelete"   VALUE="TRUE">
    <PARAM NAME="AllowUpdate"   VALUE="TRUE">
    <PARAM NAME="BackColor"     VALUE="-2147483643">
    <PARAM NAME="BackColorOdd"  VALUE="-2147483643">
    <PARAM NAME="ForeColorEven" VALUE="0">
</OBJECT>
<HR>

The OBJECT tag defines the grid control component to the program. The tag includes parameters that allow you to set the size of the grid, change the data displayed when information is updated or deleted, and dynamically change the number of rows according to the results of a query. The other parameters set the color properties of the grid control.

The following table describes the parameters associated with the OBJECT tag.
Parameter | Description
CLASSID | A unique, 128-bit number that identifies the type of embedded object to the system. This identifier is maintained in the local computer's Windows registry. It is specific to this Sheridan grid control.
CODEBASE Specifies the location of a source file of the object being called, if it is not on the client computer.

In this case, CODEBASE specifies the location of a .cab file containing the Sheridan ActiveX™ controls. The program uses Active Server Pages script (the code enclosed by the <% and %> signs) to request the server name part of the URL.

ID | Defines a document-wide identifier for the embedded object.
DATASRC | Identifies the data source that is used to bind the data grid to back-end data (in this case, SControl, which is an RDS.DataControl object).
WIDTH and HEIGHT | Identifies the dimensions of the control, in pixels.

For the Address Book application, the grid object uses several additional parameters to enable editing. Without these specifiers, the grid can only present a read-only, static view of the editable data. The following table lists editing parameter settings for the grid control in this sample application.
Parameter | Value | Description
AllowAddNew | TRUE | Allows an existing data display to add new records.
AllowDelete | TRUE | Allows an existing data display to remove records.
AllowUpdate | TRUE | Allows changes to a cell in the grid.

The BackColor, BackColorEven, and BackColorOdd parameters set the grid to a white background with black text.


Address Book Navigation Buttons

The Address Book application displays the navigation buttons at the bottom of the Web page. You can use the navigation buttons to navigate around the data in the grid display, by selecting either the first or last row of data, or rows adjacent to the current selection.

The following code defines the navigation buttons. These HTML statements appear before the VBScript section of the program. Copy and paste these controls following the comment tag which refers to them.

<INPUT TYPE=BUTTON NAME="First" 		VALUE="First">
<INPUT TYPE=BUTTON NAME="Prev" 		VALUE="Previous">
<INPUT TYPE=BUTTON NAME="Next"		VALUE="Next">
<INPUT TYPE=BUTTON NAME="Last"		VALUE="Last">

HTML uses the INPUT tag to define a form element, such as a button, option button, check box, or text. You use the TYPE parameter to specify the type of form element, which in this case is a button. The NAME parameter defines what the button will be called in code. The VALUE parameter specifies the labels associated with the button (First, Previous, Next, and Last) that are displayed on the page.

When a user clicks a button, an event is generated, and VBScript activates the appropriate navigation Sub procedure.

Navigation Sub Procedures

The Address Book application contains several procedures that allow users to click the First, Next, Previous, and Last buttons to move around the data. To enable movement, you can specify the method of the RDS.DataControl object (SControl) to the type of movement you want. The method differs for each navigation button.

For example, clicking the First button activates the VBScript First_OnClick Sub procedure. The procedure executes a MoveFirst method, which makes the first row of data the current selection. Clicking the Last button activates the Last_OnClick Sub procedure, which invokes the MoveLast method, making the last row of data the current selection. The remaining navigation buttons work in a similar fashion. Copy and paste this code within the <Script> </Script> tags.

' Move to the first record in the bound recordset.
Sub First_OnClick
    SControl.Recordset.MoveFirst
End Sub

' Move to the next record from the current position
' in the bound recordset.
Sub Next_OnClick
    If SControl.Recordset.EOF Then	'cannot move beyond bottom record
        SControl.Recordset.MoveFirst
        SControl.Recordset.MoveNext
        Exit Sub
    End If

    SControl.Recordset.MoveNext

End Sub

' Move to the previous record from the current position in the bound
' recordset.
Sub Prev_OnClick
    If SControl.Recordset.BOF Then	'cannot move beyond top record
        SControl.Recordset.MoveLast	'Get out of BOF buffer
        SControl.Recordset.MovePrevious
        Exit Sub
    End If
    SControl.Recordset.MovePrevious

End Sub

' Move to the last record in the bound recordset.
Sub Last_OnClick
    SControl.Recordset.MoveLast
End Sub


Address Book: VBScript Initialization Code

Microsoft Remote Data Service Microsoft Remote Data Service *

VBScript Initialization Code

The VBScript section of the Address Book application first declares the variable myQuery. This variable will contain the SQL query that is dynamically built from text in the search fields, and sent to the database. Later, the Find_OnClick Sub procedure sets the value of this variable.

Dim myQuery

The remaining initializations are contained in the Load Sub procedure. These include adding a caption to the data grid. The WHERE clause is such that no records are pulled, so that only column headings are provided. Copy and paste this code within the <Script> </Script> tags.

Sub Load
    Grid1.Caption = "Arcadia Bay Corporate Phone Directory"

    ' Initialize the data grid with column names only.
    SControl.SQL = "Select FirstName, LastName, Title, Email, " _
        & "Building, Room, Phone from Employee where 2 < 1"
    SControl.Refresh
End Sub


Address Book Example: Source Code

Microsoft Remote Data Service Microsoft Remote Data Service *

Address Book Application Source Code

The following code is the complete source code for the Address Book sample application.

<HTML>
<HEAD>
<TITLE>Corporate Address Book</TITLE>
</HEAD>

<!--
    Purpose:	To provide a company directory search service for Web users.
    Written By:	Microsoft Remote Data Service Team, Microsoft Corp.
    Date:		April, 1997
-->

<BODY BACKGROUND="Arcadia.gif" LANGUAGE="VBScript" onload="Load">
<tr>
    <td align="center" width="40%">
        <table border="2" cellpadding="7" cellspacing="7">
            <tr>
                <td width="100%"><font color="#160B5A"><font
                size="4"><strong>Arcadia Bay Corporate Phone Directory</strong></font></font></td>
            </tr>
        </table>
        </td>
</tr>

<hr>
<h2><font color = "#160B5A">Search Parameters</h2>
<h5><font color = "#160B5A">Please enter one or more search patterns and press FIND to search.</h5>

<FONT COLOR = "#160B5A"><B>

<PRE> First Name     <INPUT NAME=SFirst SIZE=30> </PRE>

<PRE> Last Name      <INPUT NAME=SLast  SIZE=30> </PRE>

<PRE> Title          <INPUT NAME=STitle SIZE=30> </PRE>

<PRE> E-mail Alias   <INPUT NAME=SEmail SIZE=30> </PRE>

<!--
    Command button options:
    -----------------------
    Find		Submit a search request to the database.
    Clear		Clear the QBE fields (labor saving function only).
    Update Profile	Send updated "address profile" back to the database.
    Cancel Changes	Undo all changes since the last Update Profile.
-->

<INPUT TYPE=BUTTON NAME="Find" 	VALUE="Find">
<INPUT TYPE=BUTTON NAME="Clear" 	VALUE="Clear">
<INPUT TYPE=BUTTON NAME="Update" 	VALUE="Update Profile">
<INPUT TYPE=BUTTON NAME="Cancel" 	VALUE="Cancel Changes">

<hr>
<h2><font color = "#400040">Search Results</h2>
</B>
<br>

<!--
    This Sheridan DataGrid control (SGrid) are initialized to
    allow changes to the data - these changes will be saved
    to the database when the Update Profile button is pressed.
-->

<Object CLASSID="clsid:AC05DC80-7DF1-11d0-839E-00A024A94B3A"
    CODEBASE="http://<%=Request.ServerVariables("SERVER_NAME")%>/MSADC/Samples/Sheridan.cab"
    ID=GRID1
        datasrc=#SControl
        HEIGHT=125
        WIDTH=495>
    <PARAM NAME="AllowAddNew"   VALUE="TRUE">
    <PARAM NAME="AllowDelete"   VALUE="TRUE">
    <PARAM NAME="AllowUpdate"   VALUE="TRUE">
    <PARAM NAME="BackColor"     VALUE="-2147483643">
    <PARAM NAME="BackColorOdd"  VALUE="-2147483643">
    <PARAM NAME="ForeColorEven" VALUE="0">
</OBJECT>

<br>
<br>
<INPUT TYPE=BUTTON NAME="First" 	VALUE="First">
<INPUT TYPE=BUTTON NAME="Prev" 	VALUE="Previous">
<INPUT TYPE=BUTTON NAME="Next"	VALUE="Next">
<INPUT TYPE=BUTTON NAME="Last"	VALUE="Last">
<hr>

<!-- Non-visual controls - RDS.DataControl -->

<OBJECT classid="clsid:BD96C556-65A3-11D0-983A-00C04FC29E33"
    ID=SControl
    WIDTH=1 HEIGHT=1>
    <PARAM NAME="SERVER" VALUE="http://<%=Request.ServerVariables("SERVER_NAME")%>">
    <PARAM NAME="CONNECT" VALUE="dsn=ADCDemo;UID=ADCDemo;PWD=ADCDemo;">
</OBJECT>

<!-- VBS scripting for composing queries, updating profiles, and retrieving search results. -->

<SCRIPT LANGUAGE="VBScript">

Dim myQuery

Sub Load
    Grid1.CAPTION = "Arcadia Bay Corporate Phone Directory"

    'Initialize data grid with column names only.
    SControl.SQL = "Select FirstName, LastName, Title, Email, Building, Room, Phone from Employee where 2 < 1"
    SControl.Refresh

End Sub

'Implement "Clear" button - clears all of the QBE fields in preparation for a new "Find."

Sub Clear_OnClick
    SFirst.Value=""
    SLast.Value=""
    STitle.Value=""
    SEmail.Value=""
End Sub

'Implement "Find" button - composes a dynamic SQL query to be processed by the database and returns matching records to be bound to the SGrid object.

Sub Find_OnClick

    myQuery = "Select FirstName, LastName, Title, Type, Email, ManagerEmail, Building, Room, Phone from Employee"

    'Check QBE fields and compose a dynamic SQL query.

    IF (SFirst.Value <> "") THEN
        myQuery = myQuery + " where FirstName like '" + SFirst.Value + "%'"
    End IF

    IF (SLast.Value <> "") THEN
        myQuery = myQuery + " where LastName like '" + SLast.Value + "%'"
    End IF

    IF (STitle.Value <> "") THEN
        myQuery = myQuery + " where Title like '" + STitle.Value + "%'"
    End IF

    IF (SEmail.Value <> "") THEN
        myQuery = myQuery + " where Email like '" + SEmail.Value + "%'"
    End IF

    'Set the new query and then refresh the SControl so that the new results are displayed.

    SControl.SQL = myQuery
    SControl.Refresh

End Sub

'Navigation subroutines - based on currency changes to RDS.DataControl (SControl).

'Move to the first record in the bound recordset.

Sub First_OnClick
      SControl.Recordset.MoveFirst
End Sub

'Move to the next record from the current position in the bound recordset.

Sub Next_OnClick
    If SControl.Recordset.EOF Then	'cannot move beyond bottom record
        SControl.Recordset.MoveFirst
        SControl.Recordset.MoveNext
        Exit Sub
    End If

    SControl.Recordset.MoveNext

End Sub

'Move to the previous record from the current position in the bound recordset.

Sub Prev_OnClick
If SControl.Recordset.BOF Then	'cannot move beyond top record
        SControl.Recordset.MoveLast	'Get out of BOF buffer
        SControl.Recordset.MovePrevious
        Exit Sub
    End If
    SControl.Recordset.MovePrevious
End Sub

'Move to the last record in the bound recordset.

Sub Last_OnClick
      SControl.Recordset.MoveLast
End Sub

'Submits edits made and pull a clean copy of the new data.

Sub Update_OnClick
      SControl.SubmitChanges
    SControl.Refresh        ' A Refresh is not required in ADC 1.5 after a SubmitChanges, but it ensures fresh data.
End Sub

'Cancel edits and restores original values.

Sub Cancel_OnClick
      SControl.CancelUpdate
End Sub

</SCRIPT>

<BR>
<font color = "#400040">This site powered by Microsoft Remote Data Service. </font>
</BODY>
</HTML>


What's New in Remote Data Service 1.5

Remote Data Service — A New Name for the Advanced Data Connector

The Advanced Data Connector (ADC) has now been integrated with ActiveX Data Objects (ADO) to provide data remoting within the same programming model as ADO. This makes it easier to design, code, and deploy both Web-based and LAN-based applications. For example, the ADOR.Recordset now supports all of the methods and properties available on the ADODB.Recordset object.

To clarify the relationship of ADC to ADO, the Advanced Data Connector is now known as the Remote Data Service (RDS) of ADO.

The objects also have new names. The AdvancedDataControl is now the RDS.DataControl, the AdvancedDataFactory is now the RDSServer.DataFactory, and the AdvancedDataSpace is now the RDS.DataSpace. The prefix (RDS for DataControl and DataSpace; RDSServer for DataFactory) is required. Of course, for backward-compatibility, the old names are still recognized — you don’t need to rewrite any of your version 1.0 code.

Client Cursor Engine — A New Name for the Virtual Table Manager

The new and improved VTM is now known as the Client Cursor Engine, because it provide client-side cursor functionality. Other Client Cursor Engine improvements for Version 1.5 include asynchronous population and updatability with other databases.

Asynchronous Population

The Client Cursor Engine now lets you open and populate a disconnected Recordset asynchronously. The following DataControl method and properties make this possible.
Property/Method | Description
ExecuteOptions | Indicates whether the DataControl object’s Refresh method is to execute asynchronously by running on a separate thread.
FetchOptions | Indicates whether the fetching of records into an DataControl object’s Recordset is to occur asynchronously.
ReadyState | Returns the state of the DataControl object's Recordset, such as whether the Recordset load has completed.
Cancel | Cancels the currently running asynchronous execution or fetch.

Updatability with Other Databases

Updatability is defined as being able to insert and delete records, and update the contents of one or more records of a result set.

With the Client Cursor Engine in Remote Data Service 1.5, you can update a number of databases, including Microsoft SQL Server, Microsoft Access, Oracle, and so forth. This is different from previous versions, which supported updatability only with Microsoft SQL Server databases.

Sorting and Filtering

The following DataControl properties and methods provide sorting and filtering functionality on the client-side cache. The sorting functionality orders records by values from one column. The filtering functionality displays a subset of the original Recordset based on a find criteria, while the full Recordset is maintained in the cache.
Method or Property | Description
SortColumn | Specifies the name or alias of the column to sort the Recordset by.
SortDirection | Specifies the sort order; True = ascending and False = descending.
FilterValue | Specifies a value to filter records with, for example, 'Programmer' or 125.
FilterCriterion | Specifies the evaluation operator of the FilterValue to the records. Can be any one of the following: <, <=, >, >=, =, <>
FilterColumn | Specifies the column name to evaluate the filter criteria on.
Reset | Executes the sort or filter based on the properties set. Rewrites the Recordset as read-only if it is not already read-only. Does not re-execute the query. Reset will fail if there are pending changes.

Operability within Internet Explorer 4.0

Remote Data Service now supports Microsoft Internet Explorer 4.0. Internet Explorer 4.0 includes all of the Remote Data Service client components, so that you don't need to use the CODEBASE parameter to download the Remote Data Service .cab file. This makes it easier to deploy Remote Data Service applications.

Data Binding Extensions to HTML

Two relationships are key to data binding with Internet Explorer 4.0: source and consumer. Data consumers specify binding by referencing the data source to which they are bound. To achieve this, your data consumers (controls such as text boxes or grids) specify the source of the data and the type of the data being bound. You specify the DATASRC parameter to identify the data source object (in this case, the DataControl object), and a DATAFLD parameter to identify a column of the data set.

This is slightly different coding notation from previous versions of Remote Data Service, which used the DataControl object’s Bindings property to bind controls to data.

See Also For more information about how to use the data binding extensions to HTML with Internet Explorer 4.0, see the Data Binding section of this SDK, under Dynamic HTML.

ConvertToString Method

The ConvertToString method of the DataFactory object converts a Recordset to a MIME string that represents the data.

CreateRecordset Method

The CreateRecordset method now applies to the DataControl object and the DataFactory object. This means that you can now create a Recordset object directly with the DataControl on the client side whereas with 1.0 you could only do this on the server side. This results in fewer network roundtrips, and provides more flexibility for your application.

SourceRecordset Property vs. Recordset Property

The DataControl object now supports Recordset and SourceRecordset properties. SourceRecordset is a write-only property and Recordset is a read-only property.

HTTP Protocol Settings

RDS now supports all three of the Microsoft Internet Information Server Permissions settings.


Welcome to Scriptlet Technology

Microsoft® Scripting Components (scriptlets) provide you with an easy but powerful way to create controls from Web pages (.htm files) that use Microsoft Dynamic HTML. You can use scriptlets as ordinary controls in applications such as Microsoft Visual Basic, Microsoft Internet Explorer 4.0, and Microsoft Visual InterDev.

To | See
Understand scriptlets and how they work. | Scriptlet Overview
Create scriptlets and add them to your applications | Designing and Using Scriptlets
Find descriptions of the properties, methods, and events that you can use when using a scriptlet in your application. | Scriptlet Container Object Reference
Find descriptions of the properties, methods, and events that you can use when creating a scriptlet. | Scriptlet Model Extensions


Scriptlets Overview

A scriptlet is a Web page based on Dynamic HTML (DHTML) that you can use as a control in any application that supports controls. The scriptlet is a complete Web-ready .htm file, but includes information that allows you to work with it as a control — you can get and set its properties, call its methods, and so on.

Scriptlets:

  • Allow Web page authors to create reusable user interface components without having to harness the full power of C, C++, or other control-building environments.

  • Allow developers using Visual Basic, Visual InterDev, and other development environments that support controls to make use of features built into Web pages.

  • Are easy to create and maintain.

  • Are small and efficient.

For example, with scriptlets you can:

  • Use the graphical and hypertext capabilities of Web pages as visually rich interface for your application.

  • Change the appearance and behavior of Web pages from within the host environment. For example, you can use a Visual Basic application to read information from files and then write it into the scriptlet.

  • Prototype controls that you intend to write in other environments. Because it is quick and easy to put together a scriptlet, you can test ideas. When you have completed your design, you can reimplement the control in another environment, such as C++, Visual Basic, or J++, if you want greater performance or a different means of packaging your control.

How Scriptlets Works

You use scriptlets like a standard control. In the scriptlet, you create any properties, methods, or events that you want by simply creating scripts in common active scripting languages such as JavaScript, Visual Basic Scripting Edition (VBScript), or another language. The scripts rely on the scripting capabilities of DHTML, which gives you a complete object model for elements on the scriptlet.

For example, a scriptlet might be a Web page that contains animation based on DHTML that moves and resizes text on the page. You can write scripts to expose properties that allow another application to set the text, speed, and direction of the animation text, and methods that allow another application to start, stop, and pause the animation.

Note To learn more about using Dynamic HTML in your Web pages, you can view the documentation for the Internet Client SDK located here.

Support for scriptlets is built into Internet Explorer 4.0. You can use the standard OBJECT tag to insert and work with scriptlets as you do any other object on a Web page.

To use the scriptlet in applications that support ActiveX controls, you use a control called the scriptlet container object, which hosts the scriptlet. The host application, such as Visual Basic, uses the scriptlet container object to create a window for the scriptlet and provide a way for the host application to specify what scriptlet to use, where it displays, at what size, and so on. The scriptlet container object also provides the interface for you to set and get the scriptlet's properties, call its methods, and respond to its events.

Scriptlet Security

In a security-aware host application such as Internet Explorer, the scriptlet and any controls contained within it are subject to Internet Explorer 4.0 security. For information about security settings in Internet Explorer 4.0, see Internet Explorer Help.

Typically, the security settings for the zone containing the scriptlet's server must be Medium or Low. If the setting is High, the scriptlet will not download to your computer. If you usually set custom security settings for a zone, set both Script ActiveX controls marked safe for scripting and Initialize and script ActiveX controls not marked as safe to either Prompt or Enable.

The same applies to any controls that the scriptlet contains, including other scriptlets, especially if the scriptlet contains controls that reside on a server in a different zone.

When you distribute an application that uses a scriptlet, make sure that users set the security settings in their copy of Internet Explorer to the correct level to allow them to use your scriptlets.


Designing and Using Scriptlets

You can easily create scriptlets and add them to your applications.

To | See
Choose a method for creating a scriptlet from your Web page | Designing a Scriptlet
Use your scriptlet as a control | Adding Scriptlets to Your Application
React to events in your applications | Defining Event Handlers


Designing a Scriptlet

A scriptlet is simply a DHTML page that uses certain conventions to define its properties, methods, and events.

To define the page as a scriptlet

  • Create a JavaScript Public_Description object to manage properties and methods. With this convention, you explicitly define what properties and methods the scriptlet will make available. Any behavior that is not explicitly declared using the Public_Description object is not available. For details, see Creating a Public_Description Object.

    – or –

  • Use a default interface description. You do not explicitly declare properties or methods. Instead, any variables and functions that follow certain naming conventions become available as properties and methods. You can use this method if you want to create scriptlet properties and methods in an active scripting language other than JavaScript. For details see, Using Default Interface Descriptions.

Using a Public_Description object has several advantages. You can use any names for variables and functions that you want to expose as properties and methods, because you assign them public names in the Public_Description object. In addition, using the Public_Description object provides you with a convenient way to summarize and document the properties and methods that the scriptlet exposes.

In contrast, if you use the default interface descriptions, you must use the public_ prefix on any name that you want to expose. If a scriptlet already happens to have a variable or function with the public_ prefix, it will always be exposed, whether you want it to be or not.

When you create the properties, methods, and events for the scriptlet, you can make full use of the DHTML object model to display text, animate HTML elements, change colors, or define any other behavior that you want the control to have.

You can also use extensions to the DHTML object model that are available as part of the window.external object, which is unique to scriptlets. For a summary of the extensions, see Scriptlet Model Extensions.

Note You can determine from within the .htm file whether it is being used as scriptlet or simply as a standalone Web page. For details, see the version property.


Creating a Public_Description Object

A Public_Description object is a JavaScript object that provides runtime access to the properties and methods defined by the object's constructor function. A skeleton Public_Description object with its constructor function looks like this:

<SCRIPT LANGUAGE="JavaScript">
   var Public_Description = new CreateScriplet();

   Function CreateScriptlet(){
      // statements here to define properties and methods
   }
</SCRIPT>

Note You do not use the constructor function to define events. For details, see Defining Event Handlers.

When you create the Public_Description object, the constructor function that you assign to it can have any name, as long as the corresponding function appears somewhere in the scriptlet. Within the constructor function, you declare the properties and methods that you want to expose within the scriptlet in the following ways:

Constructor syntax | Creates
This.PropertyName = expression; | Creates a read-write property.
This.get_PropertyName = function;
This.put_PropertyName = function; 		Creates a property using a function, which allows you set a property value based on a condition or trigger an event when the property is set. The function called by the property definition can be in any active scripting language. To make a property read-only, do not provide the put_ function declaration; to make it write-only, do not provide the get_ function declaration.
This.method = methodFunction; | Creates a method defined by the function methodFunction.

For example, the following Public_Description object defines two properties and a method. The first property, DefaultTitle, is created as an expression. The second property, CalculatedTitle, is created as a set of functions. The method toggleColor is defined using the function TColor.

<SCRIPT LANGUAGE="JavaScript">
// Public_Description object used to declare scriplet
var Public_Description = new ScriptletObject();

// general object description
function ScriptletObject()
{
   this.DefaultTitle = window.document.title;   //property
   this.get_CalculatedTitle = readCTitle;      //property (read)
   this.put_CalculatedTitle = writeCtitle;      //property (write)
   this.ToggleColor = TColor;                     //method
}

// read function for CalculatedTitle property
function readCTitle(){
   if (window.document.title) == ""
      return "This document has no title";
   else
      return window.document.title;
}

// write function for CalculatedTitle property
function writeCTitle(passedValue){
   if !(passedValue) == ""
      window.document.title = passedValue;
}

// function for ToggleColor method
function TColor(){
   if (window.document.bgcolor) == "#ff0000"{
      // doc is red, make it blue
      window.document.bgcolor = "#0000ff;}
   else{
      // doc is not red, make it red
      window.document.bgcolor = "#ff0000";}
}
</SCRIPT>

See Also

Using Default Interface Descriptions

Handling Standard Events

Defining Custom Events


Using Default Scriptlets

Microsoft Scriptlet Technology Microsoft Scriptlet Technology *

Using Default Interface Descriptions

If there is no Public_Description object defined in the scriptlet, the scriptlet container object exposes properties and methods using variables and functions in the scriptlet that follow certain naming conventions. To expose scriptlet properties and methods, use these conventions:

  • Use the prefix public_ to indicate that a variable or function should be exposed by the scriptlet.

  • To create a read/write property, declare a variable scoped at the page level (that is, not defined inside a function) and give it a public_ prefix.

  • To create a method, define a function with the prefix public_.

  • To create a readable property as a function, define a function with the prefix public_get_.

  • To create a writable property as a function, define a function with the prefix public_put_.

Note When a property or method is exposed, its name in the host application does not have the public_ prefix. For example, if you define a property called public_MyTitle in the scriplet, its name in the host application is MyTitle.

The following table shows examples of variables and functions in a scriptlet, and the resulting interface that they expose in the host application.

Example Exposed As Used in container
var public_Color = "red"
Property
vColor = SC1.Color SC1.Color = "blue"
function public_look(param)
Method
SC1.look(param)
function public_get_C()
Property (read)
x = SC1.C
function public_put_C(param)
Property (write)
SC1.C = "test"
function look()
Not available
(no public_ prefix)
function get_C()
Not available
(no public_ prefix)
var Color = red;
Not available
(no public_ prefix)
var get_Color = red;
Not available
(no public_ prefix)

For example, the following example shows a portion of a page containing a paragraph named "P1." The script block following the paragraph exposes a property called P1Text and a method called SetText.

<P ID=P1>This is a paragraph of text.</P>

<SCRIPT LANGUAGE="JavaScript">
<!--
public_P1Text = P1.innerText
function public_SetText(newText){
   P1.innerText = newText;
}
// -->
</SCRIPT>

The scriptlet reserves the function name prefixes public_get_ and public_put_ to define properties. For example, if the scriptlet contains a function named public_get_MyText, it will be treated as a property called MyText. If you attempt to call the function public_get_MyText as a method using the syntax SC1.get_MyText(), an error will result, because the function itself is exposed only as if it were a property named MyText.

See Also

Creating a Public_Description Object

Handling Standard Events

Defining Custom Events

Adding Scriptlets to Your Application


Adding Scriptlets to Your Application

You can use scriptlets as you would any control.

To add a scriptlet to a Web page

  1. Define the scriptlet using an <OBJECT> tag, setting its TYPE attribute to "text/x-scriptlet".

  2. Specify the scriptlet's URL by setting the DATA attribute in the <OBJECT> tag, as in the following example:
    <OBJECT ID="Scriptlet1"
            TYPE="text/x-scriptlet"
            DATA="http://myserver/sample.htm">

    – or –

    Specify a URL using the object's PARAM tag, as in the following example:

    <OBJECT ID="Scriptlet1" TYPE="text/x-scriptlet" WIDTH=300 HEIGHT=200>
   <PARAM NAME="url" VALUE="http://myserver/sample.htm"
</OBJECT>

    Note If you insert a scriptlet into a Web page using a visual tool such as a toolbox or control insertion dialog box, the resulting object definition might include a CLASSID attribute instead of the TYPE attribute.

To add a scriptlet to a host application

  1. Create a scriptlet container object in your application and set its Name property.

  2. Set the scriptlet container object's url property to the URL of the scriptlet you want to use.

Important If you are adding the scriptlet to a Web page, do not set the url property to the URL of the current page. Doing so causes a recursive call to the page and will cause the browser to stop functioning.

You can add scrollbars if the scriptlet is too small to be displayed within the container object. For details, see scrollbar.

You can also resize the container object from within the scriptlet by using a script to set the DHTML script object's pixelHeight and pixelWidth properties. For example, the following example shows how you can resize the scriptlet container when the scriptlet is first loaded:

<HTML ID="MyPage">
<HEAD>
<SCRIPT LANGUAGE="VBScript">
Sub window_onload()
   MyPage.style.pixelHeight = 300
   MyPage.style.pixelWidth = 400
End Sub
</SCRIPT>
</HEAD>
If you change the .htm file after creating the control, the display in the control is not updated until the next time the page is read. This occurs when the application is run or if you change the url property of the control again.
Note After the scriptlet has been initialized, the F5 key, used to refresh a page in Internet Explorer, is not active in the scriptlet container object.
After creating an instance of the scriptlet, you can write scripts for it as you would for any other control. The object you are using to work with properties and methods is the scriptlet container object; the exact properties and methods you can use are defined by the scriptlet identified in the container's url property.
Note If you are working in an environment that can display an object's properties and methods, such as Visual Basic, you will not see the properties, because these are not exposed to the development environment.

For example, the following code in a Visual Basic form sets a property and calls a method in the page referenced by the ScriptContainer1 control:

Sub cmdColor_Click()
   ScriptContainer1.BackgroundColor="red"
   ScriptContainer1.UpdateText (Text1.Text)
End Sub

Note In Visual Basic, you must pass a parameter to a scriptlet method even if the method does not require one, or errors can occur. For example, the following statement passes a placeholder parameter of zero to a scriptlet method that does not require parameters:

ScriptContainer1.ToggleColor (0)

Before getting a scriptlet's properties or calling its methods, you must be sure that the scriptlet has been fully loaded. For details, see the container object's onreadystatechange event and readyState property, and the scriptlet's frozen property.

Handling events that occur in the scriptlet is slightly different than it is for events in other objects. For details, see Defining Event Handlers.

See Also

Scriptlet Overview

Designing a Scriptlet


Defining Event Handlers

When you use a scriptlet in your host application, the application can be notified about events that occur in the scriptlet. The scriptlet can expose two types of events:

  • Standard DHTML events such as the onclick event and the onkeypress event. These events are triggered for the scriptlet container object as a whole — using a standard event, you cannot distinguish what control within the scriptlet triggered the event. For details, see Handling Standard Events.

  • Custom events, which are events that you define or DHTML events not provided as standard events. You can also use custom events to pinpoint which control in the scriptlet triggered the event. For details, see Defining Custom Events.


Handling Standard Events

The scriptlet can expose these standard DHTML events:

onclick onkeypress onmousemove
ondblclick onkeyup onmouseup
onkeydown onmousedown

Tip You can define a context menu that is displayed when the user right-clicks the scriptlet at runtime. For details, see the setContextMenu method.

To work with standard events in the host application, you must write handlers in two places: one in the scriptlet to send the event, and another in the host application to capture the event.

To pass an event from the scriptlet to the host application

  1. Attach an event handler script to the event that you want to pass.

  2. Within the event handler script, call the bubbleEvent method to send the event to the host application.

    Note Before passing events to the container object, you can check the scriptlet's frozen property to be sure that the container object is ready to handle events.

If the scriptlet does not include an event handler for a specific event, that event will not be passed to the host application. Similarly, if the scriptlet includes a handler for the event but does not call the bubbleEvent method, the event will not be visible to the host application.
Note The scriptlet container object exposes all standard events at design time, even if the scriptlet does not contain a script that passes the standard event to the application. For example, in Visual Basic, the code window for the scriptlet container lists all standard events, even if not all are available in a specific scriptlet.

The following scriptlet script shows how you can pass a text box's onkeyup event to the host application:

<INPUT TYPE=text ONKEYUP="passKeyUp()" NAME="t1" VALUE="">

<SCRIPT LANGUAGE="JavaScript">
function passKeyUp() {
   // script statements here if required
    window.external.bubbleEvent();
   // further script statements here if required
}
</SCRIPT>

In the host application, the corresponding event is triggered for the scriptlet container object. Additional information about the event, such as the location of the mouse pointer or the state of keys at the time the event was triggered, is available in the script container object's event property. For example, the following Visual Basic subroutine shows how you would capture the scriptlet's onkeypress event and display the key code of a character typed in a scriptlet textbox:

Sub ScriptContainer1_onkeyup()
   MsgBox "The character typed was " & ScriptContainer1.event.keyCode
   MsgBox "The shift state was " & ScriptContainer1.event.shiftKey
End Sub

In Internet Explorer, the following script does the same thing:

<SCRIPT LANGUAGE=JavaScript FOR=document EVENT=onkeyup>
   alert("Key code = " + window.event.keyCode)
   alert("Shift status  = " + window.event.shiftKey)
</SCRIPT>

See Also

Defining Custom Events


Defining Custom Events

You can use custom events to:

  • Send more detail about a standard event — for example, which of several buttons in the scriptlet was clicked.

  • Notify the host application about DHTML events that are not among the standard events handled by the bubbleEvent method.

  • Notify the host application about non-standard changes in the scriptlet, such as when the value of a property changes.

As with standard events, you must send the event from the scriptlet and capture the event in the host application.

To send a custom event in the scriptlet

  • Call the scriptlet's raiseEvent method.

    Note Before passing events to the container object, you can check the scriptlet's frozen property to be sure that the container object is ready to handle events.

For example, the following shows how you can send a custom event called oncolorchange whenever the scriptlet's backgroundColor property is reset:

<SCRIPT LANGUAGE="JavaScript">
function public_put_backgroundColor(value)
{
   window.document.bgColor = value;
   window.external.raiseEvent("event_onbgcolorchange",window.document);
}
</SCRIPT>

To handle a custom event in the host application

  • Create an event handler for the onscriptletevent event.

The following is an example in Visual Basic that shows how you can determine what control triggered an event:

Sub ScriptletContainer1_onscriptletevent( ByVal txtTitle As String, _
      ByVal eventData As Variant)
   objName = eventData.srcElement.ID
   MsgBox "The event " & txtTitle & " occurred in " & objName
End Sub

If your host application is Internet Explorer, use a script such as the following to capture the scriptlet event:

<SCRIPT   LANGUAGE="JavaScript"
         FOR=ScriptletControl1
         EVENT= onscriptletevent (name, eventData)>
   alert("The event that occurred in the scriptlet was " + name);
</SCRIPT>

You can use a Select Case structure in the onscriptletevent event to take different actions based on different events.

See Also

Handling Standard Events


Scriptlet Container Object Reference

When you work with scriptlets in your application, you can use the following properties and events of the scriptlet container object.

Properties
event
readyState
scrollbar
url

Events
onclick
ondblclick
onkeydown
onkeypress
onkeyup
onmousedown
onmousemove
onmouseup
onscriptletevent
onreadystatechange


onclick Event

Sent when the scriptlet forwards an onclick event.

Applies To

Scriptlet container object

Visual Basic Syntax

ScriptContainer_onclick()

JavaScript Syntax

< SCRIPT LANGUAGE="JavaScript"
FOR=ScriptContainer
EVENT= onclick>

Remarks

The scriptlet container object receives this event if both of these conditions are true:

  • The scriptlet contains a handler for the onclick event.

  • The scriptlet's handler calls the bubbleEvent method to pass the event to the host application.

You can get information about the state of the event by querying the scriptlet object container's event property.


ondblclick Event

Sent when the scriptlet forwards an ondblclick event.

Applies To

Scriptlet container object

Visual Basic Syntax

ScriptContainer_ondblClick()

JavaScript Syntax

< SCRIPT LANGUAGE="JavaScript"
FOR=ScriptContainer
EVENT= ondblClick>

Remarks

The scriptlet container object receives this event if both of these conditions are true:

  • The scriptlet contains a handler for the ondblclick event.

  • The scriptlet's handler calls the bubbleEvent method to pass the event to the host application.

You can get information about the state of the event by querying the scriptlet object container's event property.


onkeydown Event

Sent when the scriptlet forwards an onkeydown event.

Applies To

Scriptlet container object

Visual Basic Syntax

ScriptContainer_onkeydown()

JavaScript Syntax

< SCRIPT LANGUAGE="JavaScript"
FOR=ScriptContainer
EVENT= onkeydown()>

Remarks

The scriptlet container object receives this event if both of these conditions are true:

  • The scriptlet contains a handler for the onkeydown event.

  • The scriptlet's handler calls the bubbleEvent method to pass the event to the host application.

You can get information about the state of the event by querying the scriptlet object container's event property.


onkeypress Event

Sent when the scriptlet forwards an onkeypress event.

Applies To

Scriptlet container object

Visual Basic Syntax

ScriptContainer_onkeypress()

JavaScript Syntax

< SCRIPT LANGUAGE="JavaScript"
FOR=ScriptContainer
EVENT= onkeypress()>

Remarks

The scriptlet container object receives this event if both of these conditions are true:

  • The scriptlet contains a handler for the onkeypress event.

  • The scriptlet's handler calls the bubbleEvent method to pass the event to the host application.

You can get information about the state of the event by querying the scriptlet object container's event property.


onkeyup Event

Sent when the scriptlet forwards an onkeyup event.

Applies To

Scriptlet container object

Visual Basic Syntax

ScriptContainer_onkeyup()

JavaScript Syntax

< SCRIPT LANGUAGE="JavaScript"
FOR=ScriptContainer
EVENT= onkeyup()>

Remarks

The scriptlet container object receives this event if both of these conditions are true:

  • The scriptlet contains a handler for the onkeyup event.

  • The scriptlet's handler calls the bubbleEvent method to pass the event to the host application.

You can get information about the state of the event by querying the scriptlet object container's event property.


onmousedown Event

Microsoft Scriptlet Technology Microsoft Scriptlet Technology *

onmousedown, onmouseup Events

Sent when the scriptlet forwards an onmousedown or onmouseup event.

Applies To

Scriptlet container object

Visual Basic Syntax

ScriptContainer_onmousedown()

ScriptContainer_onmouseup()

JavaScript Syntax

< SCRIPT LANGUAGE="JavaScript"
FOR=ScriptContainer
EVENT= onmousedown()>

< SCRIPT LANGUAGE="JavaScript"
FOR=ScriptContainer
EVENT= onmouseup()>

Remarks

The scriptlet container object receives this event if both of these conditions are true:

  • The scriptlet contains a handler for the onmousedown or onmouseup event.

  • The scriptlet's handler calls the bubbleEvent method to pass the event to the host application.

You can get information about the state of the event by querying the scriptlet object container's event property.


onmousemove Event

Sent when the scriptlet forwards an onmousemove event.

Applies To

Scriptlet container object

Visual Basic Syntax

ScriptContainer_onmousemove()

JavaScript Syntax

< SCRIPT LANGUAGE="JavaScript"
FOR=ScriptContainer
EVENT= onmousemove()>

Remarks

The scriptlet container object receives this event if both of these conditions are true:

  • The scriptlet contains a handler for the onmousemove event.

  • The scriptlet's handler calls the bubbleEvent method to pass the event to the host application.

You can get information about the state of the event by querying the scriptlet object container's event property.


onscriptletevent Event

Notifies the scriptlet container object that a custom event has occurred in the scriptlet.

Applies To

Scriptlet container object

Syntax

ScriptContainer_onscriptletevent( eventName, eventObject )

Parameters

eventName

A string that typically identifies the event that is being passed.

eventObject

A variant type that typically is a reference to an object on the scriptlet.

Note The exact content of both parameters depends on what information was passed in the scriptlet's corresponding raiseEvent method.

Remarks

This event is the complement of the scriptlet's raiseEvent method. For more information, see Defining Custom Events. For information about notifying the host application about standard events, see Handling Standard Events.


onscriptletload Event

Microsoft Scriptlet Technology Microsoft Scriptlet Technology *

onreadystatechange Event

Sent to indicate whether the scriptlet has completed loading.

Applies To

Scriptlet container object

Visual Basic Syntax

ScriptContainer_onreadystatechange ()

JavaScript Syntax

< SCRIPT LANGUAGE="JavaScript"
FOR=ScriptContainer
EVENT= onreadystatechange >

Remarks

This event is fired multiple times while the scriptlet is loading. The final time, it indicates that the scriptlet's .htm page is fully loaded and its scripts can be called. To test the current state, you can get the value of the scriptlet container object's readystate property.


scrollbar Property

Specifies whether the scriptlet container object displays a scrollbar.

Applies To

Scriptlet container object

Syntax

ScriptContainer.scrollbar = boolean

Remarks

This property can be set at design time and at runtime. By default, the value of this property is false. If you set this property to true:

  • A vertical scrollbar always appears in the scriptlet container object. If the scriptlet's height is less than the height of the scriptlet container object's window, the vertical scrollbar is disabled.

  • A horizontal scrollbar appears if the scriptlet's width is greater than the width of the scriptlet container object's window

You can also set this property from within a scriptlet. For details, see the scrollbar property. To set the size of the scriptlet container object window from within the scriptlet, see Adding Scriptlets to Your Application.


url Property

Specifies the Universal Resource Locator (URL) of the scriptlet's .htm file to be displayed in the scriptlet container object.

Applies To

Scriptlet container object

Syntax

ScriptContainer.url = URLString

Remarks

You can specify the URL of any .htm file, either local or on a Web server. This property can be set at design time only.

Important If you are adding the scriptlet to a Web page, do not set this property to the URL of the current page. Doing so causes a recursive call to the page and will cause the browser stop functioning.

If you are using the scriptlet in a host application that has a Web context (such as Internet Explorer), you can specify an absolute path (for example, http://myserver/start.htm) or a relative path that does not include the protocol, or domain, or path (for example, page2.htm). If you specify a relative URL, the path is relative to the page in which the scriptlet appears.

If you specify a URL that is not valid, no error message is displayed, but the scriptlet container object remains blank.


Scriptlet Model Extensions

When creating the scripts in the scriptlet, you can use the following specific extensions to the DHTML object model. All extensions are available in the DHTML window.external object.

Properties
frozen
selectableContent
version

Methods
bubbleEvent
setContextMenu
raiseEvent


bubbleEvent Method

Sends event notification for a standard event to the host application.

Applies To

Scriptlet

Syntax

window.external.bubbleEvent()

Remarks

Use this method to pass a standard DHTML event (such as onbuttonclick, onmousemove, or onkeypress) from the scriptlet to the host application. For more details, see Handling Standard Events.


raiseEvent Method

Passes a custom event notification from the scriptlet to the host application.

Applies To

Scriptlet

Syntax

window.external.raiseEvent( eventName, eventObject )

Parameters

eventName

A string that typically identifies the event that is being passed.

eventObject

A variant type that typically includes a reference to the object on the scriptlet that triggered the event.

Remarks

This method is the complement of the scriptlet container object's onscriptletevent event. Use this method to notify the host application about a non-standard event. For more information, see Defining Custom Events. For information about notifying the host application about standard events, see Handling Standard Events.


scrollbar Property

Specifies whether the scriptlet container object displays a scrollbar.

Applies To

Scriptlet

Syntax

window.external.scrollbar = boolean

Remarks

This property provides a way to set the scriptlet container object's scrollbar property from within the scriptlet.

By default, the value of this property is false. If you set this property to true:

  • A vertical scrollbar always appears in the scriptlet container object. If the scriptlet's height is less than the height of the scriptlet container object's window, the vertical scrollbar is disabled.

  • A horizontal scrollbar appears if the scriptlet's width is greater than the width of the scriptlet container object's window

To set the size of the scriptlet container object window from within the scriptlet, see Adding Scriptlets to Your Application.


selectableContent Property

Specifies whether the user can select the contents of the scriptlet.

Applies To

Scriptlet

Syntax

window.external.selectableContent = boolean

Remarks

By default, the value of this property is false. If this property is true, users can select text or objects in the scriptlet while it is shown in the scriptlet container object, and then copy or drag them. If this property is false, users can click objects in the scriptlet, but cannot select them.


setContextMenu Method

Constructs a context menu that is displayed when a user right-clicks a scriptlet in the scriptlet container object.

Applies To

Scriptlet

Syntax

window.external.setContextMenu( menuDefinition )

Parameters

menuDefinition
Defines the command text and commands contained in the context menu. A one-dimensional array in which the menu items are defined using sequences of two elements, n and n+1.

Element n | The command text. Shortcut keys are defined by preceding a letter with "&".
Element n+1 | The method to be called when the command is chosen. You cannot pass parameters to the method.

Note Context menus can only be defined in scripts written in VBScript or JavaScript, because only those languages can create arrays usable by the setContextMenu method.

For example, the following script defines a context menu with three commands:

<SCRIPT LANGUAGE="VBScript" FOR="Menu" EVENT="onClick">
   ' Define array
   dim menuItems(6)     ' 3 commands

   ' First menu item
   menuItems(0) = "Display the &time"     ' Command text
   menuItems(1) = "SetTime"

   ' Second menu item
   menuItems(2) = "Display the &date"     ' Command text
   menuItems(3) = "SetDate"

   ' Third menu item
   menuItems(4) = "Display the document t&itle"     ' Command text
   menuItems(5) = "SetTitle"

   ' Assigns the menu to the scriplet
   ' window.external.setContextMenu(menuItems)

</SCRIPT>


version Property

Returns the version and platform of the scriptlet container object DLL.

Applies To

Scriptlet

Syntax

version = window.external.version

Remarks

This property is read-only. Version is returned in the format N.nnnn platform where N is an integer representing the major version number, nnnn is any number of characters (except a space) representing the minor version number, and platform is the platform (win32, mac, alpha, and so on). The following is an example version number:

1.0a win32

You can use the version property to determine whether the page is being used as a scriptlet or as a standalone Web page. Use a statement such as the following:

controlMode = ( typeof( window.external.version) == "string" )

If the value of controlMode is true after this statement has executed, the page is being used as a scriptlet. Otherwise the page is being used as a standalone page.


readyState Property

Returns information about the load state of the scriptlet hosted in the container object.

Applies To

Scriptlet container object

Syntax

ScriptContainer.readyState = integer

Remarks

This property is read-only. It is available only at runtime.

The readyState property returns an integer value between 1 and 4 indicating the load state of the scriptlet, with the following values:

Value | Definition
1 or 2 | Undefined
3 | Scriptlet text has been loaded, but controls on the scriptlet's .htm page might not yet be functional.
4 | Scriptlet is completely loaded

In general, you should not attempt to access the scriptlet's functionality before the readyState property is set to 4. You can check the value of this property in a handler for the onreadystatechange event.


frozen Property

Indicates whether the scriptlet container object is ready to handle events.

Applies To

Scriptlet

Syntax

boolean = window.external.frozen

Remarks

This property is read-only. When it is True, events will not be received by the scriptlet container object because the container is not yet ready. When it is False, the container will receive event notification.


event Property

Provides state information about a standard DHTML event passed from the scriptlet.

Applies To

Scriptlet object container

Syntax

value = ScriptContainer.event.member

Remarks

This property is read-only. The event property provides a way to get state information about any of the standard events passed from the scriptlet: onclick, ondblclick, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseup. This property corresponds to the DHTML event object.

To get state information, you can query the values of the event property's members, which include altKey, ctrlKey, keyCode, offsetX, offsetY, shiftKey, srcElement, type, and others. The following example script illustrates how you can use the event property to get more information about a standard event:

Sub ScriptContainer1_onkeyup()
   MsgBox "The character typed was " & ScriptContainer1.event.keyCode
   MsgBox "The Alt key state was " & ScriptContainer1.event.altKey
   MsgBox "The Ctrl key state was " & ScriptContainer1.event.ctrlKey
   MsgBox "The Shift key state was " & ScriptContainer1.event.shiftKey
   MsgBox "The mouse was at " & offsetX & ", " & offsetY
   MsgBox "The affected control was " & ScriptContainer1.event.srcElement
   MsgBox "The event was " & ScriptContainer1.event.type
End Sub

For more information about using the event property, refer to the event object in the DHTML documentation.


Windows Scripting Host Programmer's Reference

The following information is presented in this programmer's reference:

  • About Windows Scripting Host
    • ActiveX Scripting Hosts
    • Overview of the Windows Scripting Host Object Model
  • Using Windows Scripting Host
    • Writing a Scripting Engine for Windows Scripting Host
    • How Windows Scripting Host Uses the Registry
    • Registering a Scripting Engine for Windows Scripting Host
    • Running Scripts Using Wscript.Exe
    • Running Scripts Using Cscript.Exe
    • Document Conventions
  • Windows Scripting Host Object Reference
  • Wscript Object
    • Wscript.Application
    • Wscript.Arguments
    • Wscript.FullName
    • Wscript.Name
    • Wscript.Path
    • Wscript.ScriptFullName
    • Wscript.ScriptName
    • Wscript.Version
    • Wscript.CreateObject
    • Wscript.DisconnectObject
    • Wscript.Echo
    • Wscript.GetObject
    • Wscript.Quit
  • WshArguments Object
    • WshArguments.Item
    • WshArguments.Count
    • WshArguments.length
  • WshShell Object
    • WshShell.Environment
    • WshShell.SpecialFolders
    • WshShell.CreateShortcut
    • WshShell.ExpandEnvironmentStrings
    • WshShell.Popup
    • WshShell.RegDelete
    • WshShell.RegRead
    • WshShell.RegWrite
    • WshShell.Run
  • WshNetwork Object
    • WshNetwork.ComputerName
    • WshNetwork.UserDomain
    • WshNetwork.UserName
    • WshNetwork.AddPrinterConnection
    • WshNetwork.EnumNetworkDrives
    • WshNetwork.EnumPrinterConnections
    • WshNetwork.MapNetworkDrive
    • WshNetwork.RemoveNetworkDrive
    • WshNetwork.RemovePrinterConnection
    • WshNetwork.SetDefaultPrinter
  • WshCollection Object
    • WshCollection.Item
    • WshCollection.Count
    • WshCollection.length
  • WshEnvironment Object
    • WshEnvironment.Item
    • WshEnvironment.Count
    • WshEnvironment.length
    • WshEnvironment.Remove
  • WshShortcut Object
    • WshShortcut.Arguments
    • WshShortcut.Description
    • WshShortcut.FullName
    • WshShortcut.Hotkey
    • WshShortcut.IconLocation
    • WshShortcut.TargetPath
    • WshShortcut.WindowStyle
    • WshShortcut.WorkingDirectory
    • WshShortcut.Save
  • WshSpecialFolders Object
    • WshSpecialFolders.Item
    • WshSpecialFolders.Count
    • WshSpecialFolders.length
  • WshUrlShortcut Object
    • WshUrlShortcut.FullName
    • WshUrlShortcut.TargetPath
    • WshUrlShortcut.Save


Internet Client Samples

The Internet Client SDK contains samples which demonstrate the various technologies documented in the SDK. The following is a comprehensive list of these samples.

While the Dynamic HTML (DHTML) samples in the Web Authoring section below can be loaded directly from the Web Site, the other samples must be downloaded, compiled, and linked before they can be run. To view the DHTML samples, simply click on the links provided below. To run the other samples and to analyze the code, install them from the Active Setup page on this site.

You must be running Internet Explorer 4.0 to view these samples.

Web Authoring Samples
Sample Files Description

DHTML
Asteroids | Demonstrates a fully-functional DHTML version of Asteroids.
Clock | Demonstrates an example of Dynamic Content.
Styles | Demonstrates a sample of using Dynamic styles.
Path | Demonstrates a scripting version of the path control.
Popup-Menu | Creating a popup-menu through the use of DHTML.
Filter Wizard | HTML-based wizard that generates working filters code.
Wave Wizard | HTML-based wizard that generates working wave filter code.
Light Wizard | HTML-based wizard that generates working light filter code.
Centering | Demonstrates centering an object within a division on the page.
Image | Demonstrates image switching between gif files.
Position | Demonstrates 2D layer of moving images with a mouse.
Resize | Various samples demonstrating resizing capabilities.
Domain | Illustrates accessing a second-tier domain in an IFRAME.
MMAudio | Illustrates mixing several .WAV files.
MMSGX | Demonstrates how to use a structured graphic control.
Surface | Shows how the DirectAnimation DrawingSurface API is used to create a single vector shape with independent internal and external rotations.
Graphics | HTML based wizard that generates working code (for the Structured Graphics and Sequencer controls) that produces a rotating text logo, based on the parameters entered by the user.
Agent | Uses Microsoft Agent to demonstrate the use of Dynamic HTML.
Path Wizard | HTML-based wizard that generates working path control code, based on the parameters entered by the user.
Poly Wizard | HTML-based wizard that generates a polygon-shaped path, based on the parameters entered by the user.
Tricycle | Shows a sprite control on a path, and allows you to control its behavior.
Sprite | Demonstrates the ability to add still and animate images on your web page, with control over frames per second, forward or reverse playback, or dynamic reading of source files.
Banner | Demonstrates the ability to use the sprite control as a clickless control for a Banner-type advertisement.
Concentrate | Demonstrates the ability to use the sprite control to contain images for this match game.
Swapgame | Demonstrates the ability to use the sprite control to contain images for puzzle-type game.
Sequencer-JScript | JScript sequencer sample.
Sequencer-VBScript | VBScript sequencer sample.

DataBind A suite of samples demonstrating the use of Data Binding in Internet Explorer 4.0. Samples are accessible from the Show Me buttons in the Databinding overview.
Channel Demonstrates subscribing to a channel.

MultiMedia
Rectangle | Demonstrates rectangles with time-varying colors that chase each other along a path.
Text Animation | Demonstrates basic text animation as a windowless control.
Crop | Demonstrates a cropped animated image that overlays a variation of itself.
Buttons | Demonstrates using Visual Basic buttons to color an animation.

Software Developer Samples
Sample Files Description

ChatOCX
Chat2000 | Demonstrates how to use the Chat OCX inside an MDI MFC application.
ChatAd | A simple Visual Basic Application which provides monitoring capability for chat administrators.
Checkrs | A Visual Basic Application that enables you to play a Checkers game with the people you are chatting with.
ExecChat | Contains a Visual Basic application for hosting Executive Chat Sessions.
Trnscrpt | A Visual Basic application which provides a transcript of the chat session.
Webdemo | Contains four web pages that demonstrate the usage of the chat control with Visual Basic scripting.
Chappy | Chat Protocol 2.0 - MFC Sample
Procx | Chat Protocol 2.0 - HTML Sample
Nmstart | Chat Protocol 2.0 HTML sample where user can select a chat user and startup a NetMeeting conversation.
Checkers | Demonstrates how to use the Chat Protocol control to transfer data between two checkers players in a chat room.

ColBtn Demonstrates a control that accesses and changes the HTML document in which it is contained.

CommCtrl
Rebar | Demonstrates implementation and usage of the rebar control.
VListVw | Demonstrates implementation and usage of a "virtual" listview control.

Shell
BandObjs | Demonstrates implementation of three types of band objects, Desk Bands, Explorer Bars and Communication Bands.
RegView | Demonstrates implementation of a multi-level shell namespace extension.

DXM | Various samples demonstrating the use of DirectAnimation for implementation of multimedia in a web page.
DOServer | Demonstrates implementation of an ActiveX Document server.

Driller
Driller | Demonstrates implementation of an ActiveX control container using MFC.
DrillVB | Demonstrates implementation of an ActiveX control container using Visual Basic.

HTML Dlg | Demonstrates how to use the ShowHTMLDialog function.
Percy | ATL2.0 control that demonstrates the use of IPersistHistory so that state can be retained if the page containing the control is returned to using the back button.
Framer | Demonstrates in-place activation of an ActiveX Document.
Glass | Demonstrates some of the new multi-media infrustructure enhancements made to the Internet Explorer that Active X control creators can use.
Ielnk | An ATL-based control which demonstrates the usage of the Simple Hyperlink Navigation APIs.
IISLog | Demonstrates how to receive and parse the IE4 user logging profile from the server side.
IEMime | Demonstrates MIME type registration and MIME type recognition of downloads with an asynchronous URL moniker.
ObjVw | Illustrates using IE's Automation model and scripting model from within a contained ATL control.
ProfAsst | Illustrates how the IE4 Profile Assistant is used to share information.
Progress | Demonstrates the use of the URL Moniker to download data across the network.
Spruuids | Demonstrates implementation of an ActiceX Scripting host.
Task | Demonstrates the new Task Scheduler objects and API provided with installation of the Task Scheduler package
TDC | Implements an ActiveX control that displays interactive tabular data in an HTML page.
UrlPad | Enhances SUPERPAD that demonstrates getting an URL using urlostream API(from urlhlink.lib) and posting it back to the server using WebPost API(sample below).
VBScript | Sample VBScript pages.
VBIEFrm | Illustrates hosting the Web Browser control in a Visual Basic Application.
WalkAll | Demonstrates using the MSHTML.DLL as an HTML parser.
Microsoft Agent | Microsoft Agent samples in C, HTML, Java, and VB.
WabTool | Demonstrates how to program the Internet Explorer Address Book (also known as the Windows Address Book).

WebPost
StubWpp | Demonstrates authoring a Web Publishing Service Provider.
WBPost | Demonstrates the usage of WebPost APIs.

WinINet
FTPJr | Demonstrates the FTP WinInet APIs.
HTTPAuth | Demonstrates use of WinInet for HTTP authentication.
HTTPDump | Demonstrates how to create and submit an HTTP request.
InetAll | Demonstrates downloading files using FTP URL, HTTP URL or FILE URL.

Instructions

BUILDING FROM COMMAND LINE: To build samples from the command line, please run SetEnv.Bat to set up your environment variables. This SDK requires the most recent Win32 development files (you can get these from the Microsoft Platform SDK on the MSDN site; or you can get the require subset of these files from the Internet Client SDK download site) and a recent compiler (all testing was done with VC++ 5.0). The INCLUDE, LIB and PATH environment variables should first look in \INetSDK\include, \INetSDK\lib, and \INetSDK\bin respectively (from this SDK), then to the recent Win32 development files. Then your VC++ 5.0 files (i.e. \ProgramFiles\DevStudio\VC).

BUILDING FROM VC5 IDE: To build samples from within the Visual C++ 5.0 IDE, the equivalent to the above must be done within the IDE. Select "Options" from the "Tools" menu. Choose the "Directories" tab. The full path to your INetSDK\Include directory (for example, "C:\InetSDK\Include") should be the top-most entry in the list for "Include files" directories. Likewise, the full path to your INetSDK\Lib directory should be the top-most entry in the list for "Library files" directories.

WIN32 HEADERS: If you experience build errors due to missing Win32 header files or incorrect definitions in Win32 header files, your Visual C++ 5.0 headers may not be up to date with the most recent Win32 headers. To resolve, use the Win32 headers and libs installed with this SDK by adding the InetSdk\win32inc to the list of "Include files" directories and InetSDk\win32lib to the list of "Library files" as directed above. These entries should be listed immediately under the InetSDK\* entries in each list.

ATL SAMPLES: For samples that use ATL, all build configurations except "MinDependency" builds require that ATL.DLL exists and is registered on the build computer. This file is normally installed with typical Visual C++ 5.0 installations. However, in some cases this DLL will be absent from the system or not registered properly. To build these samples, please obtain a current copy of the ATL.DLL from your Visual C++ 5.0 CD (\devstudio\vc\redist\atl.dll), from a recent Visual C++ 5.0 Service Pack, or otherwise insure that ATL.DLL exists in the Windows system directory. You will then need to run "regsvr32 atl.dll" to register this DLL as appropriate. Along the same lines, some ATL samples are also dependent on MSVCRTx.DLL and MSSTKPRP.DLL.

Current SDK samples that use ATL are COLBTN, GLASS, IELNK, IEMIME, OBJVW, PERCY, and TDC.

Please refer to the Redistrb.wri file on your Visual C++ CD (\devstudio\vc\redist) for more information on redistribution of ATL.DLL or any Visual C++ DLLs.

Creating Microsoft Visual C++ Project Files.

To build the samples from within the Microsoft Visual C++ 5.0 Developer Studio environment for samples that do not come with VC++ makefiles (.mak, .dsp files), you must add appropriate paths to the Developer Studio's include and library paths, and create a Visual C++ project file. The general steps to follow are outlined below, although the exact steps vary from sample to sample.

  1. Click "Options..." on the "Tools" menu, and on the "Directories" tab add the full path to your installed INetSDK\Include directory to the includes directories, the full path to INetSDK\Lib to the library directories, and the full path to the INetSDK\Bin directory to the executable files directories. These entries should be moved to the top of the search list. Some samples may require the most recent Win32 development files. The corresponding include, lib, and bin directories should also be added and moved up just below the INetSDK entries.
  2. Create project and make files as follows:
    1. Close any open workspace from the File menu.
    2. Click "New" on the "File" menu and choose the "Projects" tab on the dialog box.
    3. In the "New Projects" tab dialog box type the root name for the output file into the "Project Name:" edit control (for example, type "Framer" for the Framer sample).
    4. Choose "Win32 Application" in the "Projects Listbox:" if you are building an application, "Win32 Dynamic-Link Library" for an ActiveX(tm) Control, or "Win32 Static Library" for a library.
    5. "Browse..." to the INetSDK\Samples directory on your system. From there move to the directory holding the sample's sources and click "OK" to close the "Choose Directory" dialog. Make sure the "Location:" edit control reflects the directory holding the sample's sources and not a new subdirectory under this root.
    6. Click "Create".
    7. Click "Add into Project...Files" on the "Project" menu.
    8. Select all of the *.Cpp, *.c, *.def, and *.Rc and click "OK". If the project contains an .Odl file add this to the project also.
    9. Click "Settings..." on the "Project" menu and select the "Link" tab. Add any appropriate libraries from the INetSDK or Win32 development files to the list of Object/library modules for both debug and release. You can search the SDK makefile in the source's directory for ".lib" to find out which additional libraries are needed by a particular sample (such as urlmon.lib, etc.). Note that some samples need to link to separate debug or release libraries.
    10. If the sample you are building uses MFC, choose which type of library to use in the "Microsoft Foundation Classes:" list box on the "General" tab of the "Project Settings" dialog.
  3. Build the project from within the IDE. Note that some samples are dependent on libraries built by other samples. These dependencies are noted in the ReadMe.Txt files.
  4. If necessary, copy and/or rename the output file appropriately, using the provided makefile as a guide.
  5. If the output is an ActiveX(tm) Control, run RegSvr32 from the command line to register the .ocx on your system. You can probably finesse the "Register Control" option on the "Tools" menu to do this without dropping to the command line, but it is set up to work with projects created using the OLE ControlWizard.

© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


Microsoft Agent Sample

Microsoft Agent Microsoft

Microsoft Agent provides access to a set of services that allow you to support an interactive character from your Web site.

Here is a sample demo using the Microsoft Agent ActiveX control. Using IE 4.0 events and object model, the character reads the text of the page as the user moves his mouse. This sample degrades gracefully under IE 3.0.

For additional samples and complete documentation, or to download Microsoft Agent, visit either of these sites:
  • The Microsoft Agent Web site
  • The Internet Client SDK Download area

© 1997 Microsoft Corporation. All rights reserved. Terms of Use.


Asteroids Sample

00 | 10000 | 00
Press any key to start
J - Rotate Left
K - Accel
L - Rotate Right
Space - Fire


Authoring tips

This is an example of how one would center something Vertically inside a division

This is the outer DIV
This is text in the inner DIV

This is the source of the above example:

<html>
<head>
<script>
function foo() {
document.all.one.style.top = 50; //Bug. Inner DIV will not re-render without forcing outer DIV to rerender.
document.all.two.style.top = document.all.one.offsetHeight/2 - document.all.two.offsetHeight/2;
document.all.two.style.left = document.all.one.offsetWidth/2 - document.all.two.offsetWidth/2;
}
window.onload=foo;
</script>
</head>

<body>
text in beginning<br>

<div id=one style="position:absolute; top:10; height:200;width:200;background-color:green">
text in the outer DIV
<div id=two style="position:absolute;left:50;width:100;color:red; border:red 2px solid">
text in the inner DIV
</div>
</div>

</body>
</html>


Dynamic Content

Dynamic Content in Action

An HTML Clock

Where do you want to go today?
What you type in below will replace this HTML


DHTML Pop-up Menu

Click the left mouse button anywhere on this page to activate a pop-up menu implemented using Dynamic HTML.


Item1
Item2
Item3
Item4
Item5
Item6
Generation


Security Demo

document.domain property

Due to raising security concerns on the web as a whole the Internet Explorer Security
has been tightened in Internet Explorer 4.0. The following is a mock-up of how one would
create a web page so that it can "talk" (access the object model) to a frame or inline-frame and vice-versa

For Example: If this page were being loaded from http://www.microsoft.com
and we wished to access the HTML of the IFRAME with parent.frames(0).document.all.myBody.innerHTML
and the IFRAME contents were coming from http://sbn.microsoft.com.

You must do two things.

  1. Set the document.domain property to the domain in common to both in this case document.domain should be set to "microsoft.com"
  2. The document.domain property MUST ALSO be set to "microsoft.com" in the FRAME or IFRAME that is on the Main page

NOTE: This specific example will not work since these pages are not residing on the servers that the document.domain property is set to.

This is how the script in the parent frame should be:


Dynamic Styles

Dynamic Styles in Action

Rollover Effects
Milk Cookies Eggs Ham Cheese Pasta Chicken

Outlining
Item 1
Item 1.1
Item 1.1.1
Iten 1.1.2
Item 1.2
Item 2

Cursor Effects
Change the cursor over any element


CSS Filters Wizard

This page helps you to build your own Filter samples

Filtered site:

Filter:

You can copy the code from the first frame and paste it into a new file to get the filter effect you've created, as displayed in the second frame.


Microsoft Image Switching Sample

 This example switches images using pre-loaded images.


CSS Filter Effects - Light effect Wizard

This page helps you build Lighting effects

Filtered site: light type: red: green: blue: strength:
x: y: z: x tgt: y tgt: spread:

You can copy the code from the first frame and paste it into a new file to get the Wave filter effect you've created, as displayed in the second frame.


ActiveMovie Mixing

Sound Mixing Using Active Movie Control

<!-- This code uses two hidden active movie objects to mix two sounds together one of a bass instrument and the second of drums. The simple scripts below set up the buttons for the two channels A & B. --> &lt;NPUT NAME=Sound1 TYPE=BUTTON VALUE="A Channel" STYLE="position:absolute; LEFT:20; TOP:80; color:white;"> &lt;INPUT NAME=Sound2 TYPE=BUTTON VALUE="B Channel" STYLE="position:absolute; LEFT:20; TOP:120; color:white;"> <!-- Use the object with the properties specified below for hidden operation--> &lt;OBJECT ID="AM1" WIDTH=0 HEIGHT=0 STYLE = "visibility:hidden" CLASSID="CLSID:05589FA1-C356-11CE-BF01-00AA0055595A"> &lt;PARAM NAME="showcontrols" VALUE="false"> &lt;PARAM NAME="showdisplay" VALUE="false"> &lt;PARAM NAME="AutoStart" VALUE="false"> &lt;PARAM NAME="AutoRewind" VALUE="false"> &lt;PARAM NAME="PlayCount" VALUE="5"> &lt;PARAM NAME="FileName" VALUE="bass.wav"> &lt;/OBJECT> &lt;OBJECT ID="AM2" WIDTH=0 HEIGHT=0 STYLE = "visibility:hidden" CLASSID="CLSID:05589FA1-C356-11CE-BF01-00AA0055595A"> &lt;PARAM NAME="showcontrols" VALUE="false"> &lt;PARAM NAME="showdisplay" VALUE="false"> &lt;PARAM NAME="AutoStart" VALUE="false"> &lt;PARAM NAME="AutoRewind" VALUE="false"> &lt;PARAM NAME="PlayCount" VALUE="5"> &lt;PARAM NAME="FileName" VALUE="drums.wav"> &lt;/OBJECT> &lt;script language="VBScript"> ' here we define a: Dim achan ' bit to define whether channel A it is playing or not Dim bchan ' bit to define whether channel B it is playing or not achan=2 ' make sure if that if loading button is clicked it does not bchan=2 ' try to play files before they are loaded, to avoid error sub AM1_ReadyStateChange() 'This event is fired when Channel A Media (wave file) is finished loading achan=0 sound1_onclick 'Make button display "play" end sub sub AM2_ReadyStateChange() 'This event is fired when Channel A Media (wave file) is finished loading bchan=0 sound2_onclick 'Make button display "play" end sub ' The following two routines take care of toggling the ' Buttons between their two states play and Stop ' as well as starting and stopping their respective ' ActiveMovie Control Sub Sound1_onclick select case achan case 0: AM1.Stop Sound1.innerText="Play Channel A" Sound1.style.backgroundColor="green" achan = 1 case 1: AM1.run Sound1.innerText="Stop Channel A" Sound1.style.backgroundColor="red" achan = 0 end select end sub Sub Sound2_onclick select case bchan case 0: AM2.Stop Sound2.innerText="Play Channel B" Sound2.style.backgroundColor="green" bchan = 1 case 1: AM2.run Sound2.innerText="Stop Channel A" Sound2.style.backgroundColor="red" bchan = 0 end select end sub &lt;/SCRIPT>


Microsoft DirectAnimation Multimedia Controls Sample - Structured Graphics utilizing DrawingSurface

Structured Graphics Sample Utilizing DrawingSurface


DirectAnimation Controls - Structured Graphics and Sequencer Wizard

This page helps you to build your own rotating text logo

Logo Text
Font to be used:

Logo Text Color - must be integer value between 0 and 255 for each color.
Red Value Green Value Blue Value

Distance from center point:
X axis distance Y axis distance Initial text rotation

Rotation angles:
X axis Y axis Z axis

Rotation Speed - seconds.milliseconds

You can copy the code from the first frame and paste it into a new file to get the logo you've created, as displayed in the second frame.


DirectAnimation Controls Path Wizard

This page helps you to build a path

Shape to be used:

Shape parameters:
X position Y position Width Height

Path motion:

Repeat:

Playback Duration - seconds.milliseconds

You can copy the code from the first frame and paste it into a new file to use the path you've created, as displayed in the second frame.


Polygon Path Wizard

This page generates a polygon shaped path.

X 1: Y 1: Shape to be used:
X 2: Y 2: Path motion:
X 3: Y 3:
Repeat:
X 4: Y 4:
X 5: Y 5: 		Playback Duration - seconds.milliseconds:

You can copy the code from the first frame and paste it into a new file to use the path you've created, as displayed in the second frame.


Positioning sample

 Use the mouse to drag and create an alien!

To help convert existing dragging samples from earlier builds try these ideas:
  • To avoid the "no drag" icons when dragging images, in the onmousemove use:
    event.cancleBubble = true;
    event.returnValue = false;
  • Also, instead of using the parameters on the event handlers, use the properties
    on the event object instead.


IE 4.0


Microsoft DirectAnimation Multimedia Controls Samples - Sequencer

DirectAnimation Controls - Sequencer Sample


Microsoft DirectAnimation Multimedia Controls Samples - Sequencer

Sequencer Sample


Multi State Buttons

 Roll over Button to activate
Roll off Button to deactivate
Click Button to change state


Microsoft DirectAnimation Controls - Sprite OnMarker and Frame Property sample

Where do you want to go

for your next vacation?


Concentration

Moves: 0, Matches: 0


Swap 'Em

Swap-0-Nauts

Moves so far: 0


CSS Filter Effects - Wave effect Wizard

This page helps you build a Wave filter effect

Filtered site: strength: frequency: light: additive: phase:
Animated:

You can copy the code from the first frame and paste it into a new file to get the Wave filter effect you've created, as displayed in the second frame.